问:
How can I restore the "default" button style
I have a save button, and when the user mouses over it, I change some styles - for example:

```<code>$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});
</code>```

When the mouse leaves the button, I would like to restore the original:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});
</code>```

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

答: Your best bed is to create a CSS class for the styles you are adding on the mouseover and add it with jQuery using "addClass".  Then you can just remove your temporary style using "removeClass".</p>

Body:
I have a save button, and when the user mouses over it, I change some styles - for example:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

When the mouse leaves the button, I would like to restore the original:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?


来源: stackexchange

问:
load a local file to spark using sc.textFile()

Question

How to load a file from the local file system to Spark using sc.textFile? Do I need to change any -env variables? Also when I tried the same on my windows where  Hadoop is not installed I got the same error.

Code

```<code>> val inputFile = sc.textFile("file///C:/Users/swaapnika/Desktop/to do list")
/17 22:28:18 INFO MemoryStore: ensureFreeSpace(63280) called with curMem=0, maxMem=278019440
/17 22:28:18 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 61.8 KB, free 265.1 MB)
/17 22:28:18 INFO MemoryStore: ensureFreeSpace(19750) called with curMem=63280, maxMem=278019440
/17 22:28:18 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 19.3 KB, free 265.1 MB)
/17 22:28:18 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:53659 (size: 19.3 KB, free: 265.1 MB)
/17 22:28:18 INFO SparkContext: Created broadcast 0 from textFile at <console>:21
File: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[1] at textFile at <console>:21

> val words = input.flatMap(line => line.split(" "))
ole>:19: error: not found: value input
  val words = input.flatMap(line => line.split(" "))
              ^

> val words = inputFile.flatMap(line => line.split(" "))
: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[2] at flatMap at <console>:23

> val counts = words.map(word => (word, 1)).reduceByKey{case (x, y) => x + y}
</code>```

Error

```<code>apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/c:/spark-1.4.1-bin-hadoop2.6/bin/file/C:/Users/swaapnika/Desktop/to do list
   at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:285)
   at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
   at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
   at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:207)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.Partitioner$.defaultPartitioner(Partitioner.scala:65)
   at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290)
   at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290)
   at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:147)
   at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:108)
   at org.apache.spark.rdd.RDD.withScope(RDD.scala:286)
   at org.apache.spark.rdd.PairRDDFunctions.reduceByKey(PairRDDFunctions.scala:289)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:25)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:30)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:32)
   at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:34)
   at $iwC$$iwC$$iwC$$iwC.<init>(<console>:36)
   at $iwC$$iwC$$iwC.<init>(<console>:38)
   at $iwC$$iwC.<init>(<console>:40)
   at $iwC.<init>(<console>:42)
   at <init>(<console>:44)
   at .<init>(<console>:48)
   at .<clinit>(<console>)
   at .<init>(<console>:7)
   at .<clinit>(<console>)
   at $print(<console>)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
   at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1338)
   at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
   at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
   at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
   at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
   at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
   at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
   at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:657)
   at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:665)
   at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$loop(SparkILoop.scala:670)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:997)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
   at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
   at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
   at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
   at org.apache.spark.repl.Main$.main(Main.scala:31)
   at org.apache.spark.repl.Main.main(Main.scala)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at

org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
   at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
   at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
   at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
   at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

>
</code>```

答:
This error happens when you run spark in a cluster. When you submit a job to spark cluster the cluster manager(YARN or Mesos or any) will submit it to worker node. When the worker node trying to find the path of the file we need to load into spark it fails because the worker doesn't have such file. So try running spark-shell in local mode and try again,

\bin\spark-shell --master local

sc.textFile("file:///C:/Users/swaapnika/Desktop/to do list")

let me know if this helps.

ContentLicense: CC BY-SA 3.0

Body:
Question

How to load a file from the local file system to Spark using sc.textFile? Do I need to change any -env variables? Also when I tried the same on my windows where  Hadoop is not installed I got the same error.

Code

> val inputFile = sc.textFile("file///C:/Users/swaapnika/Desktop/to do list")
/17 22:28:18 INFO MemoryStore: ensureFreeSpace(63280) called with curMem=0, maxMem=278019440
/17 22:28:18 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 61.8 KB, free 265.1 MB)
/17 22:28:18 INFO MemoryStore: ensureFreeSpace(19750) called with curMem=63280, maxMem=278019440
/17 22:28:18 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 19.3 KB, free 265.1 MB)
/17 22:28:18 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:53659 (size: 19.3 KB, free: 265.1 MB)
/17 22:28:18 INFO SparkContext: Created broadcast 0 from textFile at <console>:21
File: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[1] at textFile at <console>:21

> val words = input.flatMap(line => line.split(" "))
ole>:19: error: not found: value input
  val words = input.flatMap(line => line.split(" "))
              ^

> val words = inputFile.flatMap(line => line.split(" "))
: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[2] at flatMap at <console>:23

> val counts = words.map(word => (word, 1)).reduceByKey{case (x, y) => x + y}

Error

apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/c:/spark-1.4.1-bin-hadoop2.6/bin/file/C:/Users/swaapnika/Desktop/to do list
   at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:285)
   at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
   at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
   at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:207)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
   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.Partitioner$.defaultPartitioner(Partitioner.scala:65)
   at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290)
   at org.apache.spark.rdd.PairRDDFunctions$$anonfun$reduceByKey$3.apply(PairRDDFunctions.scala:290)
   at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:147)
   at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:108)
   at org.apache.spark.rdd.RDD.withScope(RDD.scala:286)
   at org.apache.spark.rdd.PairRDDFunctions.reduceByKey(PairRDDFunctions.scala:289)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:25)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:30)
   at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:32)
   at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:34)
   at $iwC$$iwC$$iwC$$iwC.<init>(<console>:36)
   at $iwC$$iwC$$iwC.<init>(<console>:38)
   at $iwC$$iwC.<init>(<console>:40)
   at $iwC.<init>(<console>:42)
   at <init>(<console>:44)
   at .<init>(<console>:48)
   at .<clinit>(<console>)
   at .<init>(<console>:7)
   at .<clinit>(<console>)
   at $print(<console>)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
   at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1338)
   at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
   at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
   at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
   at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
   at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
   at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
   at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:657)
   at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:665)
   at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$loop(SparkILoop.scala:670)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:997)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
   at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
   at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
   at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
   at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
   at org.apache.spark.repl.Main$.main(Main.scala:31)
   at org.apache.spark.repl.Main.main(Main.scala)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at

org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
   at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
   at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
   at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
   at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

>


问:
*ngif - Hide div if something becomes visible
ngif is confusing me!

I want to hide an image which is there when the page is empty, but when it becomes populated I want to hide it. I don't really know how to do this without doing it on a button.

So I have

```<code><ion-content padding>
    <template ngFor let-api [ngForOf]="shoppingList">
        <ion-card>
            <ion-card-header>
                {{api?.name}}
            </ion-card-header>
            <ion-list inset>
                <ion-item *ngFor="let ingredient of api.ingredientLines">
                    <ion-label>{{ ingredient }}</ion-label>
                    <ion-checkbox item-right></ion-checkbox>
                </ion-item>
            </ion-list>
            <button ion-button block full color="danger" (click)="clear(api)">Remove</button>
        </ion-card>
    </template>

    <div class="text">
        <img class="shopping-icon" src="assets/icon/shopping-list.svg">
        <p>This is your shopping list, add recipes and shop away!</p>
    </div>
</ion-content>
</code>```

I want to say, when there is content in the template or ion-card to hide the text div at the bottom. If someone could help me out that would be great.

答:
Assuming your content is stored in shoppingList, then you could do:

```<code><img *ngIf="shoppingList.length" class="shopping-icon" src="assets/icon/shopping-list.svg">
</code>```

Body:
ngif is confusing me!

I want to hide an image which is there when the page is empty, but when it becomes populated I want to hide it. I don't really know how to do this without doing it on a button.

So I have

<ion-content padding>
    <template ngFor let-api [ngForOf]="shoppingList">
        <ion-card>
            <ion-card-header>
                {{api?.name}}
            </ion-card-header>
            <ion-list inset>
                <ion-item *ngFor="let ingredient of api.ingredientLines">
                    <ion-label>{{ ingredient }}</ion-label>
                    <ion-checkbox item-right></ion-checkbox>
                </ion-item>
            </ion-list>
            <button ion-button block full color="danger" (click)="clear(api)">Remove</button>
        </ion-card>
    </template>

This is your shopping list, add recipes and shop away!

</ion-content>

I want to say, when there is content in the template or ion-card to hide the text div at the bottom. If someone could help me out that would be great.

Body:
Assuming your content is stored in shoppingList, then you could do:

<img *ngIf="shoppingList.length" class="shopping-icon" src="assets/icon/shopping-list.svg">


问:
iPhone - Hide Address Bar on Page Load
I have a web page that is intended to be loaded on a person's iPhone. When the page is loaded, I want to hide the status and address bar that is at the top. I have seen other sites do this. In an attempt to accomplish this, I have placed the following code in the  section of my web page:

```<code><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;" />
<script type="text/javascript">
  function page_Load() {
    setTimeout(function() { window.scrollTo(0, 1); }, 100);
  }
</script>
</code>```

The "page_Load" function is triggered through the onload event of the page's body element. Oddly, when the page loads, the status/title bar is hidden, however, not the address bar.

How do I hide both the status/title bar and the address bar when a web page loads?

Thank you!

答: This page explains more up-to-date status of 'fullscreen'.</p>

ContentLicense: CC BY-SA 2.5

Title: iPhone - Hide Address Bar on Page Load

Body:
I have a web page that is intended to be loaded on a person's iPhone. When the page is loaded, I want to hide the status and address bar that is at the top. I have seen other sites do this. In an attempt to accomplish this, I have placed the following code in the  section of my web page:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;" />

The "page_Load" function is triggered through the onload event of the page's body element. Oddly, when the page loads, the status/title bar is hidden, however, not the address bar.

How do I hide both the status/title bar and the address bar when a web page loads?

Thank you!


答:
Probably as simple as

If your shoppingList is empty it hasn't been populated by the API yet so the image will be shown and no ion-cards will be shown since there aren't any available.

You could also use a property in your controller:

```<code>loading = true;

/* snip */

this.shoppingList.push(item);
loading = false;
</code>```

Then you can use *ngIf=loading and have more explicit control over when you show this input or not.

Title: *ngif - Hide div if something becomes visible

Body:
Probably as simple as <div class="text" *ngIf="!shoppingList.length">

If your shoppingList is empty it hasn't been populated by the API yet so the image will be shown and no ion-cards will be shown since there aren't any available.

You could also use a property in your controller:

loading = true;

/* snip */

this.shoppingList.push(item);
loading = false;

Then you can use *ngIf=loading and have more explicit control over when you show this input or not.


问:
Delete all rows from a table, throws nullpointer
I'm trying to write a function that will delete every row in a given table but I'm getting a null pointer exception. Could somebody point me in the right direction? Here is the code...</p>

```<code>   public void deleteall(){
    SQLiteDatabase db = tweets.getWritableDatabase();
    String delete = "TRUNCATE FROM tweets";
    db.rawQuery(delete, null);

      }
</code>```

答:
The right answer is this:

```<code>db.delete('tweets',"1",null);
</code>```

From Android official documentation: SQLiteDatabase

Body:
I'm trying to write a function that will delete every row in a given table but I'm getting a null pointer exception. Could somebody point me in the right direction? Here is the code...

   public void deleteall(){
    SQLiteDatabase db = tweets.getWritableDatabase();
    String delete = "TRUNCATE FROM tweets";
    db.rawQuery(delete, null);

      }

Body:
The right answer is this:

db.delete('tweets',"1",null);

From Android official documentation: SQLiteDatabase


问:
How can I apply href and data-toggle to an element except one of its child elements?
I want to make a link and data-toggle for all elements inside tr except for .jill. How can I remove the link and data-toggle only for this specific child?

 $(".jill").removeAttr('data-toggle');
 $(".jill").removeAttr("href");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="width:100%">
  <tr href="#" data-toggle="control-sidebar">
    <td class="jill">Jill</td>
    <td>Smith</td>
    <td>50</td>
     <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table></code>```

The way I do it it is not working

答:
You should set href and data-toggle attributes to each td, and then you can remove this attributes only for one element.

```<code><table style="width:100%">
  <tr>
    <td href="href-test" data-toggle="test-data-toggle" class="jill" >Jill</td>
    <td href="href-test" data-toggle="test-data-toggle">Smith</td>
    <td href="href-test" data-toggle="test-data-toggle">50</td>
    <td href="href-test" data-toggle="test-data-toggle">Eve</td>
    <td href="href-test" data-toggle="test-data-toggle">Jackson</td>
    <td href="href-test" data-toggle="test-data-toggle">94</td>
  </tr>
</table>
<a class="remove">Remove</a>

$(document).ready(function() {
$(".remove").on("click", function() {
    $(".jill").removeAttr('data-toggle');
    $(".jill").removeAttr("href");
});
});
</code>```

Please check jsfiddle for live demo.

Body:
I want to make a link and data-toggle for all elements inside tr except for .jill. How can I remove the link and data-toggle only for this specific child?

 $(".jill").removeAttr('data-toggle');
 $(".jill").removeAttr("href");

    Jill
    Smith
    50
     Eve
    Jackson
    94

The way I do it it is not working

Body:
You should set href and data-toggle attributes to each td, and then you can remove this attributes only for one element.

<table style="width:100%">
  <tr>
    <td href="href-test" data-toggle="test-data-toggle" class="jill" >Jill</td>
    <td href="href-test" data-toggle="test-data-toggle">Smith</td>
    <td href="href-test" data-toggle="test-data-toggle">50</td>
    <td href="href-test" data-toggle="test-data-toggle">Eve</td>
    <td href="href-test" data-toggle="test-data-toggle">Jackson</td>
    <td href="href-test" data-toggle="test-data-toggle">94</td>
  </tr>
</table>
<a class="remove">Remove</a>

$(document).ready(function() {
$(".remove").on("click", function() {
    $(".jill").removeAttr('data-toggle');
    $(".jill").removeAttr("href");
});
});

Please check jsfiddle for live demo.


答:
You can try like this.</p>

```<code> <div class="text" *ngIf="shoppingList.length">
        <img class="shopping-icon" src="assets/icon/shopping-list.svg">
        <p>This is your shopping list, add recipes and shop away!</p>
    </div>
</code>```

Body:
You can try like this.

 <div class="text" *ngIf="shoppingList.length">
        <img class="shopping-icon" src="assets/icon/shopping-list.svg">
        <p>This is your shopping list, add recipes and shop away!</p>
    </div>


问:
C++ behaviour when const
Here's a basic struct (I hope)

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};
</code>```

And source

```<code>SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
</code>```

The I have a class

```<code>struct SomeClass {
    static const SomeType v;

    SomeClass();
};
</code>```

When I then initialise it

```<code>const SomeType SomeClass::v(0,0,0,0);
</code>```

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

答:
Another guy told you were the problem is (static initialization order fiasco). I'll provide you with one solution. You need to get rid of the constructor, so the type will become a POD

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;
};
</code>```

Then you need to initialize it with a braced initializer list that only contains constant expressions (this is not limited to only integral constant expressions)

```<code>const SomeType SomeClass::v = { 0, 0, 0, 0 };
</code>```

Alternatively, but only in the case of zeros, you can leave off the explicit values and just use empty braces

```<code>const SomeType SomeClass::v = { };
</code>```

In such cases, C++ guarantees you that the values are initialized before any of your code that tries to read it runs.

Title: C++ behaviour when const

Body:
Here's a basic struct (I hope)

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};

And source

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

The I have a class

struct SomeClass {
    static const SomeType v;

    SomeClass();
};

When I then initialise it

const SomeType SomeClass::v(0,0,0,0);

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

Body:
Another guy told you were the problem is (static initialization order fiasco). I'll provide you with one solution. You need to get rid of the constructor, so the type will become a POD

struct SomeType {
    float a;
    float b;
    float c;
    float d;
};

Then you need to initialize it with a braced initializer list that only contains constant expressions (this is not limited to only integral constant expressions)

const SomeType SomeClass::v = { 0, 0, 0, 0 };

Alternatively, but only in the case of zeros, you can leave off the explicit values and just use empty braces

const SomeType SomeClass::v = { };

In such cases, C++ guarantees you that the values are initialized before any of your code that tries to read it runs.


问:
Fetching connection string from appconfig file in c#
I have the following connection string declared in my app.config file:

```<code>  <connectionStrings>
    <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

When I try to fetch this connection string using the following C# code snippet, I get the value null. I am not able to obtain the connection string. Is there anything wrong in the syntax?

First attempt:

```<code>var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;
</code>```

Second attempt:

```<code>string result = ConfigurationSettings.AppSettings["SqlConnectionString"];
</code>```

答:
I am doing this to get my connect string "OracleDbContext"...

```<code>ConfigurationManager.ConnectionStrings["OracleDbContext"].ConnectionString;
</code>```

my web.config looks like:

```<code>  <connectionStrings>
    <add name="OracleDbContext"
         providerName="Oracle.ManagedDataAccess.Client"
         connectionString="User Id=oracle_user;
                           Password=oracle_user_password;
                           Data Source=oracle" />
  </connectionStrings>
</code>```

Body:
I have the following connection string declared in my app.config file:

  <connectionStrings>
    <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
  </connectionStrings>

When I try to fetch this connection string using the following C# code snippet, I get the value null. I am not able to obtain the connection string. Is there anything wrong in the syntax?

First attempt:

var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;

Second attempt:

string result = ConfigurationSettings.AppSettings["SqlConnectionString"];

Body:
I am doing this to get my connect string "OracleDbContext"...

ConfigurationManager.ConnectionStrings["OracleDbContext"].ConnectionString;

my web.config looks like:

  <connectionStrings>
    <add name="OracleDbContext"
         providerName="Oracle.ManagedDataAccess.Client"
         connectionString="User Id=oracle_user;
                           Password=oracle_user_password;
                           Data Source=oracle" />
  </connectionStrings>


问:
PHPUnit cannot mock __get function on mock object
I am trying to mock a mysqli object for my unit testing and therefore I have to either mock the property mysqli_result::__get() or mock the property mysqli_result::num_rows directly.
I already looked for a solution but the answers I found were just not working.

My Code looks like this:

```<code>use PHPUnit\Framework\TestCase;

class Mocks extends TestCase{
    public function makeMysqliMock(array $queries): mysqli{
        // build mocked mysqli-object
        #$link = $this
        #   ->getMockBuilder("mysqli")
        #   // set methods
        #   ->setMethods(['__get', "query", "real_escape_string"])
        #   ->getMock();
        $link = $this->createMock("mysqli");
        // set method 'real_escape_string'
        $link->expects($this->any())
            ->method("real_escape_string")
            ->will($this->returnCallback(function($str){
                return addslashes($str);
            }));
        // set method 'query'
        $link->expects($this->any())
            ->method("query")
            ->will($this->returnCallback(function(string $query) use ($queries){
                // pick the query result for the current test
                $data = isset($queries[$query]) ? $queries[$query] : null;
                // build mocked 'mysqli_result'
                if (is_array($data)){
                    $result = $this
                        ->getMockBuilder("mysqli_result")
                        ->setMethods(["fetch_assoc", "__get"])
                        ->disableOriginalConstructor()
                        ->getMock();
                    // build simulated fetch method
                    $result->expects($this->any())
                        ->method("fetch_assoc")
                        ->withAnyParameters()
                        ->will($this->returnCallback(function() use ($data){
                            // set internal result pointer
                            static $index = 0;
                            // return current result - increment pointer
                            return isset($data[$index]) ? $data[$index++] : false;
                        }));
                    $result->expects($this->at(0))
                        ->method("__get")
                        ->with($this->equalTo("mysqli_num_rows"))
                        ->will($this->returnValue(count($data)));

                    return $result;
                }else {
                    return is_null($data) ? false : 1;
                }
            }));
        return $link;
    }
}
</code>```

When I run that code phpunit gives me the following error message:

C:\xampp\htdocs\werimanage\php>php phpunit-6.0.11.phar tests
  PHPUnit 6.0.11 by Sebastian Bergmann and contributors.

PHP Fatal error:  Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

Fatal error: Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

So I do not know what the error is or how to fix it. I would really appreciate your help. Thanks!

答:
according to the php documentation the method __get requires 1 argument (more over this is the error phpUnit is returning).

You can see on the documentation :

public mixed __get ( string $name )

The $name argument is the name of
  the property being interacted with.

I imagine that you will be calling the __get method foreach of your column in your sql request. You then have to mock all the calls and the returns of the __get method with each argument (each column).

Hope this will help you.

Body:
I am trying to mock a mysqli object for my unit testing and therefore I have to either mock the property mysqli_result::__get() or mock the property mysqli_result::num_rows directly.
I already looked for a solution but the answers I found were just not working.

My Code looks like this:

use PHPUnit\Framework\TestCase;

class Mocks extends TestCase{
    public function makeMysqliMock(array $queries): mysqli{
        // build mocked mysqli-object
        #$link = $this
        #   ->getMockBuilder("mysqli")
        #   // set methods
        #   ->setMethods(['__get', "query", "real_escape_string"])
        #   ->getMock();
        $link = $this->createMock("mysqli");
        // set method 'real_escape_string'
        $link->expects($this->any())
            ->method("real_escape_string")
            ->will($this->returnCallback(function($str){
                return addslashes($str);
            }));
        // set method 'query'
        $link->expects($this->any())
            ->method("query")
            ->will($this->returnCallback(function(string $query) use ($queries){
                // pick the query result for the current test
                $data = isset($queries[$query]) ? $queries[$query] : null;
                // build mocked 'mysqli_result'
                if (is_array($data)){
                    $result = $this
                        ->getMockBuilder("mysqli_result")
                        ->setMethods(["fetch_assoc", "__get"])
                        ->disableOriginalConstructor()
                        ->getMock();
                    // build simulated fetch method
                    $result->expects($this->any())
                        ->method("fetch_assoc")
                        ->withAnyParameters()
                        ->will($this->returnCallback(function() use ($data){
                            // set internal result pointer
                            static $index = 0;
                            // return current result - increment pointer
                            return isset($data[$index]) ? $data[$index++] : false;
                        }));
                    $result->expects($this->at(0))
                        ->method("__get")
                        ->with($this->equalTo("mysqli_num_rows"))
                        ->will($this->returnValue(count($data)));

                    return $result;
                }else {
                    return is_null($data) ? false : 1;
                }
            }));
        return $link;
    }
}

When I run that code phpunit gives me the following error message:

C:\xampp\htdocs\werimanage\php>php phpunit-6.0.11.phar tests
  PHPUnit 6.0.11 by Sebastian Bergmann and contributors.

PHP Fatal error:  Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

Fatal error: Method Mock_mysqli_result_d3aa5482::__get() must take exactly 1 argument in phar://C:/xampp/htdocs/werimanage/php/phpunit-6.0.11.phar/phpunit-mock-objects/Generator.php(263) : eval()'d code on line 53

So I do not know what the error is or how to fix it. I would really appreciate your help. Thanks!


问:
Add the number gotten from a db
I collected data from a database and the data is based upon user id, ie I select data from database table based on a user id. Now the selected result has some value (numbers); how do I check if that total sum of the number is equal to a certain amount?

Using Laravel 5.4, I query my db as follows:

```<code> $money = $DBTable::where('id', Auth::user()->id)->get();
</code>```

Now I have a column called cash how do I get the total sum of the cash column?
What is the code for that since the result is an object I do a foreach loop

```<code> foreach ($money as $key => $value) {
     count($money->cash);
 }
</code>```

this will return the number count of the value:

```<code> foreach ($money as $key => $value) {
     echo $earn->earned_amount + $earn->earned_amount;
 }
</code>```

This will add up individual values to themselves, so please can anyone tell me how this is done?

答:
There are two ways to do this:

The Query builder way (https://laravel.com/docs/5.4/queries#aggregates)

DB::table('table name')->where('user_id', Auth::user()->id) ->sum('cash');

The eloquent way (https://laravel.com/docs/5.4/collections#method-sum)

Auth::user()->cashTransactions->pluck('cash')->sum('price');

I assumed you table $DBTable has a model attached to it and that you have a relationship defined between the table's model and the user model

To define  relationship you do:

in User model:

```<code>public function cashTransactions()
{
     return $this->hasMany('App\CashTransactions');
}
</code>```

in CashTransactions model:

```<code>public function user()
    {
         return $this->belongsTo('App\User');
    }
</code>```

Edit: you can also define relationships in a model with the same model (self relationship)

Title: Add the number gotten from a db

Body:
I collected data from a database and the data is based upon user id, ie I select data from database table based on a user id. Now the selected result has some value (numbers); how do I check if that total sum of the number is equal to a certain amount?

Using Laravel 5.4, I query my db as follows:

 $money = $DBTable::where('id', Auth::user()->id)->get();

Now I have a column called cash how do I get the total sum of the cash column?
What is the code for that since the result is an object I do a foreach loop

 foreach ($money as $key => $value) {
     count($money->cash);
 }

this will return the number count of the value:

 foreach ($money as $key => $value) {
     echo $earn->earned_amount + $earn->earned_amount;
 }

This will add up individual values to themselves, so please can anyone tell me how this is done?

Body:
There are two ways to do this:

The Query builder way (https://laravel.com/docs/5.4/queries#aggregates)

DB::table('table name')->where('user_id', Auth::user()->id) ->sum('cash');

The eloquent way (https://laravel.com/docs/5.4/collections#method-sum)

Auth::user()->cashTransactions->pluck('cash')->sum('price');

I assumed you table $DBTable has a model attached to it and that you have a relationship defined between the table's model and the user model

To define  relationship you do:

in User model:

public function cashTransactions()
{
     return $this->hasMany('App\CashTransactions');
}

in CashTransactions model:

public function user()
    {
         return $this->belongsTo('App\User');
    }

Edit: you can also define relationships in a model with the same model (self relationship)


问:
Android converting stream to byte array Out of Memory Exceptions
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?</p>

```<code>public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}
</code>```

答:
See if IOUtils can help you out here.

Import it

```<code>import org.apache.commons.io.IOUtils;
</code>```

Then try:

```<code>public byte[] convertStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    return baos.toByteArray();
}
</code>```

Body:
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?

public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}

Body:
See if IOUtils can help you out here.

Import it

import org.apache.commons.io.IOUtils;

Then try:

public byte[] convertStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    return baos.toByteArray();
}


问:
websocket protocol not supported trough Apache2 reverse proxy
We've set up a reverse proxy with Apache2, to hide the port in the URL and in later stages secure our connection with SSL.

We're running a Hawkbit Java container on AWS ECR. We normally go to the service's webpage by entering

```<code>ip:port/UI
</code>```

Our internship mentor wants to enter ip/UI to go to the webpage. We've set up a Apache2 reverse proxy and are able to go to the webpage with ip/UI.

However, when we log in as admin, we're not permitted to do anything. We've checked the traffic by using F12 on Firefox and we get a 501 error when trying to establish a websocket.

We're also using an application ELB on AWS.
We've tried to add the following to our conf file:

```<code>ProxyPass         /UI  ws://ip:port/UI
ProxyPassReverse  /UI  ws://ip:port/UI
</code>```

but with no effect.

答:
Have a look at THIS --> mod_proxy_wstunnel

[...]
This module requires the service of mod_proxy. It provides support for the tunnelling of web socket connections to a backend websockets server. The connection is automatically upgraded to a websocket connection:
HTTP Response

```<code>Upgrade: WebSocket
Connection: Upgrade
</code>```

Proxying requests to a websockets server like echo.websocket.org can be done using the ProxyPass directive:

```<code>ProxyPass "/ws2/"  "ws://echo.websocket.org/"
ProxyPass "/wss2/" "wss://echo.websocket.org/"
</code>```

Body:
We've set up a reverse proxy with Apache2, to hide the port in the URL and in later stages secure our connection with SSL.

We're running a Hawkbit Java container on AWS ECR. We normally go to the service's webpage by entering

ip:port/UI

Our internship mentor wants to enter ip/UI to go to the webpage. We've set up a Apache2 reverse proxy and are able to go to the webpage with ip/UI.

However, when we log in as admin, we're not permitted to do anything. We've checked the traffic by using F12 on Firefox and we get a 501 error when trying to establish a websocket.

We're also using an application ELB on AWS.
We've tried to add the following to our conf file:

ProxyPass         /UI  ws://ip:port/UI
ProxyPassReverse  /UI  ws://ip:port/UI

but with no effect.

Body:
Have a look at THIS --> mod_proxy_wstunnel

[...]
This module requires the service of mod_proxy. It provides support for the tunnelling of web socket connections to a backend websockets server. The connection is automatically upgraded to a websocket connection:
HTTP Response

Upgrade: WebSocket
Connection: Upgrade

Proxying requests to a websockets server like echo.websocket.org can be done using the ProxyPass directive:

ProxyPass "/ws2/"  "ws://echo.websocket.org/"
ProxyPass "/wss2/" "wss://echo.websocket.org/"


问:
Drawing multiple horizontal lines with the same value on ordinal scale in d3.js
I have an array that looks like this:

```<code>[
   {
      "name": "Omayeli Arenyeka",
      "positions":[
         {
            "start": 1993,
            "end": 2002,
            "title":"Senator of Abia"
         },
         {
            "start": 1993,
            "end": 2002,
            "title":"President"
         }
      ]
   },
   {
      "name": "John Cena",
      "positions":[
         {
            "start": 1993,
            "end": 2002,
            "title":"Senator of Abia"
         },
         {
            "start": 2004,
            "end": 2007,
            "title":"President"
         }
      ]
   }
];
</code>```

For each name on the y-axis I want to draw for each item in the positions array, a horizontal line across the x-axis (so for Omayeli Arenyeka a line that starts from 1993 and then ends at 2002 and then another line starting from 2003-2007) I don't want the lines to be connected.

This is what I currently have:

```<code>var parseDate = d3.time.format("%Y").parse;
var maxyear = new Date("2017");
var minyear = new Date("1980");

var xScale = d3.time.scale()
 .domain([minyear, maxyear])
 .range([padding, width - padding]);

var yScale = d3.scale.ordinal()
 .range([height - padding, padding]);   // map these to the chart  height, less padding.
//REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

// define the y axis
var yAxis = d3.svg.axis()
 .orient("left")
 .scale(yScale);

// define the y axis
var xAxis = d3.svg.axis()
 .orient("bottom")
 .scale(xScale)
 .tickFormat(d3.time.format("%Y")); // <-- format

 d3.json("data/politicians.json", function(error, data) {
  if (error) throw error;

  yScale.domain(data.map(function(d) {
   console.log(d.name);
   return d.name;
  })).rangeRoundBands([0, height - padding]);

 // draw x axis with labels and move to the bottom of the chart area
 vis.append("g")
   .attr("class", "xaxis")   // give it a class so it can be used to select only xaxis labels  below
   .attr("transform", "translate(0," + (height - padding) + ")")
   .call(xAxis);

// draw y axis with labels and move in from the size by the amount of padding
vis.append("g")
  .attr("class", "yaxis")
  .attr("transform", "translate(" + padding + ",0)")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", -36)
  .attr("x", -36)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Politicians");

var line = {
  'x1':(function(d) {
    return xScale();
  }),
  'y1':(function(d) { return yScale(d.name); }),
  'x2':(function(d) {
    return xScale();
  }),
  'y2':(function(d) { return yScale(d.name); }),
}
</code>```

});

答:
The most important thing in D3 is binding the data to the elements. There are a lot of references for you regarding this.

In short, you need an "enter" selection.

Here I'll set two enter selections: one that creates <g> elements for each politician, and another that, for each politician, creates <line> elements for each position:

```<code>var groups = vis.selectAll("foo")
    .data(data)
    .enter()
    .append("g")
    .attr("transform", function(d) {
        return "translate(0," + (padding[2] + yScale(d.name)) + ")";
    });

var people = groups.selectAll("foo")
    .data(d => d.positions)
    .enter()
    .append("line");
</code>```

So, we append the lines using d.name, d.start and d.end. Here is the demo:

var data = [{
  "name": "Omayeli Arenyeka",
  "positions": [{
    "start": 1993,
    "end": 2002,
    "title": "Senator of Abia"
  }, {
    "start": 1993,
    "end": 2002,
    "title": "President"
  }]
}, {
  "name": "John Cena",
  "positions": [{
    "start": 1993,
    "end": 2002,
    "title": "Senator of Abia"
  }, {
    "start": 2004,
    "end": 2007,
    "title": "President"
  }]
}];

var width = 500,
  height = 200,
  padding = [10, 10, 30, 130];

var color = d3.scale.category10();

var vis = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var parseDate = d3.time.format("%Y").parse;
var maxyear = new Date("2017");
var minyear = new Date("1980");

var xScale = d3.time.scale()
  .domain([minyear, maxyear])
  .range([padding[3], width - padding[1]]);

var yScale = d3.scale.ordinal()
  .rangePoints([height - padding[2], padding[0]], 1.5)
  .domain(data.map(function(d) {
    return d.name;
  })); // map these to the chart  height, less padding.
//REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

// define the y axis
var yAxis = d3.svg.axis()
  .orient("left")
  .scale(yScale);

// define the y axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .scale(xScale)
  .tickFormat(d3.time.format("%Y")); // <-- format

// draw x axis with labels and move to the bottom of the chart area
vis.append("g")
  .attr("class", "xaxis") // give it a class so it can be used to select only xaxis labels  below
  .attr("transform", "translate(0," + (height - padding[2]) + ")")
  .call(xAxis);

// draw y axis with labels and move in from the size by the amount of padding
vis.append("g")
  .attr("class", "yaxis")
  .attr("transform", "translate(" + padding[3] + ",0)")
  .call(yAxis);

var groups = vis.selectAll("foo")
  .data(data)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(0," + (yScale(d.name)) + ")";
  })
  .style("stroke", (d, i) => color(i));

var people = groups.selectAll("foo")
  .data(d => d.positions)
  .enter()
  .append("line");

var line = people.attr({
  'x1': function(d) {
    return xScale(parseDate(d.start.toString()));
  },
  'x2': function(d) {
    return xScale(parseDate(d.end.toString()));
  }
}).attr("stroke-width", 2);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.xaxis line, .yaxis line,
.xaxis path, .yaxis path {
  fill: none;
  stroke: black;
}</code>```

```

Body:
I have an array that looks like this:

[
   {
      "name": "Omayeli Arenyeka",
      "positions":[
         {
            "start": 1993,
            "end": 2002,
            "title":"Senator of Abia"
         },
         {
            "start": 1993,
            "end": 2002,
            "title":"President"
         }
      ]
   },
   {
      "name": "John Cena",
      "positions":[
         {
            "start": 1993,
            "end": 2002,
            "title":"Senator of Abia"
         },
         {
            "start": 2004,
            "end": 2007,
            "title":"President"
         }
      ]
   }
];

For each name on the y-axis I want to draw for each item in the positions array, a horizontal line across the x-axis (so for Omayeli Arenyeka a line that starts from 1993 and then ends at 2002 and then another line starting from 2003-2007) I don't want the lines to be connected.

This is what I currently have:

var parseDate = d3.time.format("%Y").parse;
var maxyear = new Date("2017");
var minyear = new Date("1980");

var xScale = d3.time.scale()
 .domain([minyear, maxyear])
 .range([padding, width - padding]);

var yScale = d3.scale.ordinal()
 .range([height - padding, padding]);   // map these to the chart  height, less padding.
//REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

// define the y axis
var yAxis = d3.svg.axis()
 .orient("left")
 .scale(yScale);

// define the y axis
var xAxis = d3.svg.axis()
 .orient("bottom")
 .scale(xScale)
 .tickFormat(d3.time.format("%Y")); // <-- format

 d3.json("data/politicians.json", function(error, data) {
  if (error) throw error;

  yScale.domain(data.map(function(d) {
   console.log(d.name);
   return d.name;
  })).rangeRoundBands([0, height - padding]);

 // draw x axis with labels and move to the bottom of the chart area
 vis.append("g")
   .attr("class", "xaxis")   // give it a class so it can be used to select only xaxis labels  below
   .attr("transform", "translate(0," + (height - padding) + ")")
   .call(xAxis);

// draw y axis with labels and move in from the size by the amount of padding
vis.append("g")
  .attr("class", "yaxis")
  .attr("transform", "translate(" + padding + ",0)")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", -36)
  .attr("x", -36)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Politicians");

var line = {
  'x1':(function(d) {
    return xScale();
  }),
  'y1':(function(d) { return yScale(d.name); }),
  'x2':(function(d) {
    return xScale();
  }),
  'y2':(function(d) { return yScale(d.name); }),
}

});

Body:
The most important thing in D3 is binding the data to the elements. There are a lot of references for you regarding this.

In short, you need an "enter" selection.

Here I'll set two enter selections: one that creates <g> elements for each politician, and another that, for each politician, creates <line> elements for each position:

var groups = vis.selectAll("foo")
    .data(data)
    .enter()
    .append("g")
    .attr("transform", function(d) {
        return "translate(0," + (padding[2] + yScale(d.name)) + ")";
    });

var people = groups.selectAll("foo")
    .data(d => d.positions)
    .enter()
    .append("line");

So, we append the lines using d.name, d.start and d.end. Here is the demo:

var data = [{
  "name": "Omayeli Arenyeka",
  "positions": [{
    "start": 1993,
    "end": 2002,
    "title": "Senator of Abia"
  }, {
    "start": 1993,
    "end": 2002,
    "title": "President"
  }]
}, {
  "name": "John Cena",
  "positions": [{
    "start": 1993,
    "end": 2002,
    "title": "Senator of Abia"
  }, {
    "start": 2004,
    "end": 2007,
    "title": "President"
  }]
}];

var width = 500,
  height = 200,
  padding = [10, 10, 30, 130];

var color = d3.scale.category10();

var vis = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var parseDate = d3.time.format("%Y").parse;
var maxyear = new Date("2017");
var minyear = new Date("1980");

var xScale = d3.time.scale()
  .domain([minyear, maxyear])
  .range([padding[3], width - padding[1]]);

var yScale = d3.scale.ordinal()
  .rangePoints([height - padding[2], padding[0]], 1.5)
  .domain(data.map(function(d) {
    return d.name;
  })); // map these to the chart  height, less padding.
//REMEMBER: y axis range has the bigger number first because the y value of zero is at the top of chart and increases as you go down.

// define the y axis
var yAxis = d3.svg.axis()
  .orient("left")
  .scale(yScale);

// define the y axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .scale(xScale)
  .tickFormat(d3.time.format("%Y")); // <-- format

// draw x axis with labels and move to the bottom of the chart area
vis.append("g")
  .attr("class", "xaxis") // give it a class so it can be used to select only xaxis labels  below
  .attr("transform", "translate(0," + (height - padding[2]) + ")")
  .call(xAxis);

// draw y axis with labels and move in from the size by the amount of padding
vis.append("g")
  .attr("class", "yaxis")
  .attr("transform", "translate(" + padding[3] + ",0)")
  .call(yAxis);

var groups = vis.selectAll("foo")
  .data(data)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(0," + (yScale(d.name)) + ")";
  })
  .style("stroke", (d, i) => color(i));

var people = groups.selectAll("foo")
  .data(d => d.positions)
  .enter()
  .append("line");

var line = people.attr({
  'x1': function(d) {
    return xScale(parseDate(d.start.toString()));
  },
  'x2': function(d) {
    return xScale(parseDate(d.end.toString()));
  }
}).attr("stroke-width", 2);

.xaxis line, .yaxis line,
.xaxis path, .yaxis path {
  fill: none;
  stroke: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


问:
Writing to a binary file python
I want to write something to a binary file using python.

I am simply doing:

```<code>import numpy as np

f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second
</code>```

The output is just:
[] []

I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.

答:
You appear to be having some confusion about types in Python.

The expression 'i' + 'j' is adding two strings together. This results in the string ij, which is most likely written to the file as two bytes.

The variable i is already an int. You can write it to a file as a 4-byte integer in a couple of different ways (which also apply to the float j):

Use the struct module as detailed in how to write integer number in particular no of bytes in python ( file writing). Something like this:

```<code>import struct
with open('binary.file', 'wb') as f:
    f.write(struct.pack("i", i))
</code>```

You would use the 'd' specifier to write j.

Use the numpy module to do the writing for you, which is especially convenient since you are already using it to read the file. The method ndarray.tofile is made just for this purpose:

```<code>i = 4
j = 5.55
with open('binary.file', 'wb') as f:
    np.array(i, dtype=np.uint32).tofile(f)
    np.array(j, dtype=np.float64).tofile(f)
</code>```

Note that in both cases I use open as a context manager when writing the file with a with block. This ensures that the file is closed, even if an error occurs during writing.

Title: Writing to a binary file python

Body:
I want to write something to a binary file using python.

I am simply doing:

import numpy as np

f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second

The output is just:
[] []

I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.

Body:
You appear to be having some confusion about types in Python.

The expression 'i' + 'j' is adding two strings together. This results in the string ij, which is most likely written to the file as two bytes.

The variable i is already an int. You can write it to a file as a 4-byte integer in a couple of different ways (which also apply to the float j):

Use the struct module as detailed in how to write integer number in particular no of bytes in python ( file writing). Something like this:

import struct
with open('binary.file', 'wb') as f:
    f.write(struct.pack("i", i))

You would use the 'd' specifier to write j.

Use the numpy module to do the writing for you, which is especially convenient since you are already using it to read the file. The method ndarray.tofile is made just for this purpose:

i = 4
j = 5.55
with open('binary.file', 'wb') as f:
    np.array(i, dtype=np.uint32).tofile(f)
    np.array(j, dtype=np.float64).tofile(f)

Note that in both cases I use open as a context manager when writing the file with a with block. This ensures that the file is closed, even if an error occurs during writing.


问:
adding variables numical values (newb question)
Yesterday i had a look at how to set values of variables from nummbers stored in external txt files

the variables then needed to be added up so i used trial and  error first

((XVAL) + (NEWVAL))

assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20

VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30

yep its a newb question could anyone explain how to achieve what im affter

答:
As you are reading from a text file I assume that you are reading your values out as strings, so when you do this:

```<code>((XVAL) + (NEWVAL))
</code>```

It is effectively concatenating the two strings together.  In order to get the mathematical product of the two values these need to be int/integers which is the number type.

There are a number of ways you can do this, but in essence you have to 'cast' the strings to ints and then do your calculation.

So in vb.net it would be something like this (pseudo code):

```<code>Dim xval As String = "10"
Dim newval As String = "20"

Dim x As Integer = Int32.Parse(xval)
Dim n As Integer = Int32.Parse(newval)

Dim prod As Integer = x + n

Console.WriteLine(prod)
</code>```

There are a number of other methods of doing this, for example using:

```<code>int.Parse(...)
</code>```

or

```<code>Integer.TryParse(...)
</code>```

More information on these sorts of type conversions can be found here:

http://dotnetperls.com/integer-parse-vbnet

One thing to bear in mind with these sorts of conversions is that you have to be certain that your input data is convertable.  Otherwise your code will throw exceptions.  This is where TryParse is useful as you can use this to check the inputs and handle invalid inputs without the need for exceptions.

Body:
As you are reading from a text file I assume that you are reading your values out as strings, so when you do this:

((XVAL) + (NEWVAL))

It is effectively concatenating the two strings together.  In order to get the mathematical product of the two values these need to be int/integers which is the number type.

There are a number of ways you can do this, but in essence you have to 'cast' the strings to ints and then do your calculation.

So in vb.net it would be something like this (pseudo code):

Dim xval As String = "10"
Dim newval As String = "20"

Dim x As Integer = Int32.Parse(xval)
Dim n As Integer = Int32.Parse(newval)

Dim prod As Integer = x + n

Console.WriteLine(prod)

There are a number of other methods of doing this, for example using:

int.Parse(...)

or

Integer.TryParse(...)

More information on these sorts of type conversions can be found here:

http://dotnetperls.com/integer-parse-vbnet

One thing to bear in mind with these sorts of conversions is that you have to be certain that your input data is convertable.  Otherwise your code will throw exceptions.  This is where TryParse is useful as you can use this to check the inputs and handle invalid inputs without the need for exceptions.


问:
First ajax call goes extremely slow, subsequent calls run quickly -- why?
I'm using a simple jQuery AJAX function that runs extremely slow (10-15 seconds) the first time it's called, and then runs normally at <1 - 2 seconds each time it's called after that first time. I cannot figure out why this is happening but need to speed it up as much as possible. Here is the function:

```<code>function getNewItemAlt(apiUrl, callType, apiKey, dataType, returnValue, appendToWrapper) {
// ajax call to the api
  return $.ajax({
    type: callType,
    url: apiUrl,
    data: apiKey,
    dataType: dataType,
    success: function(result) {

        appendToWrapper.closest('.game_play_area').find('.game_loader').remove();

        // this is the thing that we want (probably either
        // an image url or an actual value)
        var desiredReturn = deepValue(result, returnValue);

        var specialClass = '';
        console.log(typeof desiredReturn)
        if (typeof desiredReturn === 'number') {
            specialClass = 'number'
        }

        // if it's a URL then it's an image and can be setup
        // in an imgage tag and added to the dom
        if (desiredReturn.toString().substring(0, 4) == "http") {
            $(appendToWrapper).children('.game_image').remove();
            $(appendToWrapper).prepend('<img class="game_image" src="' + desiredReturn + '" />');
        } else {
            $(appendToWrapper).children('.game_value_return').remove();
            $(appendToWrapper).prepend('<p class="game_value_return ' + specialClass + '">' + desiredReturn + '</p>');
        }

        // clear the space to play the game
        // $(currentGameWrapper).children('.game_intro').remove();

        // show the game
        // currentGameWrapper.children('.game_play_area').removeClass('hide');

    },
    error: function(err) {
        console.log(err);
    }
});
}
</code>```

An example of an API that I'm making a request to is the Giphy API. I'm not convinced this is a server issue because it happens only on the first call to the api and then the subsequent calls are speedy.

Any ideas why this is happening and what can be done to make this run faster?

答:
This might be a long shot.  "appendToWrapper" is an object passed in by reference.  If it's taking a long time to resolve (ie it takes 10 seconds or so to find ".game_play_area" etc... in the DOM) then it would be slow the first time, but saved in the calling function and fast subsequent times.

It might be easy to check.  If you could make a deep copy of the object before passing it in, we would expect the AJAX to be slow every time, not just the first time.  If that's the case, you'd need to clean up your selectors to make them faster.  Perhaps use ids instead of classes.

Body:
I'm using a simple jQuery AJAX function that runs extremely slow (10-15 seconds) the first time it's called, and then runs normally at <1 - 2 seconds each time it's called after that first time. I cannot figure out why this is happening but need to speed it up as much as possible. Here is the function:

function getNewItemAlt(apiUrl, callType, apiKey, dataType, returnValue, appendToWrapper) {
// ajax call to the api
  return $.ajax({
    type: callType,
    url: apiUrl,
    data: apiKey,
    dataType: dataType,
    success: function(result) {

        appendToWrapper.closest('.game_play_area').find('.game_loader').remove();

        // this is the thing that we want (probably either
        // an image url or an actual value)
        var desiredReturn = deepValue(result, returnValue);

        var specialClass = '';
        console.log(typeof desiredReturn)
        if (typeof desiredReturn === 'number') {
            specialClass = 'number'
        }

        // if it's a URL then it's an image and can be setup
        // in an imgage tag and added to the dom
        if (desiredReturn.toString().substring(0, 4) == "http") {
            $(appendToWrapper).children('.game_image').remove();
            $(appendToWrapper).prepend('');
        } else {
            $(appendToWrapper).children('.game_value_return').remove();
            $(appendToWrapper).prepend('
' + desiredReturn + '
');
        }

        // clear the space to play the game
        // $(currentGameWrapper).children('.game_intro').remove();

        // show the game
        // currentGameWrapper.children('.game_play_area').removeClass('hide');

    },
    error: function(err) {
        console.log(err);
    }
});
}

An example of an API that I'm making a request to is the Giphy API. I'm not convinced this is a server issue because it happens only on the first call to the api and then the subsequent calls are speedy.

Any ideas why this is happening and what can be done to make this run faster?


问:
How to Change order of columns in gridview?
I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9  columns) with data from text file. Code is here:

```<code>public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
     {
        DataTable tbl = new DataTable();
        for (int col = 0; col < numberOfColumns; col++)
        tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

        string[] lines = File.ReadAllLines(filePath);
        List<string> ekran = new List<string>();
        foreach (string line in lines)
        {
            var cols = line.Split(',');
            DataRow dr = tbl.NewRow();
            for (int cIndex = 0; cIndex < 9; cIndex++)
            {
                if (cols[cIndex].Contains('_'))
                {
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
                else
                {
                    cols[cIndex] += '_';
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
            }
            for (int cIndex = 0; cIndex < 9;cIndex++ )
                if (dr[cIndex].ToString() == promenljiva)
                    tbl.Rows.Add(dr);
        }

        this.GridView1.DataSource = tbl;
        this.GridView1.DataBind();

        return tbl;
    }
</code>```

After that i have this:

```<code>ConvertToDataTable(filePath, 9);
</code>```

This is gridview:

```<code><asp:GridView ID="GridView1" runat="server"></asp:GridView>
</code>```

How can i do that?

答:
Before setting the DataSource of the grid

```<code>tbl.Columns[8].SetOrdinal(0);
</code>```

This will change the Ordinal property of the DataColumn inside the DataTable.DataColumnCollection in a way that the grid sees, as first column, your 9th column. Of course all other columns move up to a new index position

Body:
I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9  columns) with data from text file. Code is here:

public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
     {
        DataTable tbl = new DataTable();
        for (int col = 0; col < numberOfColumns; col++)
        tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

        string[] lines = File.ReadAllLines(filePath);
        List<string> ekran = new List<string>();
        foreach (string line in lines)
        {
            var cols = line.Split(',');
            DataRow dr = tbl.NewRow();
            for (int cIndex = 0; cIndex < 9; cIndex++)
            {
                if (cols[cIndex].Contains('_'))
                {
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
                else
                {
                    cols[cIndex] += '_';
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
            }
            for (int cIndex = 0; cIndex < 9;cIndex++ )
                if (dr[cIndex].ToString() == promenljiva)
                    tbl.Rows.Add(dr);
        }

        this.GridView1.DataSource = tbl;
        this.GridView1.DataBind();

        return tbl;
    }

After that i have this:

ConvertToDataTable(filePath, 9);

This is gridview:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

How can i do that?

Body:
Before setting the DataSource of the grid

tbl.Columns[8].SetOrdinal(0);

This will change the Ordinal property of the DataColumn inside the DataTable.DataColumnCollection in a way that the grid sees, as first column, your 9th column. Of course all other columns move up to a new index position


问:
how can I increase the int through a method?
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

```<code>int health;
int mana;
</code>```

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

```<code>public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}
</code>```

Please give me some insight!

答:
Right... Well I got it working somehow. The problem is that, well I don't know how to set the variable to the specific int.
Here is what I have

When I call the method I use upgrade(mana);
then for the methodm I have;

```<code>public void upgrade(int val){
            if(val < 5)
                val = val + 1;
                setMana(val);
}
</code>```

the value will increase.
The problem is that I also want to use this method separately for health, and I really don't know what to do next.
I have also been looking at passing by value;
Any insights, please?

Body:
I am new to java and I got cought in a situation which doesn't have an ending, at least for me;
Basically what I am trying to do is to increase two int through the same method but it seems that I can't figure out.

Example:

int health;
int mana;

each value will have a button near it corresponding to the actual label where the health and mana will be displayed.

public void upgrade(int health, int mana){
   the problem is that I don't know how to do it?
This method should be able to increase only one stat (mana or health), and it will be called on button clicked(action listener)
}

Please give me some insight!

Body:
Right... Well I got it working somehow. The problem is that, well I don't know how to set the variable to the specific int.
Here is what I have

When I call the method I use upgrade(mana);
then for the methodm I have;

public void upgrade(int val){
            if(val < 5)
                val = val + 1;
                setMana(val);
}

the value will increase.
The problem is that I also want to use this method separately for health, and I really don't know what to do next.
I have also been looking at passing by value;
Any insights, please?


问:
Function call inside complex query

Recently someone gave me the query below to take the open price, and then find the next price which is > the open price.

This works perfectly.

Now of course, they are changing the specs on me.  Rather than using "open price", then want "price change percent", from previous day.

I have a function for that already, which I am listing the call below.....but I am not sure how to implement it into the query.  I'm hoping someone can help.

Original Query

```<code>SELECT MAX(price_date), MIN(open_price) KEEP (DENSE_RANK FIRST ORDER BY price_date DESC)
FROM price_history p, master_Table m
WHERE p.ticker = m.ticker
AND open_price > (SELECT MIN(open_price) KEEP (DENSE_RANK FIRST ORDER BY price_date DESC)
                  FROM price_history@ p, master_table m
                  WHERE p.ticker = m.ticker
                    AND m.m_ticker = 'IBM')
AND m.m_ticker ='IBM';
</code>```

Call to Price Change Percent function:

```<code>PRICE_FUNCTIONS.NET_CHANGE('IBM', TRUNC(SYSDATE), 1, 'PCT')
</code>```

Sample Data:

```<code>IBM 20170330    173.86
IBM 20170329    174.3
IBM 20170328    173.94
IBM 20170327    172.69
IBM 20170324    175.12
</code>```

Any help would be awesome.

答:
In lieu of more information from you, maybe this will give you some ideas as to how to proceed?</p>

```<code>WITH sample_data AS (SELECT 'IBM' ticker, to_date('30/03/2017', 'dd/mm/yyyy') price_date, 173.86 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('29/03/2017', 'dd/mm/yyyy') price_date, 174.3 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('28/03/2017', 'dd/mm/yyyy') price_date, 173.94 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('27/03/2017', 'dd/mm/yyyy') price_date, 173.69 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('24/03/2017', 'dd/mm/yyyy') price_date, 175.12 open_price FROM dual),
         interim AS (SELECT ticker,
                            price_date,
                            MAX(price_date) OVER (PARTITION BY ticker) max_price_date,
                            open_price,
                            LAG(price_date) OVER (PARTITION BY ticker ORDER BY price_date) prev_price_date,
                            LAG(open_price) OVER (PARTITION BY ticker ORDER BY price_date) prev_open_price
                     FROM   sample_data)
SELECT ticker,
       price_date,
       open_price,
       prev_price_date,
       ROUND(100 * (open_price - prev_open_price) / prev_open_price, 2) percentage_change_from_yday
FROM   interim
WHERE  price_date = max_price_date;

TICKER PRICE_DATE  OPEN_PRICE PREV_PRICE_DATE PERCENTAGE_CHANGE_FROM_YDAY
------ ----------- ---------- --------------- ---------------------------
IBM    30/03/2017      173.86 29/03/2017                            -0.25
</code>```

Title: Function call inside complex query

Body:
Recently someone gave me the query below to take the open price, and then find the next price which is > the open price.

This works perfectly.

Now of course, they are changing the specs on me.  Rather than using "open price", then want "price change percent", from previous day.

I have a function for that already, which I am listing the call below.....but I am not sure how to implement it into the query.  I'm hoping someone can help.

Original Query

SELECT MAX(price_date), MIN(open_price) KEEP (DENSE_RANK FIRST ORDER BY price_date DESC)
FROM price_history p, master_Table m
WHERE p.ticker = m.ticker
AND open_price > (SELECT MIN(open_price) KEEP (DENSE_RANK FIRST ORDER BY price_date DESC)
                  FROM price_history@ p, master_table m
                  WHERE p.ticker = m.ticker
                    AND m.m_ticker = 'IBM')
AND m.m_ticker ='IBM';

Call to Price Change Percent function:

PRICE_FUNCTIONS.NET_CHANGE('IBM', TRUNC(SYSDATE), 1, 'PCT')

Sample Data:

IBM 20170330    173.86
IBM 20170329    174.3
IBM 20170328    173.94
IBM 20170327    172.69
IBM 20170324    175.12

Any help would be awesome.

Body:
In lieu of more information from you, maybe this will give you some ideas as to how to proceed?

WITH sample_data AS (SELECT 'IBM' ticker, to_date('30/03/2017', 'dd/mm/yyyy') price_date, 173.86 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('29/03/2017', 'dd/mm/yyyy') price_date, 174.3 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('28/03/2017', 'dd/mm/yyyy') price_date, 173.94 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('27/03/2017', 'dd/mm/yyyy') price_date, 173.69 open_price FROM dual UNION ALL
                     SELECT 'IBM' ticker, to_date('24/03/2017', 'dd/mm/yyyy') price_date, 175.12 open_price FROM dual),
         interim AS (SELECT ticker,
                            price_date,
                            MAX(price_date) OVER (PARTITION BY ticker) max_price_date,
                            open_price,
                            LAG(price_date) OVER (PARTITION BY ticker ORDER BY price_date) prev_price_date,
                            LAG(open_price) OVER (PARTITION BY ticker ORDER BY price_date) prev_open_price
                     FROM   sample_data)
SELECT ticker,
       price_date,
       open_price,
       prev_price_date,
       ROUND(100 * (open_price - prev_open_price) / prev_open_price, 2) percentage_change_from_yday
FROM   interim
WHERE  price_date = max_price_date;

TICKER PRICE_DATE  OPEN_PRICE PREV_PRICE_DATE PERCENTAGE_CHANGE_FROM_YDAY
------ ----------- ---------- --------------- ---------------------------
IBM    30/03/2017      173.86 29/03/2017                            -0.25


问:
Unsigned multiplication in VHDL 4bit vector?
im making an ALU with an option to do A + 2B
but im having trouble getting my head around multiplying the 2B and getting the proper answer in my test bench.

EG: A = 0110  B = 0011
Equation is A + 2B
and im getting 0110

a snippit of my code is

```<code>entity ALU is
         port( A     :IN     STD_LOGIC_VECTOR(3 DOWNTO 0) ;
               B     :IN     STD_LOGIC_VECTOR(3 DOWNTO 0) ;
               S0    :IN     STD_LOGIC ;
               S1    :IN     STD_LOGIC ;
               M     :IN     STD_LOGIC ;
                    C0    :IN     STD_LOGIC ;

               Cout  :OUT    STD_LOGIC ;
               Z     :OUT    STD_LOGIC ;
               F     :OUT    STD_LOGIC_VECTOR(3 DOWNTO 0));

  SIGNAL VariableAlu : STD_LOGIC_VECTOR(3 DOWNTO 0);
    SIGNAL FTEMP       : STD_LOGIC_VECTOR(3 DOWNTO 0);
    SIGNAL FTEMP2      : STD_LOGIC_VECTOR(4 DOWNTO 0);
    SIGNAL ZTEMP        : STD_LOGIC;
    SIGNAL BTEMP1        : STD_LOGIC_VECTOR(4 DOWNTO 0);

        END ALU ;
        PROCESS(A,B,S0,S1,M,C0)
        BEGIN

                VariableAlu <= (S0 & S1 & C0 & M);
                 --M = 1 ARITHMETIC

  (part that shifts it, lab teacher told us to do this)
                    BTEMP1(4 DOWNTO 1)<= B;
                    BTEMP1(0)<= '0';

when "1111" => FTEMP2 <= ((A) + BTEMP1);
</code>```

any help would be greatly appreciated.

答:
There are a few things to note about your code. Firstly, for any arithmetic, avoid using SLV and stick with unsigned or signed types from the numeric_std library.

Your explicit shift (multiplication by 2) for the operand B:

```<code>BTEMP1(4 DOWNTO 1)<= B;
BTEMP1(0)<= '0';
</code>```

Is, a) not required, and b) verbose. You can achieve this by simply doing BTEMP <= B & '0';, or better yet, don't even use an intermediary signal and assign directly to FTEMP2 in the switch statement. eg.

```<code>when "1111" => FTEMP2 <= std_logic_vector(unsigned(A) + unsigned(B&'0'));
</code>```

Note the conversions in the above line. They are required, as by default, SLV's do not support the + operator (unless you use the std_logic_unsigned or std_logic_signed libraries). You will need to include the numeric_std library for this.

EDIT:

I also forgot to mention that FTEMP will potentially overflow for the given function; F <= A + 2B, where A and B are both 4 bits and F is 5 bits.

Body:
im making an ALU with an option to do A + 2B
but im having trouble getting my head around multiplying the 2B and getting the proper answer in my test bench.

EG: A = 0110  B = 0011
Equation is A + 2B
and im getting 0110

a snippit of my code is

entity ALU is
         port( A     :IN     STD_LOGIC_VECTOR(3 DOWNTO 0) ;
               B     :IN     STD_LOGIC_VECTOR(3 DOWNTO 0) ;
               S0    :IN     STD_LOGIC ;
               S1    :IN     STD_LOGIC ;
               M     :IN     STD_LOGIC ;
                    C0    :IN     STD_LOGIC ;

               Cout  :OUT    STD_LOGIC ;
               Z     :OUT    STD_LOGIC ;
               F     :OUT    STD_LOGIC_VECTOR(3 DOWNTO 0));

  SIGNAL VariableAlu : STD_LOGIC_VECTOR(3 DOWNTO 0);
    SIGNAL FTEMP       : STD_LOGIC_VECTOR(3 DOWNTO 0);
    SIGNAL FTEMP2      : STD_LOGIC_VECTOR(4 DOWNTO 0);
    SIGNAL ZTEMP        : STD_LOGIC;
    SIGNAL BTEMP1        : STD_LOGIC_VECTOR(4 DOWNTO 0);

        END ALU ;
        PROCESS(A,B,S0,S1,M,C0)
        BEGIN

                VariableAlu <= (S0 & S1 & C0 & M);
                 --M = 1 ARITHMETIC

  (part that shifts it, lab teacher told us to do this)
                    BTEMP1(4 DOWNTO 1)<= B;
                    BTEMP1(0)<= '0';

when "1111" => FTEMP2 <= ((A) + BTEMP1);

any help would be greatly appreciated.

Body:
There are a few things to note about your code. Firstly, for any arithmetic, avoid using SLV and stick with unsigned or signed types from the numeric_std library.

Your explicit shift (multiplication by 2) for the operand B:

BTEMP1(4 DOWNTO 1)<= B;
BTEMP1(0)<= '0';

Is, a) not required, and b) verbose. You can achieve this by simply doing BTEMP <= B & '0';, or better yet, don't even use an intermediary signal and assign directly to FTEMP2 in the switch statement. eg.

when "1111" => FTEMP2 <= std_logic_vector(unsigned(A) + unsigned(B&'0'));

Note the conversions in the above line. They are required, as by default, SLV's do not support the + operator (unless you use the std_logic_unsigned or std_logic_signed libraries). You will need to include the numeric_std library for this.

EDIT:

I also forgot to mention that FTEMP will potentially overflow for the given function; F <= A + 2B, where A and B are both 4 bits and F is 5 bits.


问:
using html tag and elements in text box leads to error: A potentially dangerous Request.Form value was detected from the client
i want to convert my html file to pdf in that process i took all html tags and elements into an asp textfield on button click its giving the above error

code is

```<code>code.aspx

<asp:TextBox ID="TxtHtmlCode"  CausesValidation="false" runat="server" Width="90%" Text="" TextMode="MultiLine" Height="150px"></asp:TextBox>

 <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF" OnClick="BtnCreatePdf_Click" CssClass="mybutton" />

code.aspx.cs

protected void BtnCreatePdf_Click(object sender, EventArgs e)
   {
    htmlString = TxtHtmlCode.Text;
    HtmlToPdf converter = new HtmlToPdf();
    PdfDocument doc = converter.ConvertHtmlString(htmlString);
    doc.Save(Response, false, "Sample.pdf");
    doc.Close();
}
</code>```

i check with breakpoints even its not going to button click function.

please help me..

答:
Inside of your web.config you'll want to do:

```<code><HttpRuntime requestValidationMode="2.0" />
</code>```

Your other option, is to also append to your page directive at the top of your .aspx and apply:

```<code><@Page ... validateRequest="false" %>
</code>```

Keep in mind, by adding to web.config it will affect your entire site, compared to the page directive.  However, by adding this to your application, you obviate some built in security that Microsoft utilizes in the Web-Forms Framework.

Body:
i want to convert my html file to pdf in that process i took all html tags and elements into an asp textfield on button click its giving the above error

code is

code.aspx

<asp:TextBox ID="TxtHtmlCode"  CausesValidation="false" runat="server" Width="90%" Text="" TextMode="MultiLine" Height="150px"></asp:TextBox>

 <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF" OnClick="BtnCreatePdf_Click" CssClass="mybutton" />

code.aspx.cs

protected void BtnCreatePdf_Click(object sender, EventArgs e)
   {
    htmlString = TxtHtmlCode.Text;
    HtmlToPdf converter = new HtmlToPdf();
    PdfDocument doc = converter.ConvertHtmlString(htmlString);
    doc.Save(Response, false, "Sample.pdf");
    doc.Close();
}

i check with breakpoints even its not going to button click function.

please help me..

Body:
Inside of your web.config you'll want to do:

<HttpRuntime requestValidationMode="2.0" />

Your other option, is to also append to your page directive at the top of your .aspx and apply:

<@Page ... validateRequest="false" %>

Keep in mind, by adding to web.config it will affect your entire site, compared to the page directive.  However, by adding this to your application, you obviate some built in security that Microsoft utilizes in the Web-Forms Framework.


问:
Copy to clipboard using Bash for Windows
How do I copy results from the commandline directly to the clipboard?

On Windows's cmd.exe I can do simply echo "asd" | clip and it pipes output to the clipboard.

I tried to install xclip for that, and though it compiled, when called it prints:

```<code>Error: Can't open display: (null)
</code>```

Using mouse is not the solution.

答:
This still does not seem to be supported: Can Bash on Windows interact with the system clipboard?.

A clever workaround is the open source tool plak.

Body:
How do I copy results from the commandline directly to the clipboard?

On Windows's cmd.exe I can do simply echo "asd" | clip and it pipes output to the clipboard.

I tried to install xclip for that, and though it compiled, when called it prints:

Error: Can't open display: (null)

Using mouse is not the solution.

ContentLicense: CC BY-SA 4.0


问:
Element always displays at top of the fragment screen. Issue
Element is always displaying at top of the screen. I tried different ways to fix but out of luck. I want to place element at any location of the screen. This is fragment screen.</p>

```<code><FrameLayout 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"
    tools:context="myapp.com.myapp1.fragments.AddPeopleFragment">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="159dp"
        android:text="three"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginStart="110dp"
        android:layout_marginTop="167dp" />
</FrameLayout>
</code>```

答:
Have you ever noticed these lines of code ?

```<code>   "android:layout_alignParentTop="true"
    android:layout_alignParentStart="true""
</code>```

if you want to use absolute layout, do not bother these code;

eg:

```<code><FrameLayout 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"
tools:context="myapp.com.myapp1.fragmants.FragmantAddPeople">
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="159dp"
    android:text="three"

    android:layout_marginStart="110dp"
    android:layout_marginTop="167dp" />
    </android.support.constraint.ConstraintLayout>
</code>```

you can place the item(which in case is the button) anywhere by changing the dp Value of absoluteX and absoluteY;``

Body:
Element is always displaying at top of the screen. I tried different ways to fix but out of luck. I want to place element at any location of the screen. This is fragment screen.

<FrameLayout 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"
    tools:context="myapp.com.myapp1.fragments.AddPeopleFragment">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="159dp"
        android:text="three"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginStart="110dp"
        android:layout_marginTop="167dp" />
</FrameLayout>

Body:
Have you ever noticed these lines of code ?

   "android:layout_alignParentTop="true"
    android:layout_alignParentStart="true""

if you want to use absolute layout, do not bother these code;

eg:

<FrameLayout 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"
tools:context="myapp.com.myapp1.fragmants.FragmantAddPeople">
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="159dp"
    android:text="three"

    android:layout_marginStart="110dp"
    android:layout_marginTop="167dp" />
    </android.support.constraint.ConstraintLayout>

you can place the item(which in case is the button) anywhere by changing the dp Value of absoluteX and absoluteY;``


问:
compare objects by multiple fields, how to add in one method?
How can I combine the following compare method in one compare method(comparator1) and (comparator2) ?

´´´

```<code>private List<Bonus> getBonusListSortedByHasAccountAndDate(List<Bonus> bonusList) {

    final Comparator<Bonus> comparator1 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    };

    bonusList.sort(comparator1);
    List bonusList2 = bonusList;

    final Comparator<Bonus> comparator2 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    };
    bonusList2.sort(comparator2);
    return bonusList2;
}

@Test
public void test() {
    List<Bonus> bonus = createBonus();
    List<Bonus> getBonusListSortedByHasAccountAndDate = getBonusDTOListSortedByHasAccount2(bonus);
    assertThat(getBonusListSortedByHasAccountAndDate.get(0).getName(), is("2"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(1).getName(), is("3"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(2).getName(), is("1"));
}
</code>```

updated: for my compare and sorting I want to have "the oldest Bonus created" and "Bonus should be activated"

many thanks in advance.
zoram

答:
You can use Java 8 stream api:

```<code>bonusList.stream()
        .sorted(comparing(Bonus::getDate).thenComparing(Bonus::isActive))
        .collect(toList());
</code>```

You will need the following imports:

```<code>import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
</code>```

Also, in regards to your test, I would recommend using some tool which does the assertion in a single statement and gives you much better diagnostics. Have a look on Shazamcrest.

Body:
How can I combine the following compare method in one compare method(comparator1) and (comparator2) ?

´´´

private List<Bonus> getBonusListSortedByHasAccountAndDate(List<Bonus> bonusList) {

    final Comparator<Bonus> comparator1 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return Boolean.compare(o1.isActive(), o2.isActive());
        }
    };

    bonusList.sort(comparator1);
    List bonusList2 = bonusList;

    final Comparator<Bonus> comparator2 = new Comparator<Bonus>() {
        public int compare(Bonus o1, Bonus o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    };
    bonusList2.sort(comparator2);
    return bonusList2;
}

@Test
public void test() {
    List<Bonus> bonus = createBonus();
    List<Bonus> getBonusListSortedByHasAccountAndDate = getBonusDTOListSortedByHasAccount2(bonus);
    assertThat(getBonusListSortedByHasAccountAndDate.get(0).getName(), is("2"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(1).getName(), is("3"));
    assertThat(getBonusListSortedByHasAccountAndDate.get(2).getName(), is("1"));
}

updated: for my compare and sorting I want to have "the oldest Bonus created" and "Bonus should be activated"

many thanks in advance.
zoram

Body:
You can use Java 8 stream api:

bonusList.stream()
        .sorted(comparing(Bonus::getDate).thenComparing(Bonus::isActive))
        .collect(toList());

You will need the following imports:

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

Also, in regards to your test, I would recommend using some tool which does the assertion in a single statement and gives you much better diagnostics. Have a look on Shazamcrest.