问:
Color changeable SVG?
I wish to build a website where icon colors can be easily changed with the only change of the css. I've been given a set of custom icons in form of svg files.

I've already experimented with background color, filters and alike (see https://codesandbox.io/s/exciting-montalcini-xfufu?file=/index.html).

Which is the best technique to use? Should I generate a font from the SVGs?

答:
Generating a custom icon font would property be the best idea, since you have the fastest implementation in your HTML markup and don't have to care about embedding images again an again anymore.

https://icomoon.io is a great generator when you are looking for a helper software to generate your font.

Title: Color changeable SVG?


来源: stackexchange

问:
Find specific word and print till newline in Python
I have a string and I want to match something that start with specific word and end with newline. How can this be done?

```<code>Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/
</code>```

I want to extract [Website,Product,TM Link,Other Link] and save this in a CSV.
I am new to writing regular expression, I was wondering if anyone had a good solution to this that would be awesome!

答:
No need for regex, two splits do the trick here too

s = """Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/"""

res = [l.split(':')[0] for l in [line for line in s.split('\n')]]

with open('file.csv', 'w') as f:
    f.write(','.join(res))
```
<p>If you want to get the part after the first semicolon:</p>
<pre class="lang-py prettyprint-override"><code>s = """Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/"""

res = [l.split(':', maxsplit=1)[1] for l in [line for line in s.split('\n')]]

with open('file.csv', 'w') as f:
    f.write(','.join(res))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string and I want to match something that start with specific word and end with newline. How can this be done?

Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/

I want to extract [Website,Product,TM Link,Other Link] and save this in a CSV.
I am new to writing regular expression, I was wondering if anyone had a good solution to this that would be awesome!

Body:
No need for regex, two splits do the trick here too

s = """Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/"""

res = [l.split(':')[0] for l in [line for line in s.split('\n')]]

with open('file.csv', 'w') as f:
    f.write(','.join(res))

If you want to get the part after the first semicolon:

s = """Website:https://www.abc1.xyz/
Product:Apparal
TM Link:https://www.abc2.xyz/
Other Link:https://www.abc3.xyz/"""

res = [l.split(':', maxsplit=1)[1] for l in [line for line in s.split('\n')]]

with open('file.csv', 'w') as f:
    f.write(','.join(res))


问:
postgres: sql error while using string interpolation (scala + scalikejdbc)
Here is the query I execute on Postgres from scala using scalikejdbc library which works without any issue

import scalikejdbc._
import java.time.LocalDate
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
  implicit val session: AutoSession.type = AutoSession
  log.info(s"startDate = $startDate, endDate = $endDate")
  log.info(sql"""select * from $startDate""".statement)
  val query =
    sql"""select generate_series(
      |timestamp without time zone '2021-05-01',
      |timestamp without time zone '2021-05-03',
      |'1 day'
      |) as tstamp
      |""".stripMargin
  log.info(s"query = ${query.statement}")
  log.info(s"Parameters = ${query.parameters}")
  query.map(rs => rs.string("tstamp")).list().apply().foreach(x => log.info(s"Date = $x"))
}

//-- Output --
Date = 2021-05-01 00:00:00
Date = 2021-05-02 00:00:00
Date = 2021-05-03 00:00:00

```
<p>But I get error when using string interpolation for date. Here in this case I used <code>${startDate.toString}</code> instead of the string literal <code>2021-05-01</code></p>
<pre class="lang-scala prettyprint-override"><code>...
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
...
      |timestamp without time zone ${startDate.toString},
      |timestamp without time zone '2021-05-03',
...
</code>```

and the error I get is,

```<code>SQL execution failed (Reason: ERROR: syntax error at or near "$1" Position: 53):
select generate_series( timestamp without time zone '2021-05-01',
timestamp without time zone '2021-05-03', '1 day' ) as tstamp
</code>```

What am I missing here?... as the sql statement shown in error is indeed a valid one

答:
This probably looks like a string interpolation bug in scalikejdbc. Modified the query like this, which did work

```<code>...
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
...
      |${startDate.toString}::timestamp,
      |${endDate.toString}::timestamp,
...
</code>```

Body:
Here is the query I execute on Postgres from scala using scalikejdbc library which works without any issue

import scalikejdbc._
import java.time.LocalDate
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
  implicit val session: AutoSession.type = AutoSession
  log.info(s"startDate = $startDate, endDate = $endDate")
  log.info(sql"""select * from $startDate""".statement)
  val query =
    sql"""select generate_series(
      |timestamp without time zone '2021-05-01',
      |timestamp without time zone '2021-05-03',
      |'1 day'
      |) as tstamp
      |""".stripMargin
  log.info(s"query = ${query.statement}")
  log.info(s"Parameters = ${query.parameters}")
  query.map(rs => rs.string("tstamp")).list().apply().foreach(x => log.info(s"Date = $x"))
}

//-- Output --
Date = 2021-05-01 00:00:00
Date = 2021-05-02 00:00:00
Date = 2021-05-03 00:00:00

But I get error when using string interpolation for date. Here in this case I used ${startDate.toString} instead of the string literal 2021-05-01

...
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
...
      |timestamp without time zone ${startDate.toString},
      |timestamp without time zone '2021-05-03',
...

and the error I get is,

SQL execution failed (Reason: ERROR: syntax error at or near "$1" Position: 53):
select generate_series( timestamp without time zone '2021-05-01',
timestamp without time zone '2021-05-03', '1 day' ) as tstamp

What am I missing here?... as the sql statement shown in error is indeed a valid one

Body:
This probably looks like a string interpolation bug in scalikejdbc. Modified the query like this, which did work

...
def getRange(startDate: LocalDate, endDate: LocalDate): Unit =  {
...
      |${startDate.toString}::timestamp,
      |${endDate.toString}::timestamp,
...


问:
Angular D3 tree does not collapse back into its parent
We were able to use this example for Angular here(https://bl.ocks.org/d3noob/1a96af738c89b88723eb63456beb6510) and achieve the collapsible tree diagram. But it's not collapse back into its parent or our click action is not working properly.

Here is my code:
https://stackblitz.com/edit/angular-ivy-acd2yd?file=src/app/app.component.ts

答:
Transform a code from JS to typeScript it's not only Copy+Paste. We need go slower.

First, in typescript we use let or const to have a block-scope instead of var. "var" create a variable global to all the application

After, we needn't put all the code in ngOnInit. We should separate in functions all the code under ngOnInit. We can get off variables and declare outside the ngOnInit

```<code>  treeData:any={...}
  margin = { top: 0, right: 30, bottom: 0, left: 30 };
  duration = 750;

  width: number;
  height: number;
  svg: any;
  root: any;

  i = 0;
  treemap: any;
</code>```

Also we need get off the functions, so we has the functions

```<code>  update(source:any){
      ...
  }
  collapse(d: any) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach((d:any)=>this.collapse(d));
      d.children = null;
    }
  }

  click(d: any) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    this.update(d);
  }

  diagonal(s: any, d: any) {
    const path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

    return path;
  }
</code>```

And transfor all the functions use the flat arrow sintax, so

```<code>    //in stead of use
    .attr('transform', function (d: any) {
      return 'translate(' + source.y0 + ',' + source.x0 + ')';
    })

    //we use
    .attr('transform', (d: any) => {
      return 'translate(' + source.y0 + ',' + source.x0 + ')';
    })
</code>```

And use this. to make reference to the variables of the component.

After all of this, Out ngOnInit becomes like

```<code>ngOnInit(){
    this.svg = d3
      .select('#d3noob')
      .append('svg')
      .attr('viewBox','0 0 900 500')
      .append('g')
      .attr(
        'transform',
        'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
      );

    // declares a tree layout and assigns the size
    this.treemap = d3.tree().size([this.height, this.width]);

    // Assigns parent, children, height, depth
    this.root = d3.hierarchy(this.treeData, (d: any) => {
      return d.children;
    });

    this.root.x0 = this.height / 2;
    this.root.y0 = 0;
    // Collapse after the second level
    this.root.children.forEach((d:any) => {
      this.collapse(d);
    });

    this.update(this.root);
}
</code>```

And the function update

```<code>  update(source: any) {
    // Assigns the x and y position for the nodes
    const treeData = this.treemap(this.root);

    // Compute the new tree layout.
    const nodes = treeData.descendants();
    const links = treeData.descendants().slice(1);

    // Normalize for fixed-depth.
    nodes.forEach((d: any) => {
      d.y = d.depth * 180;
    });

    // ****************** Nodes section ***************************

    // Update the nodes...
    const node = this.svg.selectAll('g.node').data(nodes, (d: any) => {
      return d.id || (d.id = ++this.i);
    });

    // Enter any new modes at the parent's previous position.
    const nodeEnter = node
      .enter()
      .append('g')
      .attr('class', 'node')
      .attr('transform', (d: any) => {
        return 'translate(' + source.y0 + ',' + source.x0 + ')';
      })
      .on('click', (_, d) => this.click(d));

    // Add Circle for the nodes
    nodeEnter
      .append('circle')
      .attr('class', (d:any)=> d._children?'node fill':'node')
      .attr('r', 1e-6)
    // Add labels for the nodes
    nodeEnter
      .append('text')
      .attr('dy', '.35em')

      .attr('x', (d) => {
        return d.children || d._children ? -13 : 13;
      })
      .attr('text-anchor', (d: any) => {
        return d.children || d._children ? 'end' : 'start';
      })
      .text((d) => {
        return d.data.name;
      });
    // UPDATE
    const nodeUpdate = nodeEnter.merge(node);

    // Transition to the proper position for the node
    nodeUpdate
      .transition()
      .duration(this.duration)
      .attr('transform', (d: any) => {
        return 'translate(' + d.y + ',' + d.x + ')';
      });

    // Update the node attributes and style
    nodeUpdate
      .select('circle.node')
      .attr('r', 10)
      .attr('class', (d:any)=> d._children?'node fill':'node')
      .attr('cursor', 'pointer');

    // Remove any exiting nodes
    const nodeExit = node
      .exit()
      .transition()
      .duration(this.duration)
      .attr('transform', (d: any) => {
        return 'translate(' + source.y + ',' + source.x + ')';
      })
      .remove();

    // On exit reduce the node circles size to 0
    nodeExit.select('circle').attr('r', 1e-6);

    // On exit reduce the opacity of text labels
    nodeExit.select('text').style('fill-opacity', 1e-6);

    // ****************** links section ***************************

    // Update the links...
    const link = this.svg.selectAll('path.link').data(links, (d: any) => {
      return d.id;
    });

    // Enter any new links at the parent's previous position.
    const linkEnter = link
      .enter()
      .insert('path', 'g')
      .attr('class', 'link')
      .attr('d', (d: any) => {
        const o = { x: source.x0, y: source.y0 };
        return this.diagonal(o, o);
      });

    // UPDATE
    const linkUpdate = linkEnter.merge(link);

    // Transition back to the parent element position
    linkUpdate
      .transition()
      .duration(this.duration)
      .attr('d', (d: any) => {
        return this.diagonal(d, d.parent);
      });

    // Remove any exiting links
    const linkExit = link
      .exit()
      .transition()
      .duration(this.duration)
      .attr('d', (d: any) => {
        const o = { x: source.x, y: source.y };
        return this.diagonal(o, o);
      })
      .remove();

    // Store the old positions for transition.
    nodes.forEach((d: any) => {
      d.x0 = d.x;
      d.y0 = d.y;
    });
  }
</code>```

See that there're a minor changes because I choose use viewPort to make the svg fill the width of the screen if it's less than 960px and control the class of the "dots" using .css (In the code it was "hardcode" the "fill of the dots")

So, before, when we create the .svg we give value to width and height and now I give value to viewBox"

```<code>this.svg = d3
  .select('#d3noob')
  .append('svg')
  .attr('viewBox','0 0 960 500')
  .append('g')
  .attr(
    'transform',
    'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
  );
</code>```

Finally We create a component instead write the code in the app.component. For this we need some variables was inputs

```<code>  @Input()treeData:any={}

  @Input()margin = { top: 0, right: 30, bottom: 0, left: 30 };
  @Input()duration = 750;
</code>```

The last is give credit to the author using a comment

As I choose the svg was adaptative we need calculate the "margin" to allow the text of the first node was visible. To make this, I create a "visibility:hidden" span with the text of the this node to calculate the "margin". Futhermore, I want that the text was visible, so force the font-size was around 14px creating an observable in the way

```<code>  fontSize=fromEvent(window,'resize').pipe(
    startWith(null),
    map(_=>{
      return window.innerWidth>960?'14px':14*960/window.innerWidth+'px'
    }),
</code>```

The final stackblitz is here (you can compare the code)

Update Really I don't like so much the result

In this stackblitz I improve a bit the code. The diferences are that I change the width,height and viewPort using a function

```<code>  updateSize() {
    this.width = this.wrapper.nativeElement.getBoundingClientRect().width
    this.svg
      .attr('preserveAspectRatio', 'xMidYMid meet')
      .attr('width', '100%')
      .attr('height', this.height + 'px')
      .attr('viewBox', ''+(-this.margin.left)+' 0 ' + this.width  + ' ' + this.height);
  }
</code>```

To avoid "crop" I change the "harcode" space between the nodes

```<code>// Normalize for fixed-depth.
nodes.forEach((d: any) => {
  d.y = (d.depth * (this.width-this.margin.left-this.margin.right))
          / this.maxDepth;
});
</code>```

Where this.maxDepth is calculate using a recursive function about treeData

```<code>  update(source:any){
      ...
  }
  collapse(d: any) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach((d:any)=>this.collapse(d));
      d.children = null;
    }
  }

  click(d: any) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    this.update(d);
  }

  diagonal(s: any, d: any) {
    const path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

    return path;
  }
</code>```0

I need also use the "margin" variable that I hardcode like

```<code>  update(source:any){
      ...
  }
  collapse(d: any) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach((d:any)=>this.collapse(d));
      d.children = null;
    }
  }

  click(d: any) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    this.update(d);
  }

  diagonal(s: any, d: any) {
    const path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

    return path;
  }
</code>```1

That allow the SVG don't crop the text

Body:
Transform a code from JS to typeScript it's not only Copy+Paste. We need go slower.

First, in typescript we use let or const to have a block-scope instead of var. "var" create a variable global to all the application

After, we needn't put all the code in ngOnInit. We should separate in functions all the code under ngOnInit. We can get off variables and declare outside the ngOnInit

  treeData:any={...}
  margin = { top: 0, right: 30, bottom: 0, left: 30 };
  duration = 750;

  width: number;
  height: number;
  svg: any;
  root: any;

  i = 0;
  treemap: any;

Also we need get off the functions, so we has the functions

  update(source:any){
      ...
  }
  collapse(d: any) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach((d:any)=>this.collapse(d));
      d.children = null;
    }
  }

  click(d: any) {
    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    this.update(d);
  }

  diagonal(s: any, d: any) {
    const path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

    return path;
  }

And transfor all the functions use the flat arrow sintax, so

    //in stead of use
    .attr('transform', function (d: any) {
      return 'translate(' + source.y0 + ',' + source.x0 + ')';
    })

    //we use
    .attr('transform', (d: any) => {
      return 'translate(' + source.y0 + ',' + source.x0 + ')';
    })

And use this. to make reference to the variables of the component.

After all of this, Out ngOnInit becomes like

ngOnInit(){
    this.svg = d3
      .select('#d3noob')
      .append('svg')
      .attr('viewBox','0 0 900 500')
      .append('g')
      .attr(
        'transform',
        'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
      );

    // declares a tree layout and assigns the size
    this.treemap = d3.tree().size([this.height, this.width]);

    // Assigns parent, children, height, depth
    this.root = d3.hierarchy(this.treeData, (d: any) => {
      return d.children;
    });

    this.root.x0 = this.height / 2;
    this.root.y0 = 0;
    // Collapse after the second level
    this.root.children.forEach((d:any) => {
      this.collapse(d);
    });

    this.update(this.root);
}

And the function update

  update(source: any) {
    // Assigns the x and y position for the nodes
    const treeData = this.treemap(this.root);

    // Compute the new tree layout.
    const nodes = treeData.descendants();
    const links = treeData.descendants().slice(1);

    // Normalize for fixed-depth.
    nodes.forEach((d: any) => {
      d.y = d.depth * 180;
    });

    // ****************** Nodes section ***************************

    // Update the nodes...
    const node = this.svg.selectAll('g.node').data(nodes, (d: any) => {
      return d.id || (d.id = ++this.i);
    });

    // Enter any new modes at the parent's previous position.
    const nodeEnter = node
      .enter()
      .append('g')
      .attr('class', 'node')
      .attr('transform', (d: any) => {
        return 'translate(' + source.y0 + ',' + source.x0 + ')';
      })
      .on('click', (_, d) => this.click(d));

    // Add Circle for the nodes
    nodeEnter
      .append('circle')
      .attr('class', (d:any)=> d._children?'node fill':'node')
      .attr('r', 1e-6)
    // Add labels for the nodes
    nodeEnter
      .append('text')
      .attr('dy', '.35em')

      .attr('x', (d) => {
        return d.children || d._children ? -13 : 13;
      })
      .attr('text-anchor', (d: any) => {
        return d.children || d._children ? 'end' : 'start';
      })
      .text((d) => {
        return d.data.name;
      });
    // UPDATE
    const nodeUpdate = nodeEnter.merge(node);

    // Transition to the proper position for the node
    nodeUpdate
      .transition()
      .duration(this.duration)
      .attr('transform', (d: any) => {
        return 'translate(' + d.y + ',' + d.x + ')';
      });

    // Update the node attributes and style
    nodeUpdate
      .select('circle.node')
      .attr('r', 10)
      .attr('class', (d:any)=> d._children?'node fill':'node')
      .attr('cursor', 'pointer');

    // Remove any exiting nodes
    const nodeExit = node
      .exit()
      .transition()
      .duration(this.duration)
      .attr('transform', (d: any) => {
        return 'translate(' + source.y + ',' + source.x + ')';
      })
      .remove();

    // On exit reduce the node circles size to 0
    nodeExit.select('circle').attr('r', 1e-6);

    // On exit reduce the opacity of text labels
    nodeExit.select('text').style('fill-opacity', 1e-6);

    // ****************** links section ***************************

    // Update the links...
    const link = this.svg.selectAll('path.link').data(links, (d: any) => {
      return d.id;
    });

    // Enter any new links at the parent's previous position.
    const linkEnter = link
      .enter()
      .insert('path', 'g')
      .attr('class', 'link')
      .attr('d', (d: any) => {
        const o = { x: source.x0, y: source.y0 };
        return this.diagonal(o, o);
      });

    // UPDATE
    const linkUpdate = linkEnter.merge(link);

    // Transition back to the parent element position
    linkUpdate
      .transition()
      .duration(this.duration)
      .attr('d', (d: any) => {
        return this.diagonal(d, d.parent);
      });

    // Remove any exiting links
    const linkExit = link
      .exit()
      .transition()
      .duration(this.duration)
      .attr('d', (d: any) => {
        const o = { x: source.x, y: source.y };
        return this.diagonal(o, o);
      })
      .remove();

    // Store the old positions for transition.
    nodes.forEach((d: any) => {
      d.x0 = d.x;
      d.y0 = d.y;
    });
  }

See that there're a minor changes because I choose use viewPort to make the svg fill the width of the screen if it's less than 960px and control the class of the "dots" using .css (In the code it was "hardcode" the "fill of the dots")

So, before, when we create the .svg we give value to width and height and now I give value to viewBox"

this.svg = d3
  .select('#d3noob')
  .append('svg')
  .attr('viewBox','0 0 960 500')
  .append('g')
  .attr(
    'transform',
    'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
  );

Finally We create a component instead write the code in the app.component. For this we need some variables was inputs

  @Input()treeData:any={}

  @Input()margin = { top: 0, right: 30, bottom: 0, left: 30 };
  @Input()duration = 750;

The last is give credit to the author using a comment

As I choose the svg was adaptative we need calculate the "margin" to allow the text of the first node was visible. To make this, I create a "visibility:hidden" span with the text of the this node to calculate the "margin". Futhermore, I want that the text was visible, so force the font-size was around 14px creating an observable in the way

  fontSize=fromEvent(window,'resize').pipe(
    startWith(null),
    map(_=>{
      return window.innerWidth>960?'14px':14*960/window.innerWidth+'px'
    }),

The final stackblitz is here (you can compare the code)

Update Really I don't like so much the result

In this stackblitz I improve a bit the code. The diferences are that I change the width,height and viewPort using a function

  updateSize() {
    this.width = this.wrapper.nativeElement.getBoundingClientRect().width
    this.svg
      .attr('preserveAspectRatio', 'xMidYMid meet')
      .attr('width', '100%')
      .attr('height', this.height + 'px')
      .attr('viewBox', ''+(-this.margin.left)+' 0 ' + this.width  + ' ' + this.height);
  }

To avoid "crop" I change the "harcode" space between the nodes

// Normalize for fixed-depth.
nodes.forEach((d: any) => {
  d.y = (d.depth * (this.width-this.margin.left-this.margin.right))
          / this.maxDepth;
});

Where this.maxDepth is calculate using a recursive function about treeData

  this.maxDepth = this.depthOfTree(this.treeData);
  depthOfTree(ptr: any, maxdepth: number = 0) {
    if (ptr == null || !ptr.children) return maxdepth;

    for (let it of ptr.children)
      maxdepth = Math.max(maxdepth, this.depthOfTree(it));

    return maxdepth + 1;
  }

I need also use the "margin" variable that I hardcode like

  margin = { top: 0, right: 130, bottom: 0, left: 80 };

That allow the SVG don't crop the text


问:
What does it even mean to make an image visible to a writes (or available to reads)?
An availability operation can be compared to a cache flush - cache contents are released to main memory.
Similarly, visibility operation can be compared to a cache invalidation - cache consumes contents of main memory.

(it doesn't have to be a 1:1 hw mapping, but you get the idea)

It seems nonsensical to perform a visibility operation before a write (since we're about to override whatever is in our imaginary or no-so-imaginary cache either way) or an availability operation after a read (nothing has changed!).

I saw code, which includes memory writes in dstAccessMask and/or memory reads in srcAccessMask. What's the point?

答:
It seems nonsensical to perform a visibility operation before a write (since we're about to override whatever is in our imaginary or no-so-imaginary cache either way) or an availability operation after a read (nothing has changed!).

So which not-so-imaginary cache are you talking about? And how are you enforcing coherency with other not-so-imaginary caches in the system? GPUs have many levels of parallel caching, some of which are coherent in hardware and some of which are not. What you get is entirely implementation-defined behavior ...

memory writes in dstAccessMask

Missing invalidation before a write can cause write-after-write hazards on the GPU (you can end up with mismatches in parallel copies of data in two different caches). Can also get issues if HOST modified the data, which is why HOST is a possible stage.

memory reads in srcAccessMask

Can't think of a case where you'd need memory operations after a read-only usage.


问:
How to preserve directory layout of public headers when generating macOS frameworks
I have a CMake project for a C++ library (current version, CMake v3.21) which I'm in the process of porting to macOS, and I'm looking into generating the library as a OSX Framework.

So far I've followed CMake's documentation on add_library, and added the FRAMEWORK property to the library target as per CMake's documentation on its FRAMEWORK target property.  This seems to mostly work, except that header files exported as part of its PUBLIC_HEADER property have their directory structure stripped and flattened from the export.

To illustrate this problem, let's consider the following project tree:

```<code>include
└── A
    ├── A.hpp
    └── subA
        └── SubA.hpp
src
├── A.cpp
└── SubA.cpp
</code>```

The following CMake project generates a OSX framework when compiled on macOS:

```<code>cmake_minimum_required(VERSION 3.21)

project(libA LANGUAGES CXX)

set(a_INCLUDES
    include/A/A.hpp
    include/A/subA/SubA.hpp
)

set(a_SOURCES
    src/A.cpp
    src/SubA.cpp
)

add_library(a
    ${a_INCLUDES}
    ${a_SOURCES}
)

set_target_properties(a
    PROPERTIES
    FRAMEWORK YES
    PUBLIC_HEADER "${a_INCLUDES}"
)

target_include_directories(a
    PUBLIC
    ${CMAKE_SOURCE_DIR}/include
)
</code>```

However, the resulting framework flattens the directory structure of the header files included in its Headers, as shown below:

```<code>build/a.framework
├── Headers -> Versions/Current/Headers
├── Resources -> Versions/Current/Resources
├── Versions
│   ├── A
│   │   ├── Headers
│   │   │   ├── A.hpp
│   │   │   └── SubA.hpp
│   │   ├── Resources
│   │   │   └── Info.plist
│   │   └── a
│   └── Current -> A
└── a -> Versions/Current/a
</code>```

So, here are my questions: does CMake suppport preserving the directory tree layout of public headers shipped as part of a OSX framework? If it does, what do we need to do in a project in order to ensure that the directory tree layout is preserved?

答:
While you would expect to have your public and private headers placed including their relative path under the Headers directory this is not the case as you experienced. The entire path components are stripped. The same applies to hierarchically structured resources in the Resource directory.

What you can do to achieve this is to set the MACOSX_PACKAGE_LOCATION property on every single header using the set_source_files_properties command. The location is the path to the header plus a Headers prefix, e.g. Headers/A for your A/A.hpp header and Headers/A/subA for your A/subA/SubA.hpp header.

Typically projects use a small convenience function for this that strips unwanted prefixes and file names from the given headers and add the install prefix.

```<code>function(set_macosx_properties _file_prefixes _install_prefix _source_files)
  foreach(_file ${_source_files})
    get_filename_component(_loc "${_file}" DIRECTORY)
    foreach(_prefix ${_file_prefixes})
      string(REPLACE "${_prefix}" "" _loc "${_loc}")
    endforeach()
    set_source_files_properties(${_file} PROPERTIES MACOSX_PACKAGE_LOCATION ${_install_prefix}${_loc})
  endforeach()
endfunction()
</code>```

Dependent on how your header and resource files are give you would use it like this:

```<code>set_macosx_properties("include" "Headers" "${a_INCLUDES}")

set_macosx_properties("data" "Resources" "${a_RESOURCES}")
</code>```

Body:
I have a CMake project for a C++ library (current version, CMake v3.21) which I'm in the process of porting to macOS, and I'm looking into generating the library as a OSX Framework.

So far I've followed CMake's documentation on add_library, and added the FRAMEWORK property to the library target as per CMake's documentation on its FRAMEWORK target property.  This seems to mostly work, except that header files exported as part of its PUBLIC_HEADER property have their directory structure stripped and flattened from the export.

To illustrate this problem, let's consider the following project tree:

include
└── A
    ├── A.hpp
    └── subA
        └── SubA.hpp
src
├── A.cpp
└── SubA.cpp

The following CMake project generates a OSX framework when compiled on macOS:

cmake_minimum_required(VERSION 3.21)

project(libA LANGUAGES CXX)

set(a_INCLUDES
    include/A/A.hpp
    include/A/subA/SubA.hpp
)

set(a_SOURCES
    src/A.cpp
    src/SubA.cpp
)

add_library(a
    ${a_INCLUDES}
    ${a_SOURCES}
)

set_target_properties(a
    PROPERTIES
    FRAMEWORK YES
    PUBLIC_HEADER "${a_INCLUDES}"
)

target_include_directories(a
    PUBLIC
    ${CMAKE_SOURCE_DIR}/include
)

However, the resulting framework flattens the directory structure of the header files included in its Headers, as shown below:

build/a.framework
├── Headers -> Versions/Current/Headers
├── Resources -> Versions/Current/Resources
├── Versions
│   ├── A
│   │   ├── Headers
│   │   │   ├── A.hpp
│   │   │   └── SubA.hpp
│   │   ├── Resources
│   │   │   └── Info.plist
│   │   └── a
│   └── Current -> A
└── a -> Versions/Current/a

So, here are my questions: does CMake suppport preserving the directory tree layout of public headers shipped as part of a OSX framework? If it does, what do we need to do in a project in order to ensure that the directory tree layout is preserved?

Body:
While you would expect to have your public and private headers placed including their relative path under the Headers directory this is not the case as you experienced. The entire path components are stripped. The same applies to hierarchically structured resources in the Resource directory.

What you can do to achieve this is to set the MACOSX_PACKAGE_LOCATION property on every single header using the set_source_files_properties command. The location is the path to the header plus a Headers prefix, e.g. Headers/A for your A/A.hpp header and Headers/A/subA for your A/subA/SubA.hpp header.

Typically projects use a small convenience function for this that strips unwanted prefixes and file names from the given headers and add the install prefix.

function(set_macosx_properties _file_prefixes _install_prefix _source_files)
  foreach(_file ${_source_files})
    get_filename_component(_loc "${_file}" DIRECTORY)
    foreach(_prefix ${_file_prefixes})
      string(REPLACE "${_prefix}" "" _loc "${_loc}")
    endforeach()
    set_source_files_properties(${_file} PROPERTIES MACOSX_PACKAGE_LOCATION ${_install_prefix}${_loc})
  endforeach()
endfunction()

Dependent on how your header and resource files are give you would use it like this:

set_macosx_properties("include" "Headers" "${a_INCLUDES}")

set_macosx_properties("data" "Resources" "${a_RESOURCES}")


问:
Alternately fill numpy array between non-zero values
I have a binary numpy array, mostly zero-valued, and I want to fill the gaps bewteen non-zero values with a given value, but in an alternate way.
For example:

```<code>[0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0]
</code>```

should result in either

```<code>[0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]
</code>```

or

```<code>[1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1]
</code>```

The idea is: while scanning the array left to right, fill 0 values with 1 up the next 1, if you didn't do it up to the previous 1.
I can do this iteratively and in this way

A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
ones_index = np.where(A == 1)[0]
begins = ones_index[::2] # beginnings of filling section
ends = ones_index[1::2]  # ends of filling sections

from itertools import zip_longest

# fill those sections
for begin, end in zip_longest(begins, ends, fillvalue=len(A)):
    A[begin:end] = 1
```

but I'm looking for a more efficent solution, maybe with numpy broadcasting. Any ideas?

答:
One nice answer to this question is that we can produce the first result via np.logical_xor.accumulate(arr) | arr and the second via ~np.logical_xor.accumulate(arr) | arr.  A quick demonstration:

```<code>A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
print(np.logical_xor.accumulate(A) | A)
print(~np.logical_xor.accumulate(A) | A)
</code>```

The resulting output:

```<code>[0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 1 0 0]
[1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 1 1 1]
</code>```

Body:
I have a binary numpy array, mostly zero-valued, and I want to fill the gaps bewteen non-zero values with a given value, but in an alternate way.
For example:

[0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0]

should result in either

[0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]

or

[1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1]

The idea is: while scanning the array left to right, fill 0 values with 1 up the next 1, if you didn't do it up to the previous 1.
I can do this iteratively and in this way

A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
ones_index = np.where(A == 1)[0]
begins = ones_index[::2] # beginnings of filling section
ends = ones_index[1::2]  # ends of filling sections

from itertools import zip_longest

# fill those sections
for begin, end in zip_longest(begins, ends, fillvalue=len(A)):
    A[begin:end] = 1

but I'm looking for a more efficent solution, maybe with numpy broadcasting. Any ideas?

Body:
One nice answer to this question is that we can produce the first result via np.logical_xor.accumulate(arr) | arr and the second via ~np.logical_xor.accumulate(arr) | arr.  A quick demonstration:

A = np.array([0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,0])
print(np.logical_xor.accumulate(A) | A)
print(~np.logical_xor.accumulate(A) | A)

The resulting output:

[0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 1 0 0]
[1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0 0 1 1 1]


问:
Dagger 2 doesnt generate code. Unresolved reference: DaggerAppComponent
I have been trying to generate code in project for a week. The problem is that after i added AppComponent, Module, dependencies and plugin it doesnt work. I got compilation error. Then i repeated all this in new empty project an it works properly.
My Android Gradle plugin version:7.1.0
Gradle version:7.3

My AppComponent

  @Component(modules = [AppModule::class]) interface AppComponent { fun mainRepository(): MainRepository }

AppModule

@Module
object AppModule {

```<code>@Provides
fun provideMainRepository(): MainRepository {
    return MainRepository()
}
</code>```

}

Gradle file

```<code>plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.gms.google-services'
id 'kotlin-kapt'
id 'com.google.firebase.crashlytics'
id 'kotlin-parcelize'
</code>```

}

android {
compileSdkVersion 31
buildToolsVersion "30.0.3"

```<code>defaultConfig {
    applicationId "com.flametech.vaytoday"
    minSdkVersion 22
    targetSdkVersion 30
    versionCode 58
    versionName "2.19"
    multiDexEnabled = true
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildFeatures {
    viewBinding = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
    jvmTarget = '11'
}
</code>```

}

dependencies {

```<code>implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.firebase:firebase-database:20.0.0'
implementation 'androidx.room:room-runtime:2.3.0'
implementation 'com.google.firebase:firebase-storage-ktx:20.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.databinding:databinding-runtime:4.1.3'
implementation 'androidx.lifecycle:lifecycle-common-java8:2.3.1'
implementation 'androidx.fragment:fragment-ktx:1.3.6'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
implementation platform('com.google.firebase:firebase-bom:26.0.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-messaging'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
...

implementation "com.google.dagger:dagger:2.40.5"
kapt "com.google.dagger:dagger-compiler:2.40.5"
</code>```

}

Error

```<code> Unresolved reference: DaggerAppComponent
</code>```

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

Stactrace

```<code>> Configure project :app
</code>```

WARNING:The option setting 'android.overridePathCheck=true' is experimental.
The current default is 'false'.

Task :app:kaptDebugKotlin
app/build/tmp/kapt3/stubs/debug/com/flametech/vaytoday/domain/database/AppDatabase.java:7: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends androidx.room.RoomDatabase {
^

Task :app:compileDebugKotlin FAILED
e: app/src/main/java/MainActivity.kt: (51, 42): Unresolved reference: DaggerAppComponent

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 18s

AppComponent creating in MainActivity

```<code>   override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val appComponent: AppComponent = DaggerAppComponent.create()}
</code>```

SOLUTION!!!
The problem is solved. I checked my dependencies and understood that i had import in my AppComponent and in my Module like this import com.google.android.datatransport.runtime.dagger.Component

But the right import was import dagger.Component

答:
The problem is solved. I checked my dependencies and understood that i had import in my AppComponent and in my Module like this

```<code>import com.google.android.datatransport.runtime.dagger.Component
</code>```

But the right import was import dagger.Component

Body:
I have been trying to generate code in project for a week. The problem is that after i added AppComponent, Module, dependencies and plugin it doesnt work. I got compilation error. Then i repeated all this in new empty project an it works properly.
My Android Gradle plugin version:7.1.0
Gradle version:7.3

My AppComponent

  @Component(modules = [AppModule::class]) interface AppComponent { fun mainRepository(): MainRepository }

AppModule

@Module
object AppModule {

@Provides
fun provideMainRepository(): MainRepository {
    return MainRepository()
}

}

Gradle file

plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.gms.google-services'
id 'kotlin-kapt'
id 'com.google.firebase.crashlytics'
id 'kotlin-parcelize'

}

android {
compileSdkVersion 31
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.flametech.vaytoday"
    minSdkVersion 22
    targetSdkVersion 30
    versionCode 58
    versionName "2.19"
    multiDexEnabled = true
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildFeatures {
    viewBinding = true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
    jvmTarget = '11'
}

}

dependencies {

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.firebase:firebase-database:20.0.0'
implementation 'androidx.room:room-runtime:2.3.0'
implementation 'com.google.firebase:firebase-storage-ktx:20.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.databinding:databinding-runtime:4.1.3'
implementation 'androidx.lifecycle:lifecycle-common-java8:2.3.1'
implementation 'androidx.fragment:fragment-ktx:1.3.6'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
implementation platform('com.google.firebase:firebase-bom:26.0.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-messaging'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
...

implementation "com.google.dagger:dagger:2.40.5"
kapt "com.google.dagger:dagger-compiler:2.40.5"

}

Error

 Unresolved reference: DaggerAppComponent

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

Stactrace

> Configure project :app

WARNING:The option setting 'android.overridePathCheck=true' is experimental.
The current default is 'false'.

Task :app:kaptDebugKotlin
app/build/tmp/kapt3/stubs/debug/com/flametech/vaytoday/domain/database/AppDatabase.java:7: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends androidx.room.RoomDatabase {
^

Task :app:compileDebugKotlin FAILED
e: app/src/main/java/MainActivity.kt: (51, 42): Unresolved reference: DaggerAppComponent

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 18s

AppComponent creating in MainActivity

   override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val appComponent: AppComponent = DaggerAppComponent.create()}

SOLUTION!!!
The problem is solved. I checked my dependencies and understood that i had import in my AppComponent and in my Module like this import com.google.android.datatransport.runtime.dagger.Component

But the right import was import dagger.Component


问:
How to insert an embedded object with dot notations in MongoDB
For example, you can use dot notations while changing the contents of a object:

collection.update_one({"_id": 123456}, {"$set": {"abc.def.ghi": 123}})
```
<p>Which is great but, i cant use it to create new documents, when i do:</p>
<pre class="lang-py prettyprint-override"><code>collection.insert_one({"_id": 123456, "abc.def.ghi": 123})
</code>```

To create a new document, it just inserts a document like this:

{
    "_id": 123456,
    "abc.def.ghi": 123
}
```
<p>While i want it to insert a document like this:</p>
<pre class="lang-json prettyprint-override"><code>{
    "_id": 123456,
    "abc": {
        "def": {
            "ghi": 123
        }
    }
}
</code>```

答:
You can't use dot notation in that way on an insert_one(). Just use:

```<code>collection.insert_one({"_id": 123456, "abc": {"def": {"ghi": 123}}})
</code>```

Body:
For example, you can use dot notations while changing the contents of a object:

collection.update_one({"_id": 123456}, {"$set": {"abc.def.ghi": 123}})

Which is great but, i cant use it to create new documents, when i do:

collection.insert_one({"_id": 123456, "abc.def.ghi": 123})

To create a new document, it just inserts a document like this:

{
    "_id": 123456,
    "abc.def.ghi": 123
}

While i want it to insert a document like this:

{
    "_id": 123456,
    "abc": {
        "def": {
            "ghi": 123
        }
    }
}

Body:
You can't use dot notation in that way on an insert_one(). Just use:

collection.insert_one({"_id": 123456, "abc": {"def": {"ghi": 123}}})


问:
Why do some variables need `self.` and others don't, in 1 function?
i am starting my studies on OPP and I am struggling a little to grasp one concept. I believe this is very basic for you guys here, but I was hoping to get some help with it.

I have this code:

```<code>class Player:
    MAX_POSITION = 10

    def __init__(self):
        self.position = 0

    # Add a move() method with steps parameter
    def move(self, steps):
        if self.position + steps < Player.MAX_POSITION:
            self.position = self.position + steps
        else:
            self.position = Player.MAX_POSITION
</code>```

It is correct, it runs... but I am struggling to learn why I need the prefix self on the position argument and not on the steps within the function move for the class Player?

any explanations or reading material suggestions are more than welcome
thanks

答:
In an example like this:

```<code>def class MyClass:
    def __init__():
        self.attribute = None

    def my_method(self, some_parameter):
        self.attribute = some_parameter
</code>```

attribute is defined as an attribute (or instance variable) on MyClass. This means that every instance of MyClass (a MyClass object) will have its own copy of attribute.

Since every normal method (a function defined on the class) expects the first argument to be the object itself (which you don't have to pass; Python will pass it automatically), you can use self to refer to the instance the method was called on. (I say 'normal', because there are also 'static' and 'class' methods, but forget about those for now.)

So, in this example:

```<code>an_object = MyClass()
an_object.my_method(10)
print(an_object.attribute)
</code>```

This works, because in the body of .my_method, the passed value, which gets assigned to some_parameter is assigned to the attribute attribute of an_object, because an_object is assigned to self in that call. Mind you, self could have been called anything; naming the first parameter self is just a convention you should follow.

The reason some_parameter does not need self. is because it is just another parameter of a function. It's not an attribute of self — of the object the method was called on.

So, when compared to your code, you should say: steps does not need self. because it is not an attribute of a Player instance. It is just a parameter of a method defined on Player, and the value is accessible like any parameter is in a function body. The instance of a Player object is passed as self, and you can change its attributes by accessing them on self inside the function body.

A clue why you didn't grasp this is that you call position an 'argument', but an argument is something passed to a function, to a specific parameter; and a parameter is an internal variable of a function that is assigned the argument. position is an attribute of an object.

So, when calling player.move(2), 2 is the argument, steps is the parameter in the body of move() and position is the attribute of player, with player being the Player class instance (or 'object') accessible through the self parameter in the body of move().

Body:
i am starting my studies on OPP and I am struggling a little to grasp one concept. I believe this is very basic for you guys here, but I was hoping to get some help with it.

I have this code:

class Player:
    MAX_POSITION = 10

    def __init__(self):
        self.position = 0

    # Add a move() method with steps parameter
    def move(self, steps):
        if self.position + steps < Player.MAX_POSITION:
            self.position = self.position + steps
        else:
            self.position = Player.MAX_POSITION

It is correct, it runs... but I am struggling to learn why I need the prefix self on the position argument and not on the steps within the function move for the class Player?

any explanations or reading material suggestions are more than welcome
thanks

Body:
In an example like this:

def class MyClass:
    def __init__():
        self.attribute = None

    def my_method(self, some_parameter):
        self.attribute = some_parameter

attribute is defined as an attribute (or instance variable) on MyClass. This means that every instance of MyClass (a MyClass object) will have its own copy of attribute.

Since every normal method (a function defined on the class) expects the first argument to be the object itself (which you don't have to pass; Python will pass it automatically), you can use self to refer to the instance the method was called on. (I say 'normal', because there are also 'static' and 'class' methods, but forget about those for now.)

So, in this example:

an_object = MyClass()
an_object.my_method(10)
print(an_object.attribute)

This works, because in the body of .my_method, the passed value, which gets assigned to some_parameter is assigned to the attribute attribute of an_object, because an_object is assigned to self in that call. Mind you, self could have been called anything; naming the first parameter self is just a convention you should follow.

The reason some_parameter does not need self. is because it is just another parameter of a function. It's not an attribute of self — of the object the method was called on.

So, when compared to your code, you should say: steps does not need self. because it is not an attribute of a Player instance. It is just a parameter of a method defined on Player, and the value is accessible like any parameter is in a function body. The instance of a Player object is passed as self, and you can change its attributes by accessing them on self inside the function body.

A clue why you didn't grasp this is that you call position an 'argument', but an argument is something passed to a function, to a specific parameter; and a parameter is an internal variable of a function that is assigned the argument. position is an attribute of an object.

So, when calling player.move(2), 2 is the argument, steps is the parameter in the body of move() and position is the attribute of player, with player being the Player class instance (or 'object') accessible through the self parameter in the body of move().


问:
Why is it not possible to directly choose a random element in solidity?
We don't have access to random number generator?
if you have to pick somebody randomly we do it using pseudo random generator.</p>

答:
You can't create truly random numbers 'cause Blockchain is a deterministic system, so we must ensure that every node must give the same random number to be sure that every node can mint the same block.

Determinism is important because no matter where the smart contract code executes, it is critical that it produces the same result every time.

you can find some pseudo random generator through chainlink's contract: https://chain.link/chainlink-vrf


问:
List of Java class file format major version numbers?
I saw this list of major version numbers for Java in another post:

Java
Major version

20
64

19
63

18
62

17
61

16
60

15
59

14
58

13
57

12
56

11
55

10
54

9
53

8
52

7
51

6
50

5
49

1.4
48

1.3
47

1.2
46

1.1
45

1.0.2
45

Where does this list come from? Is there a specific reference for this? Preferably something that shows minor versions too?

答:
(Really an extended comment than an answer ..)

The question was regarding "where does the list of versions come from".

That was answered in this response, which references the JAVA SE Specification on: "The class File Format". Seems that's pretty authoritative (it's also referenced in the Wiki for the byte 6 (major version) values) and should be the accepted answer.

Several answers seem to focus on how to determine the value using javap or not using it. Those should be separate questions. Nevertheless, a non- javap means of finding the version is unix command file. file reads the magic, which is specified in the ClassFile structure.

ie: file myClass.class, or more elegantly, file -b myClass.class | awk -F',' '{print $NF}'

eg:

```<code>$ find * -name "*.class" -exec file -b {} \; | awk -F',' '{print $NF}' | sort -u
 version 45.3
 version 50.0 (Java 1.6)
 version 52.0 (Java 1.8)
</code>```

Body:
(Really an extended comment than an answer ..)

The question was regarding "where does the list of versions come from".

That was answered in this response, which references the JAVA SE Specification on: "The class File Format". Seems that's pretty authoritative (it's also referenced in the Wiki for the byte 6 (major version) values) and should be the accepted answer.

Several answers seem to focus on how to determine the value using javap or not using it. Those should be separate questions. Nevertheless, a non- javap means of finding the version is unix command file. file reads the magic, which is specified in the ClassFile structure.

ie: file myClass.class, or more elegantly, file -b myClass.class | awk -F',' '{print $NF}'

eg:

$ find * -name "*.class" -exec file -b {} \; | awk -F',' '{print $NF}' | sort -u
 version 45.3
 version 50.0 (Java 1.6)
 version 52.0 (Java 1.8)


问:
PHP Enums `__toString` magic method
I am wondering why it is not possible to provide an __toString implementation for enum.

IDE says "Enum may not include '__toString'". However it was the first thing I thought about once I created enum. Previously I used Value Objects encapsulating strings in my code, which utilized string casting when necessary. Now I would like to migrate 'em into enums, but those resist.

#[Immutable]
enum SaveKlinesFromApiQueue: string
{
    case DEFAULT = 'save_klines_from_api_queue';
    case PRIORITY = 'save_klines_from_api_priority_queue';

    public function __toString(): string
    {
        return $this->value;
    }
}
```

答:
As chris mentions, magic methods are not allowed.

For the 2 most(?) common usecases:

To get the string value of a single one, you can just use ->value.

If you want the string values of all of them, just add a loop in a method:

    public static function strings(): array
    {
        $strings = [];
        foreach(self::cases() as $case) {
            $strings[] = $case->value;
        }
        return $strings;
    }
```

Title: PHP Enums `__toString` magic method


问:
How to enable output_buffering on wordpress official image
I’m taking my first steps with Docker, specifically with wordpress official image, which is just amazing to use.

However, after installing (via docker-compose as below) and checking phpinfo() it appears that output_buffering = 0. I spent the weekend trying to find the best way to expose, or bind to php.ini to set it to on without success. Could I ask for your guidance on the best way to achieve this, please?

Thanks

```<code>version: '3.1'

services:

  wordpress:
    image: wordpress
    restart: always
    ports:
      - 8080:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser
      WORDPRESS_DB_PASSWORD: examplepass
      WORDPRESS_DB_NAME: exampledb
    volumes:
      - wordpress:/var/www/html
      - ./wp-content:/var/www/html/wp-content

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - db:/var/lib/mysql

volumes:
  wordpress:
  db:
</code>```

答:
There are several ways to achieve your goal (see below) but here is a straightforward example

Inside your docker-compose project, create an ob.ini file containing:

```<code>output_buffering=1
</code>```

Modify your wordpress service volumes as follow:

    volumes:
      - wordpress:/var/www/html
      - ./wp-content:/var/www/html/wp-content
      - ./ob.ini:/usr/local/etc/php/conf.d/ob.ini
```

You can achieve the same goal by extending the WordPress image and copying that file inside the given dir, or create it during build, or append the directive to an other existing ini file there...

Since wordpress image is based on the php image read more info there on how to customize it to your liking.

Body:
I’m taking my first steps with Docker, specifically with wordpress official image, which is just amazing to use.

However, after installing (via docker-compose as below) and checking phpinfo() it appears that output_buffering = 0. I spent the weekend trying to find the best way to expose, or bind to php.ini to set it to on without success. Could I ask for your guidance on the best way to achieve this, please?

Thanks

version: '3.1'

services:

  wordpress:
    image: wordpress
    restart: always
    ports:
      - 8080:80
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: exampleuser
      WORDPRESS_DB_PASSWORD: examplepass
      WORDPRESS_DB_NAME: exampledb
    volumes:
      - wordpress:/var/www/html
      - ./wp-content:/var/www/html/wp-content

  db:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_DATABASE: exampledb
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - db:/var/lib/mysql

volumes:
  wordpress:
  db:

Body:
There are several ways to achieve your goal (see below) but here is a straightforward example

Inside your docker-compose project, create an ob.ini file containing:

output_buffering=1

Modify your wordpress service volumes as follow:

    volumes:
      - wordpress:/var/www/html
      - ./wp-content:/var/www/html/wp-content
      - ./ob.ini:/usr/local/etc/php/conf.d/ob.ini

You can achieve the same goal by extending the WordPress image and copying that file inside the given dir, or create it during build, or append the directive to an other existing ini file there...

Since wordpress image is based on the php image read more info there on how to customize it to your liking.


问:
API calls are being redirected to root url on Azure with Angular and ASP.NET Core
I am working with the new Project Type (part of Visual Studio 2022) Angular with ASP.NET Core backend.

With the app deployed in production, the API call is being redirected to the root page and the index file is being returned.

Example: when I call https://website.com/_api/controller it would redirect to https://website.com and I would just get the html of the index file.

When running the app in the debugger, everything is working fine only when deployed in production in Azure.

Any idea how to handle this?

答:
The Issue was a Firewall restriction between the Website in Prod and the DB.
The Controller Function was actually throwing an exception and this was redirecting the api call automatically to the root url.</p>


问:
Replace content of request laravel
I want to replace the content inside a request of Laravel. How can I do that? To replace the content and save inside the same request?

答:
You can use the replace() method.

Example

```<code>$request->request->replace($newData);
</code>```

Title: Replace content of request laravel

Body:
You can use the replace() method.

Example

$request->request->replace($newData);


问:
Get the documents of order id 1 that are not in order id 2 MongoDB
I have this set of documents

```<code>{_id: ObjectId(""),orderid:1,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:1,productName:"Xiaomi 11"}
{_id: ObjectId(""),orderid:1,productName:"Pocophone F1"}
{_id: ObjectId(""),orderid:1,productName:"Samsung S22"}
{_id: ObjectId(""),orderid:2,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:2,productName:"Xiaomi 11"}
</code>```

I am trying to get the product names that are in order 1 but not in order 2, my mongodb query was:

```<code>{orderid:{$eq:orderid-1,$ne:orderid}}
</code>```

but it does not work, then I was trying with an aggregate op like:

```<code>{
    $match: {orderid:{$gte:orderid-1}} //this is because allways a will try to get the products name in max orderid - 1 to get that resutl with the last 2 orders
    $group:{
       _id: {productname: '$productName'}
       orders:{$push:'$orderid'}
       total:{$sum:1}
    }
    //Then here i'm trying to get just de maxorderid-1 docs that just have total equal 1 but i cant achive the result.
}
</code>```

Thanks you so much for your support and answers.

答:
If I've understood correctly you can try something like this:

First $group by productName and store orderids in an array

The $match by values in the array: $and condition where exists 1 and not 2.

And then rebuild the objects using $unwind and $project with the axuliar field root saved in the $group stage

```<code>db.collection.aggregate([
  {
    "$group": {
      "_id": "$productName",
      "orderids": {
        "$push": "$orderid"
      },
      "root": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$match": {
      "$and": [
        {
          "orderids": 1
        },
        {
          "orderids": {
            "$ne": 2
          }
        }
      ]
    }
  },
  {
    "$unwind": "$root"
  },
  {
    "$project": {
      "_id": "$root._id",
      "orderid": "$root.orderid",
      "productName": "$root.productName"
    }
  }
])
</code>```

Example here

Also, if you only want the productName, that value is stored in the id of the group, soy uo don't need the last two stages. Like this example

Body:
I have this set of documents

{_id: ObjectId(""),orderid:1,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:1,productName:"Xiaomi 11"}
{_id: ObjectId(""),orderid:1,productName:"Pocophone F1"}
{_id: ObjectId(""),orderid:1,productName:"Samsung S22"}
{_id: ObjectId(""),orderid:2,productName:"Iphone 13"}
{_id: ObjectId(""),orderid:2,productName:"Xiaomi 11"}

I am trying to get the product names that are in order 1 but not in order 2, my mongodb query was:

{orderid:{$eq:orderid-1,$ne:orderid}}

but it does not work, then I was trying with an aggregate op like:

{
    $match: {orderid:{$gte:orderid-1}} //this is because allways a will try to get the products name in max orderid - 1 to get that resutl with the last 2 orders
    $group:{
       _id: {productname: '$productName'}
       orders:{$push:'$orderid'}
       total:{$sum:1}
    }
    //Then here i'm trying to get just de maxorderid-1 docs that just have total equal 1 but i cant achive the result.
}

Thanks you so much for your support and answers.

Body:
If I've understood correctly you can try something like this:

First $group by productName and store orderids in an array

The $match by values in the array: $and condition where exists 1 and not 2.

And then rebuild the objects using $unwind and $project with the axuliar field root saved in the $group stage

db.collection.aggregate([
  {
    "$group": {
      "_id": "$productName",
      "orderids": {
        "$push": "$orderid"
      },
      "root": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$match": {
      "$and": [
        {
          "orderids": 1
        },
        {
          "orderids": {
            "$ne": 2
          }
        }
      ]
    }
  },
  {
    "$unwind": "$root"
  },
  {
    "$project": {
      "_id": "$root._id",
      "orderid": "$root.orderid",
      "productName": "$root.productName"
    }
  }
])

Example here

Also, if you only want the productName, that value is stored in the id of the group, soy uo don't need the last two stages. Like this example


问:
Count active users using login timestamp in MySQL
While preparing for an interview, I have come across an SQL question and I hope to get some insight as to how to better answer it.

Given timestamps, userid, how to determine the number of users who are active everyday in a week?

There's very little to it, but that's the question in front of me.

答:
This works for me</p>
```<code>select a.user_id, count(a.user_id) as active_time_in_days
from
(
select user_id, login_time, lead(login_time) over (partition by user_id order by login_time asc )  as next_day
from dev.login_info
group by 1,2
order by user_id, login_time asc
)a where a.login_time + interval '1 day' = next_day
group by 1;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This works for me

select a.user_id, count(a.user_id) as active_time_in_days
from
(
select user_id, login_time, lead(login_time) over (partition by user_id order by login_time asc )  as next_day
from dev.login_info
group by 1,2
order by user_id, login_time asc
)a where a.login_time + interval '1 day' = next_day
group by 1;


问:
Is this query possible in MongoDB?
Imagine a data set like this:

db.test.insertMany([
  { '_id':1, 'name':'aa1', 'price':10, 'quantity': 2, 'category': ['coffe'] },
  { '_id':2, 'name':'aa2', 'price':20, 'quantity': 1, 'category': ['coffe', 'snack'] },
  { '_id':3, 'name':'aa3', 'price':5,  'quantity':10, 'category': ['snack', 'coffe'] },
  { '_id':4, 'name':'aa4', 'price':5,  'quantity':20, 'category': ['coffe', 'cake'] },
  { '_id':5, 'name':'aa5', 'price':10, 'quantity':10, 'category': ['animal', 'dog'] },
  { '_id':6, 'name':'aa6', 'price':5,  'quantity': 5, 'category': ['dog', 'animal'] },
  { '_id':7, 'name':'aa7', 'price':5,  'quantity':10, 'category': ['animal', 'cat'] },
  { '_id':8, 'name':'aa8', 'price':10, 'quantity': 5, 'category': ['cat', 'animal'] },
]);
```
<p>I'm trying to make a query with this result (or something like it):</p>
<pre class="lang-js prettyprint-override"><code>[
  { ['animal', 'dog'],  125 },
  { ['animal', 'cat'],  100 },
  { ['coffe', 'cake'],  100 },
  { ['coffe', 'snack'],  70 },
  { ['coffe'],           20 }
]
</code>```

Meaning that it is:

Grouped by category.

The category is treated as a set (i.e. order is not important).

The result is sorted by price*quantity per unique category 'set'.

I've tried everything I know (which is very limited) and googled for days without getting anywhere.
Is this even possible in an aggregate query or do I have find a different way?

答:
I suppose you need something like this:

```<code>db.collection.aggregate([
 {
   $unwind: "$category"
 },
 {
  $sort: {
  _id:-1,
  category: -1
 }
 },
 {
  $group: {
    _id: "$_id",
    category: {
    $push: "$category"
  },
  price: {
    $first: "$price"
  },
   quantity: {
    $first: "$quantity"
  }
 }
 },
 {
  $group: {
    _id: "$category",
    sum: {
     $sum: {
      $multiply: [
        "$price",
        "$quantity"
      ]
     }
    }
  }
  },
  {
    $project: {
      mySet: "$_id",
      total: "$sum"
   }
  },
  {
   $sort: {
     total: -1
   }
  }
  ])
</code>```

Explained:

$unwind the $category array so you can sort the categories in same order.

$sort by category & _id so you can have same order per category & _id

$group by _id so you can push the categories back to array but sorted

$group by category set so you can sum the price*quantity

$project the needed fields

$sort by descending order as requested.

Please, note output has name for the set and total for the sum to be valid JSON since it is not possible to have the output as {[X,Y],Z} and need to be {m:[X,Y],z:Z}

playground

Title: Is this query possible in MongoDB?

Body:
Imagine a data set like this:

db.test.insertMany([
  { '_id':1, 'name':'aa1', 'price':10, 'quantity': 2, 'category': ['coffe'] },
  { '_id':2, 'name':'aa2', 'price':20, 'quantity': 1, 'category': ['coffe', 'snack'] },
  { '_id':3, 'name':'aa3', 'price':5,  'quantity':10, 'category': ['snack', 'coffe'] },
  { '_id':4, 'name':'aa4', 'price':5,  'quantity':20, 'category': ['coffe', 'cake'] },
  { '_id':5, 'name':'aa5', 'price':10, 'quantity':10, 'category': ['animal', 'dog'] },
  { '_id':6, 'name':'aa6', 'price':5,  'quantity': 5, 'category': ['dog', 'animal'] },
  { '_id':7, 'name':'aa7', 'price':5,  'quantity':10, 'category': ['animal', 'cat'] },
  { '_id':8, 'name':'aa8', 'price':10, 'quantity': 5, 'category': ['cat', 'animal'] },
]);

I'm trying to make a query with this result (or something like it):

[
  { ['animal', 'dog'],  125 },
  { ['animal', 'cat'],  100 },
  { ['coffe', 'cake'],  100 },
  { ['coffe', 'snack'],  70 },
  { ['coffe'],           20 }
]

Meaning that it is:

Grouped by category.

The category is treated as a set (i.e. order is not important).

The result is sorted by price*quantity per unique category 'set'.

I've tried everything I know (which is very limited) and googled for days without getting anywhere.
Is this even possible in an aggregate query or do I have find a different way?

Body:
I suppose you need something like this:

db.collection.aggregate([
 {
   $unwind: "$category"
 },
 {
  $sort: {
  _id:-1,
  category: -1
 }
 },
 {
  $group: {
    _id: "$_id",
    category: {
    $push: "$category"
  },
  price: {
    $first: "$price"
  },
   quantity: {
    $first: "$quantity"
  }
 }
 },
 {
  $group: {
    _id: "$category",
    sum: {
     $sum: {
      $multiply: [
        "$price",
        "$quantity"
      ]
     }
    }
  }
  },
  {
    $project: {
      mySet: "$_id",
      total: "$sum"
   }
  },
  {
   $sort: {
     total: -1
   }
  }
  ])

Explained:

$unwind the $category array so you can sort the categories in same order.

$sort by category & _id so you can have same order per category & _id

$group by _id so you can push the categories back to array but sorted

$group by category set so you can sum the price*quantity

$project the needed fields

$sort by descending order as requested.

Please, note output has name for the set and total for the sum to be valid JSON since it is not possible to have the output as {[X,Y],Z} and need to be {m:[X,Y],z:Z}

playground


问:
What's the best online source to learn Perl?
I am new to any scripting language. But, still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, what is the best online resource to learn Perl?</p>

答: I would very much recommend Programming Perl, but beware you may need a subscription to Safari in order to read it online.</p>

OwnerDisplayName: Sreenath

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy


问:
Compute intersection of two edges
I have this big graph of edges and vertices in 2D space. The big graph is returned by a function computed in a C++ library. I am reading this graph and using it to compute all the intersections of its edges (the lines segements). I use sweep algorithm. For detecting the intersection of two edges I have though some problems. I have 4 different methods according to which I test if two edges intersect and if affirmative I compute and retain their intersection:

One which test if the two edges are the diagonals of a polygon. that is
the coordinates of the edges of one line inserted into the equation of
the other line have different signs.

One which computes the intersection each time and check whether the
found intersection is between the endpoints of both segments.

One which is the code from this link implemented in C++ though.

One which implements the first method proposed by Jason Cohen ín
this question.

"The problem reduces to this question: Do two lines from A to B and from C to D intersect? Then you can ask it four times (between the line and each of the four sides of the rectangle).

Here's the vector math for doing it. I'm assuming the line from A to B is the line in question and the line from C to D is one of the rectangle lines. My notation is that Ax is the "x-coordinate of A" and Cy is the "y-coordinate of C." And "*" means dot-product, so e.g.:

```<code>A*B = Ax*Bx + Ay*By.
E = B-A = ( Bx-Ax, By-Ay )
F = D-C = ( Dx-Cx, Dy-Cy )
P = ( -Ey, Ex )
h = ( (A-C) * P ) / ( F * P )
</code>```

This h number is the key. If h is between 0 and 1, the lines intersect, otherwise they don't. If FP is zero, of course you cannot make the calculation, but in this case the lines are parallel and therefore only intersect in the obvious cases.
The exact point of intersection is C + Fh.
If h is exactly 0 or 1 the lines touch at an end-point. You can consider this an "intersection" or not as you see fit."

For data that I created (small data with double values) I obtained good results with all the 4 implemented methods. When I use anyone of these methods implemented in C++ on the data from the big graph I get different results each time and not good results:

method returns much more intersections that I need (all the points are on the graph) but I get too many points.

I always obtain 0 intersections no matter what.

I get a lot more intersection than in 1.

For some example I get points which are not on the graph (so not even the intersection). But for some examples I get the intersection points plus some other points.

I have no idea where the problem can be. Any suggestion or any other idea on how to compute the intersection and test it moreover are ore than welcomed. thank you, madalina

答:
Why re-invent the wheel?

If you can handle relying on Boost, I'd check out the GTL library in the sandbox.  For instructions on how to download this, read the wiki (instructions right there on the front page).

The GTL library lends itself to any implementation you have for your data structure (i.e. it's designed in the spirit of STL, where data structures and algorithms are orthogonal).  The code is both fast and correct.  Check it out if you can.

OwnerDisplayName: madalina

Title: Compute intersection of two edges

Body:
I have this big graph of edges and vertices in 2D space. The big graph is returned by a function computed in a C++ library. I am reading this graph and using it to compute all the intersections of its edges (the lines segements). I use sweep algorithm. For detecting the intersection of two edges I have though some problems. I have 4 different methods according to which I test if two edges intersect and if affirmative I compute and retain their intersection:

One which test if the two edges are the diagonals of a polygon. that is
the coordinates of the edges of one line inserted into the equation of
the other line have different signs.

One which computes the intersection each time and check whether the
found intersection is between the endpoints of both segments.

One which is the code from this link implemented in C++ though.

One which implements the first method proposed by Jason Cohen ín
this question.

"The problem reduces to this question: Do two lines from A to B and from C to D intersect? Then you can ask it four times (between the line and each of the four sides of the rectangle).

Here's the vector math for doing it. I'm assuming the line from A to B is the line in question and the line from C to D is one of the rectangle lines. My notation is that Ax is the "x-coordinate of A" and Cy is the "y-coordinate of C." And "*" means dot-product, so e.g.:

A*B = Ax*Bx + Ay*By.
E = B-A = ( Bx-Ax, By-Ay )
F = D-C = ( Dx-Cx, Dy-Cy )
P = ( -Ey, Ex )
h = ( (A-C) * P ) / ( F * P )

This h number is the key. If h is between 0 and 1, the lines intersect, otherwise they don't. If FP is zero, of course you cannot make the calculation, but in this case the lines are parallel and therefore only intersect in the obvious cases.
The exact point of intersection is C + Fh.
If h is exactly 0 or 1 the lines touch at an end-point. You can consider this an "intersection" or not as you see fit."

For data that I created (small data with double values) I obtained good results with all the 4 implemented methods. When I use anyone of these methods implemented in C++ on the data from the big graph I get different results each time and not good results:

method returns much more intersections that I need (all the points are on the graph) but I get too many points.

I always obtain 0 intersections no matter what.

I get a lot more intersection than in 1.

For some example I get points which are not on the graph (so not even the intersection). But for some examples I get the intersection points plus some other points.

I have no idea where the problem can be. Any suggestion or any other idea on how to compute the intersection and test it moreover are ore than welcomed. thank you, madalina

LastEditorDisplayName: unwind

OwnerDisplayName: Trey Jackson


问:
Ignore sources jar in Ivy retrieve
I would like to retrieve ONLY the library jar when I make use of a dependency entry in my ivy.xml for Red5 (or any project for that matter). No matter how I have configured it, I still get "sources" jars for dependencies. I have scoured the docs and google and have yet to find a solution that works using Ivy 2.2.0.

This set of nodes in my ivy.xml seems to work the best for most libraries, but Spring ignores them.

```<code>    <exclude ext="txt" />
    <exclude type="src" />
    <exclude artifact="!sources" />
</code>```

If anyone has any tips that would work, lets hear them!!

Links to the source xml files

http://red5.googlecode.com/svn/java/server/trunk/ivy.xml

http://red5.googlecode.com/svn/java/server/trunk/ivysettings.xml

http://red5.googlecode.com/svn/java/server/trunk/build.xml

Note

Don't say this is a duplicate, their answers do NOT work:

ivy: prevent downloading sources and .txt files

make ivy not to download sources and license files

Update 1

```<code><dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" transitive="false" /></code>```

Produces these two files in my lib directory:

```<code>org.springframework.core-3.0.5.RELEASE.jar
org.springframework.core-sources-3.0.5.RELEASE.jar</code>```

Update 2
For the bounty, I expect your solution to work with Red5 trunk which is available to everyone as open source. The sources jars are just a annoyance for me and well worth the bounty points.

答:
I would advise to not use the "transitive" attribute on the dependency declaration and instead attempt to solve your problem using configurations.

Configurations in ivy are functionally the same as scopes in Maven, but far more flexible.

I normally declare at least the following 3 configurations in my code

```<code>    <configurations>
        <conf name="compile" description="Compile time dependencies"/>
        <conf name="runtime" description="Compile time dependencies" extends="compile"/>
        <conf name="test"    description="Compile time dependencies" extends="runtime"/>
    </configurations>
</code>```

Corresponds to 3 groups of dependencies I'll need for any java project.

The secret is how you map you depdencies to your configurations. If you only want the jar without it's dependencies, then declare it as follows:

```<code><dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="compile->master"/>
</code>```

The local compile configuration mapped to the master scope of the remote Maven module. The master scope in Maven excludes any transitive dependencies.

If you want the artifact to include it's transitive dependencies then declare the configuration mapping as follows:

```<code><dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="compile->default"/>
</code>```

Working ivy.xml file

This will download a single jar.

```<code><?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info organisation="red5" module="server" />
    <configurations>
        <conf name="default"/>
        <conf name="java6" extends="default" description="Java 6 dependencies"/>
        <conf name="utest" extends="eclipse" description="Unit testing dependencies"/>
        <conf name="eclipse" description="Special dependencies in Eclipse"/>
    </configurations>
    <dependencies>
        <dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="default->master"/>
    </dependencies>
</ivy-module>
</code>```

Revised settings file

I would also recommend using the ibiblio resolver, which is designed to understand the Maven 1 and Maven 2 repository formats:

```<code><ivysettings>
    <settings defaultResolver="local"/>
    <resolvers>
        <chain name="local">
            <ibiblio name='springsource-releases' m2compatible='true' root='http://repository.springsource.com/maven/bundles/release'/>
             ..
             ..
        </chain>
    </resolvers>
</ivysettings>
</code>```

Note I'm using the Springsource Maven repository, which is more likely to be up-to-date. I don't know if they maintain the old ivy repositories properly or not anymore.

Title: Ignore sources jar in Ivy retrieve

Body:
I would like to retrieve ONLY the library jar when I make use of a dependency entry in my ivy.xml for Red5 (or any project for that matter). No matter how I have configured it, I still get "sources" jars for dependencies. I have scoured the docs and google and have yet to find a solution that works using Ivy 2.2.0.

This set of nodes in my ivy.xml seems to work the best for most libraries, but Spring ignores them.

    <exclude ext="txt" />
    <exclude type="src" />
    <exclude artifact="!sources" />

If anyone has any tips that would work, lets hear them!!

Links to the source xml files

http://red5.googlecode.com/svn/java/server/trunk/ivy.xml

http://red5.googlecode.com/svn/java/server/trunk/ivysettings.xml

http://red5.googlecode.com/svn/java/server/trunk/build.xml

Note

Don't say this is a duplicate, their answers do NOT work:

ivy: prevent downloading sources and .txt files

make ivy not to download sources and license files

Update 1

<dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" transitive="false" />

Produces these two files in my lib directory:

org.springframework.core-3.0.5.RELEASE.jar
org.springframework.core-sources-3.0.5.RELEASE.jar

Update 2
For the bounty, I expect your solution to work with Red5 trunk which is available to everyone as open source. The sources jars are just a annoyance for me and well worth the bounty points.

Body:
I would advise to not use the "transitive" attribute on the dependency declaration and instead attempt to solve your problem using configurations.

Configurations in ivy are functionally the same as scopes in Maven, but far more flexible.

I normally declare at least the following 3 configurations in my code

    <configurations>
        <conf name="compile" description="Compile time dependencies"/>
        <conf name="runtime" description="Compile time dependencies" extends="compile"/>
        <conf name="test"    description="Compile time dependencies" extends="runtime"/>
    </configurations>

Corresponds to 3 groups of dependencies I'll need for any java project.

The secret is how you map you depdencies to your configurations. If you only want the jar without it's dependencies, then declare it as follows:

<dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="compile->master"/>

The local compile configuration mapped to the master scope of the remote Maven module. The master scope in Maven excludes any transitive dependencies.

If you want the artifact to include it's transitive dependencies then declare the configuration mapping as follows:

<dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="compile->default"/>

Working ivy.xml file

This will download a single jar.

<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info organisation="red5" module="server" />
    <configurations>
        <conf name="default"/>
        <conf name="java6" extends="default" description="Java 6 dependencies"/>
        <conf name="utest" extends="eclipse" description="Unit testing dependencies"/>
        <conf name="eclipse" description="Special dependencies in Eclipse"/>
    </configurations>
    <dependencies>
        <dependency org="org.springframework" name="org.springframework.core" rev="3.0.5.RELEASE" conf="default->master"/>
    </dependencies>
</ivy-module>

Revised settings file

I would also recommend using the ibiblio resolver, which is designed to understand the Maven 1 and Maven 2 repository formats:

<ivysettings>
    <settings defaultResolver="local"/>
    <resolvers>
        <chain name="local">
            <ibiblio name='springsource-releases' m2compatible='true' root='http://repository.springsource.com/maven/bundles/release'/>
             ..
             ..
        </chain>
    </resolvers>
</ivysettings>

Note I'm using the Springsource Maven repository, which is more likely to be up-to-date. I don't know if they maintain the old ivy repositories properly or not anymore.


问:
how to hide blank space between textboxes when one of them is conditionally invisible in SSRS
My SSRS report has five text boxes, each arranged one below the other. The third text box has a visibility condition which will hide the text box in a few cases. Under such cases, there is a blank space shown between the first two and the last two boxes. Is there a way to hide this blank space without re-ordering them?

Thanks in advance !!

答:
Like others were saying, you could combine them all into one textbox. It would look something like this:

=IIF(showText1 = true, vbcrlf & "Text 1" &, "") & IIF(showText2 = true, vbcrlf & "Text 2" &, "") & IIF(showText3 = true, vbcrlf & "Text 3" &, "")

Note: You'll probably want "Allow height to increase" and "Allow height to decrease" checked in your textbox properties as well when doing this


问:
Scraping data from a site, and it returns nothing?
i'm trying to scrape some data from a site called laced.co.uk, and i'm a tad confused on whats going wrong. i'm new to this, so try and explain it simply (if possible please!). Here is my code ;

```<code>from bs4 import BeautifulSoup
import requests

url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"

result = requests.get(url)

doc = BeautifulSoup(result.text, "html.parser")

prices = doc.find_all(text=" £195 ")
print(prices)
</code>```

thank you! (the price at time of posting was 195 (it showed as the size 7 buy now price on the page).

答:
The price is loaded within a
```
<p>You can use a regular expression pattern to search for the price. Note, there's no need for <code>BeautifulSoup</code>:</p>
```import re
import requests

url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"
result = requests.get(url)

price = re.search(r"'price': '(.*?)',", result.text).group(1)
print(f"£ {price}")
```

Body:
i'm trying to scrape some data from a site called laced.co.uk, and i'm a tad confused on whats going wrong. i'm new to this, so try and explain it simply (if possible please!). Here is my code ;

from bs4 import BeautifulSoup
import requests

url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"

result = requests.get(url)

doc = BeautifulSoup(result.text, "html.parser")

prices = doc.find_all(text=" £195 ")
print(prices)

thank you! (the price at time of posting was 195 (it showed as the size 7 buy now price on the page).

Body:
The price is loaded within a <script> tag on the page:

<script>
    typeof(dataLayer) != "undefined" && dataLayer.push({
      'event': 'eec.productDetailImpression',
      'page': {
        'ecomm_prodid': 'DD1391-100'
      },
      'ecommerce': {
        'detail': {
          'actionField': {'list': 'Product Page'},
          'products': [{
            'name': 'Nike Dunk Low Retro Black White',
            'id': 'DD1391-100',
            'price': '195.0',
            'brand': 'Nike',
            'category': 'Dunk, Dunk Low, Mens Nike Dunks',
            'variant': 'White',
            'list': 'Product Page',
            'dimension1': '195.0',
            'dimension2': '7',
            'dimension3': '190',
            'dimension4': '332'
          }]
        }
      }
    });
  </script>

You can use a regular expression pattern to search for the price. Note, there's no need for BeautifulSoup:

import re
import requests

url = "https://www.laced.co.uk/products/nike-dunk-low-retro-black-white?size=7"
result = requests.get(url)

price = re.search(r"'price': '(.*?)',", result.text).group(1)
print(f"£ {price}")


问:
Set property value on object loaded from json containing comments
When loading an object from a json file one can normally set the value on properties and write the file back out like so:

```<code>$manifest = (gc $manifestPath) | ConvertFrom-Json -AsHashtable
$manifest.name = "$($manifest.name)-sxs"
$manifest | ConvertTo-Json -depth 100 | Out-File $manifestPath -Encoding utf8NoBOM
</code>```

But if the source json file contains comments, the object's properties can't be set:

```<code>// *******************************************************
// GENERATED FILE - DO NOT EDIT DIRECTLY
// *******************************************************
{
  "name": "PublishBuildArtifacts"
}
</code>```

Running the code above throws an error:

```<code>$manifest

id                 : 1D341BB0-2106-458C-8422-D00BCEA6512A
name               : PublishBuildArtifacts
friendlyName       : ms-resource:loc.friendlyName
description        : ms-resource:loc.description
category           : Build
visibility         : {Build}
author             : Microsoft Corporation
version            : @{Major=0; Minor=1; Patch=71}
demands            : {}
inputs             : {@{name=CopyRoot; type=filePath; label=ms-resource:loc.input.label.CopyRoot; defaultValue=;
                     required=False; helpMarkDown=Root folder to apply copy patterns to.  Empty is the root of the
                     repo.}, @{name=Contents; type=multiLine; label=ms-resource:loc.input.label.Contents;
                     defaultValue=; required=True; helpMarkDown=File or folder paths to include as part of the
                     artifact.}, @{name=ArtifactName; type=string; label=ms-resource:loc.input.label.ArtifactName;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.},
                     @{name=ArtifactType; type=pickList; label=ms-resource:loc.input.label.ArtifactType;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.; options=}…}
instanceNameFormat : Publish Artifact: $(ArtifactName)
execution          : @{PowerShell=; Node=}

$manifest.name
PublishBuildArtifacts

$manifest.name = "sxs"
InvalidOperation: The property 'name' cannot be found on this object. Verify that the property exists and can be set.
</code>```

When I strip the comments, I can overwrite the property.

Is there a way I can coax PowerShell to ignore the comments while loading the json file/convert the object and generate a writable object?

答:
I'm not sure if this is intended, but seems like ConvertFrom-Json is treating the comments on the Json as $null when converting it to an object. This only happens if it's receiving an object[] from pipeline, with a string or multi-line string it works fine.

A simple way to demonstrate this using the exact same Json posted in the question:

```<code>$contentAsArray = Get-Content test.json | Where-Object {
    -not $_.StartsWith('/')
} | ConvertFrom-Json -AsHashtable

$contentAsArray['name'] = 'hello' # works
</code>```

Here you can see the differences and the workaround, it is definitely recommended to use -Raw on Get-Content so you're passing a multi-line string to ConvertFrom-Json:

```<code>$contentAsString = Get-Content test.json -Raw | ConvertFrom-Json -AsHashtable
$contentAsArray = Get-Content test.json | ConvertFrom-Json -AsHashtable

$contentAsString.PSObject, $contentAsArray.PSObject | Select-Object TypeNames, BaseObject

TypeNames                                      BaseObject
---------                                      ----------
{System.Collections.Hashtable, System.Object}  {name}
{System.Object[], System.Array, System.Object} {$null, System.Collections.Hashtable}

$contentAsArray['name']      # null
$null -eq $contentAsArray[0] # True
$contentAsArray[1]['name']   # PublishBuildArtifacts
$contentAsArray[1]['name'] = 'hello'
$contentAsArray[1]['name']   # hello
</code>```

Body:
When loading an object from a json file one can normally set the value on properties and write the file back out like so:

$manifest = (gc $manifestPath) | ConvertFrom-Json -AsHashtable
$manifest.name = "$($manifest.name)-sxs"
$manifest | ConvertTo-Json -depth 100 | Out-File $manifestPath -Encoding utf8NoBOM

But if the source json file contains comments, the object's properties can't be set:

// *******************************************************
// GENERATED FILE - DO NOT EDIT DIRECTLY
// *******************************************************
{
  "name": "PublishBuildArtifacts"
}

Running the code above throws an error:

$manifest

id                 : 1D341BB0-2106-458C-8422-D00BCEA6512A
name               : PublishBuildArtifacts
friendlyName       : ms-resource:loc.friendlyName
description        : ms-resource:loc.description
category           : Build
visibility         : {Build}
author             : Microsoft Corporation
version            : @{Major=0; Minor=1; Patch=71}
demands            : {}
inputs             : {@{name=CopyRoot; type=filePath; label=ms-resource:loc.input.label.CopyRoot; defaultValue=;
                     required=False; helpMarkDown=Root folder to apply copy patterns to.  Empty is the root of the
                     repo.}, @{name=Contents; type=multiLine; label=ms-resource:loc.input.label.Contents;
                     defaultValue=; required=True; helpMarkDown=File or folder paths to include as part of the
                     artifact.}, @{name=ArtifactName; type=string; label=ms-resource:loc.input.label.ArtifactName;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.},
                     @{name=ArtifactType; type=pickList; label=ms-resource:loc.input.label.ArtifactType;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.; options=}…}
instanceNameFormat : Publish Artifact: $(ArtifactName)
execution          : @{PowerShell=; Node=}

$manifest.name
PublishBuildArtifacts

$manifest.name = "sxs"
InvalidOperation: The property 'name' cannot be found on this object. Verify that the property exists and can be set.

When I strip the comments, I can overwrite the property.

Is there a way I can coax PowerShell to ignore the comments while loading the json file/convert the object and generate a writable object?

Body:
I'm not sure if this is intended, but seems like ConvertFrom-Json is treating the comments on the Json as $null when converting it to an object. This only happens if it's receiving an object[] from pipeline, with a string or multi-line string it works fine.

A simple way to demonstrate this using the exact same Json posted in the question:

$contentAsArray = Get-Content test.json | Where-Object {
    -not $_.StartsWith('/')
} | ConvertFrom-Json -AsHashtable

$contentAsArray['name'] = 'hello' # works

Here you can see the differences and the workaround, it is definitely recommended to use -Raw on Get-Content so you're passing a multi-line string to ConvertFrom-Json:

$contentAsString = Get-Content test.json -Raw | ConvertFrom-Json -AsHashtable
$contentAsArray = Get-Content test.json | ConvertFrom-Json -AsHashtable

$contentAsString.PSObject, $contentAsArray.PSObject | Select-Object TypeNames, BaseObject

TypeNames                                      BaseObject
---------                                      ----------
{System.Collections.Hashtable, System.Object}  {name}
{System.Object[], System.Array, System.Object} {$null, System.Collections.Hashtable}

$contentAsArray['name']      # null
$null -eq $contentAsArray[0] # True
$contentAsArray[1]['name']   # PublishBuildArtifacts
$contentAsArray[1]['name'] = 'hello'
$contentAsArray[1]['name']   # hello