text:
Q: Configurar cabeçalhos de página com DOMPDF Existe alguma forma de configurar o DOMPDF para que coloque um cabeçalho em todas as páginas do PDF gerado?
Estou gerando um relatório e gostaria que todas as páginas do relatório tivessem o cabeçalho da primeira.
    //define o estilo da página pdf
$style='
    ';

//define o cabeçalho da página
$head='
Lista de Compras

';

//inclui a biblioteca do dompdf
require_once("lib/dompdf/dompdf_config.inc.php");

//recebendo os dados do Formulário
$quant=$_POST['quantidade'];
$tipo=$_POST['tipo'];
$produto=$_POST['produto'];
$obs=$_POST['obs'];

//define o corpo do documento
$body='

            Quantidade
            Tipo
            Produto
            Obs.

    ';
for ($i = 0; $i < count($quant); $i++) {
    $tmp='

        '.$quant[$i].'
        '.$tipo[$i].'
        '.$produto[$i].'
         '.$obs[$i].'
        ';
    $body=$body.$tmp;
}

//define o rodapé da página
$footer='

    ';

//concatenando as variáveis
$html=$head.$style.$body.$footer;

//gerando o pdf
$html = utf8_decode($html);
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("compras.pdf");

A: Pronto.
Mudanças

*

*Coloquei as tags html head e body em sequência, assim como se fosse uma página .html.

*Coloquei type="text/css". É bom dizer ao browser especificamente o que o código é.

*No cabeçalho #head adicionei position:fixed, é obrigatório para fixar ele em toda página. Deixei no centro da página usando o margin: auto, com left: 0 e right: 0. CSS normal.

*No @page que controla a estrutura da página em si, defini 120px de topo. E defini o margin-top do #head com -110 para o cabeçalho não subir em cima do conteúdo.

*Coloquei o thead no cabeçalho da tabela para que ele se repetisse em toda página. Foi escolha minha, mas pode tirar se quiser.

*Coloquei o tbody - não dentro da estrutura repetitiva - apenas para dizer ao código que a partir dali vem os dados tabulados (especificar).

*Depois fechei lá no final as tags body e html.

*Rodapé também deve ser position: fixed e fora do corpo do conteúdo. Assim como o cabeçalho.

Código
<?php
     //define o estilo da página pdf
     $style='
        ';

    //define o cabeçalho da página
    $head='
Lista de Compras

';

    //inclui a biblioteca do dompdf
    require_once("dompdf/dompdf_config.inc.php");

    //recebendo os dados do Formulário
    $quant      = 22;
    $tipo       = 'Unidade';
    $produto    = 'Garrafa PET';
    $obs        = 'Sem Obs';

    //define o corpo do documento
    $body='

                Quantidade
                Tipo
                Produto
                Obs.

';

    for ($i = 0; $i < 130; $i++) {
        $tmp='

            '.$quant.'
            '.$tipo.'
            '.$produto.'
             '.$obs.'	';
        $body = $body.$tmp;
    }

    //define o rodapé da página
    $footer='

Página

  ';

    //concatenando as variáveis
    $html=$head.$style.$body.$footer;

    //gerando o pdf
    $html = utf8_decode($html);
    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $dompdf->stream("compras.pdf");

?>


text:
Q: Multiple checkbox search query fetching data from database in php I have a multiple checkbox search query which fetches data from database. Below is the code:
HTML code:
<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red

<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow

<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue

<input type="checkbox" name="cloth_color[]" value="Green" /> Green

<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta

<input type="checkbox" name="cloth_color[]" value="Black" /> Black

<input type="checkbox" name="cloth_color[]" value="White" /> White

<input type="submit" value="SEARCH">
</form>

PHP code:
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
   {
      $chk .= $chk1;
   }

if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];

    echo 'The cloth with ' . $colorofcloth . ' color';
    echo '
';

}
}
?>

Now if I choose one option from the search select box I get query. But if I select two or more color I dont get the query. A help will be really appreciated.
P.S. I do have multiple joins in Mysql query but this is the place I am stuck so presenting as clear question as possible here. Also I intent to convert mysql to mysqli before the launch of this code. Thank you :)

A: <?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
   {
      $chk .= $chk1 . ",";
   }

if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($chk)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];

    echo 'The cloth with ' . $colorofcloth . ' color';
    echo '
';

}
?>

you can try this code which will use IN() of MySQL where you can pass multiple , separated values.
Hope this helps

A: What you may want to use is the Mysql IN CLause.
For this example, i am assuming that you use the correct syntax for the elements inside de IN Clause.
The correct syntax would be all the values that you need separated by commas, if you select red and blue.
$chk = 'red, blue'

Using the 'IN Clause' this query
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";

should transform to this.
$query = "SELECT * FROM clothings WHERE colorofcloth IN ('$chk')";

I do not know much about PHP, but for a database stand it should work.
Let me know if it works.

A: Ok this is what i did. first of all got great help from @Dhaval and @Carlos as wasn't familiar with IN function in Mysql.
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
   {
      $chk .= "'" . $chk1."', ";
      //This is important as it is not the number it is a word so it should have a single quote if in query we are using double quote or vice versa.
   }
$check_e = rtrim($chk,", ");
//Although i havn't checked in real time if mysql query will take last comma or not but it is a good practice to remove the last comma by rtrim.

if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($check_e)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];

    echo 'The cloth with ' . $colorofcloth . ' color';
    echo '
';

}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: In swiftui foreach onAppear Issue Here is my sample. I have a list with something to sum up. And I set up an Observe obj to store the result, trigger +1 when the subview on Appear.
class observed : ObservableObject {

@Published var listNum : Int = 0

}

struct ContentView: View {

@State private var mylist = [
    1,0,1,0,1,1
]

var body: some View {

    ForEach(mylist, id: \.self) { (value) in
        ExtractedView(value:value)
     }

    }
}

struct ExtractedView: View {

  var value : Int = 0

  @EnvironmentObject var obj : observed

  @State var listNum:String = "0"

  var body: some View {
      Text(listNum)
        .onAppear{

          if self.value != 1{
              self.obj.listNum = 0
          }else{
              self.obj.listNum += 1
          }
          self.listNum = String(self.obj.listNum)

        }
     }
  }

But the result always Upside down, not as expected.

A: Actually order of .onAppear call is undefined, so it is not clear what is expected. Anyway from what I see in provided code there might be confuse for ForEach id, `cause array value is used, but it is not unique.
Try the following
ForEach(Array(mylist.enumerated()), id: \.0) { (i, value) in
    ExtractedView(value:value)
 }


text:
Q: Standalone HBase with Spark, HBaseTest.scala is giving error Hi I am using standalone hbase and I want to test spark on it. There is no hadoop on my machine.
when I try to get count of a table using HBaseTest.scala (in scala examples)
I get following error:
ERROR TableInputFormat: java.io.IOException: java.lang.reflect.InvocationTargetException
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:416)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:393)
    at org.apache.hadoop.hbase.client.HConnectionManager.getConnection(HConnectionManager.java:274)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:194)
    at org.apache.hadoop.hbase.client.HTable.<init>(HTable.java:156)
    at org.apache.hadoop.hbase.mapreduce.TableInputFormat.setConf(TableInputFormat.java:101)
    at org.apache.spark.rdd.NewHadoopRDD.getPartitions(NewHadoopRDD.scala:91)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1632)
    at org.apache.spark.rdd.RDD.count(RDD.scala:1012)
    at org.apache.spark.examples.HBaseTest$.main(HBaseTest.scala:59)
    at org.apache.spark.examples.HBaseTest.main(HBaseTest.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:607)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:167)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:190)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:111)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:414)
    ... 23 more
Caused by: java.lang.VerifyError: class org.apache.hadoop.hbase.protobuf.generated.ClientProtos$Result overrides final method getUnknownFields.()Lcom/google/protobuf/UnknownFieldSet;
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    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 sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.apache.hadoop.hbase.protobuf.ProtobufUtil.<clinit>(ProtobufUtil.java:176)
    at org.apache.hadoop.hbase.ClusterId.parseFrom(ClusterId.java:64)
    at org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:69)
    at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:83)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.retrieveClusterId(HConnectionManager.java:857)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.<init>(HConnectionManager.java:662)
    ... 28 more

Exception in thread "main" java.io.IOException: No table was provided.
    at org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.getSplits(TableInputFormatBase.java:154)
    at org.apache.spark.rdd.NewHadoopRDD.getPartitions(NewHadoopRDD.scala:95)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1632)
    at org.apache.spark.rdd.RDD.count(RDD.scala:1012)
    at org.apache.spark.examples.HBaseTest$.main(HBaseTest.scala:59)
    at org.apache.spark.examples.HBaseTest.main(HBaseTest.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:607)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:167)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:190)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:111)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I am not able to figure out whats the issue here.
HBaseTest.scala:
object HBaseTest {
  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setAppName("HBaseTest").setMaster("local")
    val sc = new SparkContext(sparkConf)
    val conf = HBaseConfiguration.create()
    // Other options for configuring scan behavior are available. More information available at
    // http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/mapreduce/TableInputFormat.html
    conf.set("zookeeper.znode.parent", "/hbase-unsecure")
    conf.set("hbase.zookeeper.quorum", "localhost")
    conf.set("hbase.zookeeper.property.clientPort","2181")
    conf.addResource(new Path("/usr/lib/hbase/hbase-0.94.8/conf/hbase-site.xml"))
    conf.set(TableInputFormat.INPUT_TABLE,"test")
    // Initialize hBase table if necessary
    val admin = new HBaseAdmin(conf)
    if (!admin.isTableAvailable("test")) {
      print ("inside if statement")
      val tableDesc = new HTableDescriptor(TableName.valueOf("test"))
      admin.createTable(tableDesc)
    }
    val hBaseRDD = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat],
      classOf[org.apache.hadoop.hbase.io.ImmutableBytesWritable],
      classOf[org.apache.hadoop.hbase.client.Result])
    hBaseRDD.count()

    sc.stop()
  }
}

A: You ar using TableInputFormat class as input format. TableInputFormat class is belong to hadoop Map-reduce API. You need to install hadoop for using TableInputFormat.


text:
Q: Deploying ssis 2012 with visual studio 2010 I've created a new SSIS package in Visual Studio 2010 and started deploying the package to a SQL 2012 database on a remote server.
I can connect to the DB and see the SSISDB folder but when i deploy the package I get the following error:
"The path for 'ISServerExec.exe' cannot be found. The operation will now exit."

A: Are you sure you have SSIS 2012 installed on that machine? and the service is running? (check SQL Server Configuration Manager)
This looks like you created an SSIS catalog on a SQL Server machine that has no SSIS service running (or SQL is unable to see the correct version of SSIS running). You will be able to see the catalog and even go through the deployment wizard from visual studio, but will receive the error message you mentioned above when you finalize your deployment.


text:
Q: Putting an item in a array I am trying to display the actors in the array into a table when I add an actor it would show up in the table. For each actor I should be able to update and delete them.
I'm not sure on how to get the values from html to display in the table.

var actors, i;

var Info = [
            {firstName: "Jason", lastName: "Statham", birth: "July 26, 1967", gender: "Male", genre: "Action, Crime, Thriller"},
            {firstName: "Mark", lastName: "Wahlberg", birth: "June 5, 1971", gender: "Male", genre: "Action, Comedy, Drama"}
           ];
var displayActors = function(actors) {
    var str = "
";
    str += "
";
    str += "First Name	Last Name	Date of Birth	Gender	Genre	";
    str += "
";
    for(i=0; i < actors.length; i++){
        str += "
";
        str += "" + actors[i].firstName + "	";
        str += "" + actors[i].lastName + "	";
        str += "" + actors[i].birth + "	";
        str += "" + actors[i].gender + "	";
        str += "" + actors[i].genre + "	";
        str += "
";
    }
    str += "
";

    document.getElementById("actorGrid").innerHTML = str;
}

window.onload = function() {
    displayActors(Info);
}
document.getElementById("submit").onclick = function() {
    var fName = "";
 var str = "
";
    fName = document.getElementById("fname").value;
    if(fName != "") {
  str += "
";
  str += "" + Info.push({firstName: fName}) + "	";
  str += "
";
    }
    str += "
";
    document.getElementById("actorGrid").innerHTML += str;
}

Add Actors

        First Name

        <input type="text" id="fname"/>

        Last Name

        <input type="text" id="lname"/>

        Date of Birth

        <input type="date" id="dob"/>

        <form action="">
            Gender:

            Male<input type="radio" name="gender" value="Male" id="male"/>
            Female<input type="radio" name="gender" value="Female" id="female"/>

        </form>

        <form action="">
            Genre:

            Action<input type="checkbox" id="action"/>
            Adventure<input type="checkbox" id="adventure"/>
            Thriller<input type="checkbox" id="thriller"/>
            Drama<input type="checkbox" id="drama"/>
        </form>

<input type="button" id="submit" value="Add Actor" />

A: If you are OK with rerendering the whole table, then I believe your click event handler can just be
document.getElementById("submit").onclick = function() {
  var fName = document.getElementById("fname").value;
  Info.push({firstName: fName});
  displayActors(Info);
};

With regard to your questions, Array#push is exactly how you can add a new value to an array and the value property is exactly how you read values from form elements.


text:
Q: sIFR seems to be loading correctly but not displaying text I'm Using sIFR 3r436, and although I believe everything is set up correctly, and my console shows that the .swf font file is loading correctly, the HTML type is hidden but the sIFR type is not displaying. Below is a link to the site in question:
Schaffer's Website
Below is a link to a test site that uses exactly the same sifr-config.js, sifr.js, css, and swf files. And it works. The main difference between the two is the server that they are running on.
Schaffer's Test Site
I'm hoping that maybe somebody can see a problem that I'm unable to. Appreciate the help!

A: The server gives a 403 forbidden for the Flash movie – in other words, it does not load.


text:
Q: Drupal's JS and CSS optimization error I started getting errors after I turned on Drupal's performance improvements which pack all the CSS and JS files into single files. The error looks like this:

The selected file /tmp/fileO4fjBF
  could not be uploaded, because the
  destination
  js/js_8a69e612be02242c2866a4a19223bd12.js
  is not properly configured.

I'm not sure how I should configure my server for this to work correctly. There is nothing in the documentation about this.

A: Check you ' Site Configuration > Files' settings or the report. If it is a file permission issue (or maybe a missing folder) it should be apparent from one of those two places.
Often the report or files-settings also supply information on how to remedy the problem.


text:
Q: Transpile to ES5 corrupt JS library in Angular 6 project I am trying to use Dygraph library in an Angular 6 project. It works perfectly in Chrome / FF, however it does not work in IE11. I installed the library through npm, and installed the @types from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/dygraphs
I imported the library in my module using:
import { default as Dygraph } from 'dygraphs';

When I open the page on IE11, loading stops on:
this.xticks.push({pos, label, has_tick});

With error SCRIPT1003: Expected ':'.. The block where it stops loading is:
    DygraphLayout.prototype._evaluateLineTicks = function() {
      var i, tick, label, pos, v, has_tick;
      this.xticks = [];
      for (i = 0; i < this.xTicks_.length; i++) {
        tick = this.xTicks_[i];
        label = tick.label;
        has_tick = !('label_v' in tick);
        v = has_tick ? tick.v : tick.label_v;
        pos = this.dygraph_.toPercentXCoord(v);
        if ((pos >= 0.0) && (pos < 1.0)) {
          this.xticks.push({pos, label, has_tick});    <<--- This line stops
        }
      }

      this.yticks = [];
      for (i = 0; i < this.yAxes_.length; i++ ) {
        var axis = this.yAxes_[i];
        for (var j = 0; j < axis.ticks.length; j++) {
          tick = axis.ticks[j];
          label = tick.label;
          has_tick = !('label_v' in tick);
          v = has_tick ? tick.v : tick.label_v;
          pos = this.dygraph_.toPercentYCoord(v, i);
          if ((pos > 0.0) && (pos <= 1.0)) {
            this.yticks.push({axis: i, pos, label, has_tick});
          }
        }
      }
    };

By looking at the original js file, we can observe that the keys have been removed during compilation. Functions in the original file:
DygraphLayout.prototype._evaluateLineTicks = function () {
  var i, tick, label, pos, v, has_tick;
  this.xticks = [];
  for (i = 0; i < this.xTicks_.length; i++) {
    tick = this.xTicks_[i];
    label = tick.label;
    has_tick = !('label_v' in tick);
    v = has_tick ? tick.v : tick.label_v;
    pos = this.dygraph_.toPercentXCoord(v);
    if (pos >= 0.0 && pos < 1.0) {
      this.xticks.push({ pos: pos, label: label, has_tick: has_tick });
    }
  }

  this.yticks = [];
  for (i = 0; i < this.yAxes_.length; i++) {
    var axis = this.yAxes_[i];
    for (var j = 0; j < axis.ticks.length; j++) {
      tick = axis.ticks[j];
      label = tick.label;
      has_tick = !('label_v' in tick);
      v = has_tick ? tick.v : tick.label_v;
      pos = this.dygraph_.toPercentYCoord(v, i);
      if (pos > 0.0 && pos <= 1.0) {
        this.yticks.push({ axis: i, pos: pos, label: label, has_tick: has_tick });
      }
    }
  }
};

I do not understand why a working library get converted into a non working file. My tsconfig.json file is untouched:
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

Would someone have any clue ?

A: Turns out that, as recommended by jfriend00, the configuration needed to be:
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es5",
      "es6",
      "dom"
    ]
  }
}

What does lib does is not that clear in the documentation, but it seems that it should list the formats from all source codes to be compiled.
As I have DOM, ES5 and ES6 code, I needed all of them. The template I used only contained only DOM/ES6 code, that is probably why the lib was set to DOM/ES2017 only.


text:
Q: onInstall trigger wont run after installing add-on from G Suite Makrketplace I am putting together a simple Google Sheets Add-on for my internal domain. I have been able to install it from GSMP, but the onInstall trigger doesn't work. My document bound google app script works great when testing local to the document.
function onInstall(e) {
  onOpen(e);
}

function onOpen(e) {
  // Adds a text prompt to cells A1 and B1 calling for user to enter the label name to pull from, and the completed label name
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var cellA = sheet.getRange(1, 1);
  cellA.setValue("Add credit folder name to cell A2");
  var cellB = sheet.getRange(1, 2);
  cellB.setValue("Add completed credit folder name to cell B2");
}


text:
Q: Drag bubble in d3js bubblechart I was going through an example of d3js bubblechart .
Here is the link : http://jsfiddle.net/49L6uj7s/
Can someone please explain why 198 is used for calculating euclideanDistance :
var euclideanDistance = Math.sqrt(Math.pow((d.px - 198), 2) + Math.pow((d.py - 198), 2));

A: The euclidean distance that is being calculated in the example is the distance between the middle of the circle you are dragging and the parent container.
Once calculated, it is used to keep the child circle within the parent circle.
A check is made to see if the drag position is outside the parent and if so, it sets the x and y of the dragged object to stay at the edge of the parent:
  function dragmove(d) {
        var euclideanDistance = Math.sqrt(Math.pow((d.px - 198), 2) + Math.pow((d.py - 198), 2));

        if(euclideanDistance > 198 - d.radius){
            d.px = d.px - 198;
            d.py = d.py - 198;

            var radians = Math.atan2(d.py, d.px);

            d.px = Math.cos(radians) * (198 - d.radius) + 198;
            d.py = Math.sin(radians) * (198 - d.radius) + 198;
        }
    }

The parent circle is actually a rectangle thats 400*400px with a 50% border radius, hence the 198 (200 px with a 2px border).


text:
Q: Properly set the view Outlet for a navigation Controller embedded in a tabBar Controller I am making an application which implements the following structure :
MainWindow
  |_ tabBar Controller
        |_ FirstView
        |_ SecondView
        |_ ThirdView
        |_ FourthView
              |_ navigation Controller
                    |_ ViewA
                    |_ ViewB

Following a tutorial, I have the tabBar controller and switch between views (1, 2, 3) working properly, the code I need is executed for each display of those views 1, 2, 3.
Now I want to make it more complex and load a view that is just a Navigation Controller, becasuse my 4th item content is like a Blog (List of articles, when you click on one, it will show the summary)
The code for the navigation controller and 2 views works well in a separate project where the navigation Controller is in the MainWindow nib. Now that I want to move it in the FourthView, I have the following error on execution :
2010-10-03 00:26:45.248 Scaning[1037:307] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "FourthView" nib but the view outlet was not set.'

I understand this is a problem in Interface Builder where I need to associate a view outlet, but I am new at iPhone development and can't figure out why the behaviour is different if the navigation Controller is not on the main window.
Do you know any sample app that implements both tabbar controller and navigation controllers that I could analyze? Otherwise, any advice for that?
Thanks !

A: i found it... Just need to manage this directly in the tabBar Controller where we can choose the Class of each Tab...


text:
Q: How do I add the value of a variable to an array in Java? int [][] arr = new int [1][9];

column 1/2 (arr[0][0-9]), row 1 to 10 is filled with numbers.
I have the following variable that changes its value in each loop in a for loop:
for (int i = 0; i < arr.length; i++){

int value = 1;

Different if statemts are ,depending on the corresponding number within arr, adding +1 /+2 or +5 to the variables value. (already working)
I now want to take each value assigned to the corresponding number in arr and put it in a new array. (That´s where Im stuck)
Here's what I tried:
 int [] arr2 = new int [9];
 calcNumbr(arr2);
 for (int k = 0; k<arr2.length; k++){
 arr2[k] = arr2[value];

Then I want to add every number within that array to get a sum
  int sum = 0;
  sum += t;
  }

A: You can add a value of a variable to an array like this:
int value = 100;
int [] arr2 = new int [9];
int k = 0;
arr2[k] = value;

Your line arr2[k] = arr2[value]; from your sample adds the value from position value to position k.


text:
Q: E/AndroidRuntime(1382): java.lang.RuntimeException: Unable to start activity ComponentInfo I face a problem when start my app and I want to know what is the problem exactly.
I get this in log cat:
09-08 12:40:35.690: W/dalvikvm(1382): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-08 12:40:35.740: E/AndroidRuntime(1382): FATAL EXCEPTION: main
09-08 12:40:35.740: E/AndroidRuntime(1382): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yahya.myfirstapp/com.yahya.myfirstapp.Main}: java.lang.NullPointerException
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.os.Looper.loop(Looper.java:123)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread.main(ActivityThread.java:3683)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at java.lang.reflect.Method.invokeNative(Native Method)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at java.lang.reflect.Method.invoke(Method.java:507)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at dalvik.system.NativeStart.main(Native Method)
09-08 12:40:35.740: E/AndroidRuntime(1382): Caused by: java.lang.NullPointerException
09-08 12:40:35.740: E/AndroidRuntime(1382):     at com.yahya.myfirstapp.Main.onCreate(Main.java:19)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-08 12:40:35.740: E/AndroidRuntime(1382):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-08 12:40:35.740: E/AndroidRuntime(1382):     ... 11 more
09-08 12:40:41.260: I/Process(1382): Sending signal. PID: 1382 SIG: 9

and  this is Main.java
package com.yahya.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {

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

        Button b = (Button) findViewById(android.R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, Second.class));

            }
        });
    }
}

and this Second.java
package com.yahya.myfirstapp;

import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.second);
        }
}

activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/welcome" />

</RelativeLayout>

second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/test_secondactivity" />

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/welcome" />

</LinearLayout>

A: Correct this line:
Button b = (Button) findViewById(android.R.id.button1);

to be:
Button b = (Button) findViewById(R.id.button1);

android.R is used to access built in system resources imbeded in the Android OS and there is no resource called button1

A: Make sure that your class is identified in the androidmanifest.xml


text:
Q: Testing page redirect in rails How can I test this in rails:
A student goes to a list of their groups, and when they click the link, it brings them to that group page.
I have the gist of it down, but how can I test that it went to a page? I was thinking something along the lines of:
expect(page).to eq()

but then I am not sure what to do from there. I don't want to just expect the page to have the name of the group, because that that would be on the overall list and the page the link would bring them to. Any advice?

A: You're looking for the redirect_to() method. So an example would be:
require 'spec_helper'

describe FoobarController do

  describe "GET foo" do
    it "redirects to bar" do
      get :foo
      expect(response).to redirect_to(bar_path)
    end
  end
end


text:
Q: Книги о современном C# Подскажите, какие существуют книги на русском языке по C# 10 (.Net 6) или C# 9 (.Net 5) для относительно начинающего в языке (разобраться), но опыт на других языках имеется (Java). Имеет ли смысл читать старые книги где еще .Net Framework ?
Из последнего нашел:
Язык программирования C# 9 и платформа .NET 5. Основные принципы и практики программирования. 10-е издание
Есть мнение по ней?

A: Есть прекрасная (и единственная на русском языке) книжка по C# 9.0 нашего любимого Албахари:
"Джозеф Албахари: C# 9.0. Справочник. Полное описание языка"

Появилась она совсем недавно, буквально месяца три назад.
По десятому C# - не перевели еще...
Но всё не так уж плохо. Есть ряд отличий в NET Core 6 от NET Core 5, но про них можно прочитать в сконцентрированном виде, потому что платформа уже достаточно разгналась, и регулярная работа по популяризации всего, происходящего "на переднем крае" - ведётся. Другое дело, что "исходниками" будут, конечно же, англоязычные ресурсы.
А по NET Core 5 - можно читать того же Албахари, он пишет весьма хорошо. По моему, опыта в Java достатчоно, чтобы читать по C# буквально что угодно, и "въезжать" достаточно быстро.
Имеет ли смысл читать более ранние книги, например по C# 6.0? Не очень простой вопрос. С одной стороны, 60-70% информации, содержащейся в книге того же Албахари по C# 6.0 (я просто их обе читал, поэтому и говорю на их примере)
абсолютно применимо и к C# 9.0. С другой стороны, если есть более свежая информация - поему бы не воспользоваться сразу ей?
Но я не хочу, чтобы мой ответ выглядел как реклама конкретной книги. Просто с ней я знаком, и о её достоинствах могу говорить.


text:
Q: How can I change check to uncheck on this Checkbox case? Please, help me here... I have a list of checkboxes with "isChecked" value from DB, but I don't know how change this value when I pressed the checkbox. (Ex. If I have one checkbox with isChecked value "false", when I want to press it, the isChecked value needs to change "true"
Thank you!!!

renderServicesContent = section => {
    let taskrendered = [];
    let checked      = false;
    checks = this.state.isChecked;
    updateTasks    = this.state.updateTaks;
    section.default_tasks.map(function(elemen, index) {
      concatService = elemen.description ;
      if (elemen.verified == 1 || elemen.verified == 2) {
        checked = true;
      } else {
        checked = false;
      }
      let disabledCheck = false;
      if(section.status == "4"){
        disabledCheck = true;
      }else{
        disabledCheck = false;
      }
        taskrendered.push(
                <ListItem>
                <CheckBox
                    style = {{flex: 1, padding: 10}}
                    onClick = {() => {this.updateTasks(elemen)}
                    isChecked = {checked}
                    rightText = {concatService}
                    disabled = {disabledCheck}
                />
                </ListItem>
        );
    });

    return (
      <View>
        {taskrendered}
      </View>
    );
}

A: Try with value attribute in Checkbox component.
value={this.state.isChecked}

A: Are you using the CheckBox component from @react-native/community? If so, it contains a prop onValueChanged that could help you solve that problem. For more info you can review their documentation here: https://github.com/react-native-community/react-native-checkbox.
If you're using CheckBox from react-native directly, you should consider switching the the one in @react-native/community, since react-native deprecated theirs (as per their documentation here: https://reactnative.dev/docs/checkbox#__docusaurus).


text:
Q: Error message "module '__main__' has no attribute '__package__'" in Flask just a basic code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def Page():
    return 'This is a test'

app.run(debug=True)

When I run this, I get the message: AttributeError: module '__main__' has no attribute '__package__'
(it all has to do with debug=True)
I know I can start Flask in debug mode by set FLASK_DEBUG=1 in cmd. But the error message annoys me because I have no clue where it comes from and how to solve it :-)
Thx
Peter

A: Try using:app.debug = True
instead or app.config['DEBUG'] = True


text:
Q: Reset Queryable State I'm working on writing a test for my Flink system.  I want to pump data through my topology, query the state, and then reset my test.  Are there any management capabilities for Queryable state such as the ability to reset/delete current state so that I can clear my state between test runs?  I haven't found any in the docs, but I'm hoping I just missed something.  Thanks.

A: Flink's queryable state client only allows you to read the state. The write path is the data flowing in your topology. Thus, there is currently now way to use the queryable state client to write state information.
What you can do is to inject a special event in your stream which is detected by your operator and upon receiving it will clear the state.


text:
Q: Is it possible to make a SVG path block click actions? I'm trying to implement an overlay/highlight tutorial, requirements are that it should be able to highlight several elements at the same time. So I found out that working with SVG Paths worked well to generate a grayed out area and only keep the important highlighted elements on view and able to be clicked.
Now what I'm trying to achieve is to block the user whenever he tries to click on the grayed out area. Already tried pointer-events="unset" inside the path but didn't work.
Here is a screenshot for an easier reference.
Thanks for the help


text:
Q: what is mean -(IBAction) behavior function? hi i'm studying iOS but i have a trouble.
here are four kind of functions..
-(IBAction) behavior : (UIButton *) sender;

-(IBAction) behavior : (id) sender;

-(IBAction) behavior : sender;

-(IBAction) behavior;

i know about top three things. but i don't know about the last function
-(IBAction) behavior;

what is mean? and when i use this?
if i have a button, then i can use this function
but i can't use that. if i have a slider, or picker view.. whatever
it's the only use for button??

A: -(IBAction) behavior:(UIButton *)sender;

This means that you've declared a method called behavior:, and you know that the thing that will be sending you the behavior: message is a UIButton.
-(IBAction) behavior:(id)sender;

This means that you've declared a method called behavior:, but you're not sure what kind of object will be sending you the message, so you're going with a generic "any object" (id).  This method is technically identical to the first one.  The only difference between them is during code compilation, and not at runtime.
-(IBAction) behavior:sender;

This is incorrect and shouldn't compile.
-(IBAction) behavior;

This means that you've declared a method called behavior, and you're ignoring the object that's sending you the message.  This is only valid with the iOS SDK (and possibly the Lion SDK, though I haven't tried it).

A: Say this -(IBAction) behavior will only be called by one GUI component, which means you don't need to determine in -(IBAction) behavior what button get pressed, then you don't need a parameter there.
On the other hand, if you have two GUI component will trigger this very same function, then you want to know which one trigger it, and probably do different things, then you'll need a parameter there.
The first one means this function can be trigger by any object, second one means it's only for UIButton, I think the third one is wrong.


text:
Q: Error using onChange with custom component I have 2 types for my custom component InputComponent using input or textarea with boolean condition isTextArea. onChange gives me error and I cant resolve it. Could you please help? Here the source code:
export interface InputProps
  extends React.DetailedHTMLProps<
    React.InputHTMLAttributes<HTMLInputElement>,
    HTMLInputElement
  > {
  label: string;
  htmlFor?: string;
  subtitle?: string | undefined;
  isTextArea?: boolean;
}

export interface TextAreaProps
  extends React.DetailedHTMLProps<
    React.InputHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  label: string;
  htmlFor?: string;
  subtitle?: string | undefined;
  isTextArea?: boolean;
}

type InputComponentProps = InputProps | TextAreaProps;

export const Input = (props: InputComponentProps) => {
  const { type = "text", isTextArea, name, onChange, ...rest } = props;
  const InputComponent = isTextArea ? `textarea` : `input`;

  return (

{props.label}

      <InputComponent
        className={classNames(styles.input, {
          [styles.inputDescription]: name === "description",
        })}
        onChange={onChange}
        {...rest}
      />
      {props.subtitle && (

{props.subtitle}

      )}

  );
};

export default Input;

using this TypeScript gives me an error onChange:
Type 'ChangeEventHandler | ChangeEventHandler | undefined' is not assignable to type '(ChangeEventHandler & ChangeEventHandler) | undefined'.
Type 'ChangeEventHandler' is not assignable to type 'ChangeEventHandler & ChangeEventHandler'.
Type 'ChangeEventHandler' is not assignable to type 'ChangeEventHandler'.
Type 'HTMLInputElement' is missing the following properties from type 'HTMLTextAreaElement': cols, rows, textLength, wrapts(2322)
index.d.ts(2458, 9): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & ClassAttributes & TextareaHTMLAttributes & ClassAttributes<...> & InputHTMLAttributes<...>'
I don't know why but attribute onChange gives (ChangeEventHandler & ChangeEventHandler) | undefined' instead of props types.


text:
Q: Writing a device driver for Platform Bus in Embedded Systems? I have gone through some driver implementation in Linux Kernel Source and can see that these are the platform driver.
drivers/net/ethernet/smsc/smsc911x.c

  static struct platform_driver smc911x_driver = {
    .probe           = smc911x_drv_probe,
    .remove  = smc911x_drv_remove,
    .suspend         = smc911x_drv_suspend,
    .resume  = smc911x_drv_resume,
    .driver  = {
            .name    = CARDNAME,
            .owner  = THIS_MODULE,
    },
};

Above is a driver for platform device(smsc based Ethernet controller) and platform devices are devices which are not probed automatically during system boot-up unlike legacy devices sitting on the pci bus.
I guess this understanding of mine is OK here?
Now when I say it is the platform devices, is it mean these devices(Ethernet Controller) are sitting on Platform bus and on ARM architecture default platform bus is AMBA.
So when we solder the Ethernet controller on ARM based board it should be sit on or interfaced with AMBA bus?
How Do we decide that driver we're going to write is Platform driver or Normal driver?

A: From my limited experience in developing ARM platform drivers, AMBA devices typically have identification registers at the end of their memory mapped IO register interface.
Generally speaking, if you look at the reference manual for your ethernet controller and register summary specifies peripheral/component identification registers (usually at offsets 0xFE0-0xFEC and 0xFF0-0xFFC), you should write an AMBA bus driver. These drivers can be identified automatically by the bus driver.
Otherwise, if the register interface doesn't specify any ID registers at offsets 0xFE0-0xFEC and 0xFF0-0xFFC, you'll probably just want to write a platform driver. These devices cannot be automatically identified and you need to specifically attach a driver to the device.


text:
Q: How do I use small capitals in the title of a document of class article? I want to use small capitals in the title of my LaTeX document (of class article), which is all capitals by default. The following MWE does not give the expected results (it does nothing):
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,cite,url}
\usepackage{graphicx}
\usepackage{color}
\usepackage[capitalise]{cleveref}

\title{\textsc{Small capitals}: Rest of the title}

\begin{document}
\maketitle
\end{document}

Is this possible?

A: In an comment you  mentioned ismir.sty which I guess comes from here.
In that case you did not tell us that you added \usepackage{ismir} in your code.
Now the culprit is that ismir.sty uses
\def\@maketitle{
  \newpage
  \null
  \begin{center} {
    \Large \bf \uppercase \@title \par % <===============================
  }
  \vskip 2.0em {
    \large \lineskip .5em
    \begin{tabular}[t]{c}
    \@author \\
    \end{tabular}
    \par
  }
  \end{center}
  \par
  \vskip 2.0em
}

An combination of \uppercase and \textsc makes no sense, so only \uppercase is used.
As far as I see you have only two possibilitys:

*

*Use the given template if you want to submit an paper to them without any changings

*if you not have to submit an article to them use another template or simply article to build your document. Then you can use \textsc in the title as shown in your mwe, that does not include package ismir.

Without ismir (commented) the following MWE
\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,cite,url}
%\usepackage{ismir} % <==================================================
\usepackage{graphicx}
\usepackage{color}
\usepackage[capitalise]{cleveref}

\title{\textsc{Small capitals}: Rest of the title}
\author{Author}

\begin{document}
\maketitle
text.
\end{document}

results in:

and with ismir.sty you get:

Please see that that template seems to be very old, it still uses \bf.  You should contact the maintainer to get it updated ...

A: Your MWE works for me. I get
SMALL CAPITALS: Rest of the title

where SMALL CAPITALS is set in small caps (capital S, lower case small caps the rest). I don't understand your problem. GOM


text:
Q: PHP Copy and move to new folder apologies if this is a repeat of an earlier question but I've had a look at php copy and cant quite find an answer for my needs.
I need some php code that copies a file from one folder (this folder is always constant), and pastes it into a relative folder with a new name, for example
$originalfile = Templates/$filename
$newfile = $newpath/$newfilename

can someone please give me a start.  Thanks

A: As mentioned by Juhana you can use copy () function provided by PHP to copy the files from one directory to another
Full reference can be found here
http://php.net/manual/en/function.copy.php
Ex of what you are looking for
$originalfile = 'Templates/'.$filename; //provide absolute path starting from root directory
$newfile = $newpath.'/'.$newfilename;//Note you can also use DIRECTORY_SEPARATOR constant istead of "/"

copy($originalfile, $newfile);

However do NOTE to make sure that you are providing absolute path which is always better if it starts from your /var/www/projname/ directory. If you are using windows and xampp then C://xampp/projname (its an example)
That way it should definitely work.


text:
Q: How to add the rows I want by index I have df1 like this:
  Sample #    Aux
0    1      4 LA LA
1   7500    4 LA
2   15000   4 LA
3   22500   4 L L L
4   30000   4 L
... ... ...
235 1762500 W
236 1770000 W
237 1777500 W
238 1785000 2
239 1792500 2
240 rows × 2 columns

I extract the 'H' labels to have the starting points of the events with the following code:
SAS1 = df1['Aux'].str.contains('H')
print(df1[SAS1])

And I got this:
     Sample #    Aux
12      90000     3 HA
13      97500   3 H LA
36     270000  4 LA HA
46     345000      2 H
49     367500      2 H
163   1222500     2 HA
167   1252500   2 H LA
174   1305000      2 H
179   1342500     2 HA
180   1350000  2 LA HA
181   1357500   2 H LA
185   1387500   2 LA H
187   1402500      2 H
188   1410000      3 H
189   1417500     3 HA
191   1432500   3 L HA
192   1440000   2 H LA
198   1485000   2 L HA
203   1522500  2 LA HA
204   1530000   2 H LA
207   1552500     2 HA
208   1560000    2 H H
211   1582500      2 H
213   1597500     R HA
214   1605000     2 HA
216   1620000      2 H
217   1627500      2 H
218   1635000      2 H
219   1642500      R H
221   1657500     W HA
225   1687500      R H
227   1702500     R HA
230   1725000      R H
231   1732500      R H
232   1740000      R H
233   1747500      R H
234   1755000     R HA

Now I want to extract the starting and ending points simultaneously. For example, the starting point of an event is 36 and the ending point is 37 (i.e. the next one in df1). I want to do it for all of the events to do segmentation for signal data. How can I do it?
The output I want is to add the points with star:
     Sample #      Aux
 12      90000     3 HA
 13      97500   3 H LA
*14     105000
 36     270000  4 LA HA
*37     277500
 46     345000      2 H
*47     352500
 49     367500      2 H
*50     375000

I want a loop that check if the data points exist in SAS, add the next row from df1 into SAS.

A: You could create a new column using the following:
event_nos = []
event_counter = 0

for a in df1['Aux']:
  if "H" in a:
    event_counter += 1

  event_nos.append(event_counter)

df1['Event_Number'] = event_nos

And then use that to segment your data?

A: This could be a possible approach:
import pandas as pd

# This just import the table already filtered by "H"
df = pd.read_csv("gasses.txt", delimiter=r"\s{2,}", engine="python")
df = df.set_index(["Index"])

# This is the logic
data = pd.DataFrame([(x + 1, z + 7500) for x, y, z in zip(df.index[:-1],
df.index[1:], df["Sample #"]) if y != x + 1], columns=("Index", "Sample #"))
data = data.set_index("Index")

df = pd.concat([df, data]).sort_index().fillna("")
print(df)

OUTPUT
       Sample #      Aux
Index
12        90000     3 HA
13        97500   3 H LA
14       105000
36       270000  4 LA HA
37       277500
46       345000      2 H
...
...

Basically, if indeces are not consecutive numbers, it creates a new DataFrame with the previous index + 1 and the previous Sample # + 7500, which is your step.


text:
Q: WPF ExceptionValidationRule not showing in the Validation.Errors Collection I am throwing an ApplicationException if the FirstName value is null or empty and I am trying to display the error message in the TextBlock which is part of the ErrorTemplate. But it always shows "Exception has been thrown at the target of invocation".
public string FirstName
        {
            get { return _firstName;}
            set
            {
                if(String.IsNullOrEmpty(value))
                    throw new ApplicationException("FirstName cannot be null or empty!");
                _firstName = value;

                OnPropertyChanged("FirstName");
            }
        }

<Style x:Key="TextBoxStyle" TargetType="TextBox">

            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <TextBlock DockPanel.Dock="Right"
                        Foreground="Orange"
                        FontSize="12pt"
                        Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                            </TextBlock>
                            <Border BorderBrush="Green" BorderThickness="1">
                                <AdornedElementPlaceholder Name="MyAdorner" />
                            </Border>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

        </Style>

And finally here is the TextBox control:
<TextBox Name="txtFirstName" Style="{StaticResource TextBoxStyle}" Grid.Column="1"  Grid.Row="0" Height="20" Width="100" Margin="10">
                <TextBox.Text>
                    <Binding Path="FirstName">
                        <Binding.ValidationRules>
                            <ExceptionValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>

            </TextBox>

A: I went through this the other day, I ended up taking the exception off the property and using a validation class.
<TextBox Name="txtFirstName" Style="{StaticResource TextBoxStyle}" Grid.Column="1"  Grid.Row="0" Height="20" Width="100" Margin="10">
        <TextBox.Text>
            <Binding Path="FirstName" >
                <Binding.ValidationRules>
                    <validators:StringRangeValidationRule
                                    MinimumLength="1"
                                    MaximumLength="40"
                                    ErrorMessage="Required" />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>

Remove the exception from your property so it just looks like this ...
private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;

            OnPropertyChanged("FirstName");
        }
    }

Heres the validation class (I poached this off the internet somewhere) ...
public class StringRangeValidationRule : ValidationRule
{
    private int _minimumLength = -1;
    private int _maximumLength = -1;
    private string _errorMessage;

    public int MinimumLength
    {
        get { return _minimumLength; }
        set { _minimumLength = value; }
    }

    public int MaximumLength
    {
        get { return _maximumLength; }
        set { _maximumLength = value; }
    }

    public string ErrorMessage
    {
        get { return _errorMessage; }
        set { _errorMessage = value; }
    }

    public override ValidationResult Validate(object value,
        CultureInfo cultureInfo)
    {
        ValidationResult result = new ValidationResult(true, null);
        string inputString = (value ?? string.Empty).ToString();
        if (inputString.Length < this.MinimumLength ||
               (this.MaximumLength > 0 &&
                inputString.Length > this.MaximumLength))
        {
            result = new ValidationResult(false, this.ErrorMessage);
        }
        return result;
    }
}

You'll need to add a namespace reference in your xaml to where the validation class lives called validators (i'm sure you know this but just for completeness)
Something like ...
xmlns:validators="clr-namespace:WpfApplication1"

Hope this helps!
Cheers,
Andy

A: Again, I went through exactly the same thing this week!  I found the following on the web, wrap your text boxes in this ...
<validators:ValidatedContent Name="Validator" >

<!-- All your textboxes here -->

</validators:ValidatedContent>

Add the class below in the same place you put the other one ... and then you can call Validator.Validate() from a button click or where ever you want.  There is also an IsContentValid property you can use to decide whether you want to save etc.
public class ValidatedContent : Decorator
{

    #region Public Constructors

    /// <summary>
    /// Initializes a new instance of ValidatedContent
    /// </summary>
    public ValidatedContent()
    {
        ErrorMessages = new ObservableCollection<string>();

        Loaded += new RoutedEventHandler(OnValidatedContentLoaded);
    }

    #endregion

    #region Event Handlers

    /// <summary>
    /// Handles the loaded event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnValidatedContentLoaded(object sender, RoutedEventArgs e)
    {
        Queue<DependencyObject> elementQueue = new Queue<DependencyObject>();
        elementQueue.Enqueue(this.Child);

        // Iterate over all the child elements
        while (elementQueue.Count > 0)
        {
            // Dequeue the first element in the queue
            DependencyObject element = elementQueue.Dequeue();

            if (element != null)
            {
                foreach (var childElement in LogicalTreeHelper.GetChildren(element))
                {
                    if (childElement is DependencyObject)
                        elementQueue.Enqueue((DependencyObject)childElement);
                }
            }

            Control control = element as Control;

            // Mark the element as valid if it is a control
            if (control != null && GetIsRequired(element))
            {
                control.SetValue(Control.StyleProperty, RequiredControlStyle);
            }
        }

    }

    #endregion

    #region Dependency Properties

    public static readonly DependencyProperty IsContentValidProperty =
        DependencyProperty.Register("IsContentValid", typeof(bool),
        typeof(ValidatedContent), new UIPropertyMetadata(false));

    public static readonly DependencyProperty ErrorMessagesProperty =
        DependencyProperty.Register("ErrorMessages", typeof(ObservableCollection<string>),
        typeof(ValidatedContent), new UIPropertyMetadata(null));

    public static readonly DependencyProperty RequiredControlStyleProperty =
        DependencyProperty.Register("RequiredControlStyle", typeof(Style),
        typeof(ValidatedContent), new UIPropertyMetadata(null));

    public static readonly DependencyProperty IsRequiredProperty =
        DependencyProperty.RegisterAttached("IsRequired", typeof(bool),
        typeof(ValidatedContent), new UIPropertyMetadata(false));

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets or sets the style to mark a required control
    /// </summary>
    public Style RequiredControlStyle
    {
        get { return (Style)GetValue(RequiredControlStyleProperty); }
        set { SetValue(RequiredControlStyleProperty, value); }
    }

    /// <summary>
    /// Gets or sets the error messages for the validated content
    /// </summary>
    public ObservableCollection<string> ErrorMessages
    {
        get { return (ObservableCollection<string>)GetValue(ErrorMessagesProperty); }
        private set { SetValue(ErrorMessagesProperty, value); }
    }

    /// <summary>
    /// Gets if the content is valid
    /// </summary>
    public bool IsContentValid
    {
        get { return (bool)GetValue(IsContentValidProperty); }
        private set { SetValue(IsContentValidProperty, value); }
    }

    #endregion

    #region Public Methods

    /// <summary>
    /// Validates the content of the decorator
    /// </summary>
    public void Validate()
    {
        IsContentValid = true;
        ErrorMessages.Clear();

        Queue<DependencyObject> elementQueue = new Queue<DependencyObject>();
        elementQueue.Enqueue(this.Child);

        // Iterate over all the child elements
        while (elementQueue.Count > 0)
        {
            // Dequeue the first element in the queue
            DependencyObject element = elementQueue.Dequeue();

            foreach (var childElement in LogicalTreeHelper.GetChildren(element))
            {
                if (childElement is DependencyObject)
                    elementQueue.Enqueue((DependencyObject)childElement);
            }

            // Validate the bindings of the element
            ValidateBindings(element);
        }
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Validates the bindings of the dependency object
    /// </summary>
    /// <param name="element"></param>
    private void ValidateBindings(DependencyObject element)
    {
        if (element != null)
        {
            Type elementType = element.GetType();

            FieldInfo[] dependencyPropertyFields = elementType.GetFields(
                BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly);

            // Iterate over all dependency properties
            foreach (FieldInfo dependencyPropertyField in dependencyPropertyFields)
            {
                DependencyProperty dependencyProperty =
                    dependencyPropertyField.GetValue(element) as DependencyProperty;

                if (dependencyProperty != null)
                {
                    Binding binding = BindingOperations.GetBinding(element, dependencyProperty);
                    BindingExpression bindingExpression = BindingOperations.GetBindingExpression(element, dependencyProperty);

                    // Issue 1822 - Extra check added to prevent null reference exceptions
                    if (binding != null && bindingExpression != null)
                    {
                        // Validate the validation rules of the binding
                        foreach (ValidationRule rule in binding.ValidationRules)
                        {
                            ValidationResult result = rule.Validate(element.GetValue(dependencyProperty),
                                CultureInfo.CurrentCulture);

                            bindingExpression.UpdateSource();

                            if (!result.IsValid)
                            {
                                ErrorMessages.Add(result.ErrorContent.ToString());
                            }

                            IsContentValid &= result.IsValid;
                        }
                    }
                }
            }
        }
    }

    #endregion

    #region Static Methods

    /// <summary>
    /// Gets the value for the IsRequired attached property
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static bool GetIsRequired(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsRequiredProperty);
    }

    /// <summary>
    /// Sets the value for the IsRequired attached property
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="value"></param>
    public static void SetIsRequired(DependencyObject obj, bool value)
    {
        obj.SetValue(IsRequiredProperty, value);
    }

    #endregion
}

A: I had some issues with this too so I am posting my workaround in case it would help someone.
The message shown in the Text block in not the correct one because the Exception that is triggered in the code is wrapped up into a TargetInvocationException. So the error message displayed is the one of that exception which is "Exception has been thrown at the target of invocation".
The exception you want to display is actually accessible in the InnerException of the TargetInvocationException and you can therefore display it message using the following statement in your XAML
 Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent.InnerException.Message}"

I am pretty sure there must be a way that the error contained in the ErrorContent field is the correct one but I have not digged enough to understand how.


text:
Q: Find hyperbolic area of hyperbolic triangle Given $u=(0,0)$, $v=(\frac12,0)$, $w=(\frac12,\frac12)$. Find the hyperbolic area of the hyperbolic triangle $[u,v,w]$ in $\mathbb{H}^2$.
My approach:
One of the angles, say $\alpha$, is a right angle, so we have that $\alpha=\frac{\pi}2$, so that $[u,v,w]$ is a right triangle. Now, this triangle is also isosceles, so two of its sides, say $b$ and $c$, are equal.
Now, $$b=c=\cosh^{-1}\left(\frac53\right)$$
Also, the other side, say $a$, is determined as follows:
$$a=\cosh^{-1}\left(\frac73\right)$$
Now, we get
$$\frac73 = \cosh b=\frac{\cos\beta}{\sin\alpha}=\cot\beta$$
$$\implies \beta = \cot^{-1}\left(\frac73\right)=\alpha$$
$$\implies A=\frac{\pi}2-2\cot^{-1}\left(\frac73\right)$$
I'd appreciate if someone would let me know whether or not my reasoning is correct in this solution.

A: The area of a hyperbolic triangle is equal to the angle deficit, i.e. to the difference between the hyperbolic sum of interior angles and the Euclidean sum of $\pi$.
Poincaré half plane
Draw the triangle, and it will look like this:

This triangle has two ideal points. I'm not sure I'd call it isosceles, since two legs have infinite length, but you might as well. It has two angles of $0$ and one of $\frac\pi2$, so the sum is $\frac\pi2$, which is $\frac\pi2$ less than the Euclidean sum of a triangle. Thus the area is $\frac\pi2\approx1.5708$.
Poincaré disk
Draw the triangle, and it will look like this:

No right angle here, nor is it obviously isosceles. The segment $vw$ belongs to a circle with center at $\left(\frac54,\frac14\right)$. You can verify that by checking that inverting $v$ or $w$ results in a point on that circle, too. You can use that to compute the lines connecting that center to $v$ resp. $w$, then have the tangents in these points orthogonal to that, and finally compute the angle between tangent and the line to the origin. Sum the angles, subtract it from $\pi$ and you have the area $\pi-2\arctan3\approx0.6435$.


text:
Q: jquery variables, functions and the wrap tag (beginner) Issues 1:
$('#msg').html($('#quote').text());

now changed quote for a variable - quotevar:
$("#msg").html(quotevar);

How would I incorporate the text function there to get the same result I did with #quote? I can't even seem to understand how to properly handle variables and functions in jquery.
Issue 2:
I need to add [quote] [/quote] bbode tags around my variable quotevar. This is actually the reason I created the variable in issue 1.
If it's possible to do it without the new var using this:
$('#msg').html($('#quote').text()); then I'd like to know how that is done also.
I assume the wrap() function is needed to add the tags.

A: if I understand you correctly, are you just wanting to do this?
var quotevar = "<quote>" + $('#quote').text() + "</quote>";

or using wrap()
var quotevar = $('#quote').text().wrap("<quote />");
$('#msg').html(quotevar);


text:
Q: run shell command in compute engine from java app engine I'm trying to figure out if it's possible to run a shell command in a compute engine instance from java app engine
I couldn't find a clean and good solution to do that so, at the moment what I'm doing is to update our database from our app engine, to run an app into the compute engine instance that check the database and in case there are some changes, run the shell command in the compute engine instance directly from the app that is checking the db and running inside the compute engine instance
I think that is not the best solution but it's the only one that I could find.
The best solution should be just send the command to run from our app engine to the compute engine instance, but I'm not sure if there is a way to do that
Any tip?
Regards!

A: The best way to instance processes on a GCE instance from GAE would be to use either pull queues or sub/pub
There is no way to directly start a shell command on GCE for GAE instances since that would be different systems/servers.


text:
Q: R, ImageMagick: How to add delay after each loop in animation I have created a .gif animation from a series of .png images using the following code:
gif <- function(name, imgDir, format, fps, delete) {

  require(magick)
  require(gtools)

  imgs <- mixedsort(list.files(path = imgDir, pattern = paste("*.", format, sep = "")))
  image <- image_read(paste(imgDir, "/", imgs, sep = ""))
  animation <- image_animate(image, fps = fps)
  image_write(animation, paste(name, ".gif", sep = ""))

  if (delete) unlink(paste(imgDir, "/*", sep = ""))

}

gif("animation", "tmp", "png", 10, TRUE)

The animated .gif repeats continuously. I want to add a delay of x seconds after each loop. Is there a parameter for image_animate() or something for the purpose?

A: Use the index of individual frames from the .gif to construct a new .gif with a "pause". You create the effect of pausing by repeating the same frame.  Use rep() to replicate the "pause" frame N number of times to control length of the pause.
From your example, if you want to linger on the last frame of the gif, you would want something like this:
gif <- function(name, imgDir, format, fps, delete) {
  require(magick)
  require(gtools)
  imgs <- mixedsort(list.files(path = imgDir, pattern = paste("*.", format, sep = "")))
  image <- image_read(paste(imgDir, "/", imgs, sep = ""))
  animation <- image_animate(image, fps = fps)
  #Pause on the last frame for 1 second
  #Use c() to combine image frames from one or more magick gif objects
  gif_with_pause<-c(animation, rep(animation[length(animation)],10))
  image_write(gif_with_pause, paste(name, ".gif", sep = ""))
}
gif("animation_with_pause", "tmp", "png", 10, TRUE)

For anyone else interested in making a .gif as an image gallery, you might want to check out magick::image_morph() which can add nice transitions between images. It's also possible to extend time an individual frame appears. You can also make the GIF smoothly loop by combining your gif with a 2nd gif (showing the last frame smoothly transitioning to the first frame). Let me provide a working example of a two image gif slideshow that smoothly loops and also pauses on each image:
library(magick)
library(dplyr)
#read in some images
i1<-image_read("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Ghostscript_Tiger.svg/512px-Ghostscript_Tiger.svg.png")
i2<-image_read("https://jeroen.github.io/images/frink.png")

#make a gif image
initial_gif<-image_resize(c(i1, i2), '200x200!') %>%
  image_background('white') %>%
  image_morph( frames = 10) %>%
  image_animate(optimize = TRUE, fps = 10)

#make another gif with the last image moving to the first image
last_img_to_1st_gif<-image_resize(c(i2,i1), '200x200!') %>%
  image_background('white') %>%
  image_morph( frames = 10) %>%
  image_animate(optimize = TRUE, fps = 10)

#use rep() to linger on the first image, cycle the gif, linger on the second image,
#then show a transition back to the first image.
new_gif<-c(rep(initial_gif[1],10),
             initial_gif,
             rep(initial_gif[length(initial_gif)],10),
             last_img_to_1st_gif)

Here is the result:


text:
Q: AWALL - Alpine firewall, rule that accept traffic from certain IP I need a rule that permits a specific traffic from determinate IP. I tried this, but it doesn't work.
{
  "src": ["$FDFARM", "$FARM"],
  "in": "internet",
  "out": "_fw",
  "service": "APIDOCKER",
  "action": "accept",
  "conn-limit": { "count": 3, "interval": 60 }
}

Any idea?


text:
Q: SQL Server DB Mail attachment from App Service Folder I have a web app running in Azure and one of its requirement is to send e-mail from SQL Server's DB Mail; however the attachments are stored in App Service environment.
My question is how can access the attachment in App Service folder?
My Setup:

*

*Web App on Azure App Services

*SQL Server PAAS model

*NO VMs used
In App Service Editor, I have an URL for each file like
https://xxxxx.scm.azurewebsites.net/dev/wwwroot/uploads/test.pdf;

Can I use this URL? Or is there anyway I can use?

A: As hiFI said, Database mail feature is not supported in Azure SQL Database.
If possible, please send email in your web app code behind (when you do operations on your database in your code) and use https://{your app name}.azurewebsites.net/uploads/test.pdf that would be accessible.
Besides, you could store the pdf files in Azure Blob storage and provide the URL to the pdf file, and a SAS could be used to grant limited access to objects in storage account.


text:
Q: Replacing 'add to cart' with a font icon I would like to replace my 'add to cart' as well as my 'view details' button texts for (font) icons. Does anyone know a best practice way to do this?
Thanks in advance!

A: Yes I do. Edit your theme (or create a new one by copying the default theme for example) and put an <img/> tag where the 'add to cart' text was.

credits to @7ochem
This in the correct place in the right file will do the trick. You'll have to find that on your own though.

<button><i>-icon-character-</i> Add to cart</button>


text:
Q: Check if static function is available in class at compile time I am currently wiring an application that has several implementations for a single purpose. It is checked at runtime if the appropriate implementation can be used or if a fallback is used.
For that purpose I want all implementations to implement a static function static bool is_available().
As static functions cannot be made abstract in the underlying base class, is there some preprocessor magic that will allow me to output an error message if the method is not statically implemented in the child class?

A: In the same vein that user9400869's answer, you can define a trait using SFINAE to check, at compilation time, the availability of your classes:
#include <type_traits>

template<class LIB, class = void>
struct is_available
: std::false_type
{};

template<class LIB>
struct is_available<LIB, std::enable_if_t<std::is_invocable_r<bool, decltype(LIB::is_available)>::value>>
: std::integral_constant<bool, LIB::is_available()>
{};

template<class LIB>
constexpr bool is_available_v = is_available<LIB>::value;

This implies C++17 and constexpr functions is_available for the libs:
#include <iostream>

struct A {};
struct B { static constexpr bool is_available() { return false; } };
struct C { static constexpr bool is_available() { return true; } };

int main()
{
    std::cout << is_available_v<A> // 0
              << is_available_v<B> // 0
              << is_available_v<C> // 1 :)
              << '\n';
}

Full demo

If C++17 is not an option, you can implement std::is_invocable_r using C++14 features only.
If constexpr static member functions are not an option for your library classes, you cannot rely on std::true_type and std::false_type and must use run-time result gathering:
#include <type_traits>

template<class LIB, class = void>
struct is_available
{
    static bool value() { return false; }
};

template<class LIB>
struct is_available<LIB, std::enable_if_t<std::is_invocable_r<bool, decltype(LIB::is_available)>::value>>
{
    static bool value() { return LIB::is_available(); }
};

Full demo

A: you could test this at compiletime with templates.
It goes something like this (sorry not tested):
template<class Type_to_test, class Technical_Detail = void>
struct has_isAvilable : std::false_type {}

template<class Type_to_test>
struct has_isAvilable<Type_to_test, std::enable_if_t<
  std::is_same<bool,decltype(Type_to_test::is_available())>::value
> > : std::true_type {}

Then you can use somewhere in your code:
static_assert(has_isAvilable<Implementation>::value,"Usefull error message");

Where Implementation is the class you wish to test.
Have a look at std::type_traits for examples of this.

A: I would suggest an alternative: tag dispatching:
template <typename T> struct Tag {};

struct Base { /**/ };
struct Child1 : Base { /**/ };
struct Child2 : Base { /**/ };

bool is_available(Tag<Base>) {/*..*/}
bool is_available(Tag<Child1>) {/*..*/}
bool is_available(Tag<Child2>) {/*..*/}

Tag "blocks" Inheritance, contrary to:
struct Base { static constexpr bool is_available() { return false; } };
struct Child1 : Base { static constexpr bool is_available() { return true; } };
struct Child2 : Base { /**/ };

static_assert(Base::is_available() == false);
static_assert(Child1::is_available() == true);
static_assert(Child2::is_available() == false); // Call Base::is_available()


text:
Q: How can I deal with my released app's crashes in main.m? I used Bugly(a tool same as Crashlytics) to recored crashes in my app which had released.But sometimes there are some crashes in main.m as the report showed:
With these information I can't location problem in my code at all.I need to know which class and which method the problem occured so I can location this problem.
I wonder is there any way I can location problem more precise?And how do you deal with these crashes in your released app?
Wish you can share,thanks a lot.

A: Finally I find this is memory leak result.Use Xcode instrument check is a good way.


text:
Q: How do I turn a proc print result of eigenvectors into a SAS data table I want to sort my table of eigenvectors into ascending order. In order to do that I  think need to turn my table of eigenvectors into a SAS data table. How do I do that? Below is part of the code I used to created my eigenvectors.
proc princomp data = test;
ID$ name$ DOB$ Job_Title$ Salary$
{DATA IS INSERTED HERE}
run;

A: Use the outstat= option in your proc princomp statement:
OUTSTAT= Option

OUTSTAT=SAS-data-set
creates an output SAS data set that contains means, standard deviations, number of observations, correlations or covariances, eigenvalues, and eigenvectors. If you specify the COV option, the data set is TYPE=COV or TYPE=UCOV, depending on the NOINT option, and it contains covariances; otherwise, the data set is TYPE=CORR or TYPE=UCORR, depending on the NOINT option, and it contains correlations. If you specify the PARTIAL statement, the OUTSTAT= data set contains R squares as well.


text:
Q: Sextante grass folder incorrect? What is the correct grass folder in Sextante?
I always get this message:

The specified GRASS folder does not contain a valid set of GRASS
modules. Please, go to the SEXTANTE settings dialog, and check that
the GRASS folder is correctly configured

This is the current sextante grass folder. I did not change anything after the Osgeo4W installation. I guess that the path isn't correct.

A: Make sure that you configure the GRASS folder for the sextante plugin.
If you click Analysis --> SEXTANTE options and configuration you can define the paths to your GRASS installation.
My path is: C:\PROGRA~2\Quantum GIS Lisboa\apps\grass\grass-6.4.2
I´m using Sextante 1.0.9 for QGIS, which comes with its own GRASS installation


text:
Q: Huawei Tool Converter Cannot Resolve Symbol 'xms' I'm using the HMS Toolkit- Converter to add HMS API to my app automatically. After it converts import com.google.android.gms.analytics.HitBuilders; into import org.xms.g.analytics.HitBuilders; it tells me that Cannot Resolve Symbole 'xms'. I also tried going to HMS repository and add the Analytics Kit then hit Apply but it gives me an error HMS Analytics Kit  applyplugin dependence added failed:/Users.....
How can I resolve the issue on 'xms' during the conversion? (I used Add HMS API conversion policy.)

A: Is Cannot Resolve Symbol 'xms' displayed when you use the Add HMS API(HMS API First) or Add HMS API(GMS API First) function?
If so, check whether the following method could solve your problem:

*

*Check whether your HMS Core Toolkit is the latest version. If not, download the latest one.

*After obtaining the latest version of HMS Core Toolkit, try again to generate the XMS code.

*If the steps above do not work, try to use Sync Project With Gradle File.

A: Did you try add the HMS toolkit to your application from android studio. I think you can solve the issue with it.
https://developer.huawei.com/consumer/en/doc/development/Tools-Guides/95569931

A: How to open a file with the suffix "XMS"?
Do you have to use  software?
The memory located after 1MB  called extended memory.
Generally, programs cannot directly use extended memory.
The usage of extended memory is supported by XMS (extended memory specification), so the extended memory is sometimes referred to as XMS.
Before using extended memory, you should add the command of HIMEM.SYS in the CONFIG.SYS firstly.
Here is the link about what is XMS.
Here is the link reffering to the extended memory of Huawei mobile phone.


text:
Q: Trouble with navbar and scroll jQuery I need help, my navbar is transparent background, so when I do scroll > 540px the navbar turns black, but when the scrolling is > 540px and updated the page the navbar becomes transparent until I make a minimum scroll, how can I fix the problem?
$(window).on('scroll', function() {
    if ($(this).scrollTop() > 540) {
        $('.sec').addClass('navbar-index-scroll animated fadeInDown').removeClass('fadeOutUp');
    } else {
        $('.sec').removeClass('fadeInDown').addClass('fadeOutUp');
    }
});

A: When you navigate the website, say using refresh or history (Back/Forward) buttons, the old scroll state can be remembered by the browser.
To compensate for the page being already scrolled you can:
// 1. Create a function to handle the navbar states/styles

function navbarScrollposStyles() {
    if($(window).scrollTop() > 540) {
        $('.sec').addClass('navbar-index-scroll animated fadeInDown').removeClass('fadeOutUp');
    } else {
        $('.sec').removeClass('fadeInDown').addClass('fadeOutUp');
    }
}

$(navbarScrollposStyles);                           // 2. Do on DOM ready and
$(window).on('load scroll', navbarScrollposStyles); // 3. on window.onload and onscroll

P.S: in your specific code I cannot make sense of the classes navbar-index-scroll animated not being handled properly in the else block, …but that's another pair of shoes.
Additionally it's really expensive to query the document on every scroll "tick" (event) for some .sec elements. You should cache your selectors into a variable like var $sec = $(".sec"); -
also you could prevent such event from being fired too much times and degrade performance - by using some Throttle function.


text:
Q: Java Persistance Application Stateless vs. Stateful I am new in JPA and I can't understand the use and the difference between stateless and stateful.
Any experiences?
regards,
Haythem

A: Stateless and Stateful are EJB Session Bean concept, not of JPA.
Nota bene: JPA is part of EJB specification, but can be used separately and outside of an EJB container. This is what usually causes the confusion.
Edited: A useful SO thread, Why Use Stateful Session Beans.

A: "Stateful" and "Stateless" are attributes for session beans.
A session bean (in brief) provides a way to call methods on an application server. The bean is an instance of a java class. Usually, a bean is destroyed after the remote method terminates (and returns a result). Those bean are "stateless".
It is possible (but rather unusual) to add fields and attributes to the bean so that a client can "create" this instance on the server and use it for more then one operation. Those beans are "stateful" (and should be avoided).

A: Stateful and Stateless are properties of EJB's (Java EE container managed session Beans), rather than anything specific to the JPA spec. A Stateful bean will have state associated with it for each request from the same client. Stateless beans have no client specific state and a single instance could be used concurrently, threadsafe, between multiple clients requests.
JPA is one persistence strategy that can be used to persist stateful beans (I'm guessing you could  also use JDBC directly, or plugin some other persistence strategy).

A: I think part of the confusion is that Java Persistence API is part of the EJB3 spec and sometimes seems to be used interchangeably with EJB.  I didn't really understand this until I first picked up Pro EJB 3: Java Persistence API. Take a look at http://en.wikipedia.org/wiki/Enterprise_JavaBean it seems to provide a good overview on the subject.

A: Basically, as you know, Java compiles things and then you see the app during runtime if everything went well after the class loader things and avoiding execution stage errors and all that, when you are storing variables, objects and so on in any place like RAM or Databases and these data can change when user interact with your application, then you developed a statefull application, if you believe there's nothing be dynamic in your code logic( things that can reshape a behavior of your application) then you are about to develop a stateless application.
In short, statefull application means dynamic change in your class properties during runtime.


text:
Q: firefox updates I bought a laptop with preinstalled ubuntu 18.04.4; the firefox version also preinstalled is 72.01 but when running updates these are not allowed.
Can anyone suggest whether I should uninstall it and then install the most recent firefox version or not bother since it seems to be working ok apart from being slower than chrome?
thanks


text:
Q: How To Obtain An Annotation Of A Function Literal At Runtime package _z_additional

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.reflect.KFunction
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.jvm.reflect

/*https://stackoverflow.com/questions/63439469/how-to-obtain-an-annotation-of-a-function-literal-at-runtime*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
object _13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test {

    @Target(AnnotationTarget.FUNCTION)
    private annotation class A

    //@formatter:off
    @A private fun f1() {}
    private val f2: () -> Unit = @A {}
    private val f3: () -> Unit = @A fun() {}
    //@formatter:on

    @Test
    fun demonstrate_usingReflect() {
        listOf(::f1, f2.reflect(), f3.reflect()).filterNotNull().withIndex().forEach { (index, f) ->
            println("[$index] Function name = ${f.name}")
            println("[$index] Annotations = ${f.annotations.joinToString()}")
            println()
        }
    }

    @Test
    fun demonstrate_usingClass() {
        listOf(f2::class, f3::class).withIndex().forEach { (index, cls) ->
            val invokeFunction: KFunction<*> = cls.declaredMemberFunctions.first {it.name == "invoke" && it.isOperator}
            println("[$index] Function name = ${invokeFunction.name}")
            println("[$index] Annotations = ${invokeFunction.annotations.joinToString()}")
            println()
        }
    }

}

demonstrate_usingReflect Output

[0] Function name = f1
[0] Annotations = @_z_additional._13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test$A()
[1] Function name =
[1] Annotations =
[2] Function name =
[2] Annotations =

demonstrate_usingClass Error Output

java.lang.UnsupportedOperationException: This class is an internal synthetic class generated by the Kotlin compiler, such as an anonymous class for a lambda, a SAM wrapper, a callable reference, etc. It's not a Kotlin class or interface, so the reflection library has no idea what declarations does it have. Please use Java reflection to inspect this class: class _z_additional._13_Reflection_ObtainingAnnotationOfAFunctionLiteral_Test$f2$1


text:
Q: unhandled Exception C# I have a C# project which is an exe file (console app) and some dlls and one dll ist written in C++. On Winodws 10 it runs fine and on a Win 7 too. But on a Win 7 and Win2008 Server on a Virtual Maschine I get an unhandled exception. In the main function I have already added
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

But unfortunately the exception must be thrown before the main function is called. How can I catch this exception?
I have installed .net 4.6.1 and I compared the installed packages between Win 10 and Win 7 on real PCs with the installed packages on the virutal maschines and I fine no different.
Thats what I can see in the event log:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Application Error" />
<EventID Qualifiers="0">1000</EventID>
<Level>2</Level>
<Task>100</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2020-08-14T10:03:41.000000000Z" />
<EventRecordID>5060</EventRecordID>
<Channel>Application</Channel>
<Computer>PC-dummy</Computer>
<Security />
</System>
<EventData>
<Data>MyApp.exe</Data>
<Data>1.6.1.1</Data>
<Data>5f365f53</Data>
<Data>KERNELBASE.dll</Data>
<Data>6.1.7601.24511</Data>
<Data>5d3fa9ff</Data>
<Data>e0434352</Data>
<Data>000000000000b87d</Data>
<Data>658</Data>
<Data>01d67222300b6618</Data>
<Data>D:\MyProject\MyApp.exe</Data>
<Data>C:\Windows\system32\KERNELBASE.dll</Data>
<Data>6dbcb3b9-de15-11ea-b17f-000c29a2a32b</Data>
</EventData>
</Event>

and
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name=".NET Runtime" />
<EventID Qualifiers="0">1026</EventID>
<Level>2</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2020-08-14T10:03:41.000000000Z" />
<EventRecordID>5059</EventRecordID>
<Channel>Application</Channel>
<Computer>PC-dummy</Computer>
<Security />
</System>
<EventData>
<Data>Application: MyApp.exe Framework Version: v4.0.30319 Description: The  process was terminated due to an unhandled exception. Exception Info: System.IO.FileNotFoundException at MyConsole.Program.Main(System.String[])</Data>
</EventData>
</Event>


text:
Q: Splat.Locator Multiple views for one ViewModel I use the following code
 Splat.Locator.Current.GetService(...)

to get view for view model. But this method allows to use only one view for one view model. But I have to show 1 data (view model) in multiple views. Is it possible by Splat.Locator?

A: The Register() and GetService() have a contract argument, which you can use as a key to get the implementation you need.
Example, where "giveMeBar"/"giveMeBaz" are values for the contract argument:
using System;
using Splat;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main()
        {
            // Register
            Locator.CurrentMutable.Register(() => new Bar(), typeof(IFoo), "giveMeBar");
            Locator.CurrentMutable.Register(() => new Baz(), typeof(IFoo), "giveMeBaz");

            // Resolve
            var bar = Locator.Current.GetService<IFoo>("giveMeBar");
            var baz = Locator.Current.GetService<IFoo>("giveMeBaz");

            // Which types did we get?
            Console.WriteLine(bar);
            Console.WriteLine(baz);
            Console.ReadLine();

            // Outputs:
            // ConsoleApp1.Bar
            // ConsoleApp1.Baz
        }
    }

    internal interface IFoo { }
    internal class Bar : IFoo { }
    internal class Baz : IFoo { }
}

A: I don't think this is possible because Locator will get confused when you navigate using ViewModel first so it will always instantiate latest view your associated with ViewModel. My suggestion maybe you create that ViewModel as base class and create another ViewModel which inherit that ViewModel and then assign it in Splat.Locator like usual


text:
Q: Finder tags not saved for downloaded files When I save a file and add tags to it in the save dialog box, these tags are not added to the file. This happens in all browsers I have tried (Safari, Firefox, Chrome). Tags do appear to get added to files when they are created locally in an application. This just seems to be an issue when downloading a file. This seems to happen with any file that is downloaded to any folder on my Mac.
I have searched everywhere and only found this thread on discussions.apple.com from 2017. It is focused only on a similar issue with Microsoft Office that Apple claimed was not their fault, and that was fixed when upgrading to a newer version of Office.
Any help/advice is greatly appreciated, this issue has disrupted a lot of automation I have set up for sorting files.
Thanks!
Edit: I am running macOS Mojave 10.14.6 on a Early 2014 MacBook Air, 1.4GHz i5, 4GB RAM and 120GB SSD.
Edit #2: I just tested this again after clearing my Finder cache and restarting Finder. Firefox and Safari still delete tags assigned on download, but Chrome works. Any idea why this might be the case and what I can do to fix it?


text:
Q: Which one is the more efficient way of use an array's size? (Kotlin) I have to iterate through a whole array and filter something specific using it's size and i started to think that the second approach might save some processing power and memory. Any thoughts on which one is better and why?
1st Approach
override fun functionA(query: String) {
        Items = startItems.filter { entity ->
            entity.functionB(query)
        }
    }

entity class
override fun functionB(query: String): Boolean {
        queryWords = query.splitWords()
        var words = queryWords.size
        queryWords.doSomething()
        return words == 0
    }

2nd Approach
override fun functionA(query: String) {
        val queryWords = query.splitWords()
        val querySize = queryWords.size
        Items = startItems.filter { entity ->
            entity.functionB(queryWords, querySize)
        }
    }

entity class
override fun functionB(queryWords: List<String>, size: Int): Boolean {
        var words = size
        queryWords.doSomething()
        return words == 0
    }

My first tought was that i might save a couple operations(CPU wise) by calling it at the top and passing queryWord and size as parameters(2nd Approach) instead of obtaining them every time(The array of startItems will get bigger with time, at the moment it has >180 objects)


text:
Q: how to access multidimensional array input in C++ mex file I have written my program in c++ and needed to write a c++mex function to pass input parameter and retrieve some output values in matlab. but i have been facing some issues accessing my multidimensional array. here follows a piece of what i have written and the error message.
w was declare as follows:
double **W;

W[i][j];

for  (int i=0;i < 6; i++)
{
    for (int j=0;j<6;j++)
    {
        //B[j + 6*i] = W[i][j];
        B[j + 6*i] = W[i + 6*j];
    }
}

and when compiling i get the following error message:
cannot convert 'double*' to 'double' in assignment

A: Your 2-D array represented as double** W needs to have space allocated. First you need to allocate each row. The code below illustrates this:
#include <iostream>

using namespace std;

int main() {

int rows = 6, cols = 6;
double **W;

W = new double* [rows];

// allocate each row
for (int i = 0; i < rows; i++) {
    W[i] = new double [cols];
}

for (int i = 0; i < 6; i++) {
    for (int j = 0; j<6; j++) {
        // do work here
    }
}

// clean up in the end:
if (W != nullptr) {
    for (int i = 0; i < rows; i++) {
        delete[] W[i];
    }
    delete[] W;
    W = nullptr;
}

return 0;
}

A: The following code is wrong:
double **W;

W[i][j];

Either declare W as:
double W[i][j];

Or read: How do I declare a 2d array in C++ using new.
Your 2D array accessing syntax
B[j + 6*i] = W[i + 6*j];

is wrong too.
Are you trying to do this?
B[j][6*i] = W[i][6*j];// if B is 2D array

Or
B[j + 6*i] = W[i][6*j];// if B is 1D array


text: Q: Chromatic aberration in human eye A lens focuses the different colours of white light at different points. Since our eye has a convex lens there should also be such an aberration but we see objects clearly with normal eye. I want to know how eye is able to correct this aberration?