问:
Multiplying two images together in ImageJ
I'd like to do some image processing in FIJI / ImageJ but not sure how to go about it. I have a first image, call it "imageA" and would like to perform several operations on it. I know you can go to Process->Math and have some options for operations (add subtract multlipy etc) and there is a tool for writing a macro so that you can combine a few operations into one step, but I'm not sure how to approach it for adding in a second image which I'd like to include in the operation.

I'd like to take imageA and multiply it by a second image of the same size, imageB, together with a few other steps which are outlined in the function below:

output image = sqrt((constant*constant) + (constant2*constant2) + (imageB*imageB))

Image A * Output Image.

The constants are pretty straightforward inputs that I can simply add, but I'm not sure how to make it so imageB is also included in the function to produce the final output that I will then apply to imageA.

答:
The approach is to first open "imageB", perform the operations (using Process > Math) to create the "Output image", open "imageA" and then use the Process > Image Calculator, selecting imageA and Output image with the multiply operation.

In the ImageJ macro language, it will look something like this:

```<code>//open imageB
open("LOCATIONOFIMAGEB");
//square ImageB
run("Square");
//add your constants to image
run("Add...", "value=CONSTANT1"); //Constant1 should be an integer
run("Add...", "value=CONSTANT2"); //Constant2 should be an integer
//squareroot to make your outputImage
run("Square Root");
//open ImageA
open("LOCATIONOFIMAGEA");
//multiple images
imageCalculator("Multiply create", "WINDOWTITLEOFIMAGEA","WINDOWTITLEOFIMAGEB");
</code>```

Insert the relevant constants, location of images and windowTitles and it should work...

Body:
The approach is to first open "imageB", perform the operations (using Process > Math) to create the "Output image", open "imageA" and then use the Process > Image Calculator, selecting imageA and Output image with the multiply operation.

In the ImageJ macro language, it will look something like this:

//open imageB
open("LOCATIONOFIMAGEB");
//square ImageB
run("Square");
//add your constants to image
run("Add...", "value=CONSTANT1"); //Constant1 should be an integer
run("Add...", "value=CONSTANT2"); //Constant2 should be an integer
//squareroot to make your outputImage
run("Square Root");
//open ImageA
open("LOCATIONOFIMAGEA");
//multiple images
imageCalculator("Multiply create", "WINDOWTITLEOFIMAGEA","WINDOWTITLEOFIMAGEB");

Insert the relevant constants, location of images and windowTitles and it should work...


来源: stackexchange

问:
html wont render from inside angular 2 component
I'm using a service to dynamically change the content in my header depending on the page I'm on, however when I put HTML in my component it doesn't render in the browser (see example below)

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle(`
      We strive to create things
      <br> that are engaging, progressive
      <br> & above all
      <span class="highlight">
      <em>innovative.</em>
      </span>
    `);
  }

}
</code>```

header.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  title: any;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}
</code>```

header.component.html

```<code><h1>{{title}}</h1>
</code>```

so Im trying to set the title to be a string that has html tags in it that I want to be rendered but what happens is the whole thing comes out as a string instead of how it would look like it I had put it in my home.component.html.

Is there a way I can do this??

答:
You can set the [innerHtml] property

```<code><h1 [innerHtml]="title"></h1>
</code>```

Example

ContentLicense: CC BY-SA 3.0

Body:
I'm using a service to dynamically change the content in my header depending on the page I'm on, however when I put HTML in my component it doesn't render in the browser (see example below)

home.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle(`
      We strive to create things

 that are engaging, progressive

 & above all

      innovative.

    `);
  }

}

header.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  title: any;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}

header.component.html

{{title}}

so Im trying to set the title to be a string that has html tags in it that I want to be rendered but what happens is the whole thing comes out as a string instead of how it would look like it I had put it in my home.component.html.

Is there a way I can do this??

Body:
You can set the [innerHtml] property

<h1 [innerHtml]="title"></h1>

Example


问:
Find the first record according to a chain of JOIN rules in SQL
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

```<code>SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);
</code>```

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

```<code>SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;
</code>```

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

```<code>CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/
</code>```

答:
left join lateral may work for you on this as it allows limiting the results to one row (each):.

```<code>CREATE TABLE table1 (A1 INT, A2 INT, A3 INT);
CREATE TABLE table2 (B1 INT, B2 INT, B3 INT, B4 VARCHAR(10));

INSERT INTO table1 VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO table2 VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');
</code>```

```<code>select
a1,a2,a3,coalesce(ljl1.b4,ljl2.b4,ljl3.b4)
from table1
left join lateral (
  select b4 from table2
  where table1.a1 = b1 and table1.a2 = b2 and table1.a3 = b3
  order by b1, b2, b3, b4
  limit 1
  ) ljl1 ON true
left join lateral (
  select b4 from table2
  where table1.a1 = b1 and table1.a2 = b2
  order by b1, b2, b3, b4
  limit 1
  ) ljl2 On true
left join lateral (
  select b4 from table2
  where table1.a1 = b1
  order by b1, b2, b3, b4
  limit 1
  ) ljl3 ON true
</code>```

```
a1 | a2 | a3 | coalesce
-: | -: | -: | :-------
10 | 20 | 30 | A1
11 | 21 | 31 | B
12 | 22 | 32 | C
13 | 23 | 33 | <em>null</em>
14 | 24 | 34 | D
```

dbfiddle demo here

You can add where coalesce(ljl1.b4,ljl2.b4,ljl3.b4) IS NOT NULL if required to more closely match the expected result, but I'm not sure why his row isn;t in your expected result:

```
14 | 24 | 34 | D
```

Body:
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/

Body:
left join lateral may work for you on this as it allows limiting the results to one row (each):.

CREATE TABLE table1 (A1 INT, A2 INT, A3 INT);
CREATE TABLE table2 (B1 INT, B2 INT, B3 INT, B4 VARCHAR(10));

INSERT INTO table1 VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO table2 VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

select
a1,a2,a3,coalesce(ljl1.b4,ljl2.b4,ljl3.b4)
from table1
left join lateral (
  select b4 from table2
  where table1.a1 = b1 and table1.a2 = b2 and table1.a3 = b3
  order by b1, b2, b3, b4
  limit 1
  ) ljl1 ON true
left join lateral (
  select b4 from table2
  where table1.a1 = b1 and table1.a2 = b2
  order by b1, b2, b3, b4
  limit 1
  ) ljl2 On true
left join lateral (
  select b4 from table2
  where table1.a1 = b1
  order by b1, b2, b3, b4
  limit 1
  ) ljl3 ON true

a1 | a2 | a3 | coalesce
-: | -: | -: | :-------
10 | 20 | 30 | A1
11 | 21 | 31 | B
12 | 22 | 32 | C
13 | 23 | 33 | null
14 | 24 | 34 | D

dbfiddle demo here

You can add where coalesce(ljl1.b4,ljl2.b4,ljl3.b4) IS NOT NULL if required to more closely match the expected result, but I'm not sure why his row isn;t in your expected result:

14 | 24 | 34 | D


问:
Why do I get 'No -renderInContext: method found' warning?
I get a compiler warning at the -renderInContext:

```<code>- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
</code>```

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

```<code>warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)
</code>```

答:
Try importing the Quartz framework into your application.

Then add,

#include <QuartzCore/QuartzCore.h>

to your application.

ContentLicense: CC BY-SA 2.5

Body:
I get a compiler warning at the -renderInContext:

- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)


问:
bash bad substitution - access an environment variable from another
How can I access an environment variable from another?  I have the following in my shell

```<code>#!/usr/bin/env bash

set -x

export A_version=1.0.0

component=A

echo ${${component}_version}}
</code>```

the bash script after the run gives me

```<code>temp.sh: line 9: ${${component}_version}}: bad substitution
</code>```

答:
You can use eval to do this.  Here is a working version of your script that prints 1.0.0:

```<code>export A_version=1.0.0
component=A
eval "echo \$${component}_version"
</code>```

For more information, see this page:

http://tldp.org/LDP/abs/html/ivr.html

Update:  A safer way to do the same thing in Bash would be:

```<code>export A_version=1.0.0
component=A
var=${component}_version; echo "${!var}"
</code>```

Note that you have to run this script with bash, not sh.

Body:
How can I access an environment variable from another?  I have the following in my shell

#!/usr/bin/env bash

set -x

export A_version=1.0.0

component=A

echo ${${component}_version}}

the bash script after the run gives me

temp.sh: line 9: ${${component}_version}}: bad substitution

Body:
You can use eval to do this.  Here is a working version of your script that prints 1.0.0:

export A_version=1.0.0
component=A
eval "echo \$${component}_version"

For more information, see this page:

http://tldp.org/LDP/abs/html/ivr.html

Update:  A safer way to do the same thing in Bash would be:

export A_version=1.0.0
component=A
var=${component}_version; echo "${!var}"

Note that you have to run this script with bash, not sh.


问:
Selecting TOP ranking through SQL in Unica
I have a table with 2 columns; sub_ID and RANK.

All sub_ID are unique and there are around 100k and have all been given a RANK between 1 - 38 in the RANK column.

I am working in Unica or IBM Campaign where in a SELECT cell I need to enter raw SQL that only returns 5000 subscribers where it selects based on the RANK in preference for 38 and less.

答: Use a sample process box. Limiting number of cells to 1 with number of records to 5000 and sorting based on rank column</p>


问:
fill color svg created with PhotoShop
I got this icon that was created in photoshop and saved in svg format.

How can I change the color fill?

-- EDIT --

I made this JS bin: https://jsbin.com/kazujoq/

SO seems to cut out this code: xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC".

```<code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65">
  <metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""/>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?></metadata>
<image id="Vector_Smart_Object" data-name="Vector Smart Object" x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC"/>
</svg>
</code>```

答:
The bitmap converted to svg can not be stylized using the usual methods: fill: orange;

But you can change its color entirely using SVG filters

Browser support SVG filter

To fill the color I will use  filter primitive feColorMatrix

This filter applies a matrix transformation:

The theory looks frightening, but in reality it is quite easy to use filters in practice.

To fill in red, I will use the following matrix:

```<code>    <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
            <feColorMatrix in="SourceGraphic" type="matrix"
                    values="0 0 0 1 0
                            0 0 0 0 0
                            0 0 0 0 0
                            0 0 0 1 0
                    "/>
   </filter>
</code>```

"1" is in the first line, which is responsible for the red color, in the fourth line - the alpha channel responsible for transparency.

Below is the full code of filling in red:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65"
>

  <defs>
 <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>

   <image   id="Vector_Smart_Object"   x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC" />
   </defs>
   <use xlink:href="#Vector_Smart_Object" filter="url(#RedFilter)" ></use>

</svg>```
</div>
</div>
    </p>

<p>For filling with other colors, minor changes in the matrix will be required. The green color is "1" in the second line, the rest of the line, except for the alpha channel is zeros.    </p>

<p>In the example below, the <code><use></code> command is used, which makes it possible to color the clones in different colors by applying a filter with different matrix formulas to them.   </p>

```             <use xlink:href="#Vector_Smart_Object" x="0" y="0"  filter="url(#RedFilter)" ></use>
             <use xlink:href="#Vector_Smart_Object" x="100" y="0" filter="url(#GreenFilter)" ></use>
             <use xlink:href="#Vector_Smart_Object" x="200" y="0" filter="url(#BlueFilter)" ></use>
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="65" viewBox="0 0 400 65"
>

  <defs>
 <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>
 <filter id="GreenFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 0
                        0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>

 <filter id="BlueFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                        0 0 0 1 0
                "/>
    </filter>

   <image   id="Vector_Smart_Object"   x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC" />
   </defs>
   <use xlink:href="#Vector_Smart_Object" x="0" y="0"  filter="url(#RedFilter)" ></use>
   <use xlink:href="#Vector_Smart_Object" x="100" y="0" filter="url(#GreenFilter)" ></use>
    <use xlink:href="#Vector_Smart_Object" x="200" y="0" filter="url(#BlueFilter)" ></use>

</svg></code>```

Title: fill color svg created with PhotoShop

Body:
I got this icon that was created in photoshop and saved in svg format.

How can I change the color fill?

-- EDIT --

I made this JS bin: https://jsbin.com/kazujoq/

SO seems to cut out this code: xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC".

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65">
  <metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""/>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?></metadata>
<image id="Vector_Smart_Object" data-name="Vector Smart Object" x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC"/>
</svg>

Body:
The bitmap converted to svg can not be stylized using the usual methods: fill: orange;

But you can change its color entirely using SVG filters

Browser support SVG filter

To fill the color I will use  filter primitive feColorMatrix

This filter applies a matrix transformation:

The theory looks frightening, but in reality it is quite easy to use filters in practice.

To fill in red, I will use the following matrix:

    <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
            <feColorMatrix in="SourceGraphic" type="matrix"
                    values="0 0 0 1 0
                            0 0 0 0 0
                            0 0 0 0 0
                            0 0 0 1 0
                    "/>
   </filter>

"1" is in the first line, which is responsible for the red color, in the fourth line - the alpha channel responsible for transparency.

Below is the full code of filling in red:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="65" viewBox="0 0 99 65"
>

  <defs>
 <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>

   <image   id="Vector_Smart_Object"   x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC" />
   </defs>
   <use xlink:href="#Vector_Smart_Object" filter="url(#RedFilter)" ></use>

</svg>

For filling with other colors, minor changes in the matrix will be required. The green color is "1" in the second line, the rest of the line, except for the alpha channel is zeros.

In the example below, the <use> command is used, which makes it possible to color the clones in different colors by applying a filter with different matrix formulas to them.

             <use xlink:href="#Vector_Smart_Object" x="0" y="0"  filter="url(#RedFilter)" ></use>
             <use xlink:href="#Vector_Smart_Object" x="100" y="0" filter="url(#GreenFilter)" ></use>
             <use xlink:href="#Vector_Smart_Object" x="200" y="0" filter="url(#BlueFilter)" ></use>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="65" viewBox="0 0 400 65"
>

  <defs>
 <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>
 <filter id="GreenFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 0
                        0 0 0 1 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>

 <filter id="BlueFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                        0 0 0 1 0
                "/>
    </filter>

   <image   id="Vector_Smart_Object"   x="14" y="19" width="67" height="30" xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAeCAQAAADd02vRAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAAHdElNRQfhDAcMHSMd+lM1AAADSElEQVRIx83WX2iVdRzH8ZfHMzZqzrlyUVMHioPEgXqhSEkiQVfWMKErwz8oIgYRdCEYBdWVIIRZeRmRJV2MQqygCRIRhLmy0OlEbbPN3FYHmjvzHLdfF3t29uy4nc45k9b3d3O+n+fz+z7v53u+zzm/OYqJhMc9odkiizxkoepIzxrQ5zdXnXfOeSNFVZsUoUjfeu/rF4pYf2q1TU2pGEEwp6Bngzc9FX3+wzldevToN2zYg07iQ+0aNVntscg35BOHXbhf3XjAuxHqsFctn+ZBWnJZg+0+kxYEoz61tJRuTBf1zuaafaFAhZY8bb59Lkfwr0nODGOhTsGot30suF4CBiRs97sg+N7i8jGq/CDIeAEvl4EB1Y4JgpvWlovxgSB4kRlgwBaDgkGbysF4RhB8FGWvCG5MuT8pCLYUfNRNguB2oY5M9cI+7DmvW4whnaBRLS4Zvmf/PEtxS28BjFqNIKVdSkqfSy7okIpjxONRe7UZKepnaubrV+/YMNaCiS9ls2+N/kcA8dVpt+QERu8sIIyvsxaNY6RmESP4UTJImO1Y43n/Awye/TeMv+/jzaav1TQdRtph61WpUWmdQ27P4Pa3HbJOpRpV1jssfY8jOkTlj+gZDXnGem1lDmCb+rxaDc7keboCTuaJX6nAEkd0SLnsqGWY64syID43F8scdVlKhyOWoMLXeb6T8oRetdhsMKYN2Ypq3SVCdKvGVkMxbdBm1LqZ581L96NZWnDLQS0O6BFkrMbOEjF2Yo2MoMcBLQ66JUhrxv5CGHfVoVXQnZuPR1wTnEKNOyVA3DEPXwqu5eajQbegFXXuTo/RgYS0YG9sqHYIsirRXgLGOVTKCnbEau0TpCXQEXcnxP9pb2CBKvwSU39CUj26S3hRe1EvGe0fj59RZQG6YmpIesnT0akj4xhSsios913OtAKj+vGWtMqiIDLeQ79RCSu05/QmZKXwhr+iWsE3U5U4JbiiLsrmuyg4XUIf4nFacNH8KKtzJZqziUaMjcYUsVZWcNUeG+3WKRjxZJkYG4wYO1lstMdVQXbykXB6DLbJxAYoa1eZELBLNlYrY9vky4UwWOm4PsGAE1bNAAJWOWFA0Oe4lfkXxzD+AbFgJVHPGGAuAAAAAElFTkSuQmCC" />
   </defs>
   <use xlink:href="#Vector_Smart_Object" x="0" y="0"  filter="url(#RedFilter)" ></use>
   <use xlink:href="#Vector_Smart_Object" x="100" y="0" filter="url(#GreenFilter)" ></use>
    <use xlink:href="#Vector_Smart_Object" x="200" y="0" filter="url(#BlueFilter)" ></use>

</svg>


问:
How i can style SVG <use> elements on hover?
I'm beginner in SVG. I'm trying to change style of multiple <use> elements on hover at a specific <use> element with css, but I can't, because <use> elements using Shadow DOM.

I have the following <defs>:

<defs>
    <filter id="Sjax0b81q1" filterUnits="userSpaceOnUse">...</filter>
    <circle cx="0" cy="0" r="40" id="action-circle" style="cursor: move; fill: #fff;" filter="url('#Sjax0b81q1')" class="el action-el"></circle>
    <g id="condition-rhombus" style="cursor: move; fill: #fff;" class="el condition-el" transform="matrix(1,0,0,1,0,0)">
        <circle cx="0" cy="0" r="40" fill="none"></circle>
        <path d="M -35 0, L 0 -35, L 35 0, L 0 35 L -35 0" style="stroke-linecap: round; stroke: white;" filter="url('#Sjax0b81q1')" class="condition-rhombus"></path>
    </g>
    <g id="svg-plus-button">
        <circle cx="0" cy="40" r="10" id="svg-plus-circle" fill="none" style="fill-opacity: 1;" class="svg-plus-circle"></circle>
        <path d="M956.8,408.....408.5z" id="svg-plus-sign" fill="none" transform="matrix(0.008,0,0,0.008,-4,36)" style="pointer-events: none;" class="svg-plus-sign"></path>
    </g>
    <rect x="-20" y="-20" width="40" height="40" id="rect-active-layer" fill="none" style="pointer-events: visible;" class="rect-active-layer"></rect>
    <path d="M252.967.....2v1Z" id="api-svg" class="cls-1"></path>
</defs>
```
<p>And I have a group of elements that contains several <code><use></code> elements:</p>
<pre class="lang-xml prettyprint-override"><code><g id="action-group-2" class="external action-group" transform="matrix(1,0,0,1,420,180)">
    <g class="internal action-group">
        <rect x="-40" y="-40" width="80" height="80" fill="none"></rect>
    </g>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#action-circle"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-plus-button" id="useSjax0b81q1k"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#rect-active-layer"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#api-svg"></use>
</g>
</code>```

For example, I need to change the <path> fill in element with id #api-svg, when I hover on the #action-circle.

How can I do this? Maybe there is another way to render and styling reusable elements on hover.

答:
Define the path to have fill="inherit", then you should be able to set fill="whatever" on the <use> element's styles and it will work.

use:hover {
  fill: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg>
  <defs>
    <circle id="test" fill="inherit" cy="10" r="10" />
  </defs>
  <use xlink:href="#test" transform="translate(10,0)" />
  <use xlink:href="#test" transform="translate(30,0)" />
  <use xlink:href="#test" transform="translate(50,0)" />
  <text y="40">Hover over the circles!</text>
</svg></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm beginner in SVG. I'm trying to change style of multiple <use> elements on hover at a specific <use> element with css, but I can't, because <use> elements using Shadow DOM.

I have the following <defs>:

<defs>
    <filter id="Sjax0b81q1" filterUnits="userSpaceOnUse">...</filter>
    <circle cx="0" cy="0" r="40" id="action-circle" style="cursor: move; fill: #fff;" filter="url('#Sjax0b81q1')" class="el action-el"></circle>
    <g id="condition-rhombus" style="cursor: move; fill: #fff;" class="el condition-el" transform="matrix(1,0,0,1,0,0)">
        <circle cx="0" cy="0" r="40" fill="none"></circle>
        <path d="M -35 0, L 0 -35, L 35 0, L 0 35 L -35 0" style="stroke-linecap: round; stroke: white;" filter="url('#Sjax0b81q1')" class="condition-rhombus"></path>
    </g>
    <g id="svg-plus-button">
        <circle cx="0" cy="40" r="10" id="svg-plus-circle" fill="none" style="fill-opacity: 1;" class="svg-plus-circle"></circle>
        <path d="M956.8,408.....408.5z" id="svg-plus-sign" fill="none" transform="matrix(0.008,0,0,0.008,-4,36)" style="pointer-events: none;" class="svg-plus-sign"></path>
    </g>
    <rect x="-20" y="-20" width="40" height="40" id="rect-active-layer" fill="none" style="pointer-events: visible;" class="rect-active-layer"></rect>
    <path d="M252.967.....2v1Z" id="api-svg" class="cls-1"></path>
</defs>

And I have a group of elements that contains several <use> elements:

<g id="action-group-2" class="external action-group" transform="matrix(1,0,0,1,420,180)">
    <g class="internal action-group">
        <rect x="-40" y="-40" width="80" height="80" fill="none"></rect>
    </g>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#action-circle"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-plus-button" id="useSjax0b81q1k"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#rect-active-layer"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#api-svg"></use>
</g>

For example, I need to change the <path> fill in element with id #api-svg, when I hover on the #action-circle.

How can I do this? Maybe there is another way to render and styling reusable elements on hover.

Body:
Define the path to have fill="inherit", then you should be able to set fill="whatever" on the <use> element's styles and it will work.

use:hover {
  fill: red;
}

<svg>
  <defs>
    <circle id="test" fill="inherit" cy="10" r="10" />
  </defs>
  <use xlink:href="#test" transform="translate(10,0)" />
  <use xlink:href="#test" transform="translate(30,0)" />
  <use xlink:href="#test" transform="translate(50,0)" />
  <text y="40">Hover over the circles!</text>
</svg>


问:
Electron error: jQuery is not defined
Ok, I apologize that this question is a duplicate, as I found my exact question asked and answered here: Electron: jQuery is not defined.  Unfortunately, I'm too much of a noob to wrap my head around the answer.

I've been programming desktop apps for a long time(TM), so I'm not new to programming or development, but Electron, Node.js, JavaScript, Angular, et al. are a new domain for me and I'm still pretty green.

I was able to install node and get the basics of npm figured out.  After that, I used npm to install electron, jQuery, and a treeview package called FancyTree (specifically version 2.24 as 2.26 seems to have an unrelated issue).

Now, following along with some basic Electron tutorials, my index.js looks like this:

```<code>const electron = require('electron');
const url = require('url');
const path = require('path');
const fs = require('fs');
const { app, BrowserWindow } = electron;

let mainWindow;

app.on('ready', function() {

    mainWindow = new BrowserWindow({ });

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'mainWindow.html'),
        protocol: 'file:',
        slashes: true
    }));

});
</code>```

I grasp that this is simply creating my main browser window during the 'ready' event handler, and navigating to my corresponding html, which looks like this:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Getting my Feet Wet</title>
</head>
<body>
    <h1>My feet are wet.  Weird.</h1>
</body>
</html>
</code>```

Nothing exciting so far.

But now I install jQuery and Fancytree using npm and I try to 'require' fancytree (just after the line for fs) like this:

```<code>const fancytree = require('jquery.fancytree');
</code>```

which doesn't work.  After some googling, it appears that (for reasons I don't completely understand) it is better to 'require' fancytree like this:

```<code>const fancytree = require('jquery.fancytree/dist/jquery.fancytree.js');
</code>```

For now, I'm willing to accept that without fully understanding the 'why'.

But I'm still throwing an error:

App threw an error during load ReferenceError: jQuery is not defined
      at Object. (C:\Scratch\QuickStart\node_modules\jquery.fancytree\dist\jquery.fancytree.js:5249:3)
  etc.

This seems to stem from the fact that Electron's use of Node.js defines some 'global-ish' references that conflict with various packages expectations.  Electron seems to outline one solution as passing the nodeIntegration: parameter as false when constructing the new browser window, which I tried without any joy.

The other answers all deal with various script blocks in the html, which makes no sense to me at all because it creates an order-of-operation problem.  For example, the statement to 'require' Fancytree will execute before my 'ready' event, which means it would happen well before the browser window is constructed, which would be long before any script blocks are run in the html; so that can't possibly work.

Thinking procedurally for a moment, I would expect my index.js to look more like this (presented in pseudo-code):

```<code>const electron = require('electron');
const url = require('url');
const path = require('path');
const fs = require('fs');

const fancytree; //this obviously isn't valid

const { app, BrowserWindow } = electron;

let mainWindow;

app.on('ready', function() {

    mainWindow = new BrowserWindow({ });

    //I hijacked this from the original Q/A on stack but don't
    //completely understand what it's doing, or if it's even
    //legit, but the idea is to fix the mainWindow / jQuery
    //reference now that the window is constructed but before
    //I try to require the FancyTree.
    //
    mainWindow.$ = mainWindow.jQuery = require('jquery');

    //And now that jQuery is sorted out it's marbles, let's get back
    //to business...
    //
    fancytree = require('jquery.fancytree/dist/jquery.fancytree.js');

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'mainWindow.html'),
        protocol: 'file:',
        slashes: true
    }));

});
</code>```

Obviously this is wrong, and I'm displaying my lack of depth of understanding with these technologies, but what should this look like?  How do I structure my initialization logic to properly 'fix' jQuery after my browser window is constructed and still execute the 'require' for Fancytree?

If it is helpful, what I am driving at is simply getting a basic tree visible in my UI in Electron. Preferably without sacrificing Node.js to any 'workarounds' as my hope is to learn more about Node, Angular, and jQuery as part of this experiment.  Generally, I like to avoid hacks/shims/workarounds when learning new technologies.  It feels like you are already 'doing it wrong'.

As always, any help is most appreciated!

答:
If your app does not need node-integration, add "node-integration": false to your BrowserWindow options. In this case module.exports is not available, jQuery works like expected.

And try installing it via npm:

```<code>npm install jquery
</code>```

This worked for me while trying the same. Then you don't need to give a path, you just say:

```<code>mainWindow.$ = mainWindow.jQuery = require('jquery');
console.log( [$, jQuery ]);

fancytree = require('jquery.fancytree');
</code>```

Title: Electron error: jQuery is not defined

Body:
Ok, I apologize that this question is a duplicate, as I found my exact question asked and answered here: Electron: jQuery is not defined.  Unfortunately, I'm too much of a noob to wrap my head around the answer.

I've been programming desktop apps for a long time(TM), so I'm not new to programming or development, but Electron, Node.js, JavaScript, Angular, et al. are a new domain for me and I'm still pretty green.

I was able to install node and get the basics of npm figured out.  After that, I used npm to install electron, jQuery, and a treeview package called FancyTree (specifically version 2.24 as 2.26 seems to have an unrelated issue).

Now, following along with some basic Electron tutorials, my index.js looks like this:

const electron = require('electron');
const url = require('url');
const path = require('path');
const fs = require('fs');
const { app, BrowserWindow } = electron;

let mainWindow;

app.on('ready', function() {

    mainWindow = new BrowserWindow({ });

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'mainWindow.html'),
        protocol: 'file:',
        slashes: true
    }));

});

I grasp that this is simply creating my main browser window during the 'ready' event handler, and navigating to my corresponding html, which looks like this:

<!DOCTYPE html>

    <title>Getting my Feet Wet</title>

My feet are wet.  Weird.

Nothing exciting so far.

But now I install jQuery and Fancytree using npm and I try to 'require' fancytree (just after the line for fs) like this:

const fancytree = require('jquery.fancytree');

which doesn't work.  After some googling, it appears that (for reasons I don't completely understand) it is better to 'require' fancytree like this:

const fancytree = require('jquery.fancytree/dist/jquery.fancytree.js');

For now, I'm willing to accept that without fully understanding the 'why'.

But I'm still throwing an error:

App threw an error during load ReferenceError: jQuery is not defined
      at Object. (C:\Scratch\QuickStart\node_modules\jquery.fancytree\dist\jquery.fancytree.js:5249:3)
  etc.

This seems to stem from the fact that Electron's use of Node.js defines some 'global-ish' references that conflict with various packages expectations.  Electron seems to outline one solution as passing the nodeIntegration: parameter as false when constructing the new browser window, which I tried without any joy.

The other answers all deal with various script blocks in the html, which makes no sense to me at all because it creates an order-of-operation problem.  For example, the statement to 'require' Fancytree will execute before my 'ready' event, which means it would happen well before the browser window is constructed, which would be long before any script blocks are run in the html; so that can't possibly work.

Thinking procedurally for a moment, I would expect my index.js to look more like this (presented in pseudo-code):

const electron = require('electron');
const url = require('url');
const path = require('path');
const fs = require('fs');

const fancytree; //this obviously isn't valid

const { app, BrowserWindow } = electron;

let mainWindow;

app.on('ready', function() {

    mainWindow = new BrowserWindow({ });

    //I hijacked this from the original Q/A on stack but don't
    //completely understand what it's doing, or if it's even
    //legit, but the idea is to fix the mainWindow / jQuery
    //reference now that the window is constructed but before
    //I try to require the FancyTree.
    //
    mainWindow.$ = mainWindow.jQuery = require('jquery');

    //And now that jQuery is sorted out it's marbles, let's get back
    //to business...
    //
    fancytree = require('jquery.fancytree/dist/jquery.fancytree.js');

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'mainWindow.html'),
        protocol: 'file:',
        slashes: true
    }));

});

Obviously this is wrong, and I'm displaying my lack of depth of understanding with these technologies, but what should this look like?  How do I structure my initialization logic to properly 'fix' jQuery after my browser window is constructed and still execute the 'require' for Fancytree?

If it is helpful, what I am driving at is simply getting a basic tree visible in my UI in Electron. Preferably without sacrificing Node.js to any 'workarounds' as my hope is to learn more about Node, Angular, and jQuery as part of this experiment.  Generally, I like to avoid hacks/shims/workarounds when learning new technologies.  It feels like you are already 'doing it wrong'.

As always, any help is most appreciated!

Body:
If your app does not need node-integration, add "node-integration": false to your BrowserWindow options. In this case module.exports is not available, jQuery works like expected.

And try installing it via npm:

npm install jquery

This worked for me while trying the same. Then you don't need to give a path, you just say:

mainWindow.$ = mainWindow.jQuery = require('jquery');
console.log( [$, jQuery ]);

fancytree = require('jquery.fancytree');


问:
TF tflite toco: Unsupported operator: Pad
```<code>$ bazel-bin/tensorflow/contrib/lite/toco/toco     --input_file=resnet_v2_152/model.pb     --input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE     --output_file=resnet_v2_152/model.tflite     --inference_type=FLOAT  --input_type=FLOAT --input_arrays=input     --output_arrays=resnet_v2_152/predictions/Reshape_1   --input_shapes=1,224,224,3
======================================================
2017-12-07 21:53:10.782352: W tensorflow/contrib/lite/toco/toco_cmdline_flags.cc:177] --input_type is deprecated. Use --inference_input_type.
2017-12-07 21:53:11.357279: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before general graph transformations: 2003 operators, 2977 arrays (0 quantized)
2017-12-07 21:53:11.745847: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] After general graph transformations pass 1: 319 operators, 739 arrays (0 quantized)
2017-12-07 21:53:11.749607: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before dequantization graph transformations: 319 operators, 739 arrays (0 quantized)
2017-12-07 21:53:11.751028: I tensorflow/contrib/lite/toco/allocate_transient_arrays.cc:312] Total transient array allocated size: 11239424 bytes, theoretical optimal value: 9633792 bytes.
2017-12-07 21:53:11.752708: I tensorflow/contrib/lite/toco/toco_tooling.cc:264] Estimated count of arithmetic ops: 21.8689 billion (note that a multiply-add is counted as 2 ops).
2017-12-07 21:53:11.753937: F tensorflow/contrib/lite/toco/tflite/export.cc:192] Unsupported operator: Pad
Aborted (core dumped)
</code>```

答:
Pad is not supported by TensorFlow Lite yet. The team is working on supporting more ops (including Pad) now. Hopefully it will work in the near future.

Please refer to this doc to see the current ops compatibility.


问:
When NOT to use Cassandra?
There has been a lot of talk related to Cassandra lately.

Twitter, Digg, Facebook, etc all use it.

When does it make sense to:

use Cassandra,

not use Cassandra, and

use a RDMS instead of Cassandra.

答:
Apache cassandra is a distributed database for managing large amounts of structured data across many commodity servers, while providing highly available service and no single point of failure.

The archichecture is purely based on the cap theorem, which is availability , and partition tolerance, and interestingly eventual consistently.

Dont Use it, if your not storing volumes of data across racks of clusters,
  Dont use if you are not storing Time series data,
  Dont Use if you not patitioning your servers,
  Dont use if you require strong Consistency.

Title: When NOT to use Cassandra?


问:
How to install spring boot CLI on Mac?
I am trying to install the Spring Boot CLI. I followed the instructions from the website. (https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-installing-spring-boot.html) The error I am getting is:

$ spring --version
rbenv: spring: command not found

The `spring' command exists in these Ruby versions:
  2.4.0

I ran all the brew and bundle installs, but I am still running into issues. Any suggestions?

答: You can use sdkman http://sdkman.io/ I cannot submit such a short answer so added more text...</p>

Title: How to install spring boot CLI on Mac?


问:
Grouping elements of a character vector by the first n letters that match each other
Goal: I want to find a way to group a character vector like:

```<code>x <- c("a800k blue 5", "a800j", "bb-blah5", "a800 7", "bb-blah2", "bb-blah3")
</code>```

into groups with sort of "lead matches" that give the minimum elements so that they would be called in a grep search. So the solution to the toy example above would be:

```<code>solution <- c("a800", "bb-blah")
</code>```

because a grep search of x using the pattern "a800" would yield all 3 elements that start with "a800."

Note: I can make very few assumptions about the character strings that will be contained in the vector. There will be lengths varying between just a few and quite long strings (possibly 10 or more), containing combinations of numbers, letters, spaces, and some special characters that make life very difficult.

So I would love a function that works something like intersect, maybe, but on each individual string.
Any thoughts?

答:
There may be more elegant (efficient) ways, but this works on your sample strings. The longest common prefix is calculated (Biobase::lcPrefixC*) on pairwise combinations (combn) of strings.

```<code>source("https://bioconductor.org/biocLite.R")
biocLite("Biobase")

unique(combn(seq_along(x), 2, FUN = function(cm) lcPrefixC(x[cm])))
# [1] "a800"    ""        "bb-blah"
</code>```

It's unclear if you are trading between length of prefix and size of groups. For example:

```<code>x <- c("1234", "1235", "1245", "1246")
</code>```

Would you rather have one larger group with a shorter prefix ("12"), or two smaller groups with with longer prefix ("123" and "124")?

*"lcPrefixC is a faster implementation in C. [But note that] It only handles ascii characters". See also lcPrefix.

Body:
Goal: I want to find a way to group a character vector like:

x <- c("a800k blue 5", "a800j", "bb-blah5", "a800 7", "bb-blah2", "bb-blah3")

into groups with sort of "lead matches" that give the minimum elements so that they would be called in a grep search. So the solution to the toy example above would be:

solution <- c("a800", "bb-blah")

because a grep search of x using the pattern "a800" would yield all 3 elements that start with "a800."

Note: I can make very few assumptions about the character strings that will be contained in the vector. There will be lengths varying between just a few and quite long strings (possibly 10 or more), containing combinations of numbers, letters, spaces, and some special characters that make life very difficult.

So I would love a function that works something like intersect, maybe, but on each individual string.
Any thoughts?

Body:
There may be more elegant (efficient) ways, but this works on your sample strings. The longest common prefix is calculated (Biobase::lcPrefixC*) on pairwise combinations (combn) of strings.

source("https://bioconductor.org/biocLite.R")
biocLite("Biobase")

unique(combn(seq_along(x), 2, FUN = function(cm) lcPrefixC(x[cm])))
# [1] "a800"    ""        "bb-blah"

It's unclear if you are trading between length of prefix and size of groups. For example:

x <- c("1234", "1235", "1245", "1246")

Would you rather have one larger group with a shorter prefix ("12"), or two smaller groups with with longer prefix ("123" and "124")?

*"lcPrefixC is a faster implementation in C. [But note that] It only handles ascii characters". See also lcPrefix.


问:
Fastest way to perform calculation between two dataframe colums?
I have a pandas dataframe with 6 million rows. The columns are:

```<code>['x', 'y']
</code>```

I need to apply a simple calculation between x an y, and append it to the dataframe.

This is what I've tried:

```<code>'''
Calculates the height of a pressure level in feet
'''
def pressure_to_elevation(P, T = None):

    sea_level_pressure = 1013.25

    if T is not None:
        # https://www.omnicalculator.com/physics/air-pressure-at-altitude

        P0 = sea_level_pressure
        g = 9.80665
        M = 0.0289644
        R0 = 8.31447

        m = (np.log(P/P0)*T) / -(g*M/R0)
        f = 3.28084 * m
        return f

    b = 0.190284
    c = 145366.45

    return (1-math.pow((P/sea_level_pressure), b)) * c

test_df['result'] = test_fd.apply(lambda row: pressure_to_elevation(row['x'], row['y']),axis=1)
</code>```

Unfortunately, this takes a ridiculous amount of time... in fact, I've yet to see it complete.

Is there a faster way to do this?

答:
I believe if you break this out into separate steps and avoid iterating through the entire dataframe, the speed will increase dramatically.  Give the following a shot.</p>

```<code>test_df['result_1'] = (test_df['x']/sea_level_pressure)
test_df['result_1'] = test_df['result']**0.190284
test_df['result_1'] = (1 - test_df['result'])*145366.45

test_df['result_2'] = 3.28084*((np.log(test_df['x']/sea_level_pressure)*test_df['y'])/(-1*(9.80665*0.0289644/8.31447)))

test_df['final_result'] = np.where(pd.isnull(test_df['y']), test_df['result_1'], test_df['result_2'])
</code>```

Body:
I have a pandas dataframe with 6 million rows. The columns are:

['x', 'y']

I need to apply a simple calculation between x an y, and append it to the dataframe.

This is what I've tried:

'''
Calculates the height of a pressure level in feet
'''
def pressure_to_elevation(P, T = None):

    sea_level_pressure = 1013.25

    if T is not None:
        # https://www.omnicalculator.com/physics/air-pressure-at-altitude

        P0 = sea_level_pressure
        g = 9.80665
        M = 0.0289644
        R0 = 8.31447

        m = (np.log(P/P0)*T) / -(g*M/R0)
        f = 3.28084 * m
        return f

    b = 0.190284
    c = 145366.45

    return (1-math.pow((P/sea_level_pressure), b)) * c

test_df['result'] = test_fd.apply(lambda row: pressure_to_elevation(row['x'], row['y']),axis=1)

Unfortunately, this takes a ridiculous amount of time... in fact, I've yet to see it complete.

Is there a faster way to do this?

Body:
I believe if you break this out into separate steps and avoid iterating through the entire dataframe, the speed will increase dramatically.  Give the following a shot.

test_df['result_1'] = (test_df['x']/sea_level_pressure)
test_df['result_1'] = test_df['result']**0.190284
test_df['result_1'] = (1 - test_df['result'])*145366.45

test_df['result_2'] = 3.28084*((np.log(test_df['x']/sea_level_pressure)*test_df['y'])/(-1*(9.80665*0.0289644/8.31447)))

test_df['final_result'] = np.where(pd.isnull(test_df['y']), test_df['result_1'], test_df['result_2'])


问:
Connecting and manuplating data on an access database?
I'm working on my thesis project with Windows Phone 7. I'm developing an application requires store data in a database, my thesis supervisor said an Microsoft Access database is enough for this step, because I'm newbie at developing applications for Windows Phone 7.

How can i do that?

答:
Unfortunately I cannot remember the details, but I saw a fairly recent presentation on integrating Sharepoint, Access and the Windows phone.

EDIT

I just found this video:

http://pocketnow.com/windows-phone/sharepoint-office-2010-on-windows-phone-7


问:
Angular5 ParamMap and HttpClient
How can I get ParamMap to work with the HttpClient via a service in Angular5?

Component

```<code>// importing the service, ActivatedRoute, ParamMap, switchMap, etc

public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }

ngOnInit() {
    this.value = this.activatedRouter.paramMap
    .switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
  }
</code>```

Service

```<code>import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
    return this.httpClient.get(`http://my.api/${id}`);
  }
</code>```

At the moment if I do console.log(this.value) in my component I get a AnonymousSubject.

The question is, how can I use ParamMap and get the value from the HttpClient? I know I could use a router snapshot - which I have done and it works but I'd like to get this example working as well.

答:
You need subscribe() to get the data. it's in the subscribe where you get the data </p>

```<code>ngOnInit() {
   this.activatedRouter.paramMap
   .switchMap((params: ParamMap) =>
      this.myService.getOne(params.get('id'))).subscribe((data:any)=>{
           this.value=data
   });
 }
</code>```

Title: Angular5 ParamMap and HttpClient

Body:
How can I get ParamMap to work with the HttpClient via a service in Angular5?

Component

// importing the service, ActivatedRoute, ParamMap, switchMap, etc

public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }

ngOnInit() {
    this.value = this.activatedRouter.paramMap
    .switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
  }

Service

import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
    return this.httpClient.get(`http://my.api/${id}`);
  }

At the moment if I do console.log(this.value) in my component I get a AnonymousSubject.

The question is, how can I use ParamMap and get the value from the HttpClient? I know I could use a router snapshot - which I have done and it works but I'd like to get this example working as well.

Body:
You need subscribe() to get the data. it's in the subscribe where you get the data

ngOnInit() {
   this.activatedRouter.paramMap
   .switchMap((params: ParamMap) =>
      this.myService.getOne(params.get('id'))).subscribe((data:any)=>{
           this.value=data
   });
 }


问:
Adaptivecard with 2 actions (Accept/Decline)
Can someone help how to handle 2 submit actions in an adaptive card?
If the user clicks on the acceptbutton, another dialog must start.
If the user clicks on the declinebutton, the restart dialog has to start.

The json layout

```<code>        "actions": [
        {
            "type": "Action.Submit",
            "title": "Accept",
            "data": { "choice": "Accept"}
        },
        {
            "type": "Action.Submit",
            "title": "Decline",
            "data": { "choice": "Decline"}
        }
    ]
</code>```

Code:

```<code>bot.dialog('overview', function (session, options) {
    if (session.message && session.message.value) {
        if(choice == "Accept"){
            session.beginDialog('otherDialog');
        } else if (choice == "Decline"){
            session.beginDialog('restart');
        }
        return;
    }
</code>```

答:
choice will be a property on .value

```<code>bot.dialog('overview', function (session, options) {
    if (session.message && session.message.value) {
        session.endDialog();
        switch (session.message.value.choice) {
            case 'Accept':
                session.beginDialog('otherDialog');
                break;
            case 'Decline':
                session.beginDialog('restart');
                break;
          }
        return;
    }else{
        //show the card, since there has not been a choice
        var cardMessage  = require('./overviewCard.json');
        cardMessage.address = session.message.address
        bot.send(cardMessage)
    }
})
</code>```

Body:
Can someone help how to handle 2 submit actions in an adaptive card?
If the user clicks on the acceptbutton, another dialog must start.
If the user clicks on the declinebutton, the restart dialog has to start.

The json layout

        "actions": [
        {
            "type": "Action.Submit",
            "title": "Accept",
            "data": { "choice": "Accept"}
        },
        {
            "type": "Action.Submit",
            "title": "Decline",
            "data": { "choice": "Decline"}
        }
    ]

Code:

bot.dialog('overview', function (session, options) {
    if (session.message && session.message.value) {
        if(choice == "Accept"){
            session.beginDialog('otherDialog');
        } else if (choice == "Decline"){
            session.beginDialog('restart');
        }
        return;
    }

Body:
choice will be a property on .value

bot.dialog('overview', function (session, options) {
    if (session.message && session.message.value) {
        session.endDialog();
        switch (session.message.value.choice) {
            case 'Accept':
                session.beginDialog('otherDialog');
                break;
            case 'Decline':
                session.beginDialog('restart');
                break;
          }
        return;
    }else{
        //show the card, since there has not been a choice
        var cardMessage  = require('./overviewCard.json');
        cardMessage.address = session.message.address
        bot.send(cardMessage)
    }
})


问:
Fastest way to zero out a range of positions of an array?
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

```<code>ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;
</code>```

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?

答:
memset can do the job.
See the illustrative example where 14 elements are zeroed.

```<code>#include <stdio.h>
#include <string.h> // for memset

void print_array(unsigned long *array, int len)
{
    int i;
    for (i = 0; i<len; i++ )
    {
         printf("%lu ", array[i]);
    };

    printf("\n");
}

int main()
{
     unsigned long st[25];

    // initialize all elements in the table (25 of them)
    for(int i = 0; i < 25; ++i)
        st[i] = i;

    // Assign zeroes from position 10 to position 24 (14 zeroes)
    // Note: The last position of the st[] table is not zeroed on purpose!

    // remember of the type of the array `sizeof(unsigned long)`:
    memset( st+10, 0, 14*sizeof(unsigned long) );

    print_array(st, 25);

    return 0;
}
</code>```

OUTPUT:

```<code>0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24
</code>```

Assembly for both cases x86-64 gcc 7.2 (no optimization!):

```<code>int main()
{
    unsigned long st[25];
    memset( st+10, 0, 15*sizeof(unsigned long) );
    return 0;
}

  main:
  push rbp
  mov rbp, rsp
  sub rsp, 208
  lea rax, [rbp-208]
  add rax, 80
  mov edx, 120
  mov esi, 0
  mov rdi, rax
  call memset
  mov eax, 0
  leave
  ret

int main()
{
    unsigned long st[25];
    for(int i = 10; i < 25; ++i) st[i] = 0;
    return 0;
}
  main:
  push rbp
  mov rbp, rsp
  sub rsp, 88
  mov DWORD PTR [rbp-4], 10
.L3:
  cmp DWORD PTR [rbp-4], 24
  jg .L2
  mov eax, DWORD PTR [rbp-4]
  cdqe
  mov QWORD PTR [rbp-208+rax*8], 0
  add DWORD PTR [rbp-4], 1
  jmp .L3
.L2:
  mov eax, 0
  leave
  ret
</code>```

Body:
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?

Body:
memset can do the job.
See the illustrative example where 14 elements are zeroed.

#include <stdio.h>
#include <string.h> // for memset

void print_array(unsigned long *array, int len)
{
    int i;
    for (i = 0; i<len; i++ )
    {
         printf("%lu ", array[i]);
    };

    printf("\n");
}

int main()
{
     unsigned long st[25];

    // initialize all elements in the table (25 of them)
    for(int i = 0; i < 25; ++i)
        st[i] = i;

    // Assign zeroes from position 10 to position 24 (14 zeroes)
    // Note: The last position of the st[] table is not zeroed on purpose!

    // remember of the type of the array `sizeof(unsigned long)`:
    memset( st+10, 0, 14*sizeof(unsigned long) );

    print_array(st, 25);

    return 0;
}

OUTPUT:

0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24

Assembly for both cases x86-64 gcc 7.2 (no optimization!):

int main()
{
    unsigned long st[25];
    memset( st+10, 0, 15*sizeof(unsigned long) );
    return 0;
}

  main:
  push rbp
  mov rbp, rsp
  sub rsp, 208
  lea rax, [rbp-208]
  add rax, 80
  mov edx, 120
  mov esi, 0
  mov rdi, rax
  call memset
  mov eax, 0
  leave
  ret

int main()
{
    unsigned long st[25];
    for(int i = 10; i < 25; ++i) st[i] = 0;
    return 0;
}
  main:
  push rbp
  mov rbp, rsp
  sub rsp, 88
  mov DWORD PTR [rbp-4], 10
.L3:
  cmp DWORD PTR [rbp-4], 24
  jg .L2
  mov eax, DWORD PTR [rbp-4]
  cdqe
  mov QWORD PTR [rbp-208+rax*8], 0
  add DWORD PTR [rbp-4], 1
  jmp .L3
.L2:
  mov eax, 0
  leave
  ret


问:
kafka stream processor api Global state store multiple topics
I am trying to create a kafka stream using processor api as i have custom process. I faced an issue when my processor was listning to multiple topics with different number of partitions. I realized i need to create a global state store.
I need to know how to be able to add a processor and also add a global state store while that listens to multiple topics?

Any code examples or links will help.
Thank You!!

答:
A global state store can only read from a single topic. But you can create one global store per topic. Also, global stores don't need to be added to any processor and can be access by all processor automatically.

Our examples repo should help: https://github.com/confluentinc/kafka-streams-examples

Also check out the docs: http://docs.confluent.io/current


问:
How can I get only 1 result to be printed to the console and not both of them?

My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

```<code>keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)
</code>```

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

```<code>Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print
</code>```

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

Body:
My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

Body:
Generate the modified grades and add them to the dictionary. Then look up the entire grade string.

>>> keydict = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0}
>>> modifiers = {'+': 0.3, '-': -0.3}
>>> keydict.update({ k + mk: v + mv for k, v in keydict.items() for mk, mv in modifiers.items() })
>>> keydict
{'D': 1.0, 'F+': 0.3, 'A+': 4.3, 'F': 0, 'F-': -0.3, 'C+': 2.3, 'B': 3.0, 'C': 2.0, 'D-': 0.7, 'C-': 1.7, 'B-': 2.7, 'D+': 1.3, 'B+': 3.3, 'A-': 3.7, 'A': 4.0}
>>> grade = 'C-'
>>> keydict[grade]
1.7


问:
How do I map true/false/unknown to -1/0/null without repetition?
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

```<code>select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;
</code>```

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

```<code>select A.x and exists (select * from B where B.y=A.y) from A;
</code>```

答:
Boolean handling

Access seems to use the logic that given 2 booleans

Both have to be true to return true

Either being false returns false (regardless of nulls)

Otherwise return null

I'm not sure if this is how other DBMS (Oracle, DB2, PostgreSQL) deal with bool+null, but this answer is based on the Access determination (MySQL and SQLite agree).  The table of outcomes is presented below.

```<code>X      Y      A.X AND B.Y
0      0      0
0      -1     0
0      (null) 0
-1     0      0
-1     -1     -1
-1     (null) (null)
(null) 0      0
(null) -1     (null)
(null) (null) (null)
</code>```

SQL Server helper 1: function for boolean from any "single value"

In SQL Server in general, this function will fill the gap for the missing any value as boolean functionality.  It returns a ternary result, either 1/0/null - 1 and 0 being the SQL Server equivalent of true/false (without actually being boolean).

```<code>drop function dbo.BoolFromAny
GO
create function dbo.BoolFromAny(@v varchar(max)) returns bit as
begin
return (case
    when @v is null then null
    when isnumeric(@v) = 1 and @v like '[0-9]%' and (@v * 1.0 = 0) then 0
    else 1 end)
end
GO
</code>```

Note: taking Access as a starting point, only the numeric value 0 evaluates to FALSE
This uses some SQL Server tricks

everything is convertible to varchar. Therefore only one function taking varchar input is required.

isnumeric is not comprehensive, '.' returns 1 for isnumeric but will fail at @v * 1.0, so an explicit test for LIKE [0-9]%`` is required to "fix" isnumeric.

@v * 1.0 is required to overcome some arithmetic issues. If you pass the string "1" into the function without *1.0, it will bomb

Now we can test the function.

```<code>select dbo.BoolFromAny('abc')
select dbo.BoolFromAny(1)
select dbo.BoolFromAny(0)  -- the only false
select dbo.BoolFromAny(0.1)
select dbo.BoolFromAny(-1)
select dbo.BoolFromAny('')
select dbo.BoolFromAny('.')
select dbo.BoolFromAny(null)  -- the only null
</code>```

You can now safely use it in a query against ANY SINGLE COLUMN, such as

```<code>SELECT dbo.BoolFromAny(X) = 1
</code>```

SQL Server helper 2: function to return result of BOOL AND BOOL

Now the next part is creating the same truth table in SQL Server.  This query shows you how two bit columns interact and the simple CASE statement to produce the same table as Access and your more complicated one.

```<code>select a.a, b.a,
  case
  when a.a = 0 or b.a = 0 then 0
  when a.a = b.a then 1
  end
from
(select 1 A union all select 0 union all select null) a,
(select 1 A union all select 0 union all select null) b
order by a.a, b.a
</code>```

This is easily expressed as a function

```<code>create function dbo.BoolFromBits(@a bit, @b bit) returns bit as
begin
  return case
    when @a = 0 or @b = 0 then 0
    when @a = @b then 1
    end
end
</code>```

SQL Server conversion of other expressions (not of a single value)

Due to lack of support for bit-from-boolean conversion, expressions that are already [true/false/null] in SQL Server require repetition in a CASE statement.

An example is a "true boolean" in SQL Server, which cannot be the result for a column.

```<code>select A > B -- A=B resolves to one of true/false/null
from C
</code>```

Needs to be expressed as

```<code>select case when A is null or B is null then null when A > B then 1 else 0 end
from C
</code>```

But if A is not a scalar value but a subquery like (select sum(x)...), then as you can see A will appear twice and be evaluated twice in the CASE statement (repeated).

FINAL TEST
Now we put all the conversion rules to use in this long expression

```<code>SELECT X AND Y=Z AND C FROM ..
( assume X is numeric 5, and C is varchar "H" )
( note C contributes either TRUE or NULL in Access )
</code>```

This translates to SQL Server (chaining the two functions and using CASE)

```<code>SELECT dbo.BoolFromBits(
       dbo.BoolFromBits(dbo.BoolFromAny(X), CASE WHEN Y=Z then 1 else 0 end),
                       dbo.BoolFromAny(C))
FROM ...
</code>```

Access Bool or bool

For completeness, here is the truth table for Access bool OR bool.  Essentially, it is the opposite of AND, so

Both have to be false to return false

Either being true returns true (regardless of nulls)

Otherwise return null

The SQL SERVER case statement would therefore be

```<code>  case
  when a.a = 1 or b.a = 1 then 1
  when a.a = b.a then 0
  end
</code>```

(the omission of an ELSE clause is intentional as the result is NULL when omitted)

Body:
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

select A.x and exists (select * from B where B.y=A.y) from A;

Body:
Boolean handling

Access seems to use the logic that given 2 booleans

Both have to be true to return true

Either being false returns false (regardless of nulls)

Otherwise return null

I'm not sure if this is how other DBMS (Oracle, DB2, PostgreSQL) deal with bool+null, but this answer is based on the Access determination (MySQL and SQLite agree).  The table of outcomes is presented below.

X      Y      A.X AND B.Y
0      0      0
0      -1     0
0      (null) 0
-1     0      0
-1     -1     -1
-1     (null) (null)
(null) 0      0
(null) -1     (null)
(null) (null) (null)

SQL Server helper 1: function for boolean from any "single value"

In SQL Server in general, this function will fill the gap for the missing any value as boolean functionality.  It returns a ternary result, either 1/0/null - 1 and 0 being the SQL Server equivalent of true/false (without actually being boolean).

drop function dbo.BoolFromAny
GO
create function dbo.BoolFromAny(@v varchar(max)) returns bit as
begin
return (case
    when @v is null then null
    when isnumeric(@v) = 1 and @v like '[0-9]%' and (@v * 1.0 = 0) then 0
    else 1 end)
end
GO

Note: taking Access as a starting point, only the numeric value 0 evaluates to FALSE
This uses some SQL Server tricks

everything is convertible to varchar. Therefore only one function taking varchar input is required.

isnumeric is not comprehensive, '.' returns 1 for isnumeric but will fail at @v * 1.0, so an explicit test for LIKE [0-9]%`` is required to "fix" isnumeric.

@v * 1.0 is required to overcome some arithmetic issues. If you pass the string "1" into the function without *1.0, it will bomb

Now we can test the function.

select dbo.BoolFromAny('abc')
select dbo.BoolFromAny(1)
select dbo.BoolFromAny(0)  -- the only false
select dbo.BoolFromAny(0.1)
select dbo.BoolFromAny(-1)
select dbo.BoolFromAny('')
select dbo.BoolFromAny('.')
select dbo.BoolFromAny(null)  -- the only null

You can now safely use it in a query against ANY SINGLE COLUMN, such as

SELECT dbo.BoolFromAny(X) = 1

SQL Server helper 2: function to return result of BOOL AND BOOL

Now the next part is creating the same truth table in SQL Server.  This query shows you how two bit columns interact and the simple CASE statement to produce the same table as Access and your more complicated one.

select a.a, b.a,
  case
  when a.a = 0 or b.a = 0 then 0
  when a.a = b.a then 1
  end
from
(select 1 A union all select 0 union all select null) a,
(select 1 A union all select 0 union all select null) b
order by a.a, b.a

This is easily expressed as a function

create function dbo.BoolFromBits(@a bit, @b bit) returns bit as
begin
  return case
    when @a = 0 or @b = 0 then 0
    when @a = @b then 1
    end
end

SQL Server conversion of other expressions (not of a single value)

Due to lack of support for bit-from-boolean conversion, expressions that are already [true/false/null] in SQL Server require repetition in a CASE statement.

An example is a "true boolean" in SQL Server, which cannot be the result for a column.

select A > B -- A=B resolves to one of true/false/null
from C

Needs to be expressed as

select case when A is null or B is null then null when A > B then 1 else 0 end
from C

But if A is not a scalar value but a subquery like (select sum(x)...), then as you can see A will appear twice and be evaluated twice in the CASE statement (repeated).

FINAL TEST
Now we put all the conversion rules to use in this long expression

SELECT X AND Y=Z AND C FROM ..
( assume X is numeric 5, and C is varchar "H" )
( note C contributes either TRUE or NULL in Access )

This translates to SQL Server (chaining the two functions and using CASE)

SELECT dbo.BoolFromBits(
       dbo.BoolFromBits(dbo.BoolFromAny(X), CASE WHEN Y=Z then 1 else 0 end),
                       dbo.BoolFromAny(C))
FROM ...

Access Bool or bool

For completeness, here is the truth table for Access bool OR bool.  Essentially, it is the opposite of AND, so

Both have to be false to return false

Either being true returns true (regardless of nulls)

Otherwise return null

The SQL SERVER case statement would therefore be

  case
  when a.a = 1 or b.a = 1 then 1
  when a.a = b.a then 0
  end

(the omission of an ELSE clause is intentional as the result is NULL when omitted)


问:
Is there a better way to make this queryset using Q? django
I have a query which uses filter but I know there is this thing called Q but trying to play around with it, I am not sure how I can use Q.  I am not sure which one would be better but trying to know another way to do the query.

What I actually want to do is...
for my queryset return I have a default field and two input fields which are options.

let's say, language in default is english, there is a location and title field.  If location and title fields are available, make a query to query location, title, and language.  If only location then only query location and language, if only title then only query title and language.

I have done it two ways, one with filter only which has less code...

```<code>    postings = Posting.objects.filter(language='EN')
    if kwargs.get('title'):
        postings = postings.filter(title__icontains=kwargs.get('title'))
    if kwargs.get('location'):
        postings = postings.filter(location__icontains=kwargs.get('location'))
</code>```

the above does work with using only filter

I am trying to see if I can do it with using Q but cannot seem to make it work

I have something like this at the moment

```<code>    if title and location:
        postings = Posting.objects.filter(title__icontains=title, location__icontains=location, language='EN')
    else:
        queryQ = Q(posting_language='EN')
        if title:
            queryQ |= Q(title__icontains=title)
        if location:
            queryQ |= Q(location__icontains=location)

        postings = Posting.objects.filter(queryQ)
</code>```

can someone please give me a hand?
Thanks in advance

答:
I think you've misunderstood what Q is for. Q is mostly used in django for more complex query statements that require OR/AND.

So, you could do something like this:

```<code>postings = Posting.objects.filter(Q(title__icontain=title) | Q(location=location))
</code>```

This will give you all the postings where title contains the title OR the location contains the location. It's not very useful in this context because icontains will fail with a Null value and return everything for an empty string value.

Q would be very useful if you needed postings for titles that used two different icontains

```<code>postings = Posting.objects.filter(Q(title__icontains=search_term_a) & Q(title__icontains=search_term_b))
</code>```

Body:
I have a query which uses filter but I know there is this thing called Q but trying to play around with it, I am not sure how I can use Q.  I am not sure which one would be better but trying to know another way to do the query.

What I actually want to do is...
for my queryset return I have a default field and two input fields which are options.

let's say, language in default is english, there is a location and title field.  If location and title fields are available, make a query to query location, title, and language.  If only location then only query location and language, if only title then only query title and language.

I have done it two ways, one with filter only which has less code...

    postings = Posting.objects.filter(language='EN')
    if kwargs.get('title'):
        postings = postings.filter(title__icontains=kwargs.get('title'))
    if kwargs.get('location'):
        postings = postings.filter(location__icontains=kwargs.get('location'))

the above does work with using only filter

I am trying to see if I can do it with using Q but cannot seem to make it work

I have something like this at the moment

    if title and location:
        postings = Posting.objects.filter(title__icontains=title, location__icontains=location, language='EN')
    else:
        queryQ = Q(posting_language='EN')
        if title:
            queryQ |= Q(title__icontains=title)
        if location:
            queryQ |= Q(location__icontains=location)

        postings = Posting.objects.filter(queryQ)

can someone please give me a hand?
Thanks in advance

Body:
I think you've misunderstood what Q is for. Q is mostly used in django for more complex query statements that require OR/AND.

So, you could do something like this:

postings = Posting.objects.filter(Q(title__icontain=title) | Q(location=location))

This will give you all the postings where title contains the title OR the location contains the location. It's not very useful in this context because icontains will fail with a Null value and return everything for an empty string value.

Q would be very useful if you needed postings for titles that used two different icontains

postings = Posting.objects.filter(Q(title__icontains=search_term_a) & Q(title__icontains=search_term_b))


答:
Firstly, | is for ORing Q objects. You want & for ANDing them.

You could rewrite your filter code as:

```<code>queryQ = Q(posting_language='EN')
if title:
    queryQ &= Q(title__icontains=title)
if location:
    queryQ &= Q(location__icontains=location)

postings = Posting.objects.filter(queryQ)
</code>```

However I don't see any real advantage of this. Personally I think your original code is more readable.

Title: Is there a better way to make this queryset using Q? django

Body:
Firstly, | is for ORing Q objects. You want & for ANDing them.

You could rewrite your filter code as:

queryQ = Q(posting_language='EN')
if title:
    queryQ &= Q(title__icontains=title)
if location:
    queryQ &= Q(location__icontains=location)

postings = Posting.objects.filter(queryQ)

However I don't see any real advantage of this. Personally I think your original code is more readable.