问:
switching views in iphone

Possible Duplicate:

  switching views in iphone

I am making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help.i also asked same question five hours ago but the answer was not satisfactory again same error is pertaining.

"clientserverprogram view.h"

```<code>#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end
</code>```

"clientserverprogram view.m"

```<code> #import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);
 }

 - (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

  -(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

答:
I used your code and the problem here is your class name  "secondview" and the instance you are making from it IBOutlet secondview *secondview are same. Please use different name for class names and the instances you create.

Always start with uppercase for class names and start with lowercase for class instances you create.
Hence, your class name should be SecondView and you should write IBOutlet SecondView *secondView.

Or you should just use different names. Its very confusing.

Title: switching views in iphone

Body:
Possible Duplicate:

  switching views in iphone

I am making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help.i also asked same question five hours ago but the answer was not satisfactory again same error is pertaining.

"clientserverprogram view.h"

#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end

"clientserverprogram view.m"

 #import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);
 }

 - (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

  -(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end


来源: stackexchange

问:
AmCharts - How to make sense of the source code?
My name is Minh Vuong Nguyen who is practicing duplicating AmChart's interactive map. The error I am encountering is about the HTML code they provide in the link above.

After I have copy-pasted this link to my JavaScript, I have been looking at their JavaScript sourcecode, such as

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

<p>Nonetheless, as I come to the <strong>"ammap.js"</strong> and <strong>"worldHigh.js"</strong> file, the code lines is very complicated because:</p>

<ol>
<li>A command like: <strong>(function)(){}</strong> is unknown to me, as you cannot use the bracket before announcing the function. Furthermore, some lines of code such as <strong>window.AmCharts?d=window.AmCharts:(</strong> is very complicated.</li>
<li>The order from the source website itself is all over the place. I do not know how to organize it line-by-line like the normal JavaScript.</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function(){
    var d;
    window.AmCharts?d=window.AmCharts:(
        d={},window.AmCharts=d,
        d.themes={},
        d.maps={},
        d.inheriting={},d.charts=[],d.onReadyArray=[],d.useUTC=!1,d.updateRate=60,d.uid=0,
        d.lang={},d.translations={},d.mapTranslations={},d.windows={},d.initHandlers=[],d.amString="am",d.pmString="pm");d.Class=function(a){var b=function(){arguments[0]!==d.inheriting&&(this.events={},this.construct.apply(this,arguments))};a.inherits?(b.prototype=new a.inherits(d.inheriting),b.base=a.inherits.prototype,delete a.inherits):(b.prototype.createEvents=function(){for(var a=0;a<arguments.length;a++)this.events[arguments[a]]=[]},b.prototype.listenTo=function(a,b,c){this.removeListener(a,b,c);</code>```

Please kind me provide me with the appropriate approaches regarding this issue. I would love to thank you in advance.

答:
To answer your first question, (function(){ is an anonymous function. However, this is not part of your problem. These are not js files that you are going to modify. These are simply files that need to be linked to your page to make the whole chart essentially function.

ammap.js contains basic map functionality and the worldhigh.js contains a HighRes very detailed map of the entire world (so be careful with that one it is very heavy).

The code you are going to want to modify is going to look more like this:

```<code>  <!-- Styles -->
    <style>
    #chartdiv {
      width: 100%;
      height: 500px;
    }

    </style>

    <!-- Resources -->
    <script src="https://www.amcharts.com/lib/4/core.js"></script>
    <script src="https://www.amcharts.com/lib/4/maps.js"></script>
    <script src="https://www.amcharts.com/lib/4/geodata/worldLow.js"></script>
    <script src="https://www.amcharts.com/lib/4/geodata/usaLow.js"></script>
    <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>

    <!-- Chart code -->
    <script>
    am4core.ready(function() {

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end

    // Create map instance
    var chart = am4core.create("chartdiv", am4maps.MapChart);

    // Set map definition
    chart.geodata = am4geodata_worldLow;

    // Set projection
    chart.projection = new am4maps.projections.Miller();

    // Series for World map
    var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
    worldSeries.exclude = ["AQ"];
    worldSeries.useGeodata = true;

    var polygonTemplate = worldSeries.mapPolygons.template;
    polygonTemplate.tooltipText = "{name}";
    polygonTemplate.fill = chart.colors.getIndex(0);
    polygonTemplate.nonScalingStroke = true;

    // Hover state
    var hs = polygonTemplate.states.create("hover");
    hs.properties.fill = am4core.color("#367B25");

    // Series for United States map
    var usaSeries = chart.series.push(new am4maps.MapPolygonSeries());
    usaSeries.geodata = am4geodata_usaLow;

    var usPolygonTemplate = usaSeries.mapPolygons.template;
    usPolygonTemplate.tooltipText = "{name}";
    usPolygonTemplate.fill = chart.colors.getIndex(1);
    usPolygonTemplate.nonScalingStroke = true;

    // Hover state
    var hs = usPolygonTemplate .states.create("hover");
    hs.properties.fill = am4core.color("#367B25");

    }); // end am4core.ready()
    </script>

    <!-- HTML -->
    <div id="chartdiv"></div>
</code>```

This code was borrowed right from the amcharts demo site at https://www.amcharts.com/demos/multi-series-map/

This is using a multiseries map. I am not sure which one you are using, but you will want to navigate to the demo of that map and then copy the demo code from the bottom. DONT WORRY ABOUT THE JS FILES. Just link those to your page and then copy the demo code. The map should work out of the box.

ContentLicense: CC BY-SA 4.0

Body:
My name is Minh Vuong Nguyen who is practicing duplicating AmChart's interactive map. The error I am encountering is about the HTML code they provide in the link above.

After I have copy-pasted this link to my JavaScript, I have been looking at their JavaScript sourcecode, such as

Nonetheless, as I come to the "ammap.js" and "worldHigh.js" file, the code lines is very complicated because:

A command like: (function)(){} is unknown to me, as you cannot use the bracket before announcing the function. Furthermore, some lines of code such as window.AmCharts?d=window.AmCharts:( is very complicated.

The order from the source website itself is all over the place. I do not know how to organize it line-by-line like the normal JavaScript.

(function(){
    var d;
    window.AmCharts?d=window.AmCharts:(
        d={},window.AmCharts=d,
        d.themes={},
        d.maps={},
        d.inheriting={},d.charts=[],d.onReadyArray=[],d.useUTC=!1,d.updateRate=60,d.uid=0,
        d.lang={},d.translations={},d.mapTranslations={},d.windows={},d.initHandlers=[],d.amString="am",d.pmString="pm");d.Class=function(a){var b=function(){arguments[0]!==d.inheriting&&(this.events={},this.construct.apply(this,arguments))};a.inherits?(b.prototype=new a.inherits(d.inheriting),b.base=a.inherits.prototype,delete a.inherits):(b.prototype.createEvents=function(){for(var a=0;a<arguments.length;a++)this.events[arguments[a]]=[]},b.prototype.listenTo=function(a,b,c){this.removeListener(a,b,c);

Please kind me provide me with the appropriate approaches regarding this issue. I would love to thank you in advance.

Body:
To answer your first question, (function(){ is an anonymous function. However, this is not part of your problem. These are not js files that you are going to modify. These are simply files that need to be linked to your page to make the whole chart essentially function.

ammap.js contains basic map functionality and the worldhigh.js contains a HighRes very detailed map of the entire world (so be careful with that one it is very heavy).

The code you are going to want to modify is going to look more like this:

  <!-- Styles -->
    <style>
    #chartdiv {
      width: 100%;
      height: 500px;
    }

    </style>

    <!-- Resources -->
    <script src="https://www.amcharts.com/lib/4/core.js"></script>
    <script src="https://www.amcharts.com/lib/4/maps.js"></script>
    <script src="https://www.amcharts.com/lib/4/geodata/worldLow.js"></script>
    <script src="https://www.amcharts.com/lib/4/geodata/usaLow.js"></script>
    <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>

    <!-- Chart code -->
    <script>
    am4core.ready(function() {

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end

    // Create map instance
    var chart = am4core.create("chartdiv", am4maps.MapChart);

    // Set map definition
    chart.geodata = am4geodata_worldLow;

    // Set projection
    chart.projection = new am4maps.projections.Miller();

    // Series for World map
    var worldSeries = chart.series.push(new am4maps.MapPolygonSeries());
    worldSeries.exclude = ["AQ"];
    worldSeries.useGeodata = true;

    var polygonTemplate = worldSeries.mapPolygons.template;
    polygonTemplate.tooltipText = "{name}";
    polygonTemplate.fill = chart.colors.getIndex(0);
    polygonTemplate.nonScalingStroke = true;

    // Hover state
    var hs = polygonTemplate.states.create("hover");
    hs.properties.fill = am4core.color("#367B25");

    // Series for United States map
    var usaSeries = chart.series.push(new am4maps.MapPolygonSeries());
    usaSeries.geodata = am4geodata_usaLow;

    var usPolygonTemplate = usaSeries.mapPolygons.template;
    usPolygonTemplate.tooltipText = "{name}";
    usPolygonTemplate.fill = chart.colors.getIndex(1);
    usPolygonTemplate.nonScalingStroke = true;

    // Hover state
    var hs = usPolygonTemplate .states.create("hover");
    hs.properties.fill = am4core.color("#367B25");

    }); // end am4core.ready()
    </script>

    <!-- HTML -->
    <div id="chartdiv"></div>

This code was borrowed right from the amcharts demo site at https://www.amcharts.com/demos/multi-series-map/

This is using a multiseries map. I am not sure which one you are using, but you will want to navigate to the demo of that map and then copy the demo code from the bottom. DONT WORRY ABOUT THE JS FILES. Just link those to your page and then copy the demo code. The map should work out of the box.


问:
A way to send a Microsoft Teams chat message from SSIS
Is it possible to send an MS Teams chat message to one or more people or even to a Team Post from SSIS?

We have some processes that send notices via Email, but anymore email is just too busy and it would be nice to have a central location in Teams to have messages when certain items complete or fail via SSIS.

答:
The are a few possible options for this. If you're sending email already, the most simple might be to just use the Team (i.e. Channel's) email address. To access this, go to the "..." menu next to the channel name, and select "get email address", as shown below.

A popup will appear showing the channel's email address.

Here's a video showing this.

Another option is to set up an "incoming webhook". I've not done this in SSIS, but I think this would involve using a Script Task to call the endpoint that gets created.


问:
Drawing bezierCurve in d3.js
How to draw the line using bezierCurveTo method in d3.js such that lines appears as below image

I have just referred bezier Curve but i'm not getting any idea on it.

答:
There are a lot of ways this could be done. One could make a custom curve that achieves this.

But, we could keep it simpler too. The datum passed to the link generator, such as d3.linkHorizontal, from a d3 layout generally contains a source and target property, each of these usually contain x and y properties. Assuming this structure, we could create a function that uses these and creates and returns the appropriate path data with a bezier curve:

```<code>var linker = function(d) {
  var x0 = d.source.x;
  var y0 = d.source.y;
  var y1 = d.target.y;
  var x1 = d.target.x;
  var k = 120;

  var path = d3.path()
  path.moveTo(y0,x0)
  path.bezierCurveTo(y1-k,x0,y0,x1,y1-k,x1);
  path.lineTo(y1,x1);

  return path.toString();
}
</code>```

The above is pretty basic, it uses d3.path but you could easily just construct the SVG path string yourself. There are lots of interactive bezier curve explorers online so you can figure out what control points work best. As the tree layout I've used is vertical, I've turned it horizontal by inverting x and y, which is why my coordinates are [y,x]. I use k above to offset the bezier curve to a small portion of the overall link on the left:

But you could easily toy with this to place the curve in the middle of the link:

Here's it in action:

var data = { "name": "Parent", "children": [
    { "name": "Child A", "children": [ { "name": "Grandchild1"}, {"name":"Grandchild2" } ] },
    { "name": "Child B", }
    ] };

var width = 400;
var height = 300;

margin = {left: 50, top: 10, right:30, bottom: 10}

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

var g = svg.append("g").attr('transform','translate('+ margin.left +','+ margin.right +')');

var root = d3.hierarchy(data);

var tree = d3.tree()
   .size([height-margin.top-margin.bottom,width-margin.left-margin.right]);

var linker = function(d) {
  var x0 = d.source.x;
  var y0 = d.source.y;
  var y1 = d.target.y;
  var x1 = d.target.x;
  var k = (y1-y0)/2;

  var path = d3.path()
  path.moveTo(y0,x0)
  path.lineTo(y0+k/2,x0)
  path.bezierCurveTo(y1-k,x0,y0+k,x1,y1-k/2,x1);
  path.lineTo(y1,x1);

  return path.toString();
}

 var link = g.selectAll(".link")
    .data(tree(root).links())
    .enter().append("path")
      .attr("class", "link")
      .attr("d", linker);

  var node = g.selectAll(".node")
    .data(root.descendants())
    .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 2.5);

  node.append("text")
     .text(function(d) { return d.data.name; })
     .attr('y',-10)
     .attr('x',-10)
     .attr('text-anchor','middle');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node circle {
          fill: #fff;
          stroke: steelblue;
          stroke-width: 3px;
        }

        .link {
          fill: none;
          stroke: #ccc;
          stroke-width: 2px;
        }</code>```

```
</div>
</div>
</p>
<p><em>But, in reading the comments I notice that your question may be more about dagreD3 - which changes things considerably.</em> Dagre D3 offers better ease of use relative to D3 at the cost of the some of D3's flexibility. If you want to provide a certain type of curve to DagreD3, then you should use a d3 curve, or some custom curve (as in the linked answer above). You can specify the curve when adding edges easily enough.</p>
<p>But that doesn't solve the issue of edges originating from the same point as in your image. I'll provide a d3 based solution - which probably breaks edge label placement, transitions, etc - so it should be built out a bit if you need that functionality. I'll use the bezier generator from above. The following is inspired by this:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var g = new dagreD3.graphlib.Graph()
  .setGraph({rankdir: 'LR'})
  .setDefaultEdgeLabel(function() { return {}; });

g.setNode(0,  { label: "0"});
g.setNode(1,  { label: "1"});
g.setNode(2,  { label: "2"});
g.setNode(3,  { label: "3"});
g.setNode(4,  { label: "4"});

g.setEdge(0, 1);
g.setEdge(0, 2);
g.setEdge(1, 3);
g.setEdge(1, 4);

var render = new dagreD3.render().createEdgePaths(createEdgePaths);

var svg = d3.select("svg"),
    svgGroup = svg.append("g"),
    zoom = d3.zoom().on("zoom", function() {
      svgGroup.attr("transform", d3.event.transform);
    });
svg.call(zoom);

render(svgGroup, g);

function createEdgePaths(selection, g, arrows) {
   selection.selectAll("g.edgePath")
    .data(g.edges())
    .enter()
    .append("path")
    .attr("d", function(e) {
      return calcPoints(g,e);
    });
}

function calcPoints(g, e) {
  var source = g.node(e.v);
  var target = g.node(e.w);
  var x0 = source.x + source.width/2;
  var x1 = target.x - target.width/2;
  var y0 = source.y;
  var y1 = target.y;
  return linker(x0,y0,x1,y1)
}
function linker(x0,y0,x1,y1) {
 var dx = x1 -x0;
 var k = dx/3;

 var path = d3.path()
 path.moveTo(x0,y0)
 path.bezierCurveTo(x1-k,y0,x0,y1,x1-k,y1);
 path.lineTo(x1,y1);

 return path.toString();
}</code>```

path {
  stroke: #333;
  stroke-width: 1.5px;
  fill: none;
}
rect {
  fill: none;
  stroke:black;
  stroke-width: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dagre-d3@0.6.1/dist/dagre-d3.min.js"></script>
<svg width="800" height="600"></svg></code>```

Title: Drawing bezierCurve in d3.js

Body:
There are a lot of ways this could be done. One could make a custom curve that achieves this.

But, we could keep it simpler too. The datum passed to the link generator, such as d3.linkHorizontal, from a d3 layout generally contains a source and target property, each of these usually contain x and y properties. Assuming this structure, we could create a function that uses these and creates and returns the appropriate path data with a bezier curve:

var linker = function(d) {
  var x0 = d.source.x;
  var y0 = d.source.y;
  var y1 = d.target.y;
  var x1 = d.target.x;
  var k = 120;

  var path = d3.path()
  path.moveTo(y0,x0)
  path.bezierCurveTo(y1-k,x0,y0,x1,y1-k,x1);
  path.lineTo(y1,x1);

  return path.toString();
}

The above is pretty basic, it uses d3.path but you could easily just construct the SVG path string yourself. There are lots of interactive bezier curve explorers online so you can figure out what control points work best. As the tree layout I've used is vertical, I've turned it horizontal by inverting x and y, which is why my coordinates are [y,x]. I use k above to offset the bezier curve to a small portion of the overall link on the left:

But you could easily toy with this to place the curve in the middle of the link:

Here's it in action:

var data = { "name": "Parent", "children": [
    { "name": "Child A", "children": [ { "name": "Grandchild1"}, {"name":"Grandchild2" } ] },
    { "name": "Child B", }
    ] };

var width = 400;
var height = 300;

margin = {left: 50, top: 10, right:30, bottom: 10}

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

var g = svg.append("g").attr('transform','translate('+ margin.left +','+ margin.right +')');

var root = d3.hierarchy(data);

var tree = d3.tree()
   .size([height-margin.top-margin.bottom,width-margin.left-margin.right]);

var linker = function(d) {
  var x0 = d.source.x;
  var y0 = d.source.y;
  var y1 = d.target.y;
  var x1 = d.target.x;
  var k = (y1-y0)/2;

  var path = d3.path()
  path.moveTo(y0,x0)
  path.lineTo(y0+k/2,x0)
  path.bezierCurveTo(y1-k,x0,y0+k,x1,y1-k/2,x1);
  path.lineTo(y1,x1);

  return path.toString();
}

 var link = g.selectAll(".link")
    .data(tree(root).links())
    .enter().append("path")
      .attr("class", "link")
      .attr("d", linker);

  var node = g.selectAll(".node")
    .data(root.descendants())
    .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 2.5);

  node.append("text")
     .text(function(d) { return d.data.name; })
     .attr('y',-10)
     .attr('x',-10)
     .attr('text-anchor','middle');

.node circle {
          fill: #fff;
          stroke: steelblue;
          stroke-width: 3px;
        }

        .link {
          fill: none;
          stroke: #ccc;
          stroke-width: 2px;
        }

<script src="https://d3js.org/d3.v4.min.js"></script>

But, in reading the comments I notice that your question may be more about dagreD3 - which changes things considerably. Dagre D3 offers better ease of use relative to D3 at the cost of the some of D3's flexibility. If you want to provide a certain type of curve to DagreD3, then you should use a d3 curve, or some custom curve (as in the linked answer above). You can specify the curve when adding edges easily enough.

But that doesn't solve the issue of edges originating from the same point as in your image. I'll provide a d3 based solution - which probably breaks edge label placement, transitions, etc - so it should be built out a bit if you need that functionality. I'll use the bezier generator from above. The following is inspired by this:

var g = new dagreD3.graphlib.Graph()
  .setGraph({rankdir: 'LR'})
  .setDefaultEdgeLabel(function() { return {}; });

g.setNode(0,  { label: "0"});
g.setNode(1,  { label: "1"});
g.setNode(2,  { label: "2"});
g.setNode(3,  { label: "3"});
g.setNode(4,  { label: "4"});

g.setEdge(0, 1);
g.setEdge(0, 2);
g.setEdge(1, 3);
g.setEdge(1, 4);

var render = new dagreD3.render().createEdgePaths(createEdgePaths);

var svg = d3.select("svg"),
    svgGroup = svg.append("g"),
    zoom = d3.zoom().on("zoom", function() {
      svgGroup.attr("transform", d3.event.transform);
    });
svg.call(zoom);

render(svgGroup, g);

function createEdgePaths(selection, g, arrows) {
   selection.selectAll("g.edgePath")
    .data(g.edges())
    .enter()
    .append("path")
    .attr("d", function(e) {
      return calcPoints(g,e);
    });
}

function calcPoints(g, e) {
  var source = g.node(e.v);
  var target = g.node(e.w);
  var x0 = source.x + source.width/2;
  var x1 = target.x - target.width/2;
  var y0 = source.y;
  var y1 = target.y;
  return linker(x0,y0,x1,y1)
}
function linker(x0,y0,x1,y1) {
 var dx = x1 -x0;
 var k = dx/3;

 var path = d3.path()
 path.moveTo(x0,y0)
 path.bezierCurveTo(x1-k,y0,x0,y1,x1-k,y1);
 path.lineTo(x1,y1);

 return path.toString();
}

path {
  stroke: #333;
  stroke-width: 1.5px;
  fill: none;
}
rect {
  fill: none;
  stroke:black;
  stroke-width: 1px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dagre-d3@0.6.1/dist/dagre-d3.min.js"></script>
<svg width="800" height="600"></svg>


问:
Compass setting
Compass calibrated correctly. To get the compass angle (360 degrees) I'm using the code

```<code>        heading = 180 * math.atan2(yh,xh)/math.pi
        if (yh >= 0):
            return heading
        else:
            return 360 + heading
</code>```

Its ok. North indicates correctly. The question is what to do to add or leave the result eg. + 20 / -20 degrees (I need to put the compass in one fixed position.)

Thanks for help!

答:
You can add (or subtract) from the heading and use the modulo operator to stay between 0-359 if you like:

```<code>def rotate(heading, degree_change):
    return (heading + degree_change) % 360
</code>```

In addition, you could use the modulo operator to simplify the code you already have:

```<code>heading = (180 * math.atan2(yh,xh)/math.pi) % 360
</code>```

Title: Compass setting

Body:
Compass calibrated correctly. To get the compass angle (360 degrees) I'm using the code

        heading = 180 * math.atan2(yh,xh)/math.pi
        if (yh >= 0):
            return heading
        else:
            return 360 + heading

Its ok. North indicates correctly. The question is what to do to add or leave the result eg. + 20 / -20 degrees (I need to put the compass in one fixed position.)

Thanks for help!

Body:
You can add (or subtract) from the heading and use the modulo operator to stay between 0-359 if you like:

def rotate(heading, degree_change):
    return (heading + degree_change) % 360

In addition, you could use the modulo operator to simplify the code you already have:

heading = (180 * math.atan2(yh,xh)/math.pi) % 360


问:
In PHP Remove several characters from the beginning of a String?
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

```<code>JOHN
MIKE
BEN
*BJAMES
PETE
</code>```

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

```<code>if ( preg_match( "/^\*(B)/",$contents[$a] ) )
</code>```

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

答:
Have a try with:</p>

```<code>preg_replace('/^\*B/', '', $content[$a], -1, $count);
if ($count) {
    fwrite($file, $content[$a]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

JOHN
MIKE
BEN
*BJAMES
PETE

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

if ( preg_match( "/^\*(B)/",$contents[$a] ) )

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

Body:
Have a try with:

preg_replace('/^\*B/', '', $content[$a], -1, $count);
if ($count) {
    fwrite($file, $content[$a]);
}


问:
Calling saxon from python 3.7
I am trying to call saxon from python. Before I was using os.system(command) in python 2.x and everything worked fine, but something has changed between 2.7 and 3.7. My code no longer works. I have tried using "subprocess.call(command)" and "subprocess.run(command)", but neither seems to work. Here's what was working before:

```<code>command = "java -jar C:\\saxon\\saxon9he.jar -o:\"" + directory + "\\_new.xml\" " + "-xsl:\"" + xslDir + "\" -s:\"" + newFile + "\""
os.system(command)
</code>```

The command runs fine in a cmd prompt (when I replace the variables with actual files). But nothing is working in 3.7. Thanks in advance.

答: Hi the latest Saxon/C version supports Python 3. See: details: https://www.saxonica.com/saxon-c/index.xml</p>

Title: Calling saxon from python 3.7

Body:
I am trying to call saxon from python. Before I was using os.system(command) in python 2.x and everything worked fine, but something has changed between 2.7 and 3.7. My code no longer works. I have tried using "subprocess.call(command)" and "subprocess.run(command)", but neither seems to work. Here's what was working before:

command = "java -jar C:\\saxon\\saxon9he.jar -o:\"" + directory + "\\_new.xml\" " + "-xsl:\"" + xslDir + "\" -s:\"" + newFile + "\""
os.system(command)

The command runs fine in a cmd prompt (when I replace the variables with actual files). But nothing is working in 3.7. Thanks in advance.


问:
How can I replace a tkinter label with a new one?
I'm trying to write a fairly simple program that converts a number into binary using a tkinter GUI. The problem I'm running into is that when I enter a large number (1000 for example) and then input a smaller number (like 2) and hit submit, the new output just shows up in the middle of the old one. With the examples I used it looks something like "1000 i 2 in binary is 10 01000"

How can I remove the old label entirely right before showing the new one?

```<code>from tkinter import *

win = Tk()

def compute_binary():
    user_num = binary_entry.get()
    user_num = int(user_num)
    binary_equivalent = ("{:b}".format(user_num))
    binary_output = StringVar()
    binary_output.set(str(user_num) + " in binary is " + binary_equivalent)
    binary_label = Label(win, textvariable = binary_output)
    binary_label.grid(row = 1, column = 1)

win.title("Number to Binary Converter")

win.geometry("450x75")

input_request = Label(win, text = "Input a number to\nconvert to binary:")
input_request.grid(row = 0, column = 0)

binary_entry = Entry(win)
binary_entry.grid(row = 0, column = 1)

entry_confirm = Button(win, text = "Submit", command = compute_binary)
entry_confirm.grid(row=0, column = 2)

win.mainloop()
</code>```

答:
You recreate new label for the result in each conversion and the new label is overlay on top of the previous label.

You need to create the result label once and update it in each conversion:

```<code>from tkinter import *

win = Tk()

def compute_binary():
    user_num = binary_entry.get()
    user_num = int(user_num)
    binary_equivalent = ("{:b}".format(user_num))
    binary_output.set("{} in binary is {}".format(user_num, binary_equivalent))

win.title("Number to Binary Converter")

win.geometry("450x75")

input_request = Label(win, text="Input a number to\nconvert to binary:")
input_request.grid(row=0, column=0)

binary_entry = Entry(win)
binary_entry.grid(row=0, column=1)

entry_confirm = Button(win, text="Submit", command=compute_binary)
entry_confirm.grid(row=0, column=2)

binary_output = StringVar()
binary_label = Label(win, textvariable=binary_output)
binary_label.grid(row=1, column=0, columnspan=3)

win.mainloop()
</code>```

Body:
I'm trying to write a fairly simple program that converts a number into binary using a tkinter GUI. The problem I'm running into is that when I enter a large number (1000 for example) and then input a smaller number (like 2) and hit submit, the new output just shows up in the middle of the old one. With the examples I used it looks something like "1000 i 2 in binary is 10 01000"

How can I remove the old label entirely right before showing the new one?

from tkinter import *

win = Tk()

def compute_binary():
    user_num = binary_entry.get()
    user_num = int(user_num)
    binary_equivalent = ("{:b}".format(user_num))
    binary_output = StringVar()
    binary_output.set(str(user_num) + " in binary is " + binary_equivalent)
    binary_label = Label(win, textvariable = binary_output)
    binary_label.grid(row = 1, column = 1)

win.title("Number to Binary Converter")

win.geometry("450x75")

input_request = Label(win, text = "Input a number to\nconvert to binary:")
input_request.grid(row = 0, column = 0)

binary_entry = Entry(win)
binary_entry.grid(row = 0, column = 1)

entry_confirm = Button(win, text = "Submit", command = compute_binary)
entry_confirm.grid(row=0, column = 2)

win.mainloop()

Body:
You recreate new label for the result in each conversion and the new label is overlay on top of the previous label.

You need to create the result label once and update it in each conversion:

from tkinter import *

win = Tk()

def compute_binary():
    user_num = binary_entry.get()
    user_num = int(user_num)
    binary_equivalent = ("{:b}".format(user_num))
    binary_output.set("{} in binary is {}".format(user_num, binary_equivalent))

win.title("Number to Binary Converter")

win.geometry("450x75")

input_request = Label(win, text="Input a number to\nconvert to binary:")
input_request.grid(row=0, column=0)

binary_entry = Entry(win)
binary_entry.grid(row=0, column=1)

entry_confirm = Button(win, text="Submit", command=compute_binary)
entry_confirm.grid(row=0, column=2)

binary_output = StringVar()
binary_label = Label(win, textvariable=binary_output)
binary_label.grid(row=1, column=0, columnspan=3)

win.mainloop()


问:
How to set an alarm to be scheduled at an exact time after all the newest restrictions on Android?
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

```<code>            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }
</code>```

```<code>class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}
</code>```

Usage:

```<code>            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)
</code>```

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

```<code>            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
</code>```

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks

答:
We Don't have anything to do.

Once your app is not whitelisted it will be always killed once removed from recent-apps.

Because Original Equipment Manufacturer (OMEs) constantly violating Android compliance.

So If your app is not whitelisted from the device Manufacture it won't fire any background work even alarms - in case your app is removed from recent-apps.

You can find a list of devices with that behavior here ALSO you might find a side-solution, However, it won't work well.

Body:
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}

Usage:

            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks


问:
sum of TOP N in Mysql
Below is my sample table. I want to get the TOP1 student for sum of score of each course

```<code>    create table SC(
SId varchar(10) comment "Student ID",
CId varchar(10) comment "Course ID",
score decimal(18,1) comment "Test Score");

insert into SC values('01' , '01' , 100);
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 60);
insert into SC values('02' , '03' , 70);
</code>```

so the result would be:

I used below code but the score was not sum

```<code>SELECT SId,CId,sum(score)  from sc a
where 1 > (SELECT count(*) from sc where a.CId=CId and  a.score <score)
group by CId
ORDER BY CId
</code>```

I have Mysql 5.7, can you plz help?

答:
```<code>SELECT SId,
       CId,
       SUM(score) score
FROM SC a
GROUP BY SId, CId
HAVING score >= ALL ( SELECT SUM(score)
                      FROM SC b
                      WHERE a.CId=b.CId
                      GROUP BY b.SId, b.CId );
</code>```

fiddle

what if there are more students and I want TOP3 for example?

```<code>SELECT SId, CId, score
FROM ( SELECT SId, CId, score,
              @rownumber := IF(@course = CId, @rownumber + 1, 1) rownumber,
              @course := CId
       FROM ( SELECT SId, CId, SUM(score) score
              FROM SC a
              GROUP BY SId, CId ) data,
            ( SELECT @rownumber:=0, @course:='' ) vars
       ORDER BY CId, score DESC ) data
WHERE rownumber <= 3;
</code>```

fiddle

Title: sum of TOP N in Mysql

Body:
Below is my sample table. I want to get the TOP1 student for sum of score of each course

    create table SC(
SId varchar(10) comment "Student ID",
CId varchar(10) comment "Course ID",
score decimal(18,1) comment "Test Score");

insert into SC values('01' , '01' , 100);
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 60);
insert into SC values('02' , '03' , 70);

so the result would be:

I used below code but the score was not sum

SELECT SId,CId,sum(score)  from sc a
where 1 > (SELECT count(*) from sc where a.CId=CId and  a.score <score)
group by CId
ORDER BY CId

I have Mysql 5.7, can you plz help?

Body:
SELECT SId,
       CId,
       SUM(score) score
FROM SC a
GROUP BY SId, CId
HAVING score >= ALL ( SELECT SUM(score)
                      FROM SC b
                      WHERE a.CId=b.CId
                      GROUP BY b.SId, b.CId );

fiddle

what if there are more students and I want TOP3 for example?

SELECT SId, CId, score
FROM ( SELECT SId, CId, score,
              @rownumber := IF(@course = CId, @rownumber + 1, 1) rownumber,
              @course := CId
       FROM ( SELECT SId, CId, SUM(score) score
              FROM SC a
              GROUP BY SId, CId ) data,
            ( SELECT @rownumber:=0, @course:='' ) vars
       ORDER BY CId, score DESC ) data
WHERE rownumber <= 3;

fiddle


问:
Find length of a string in SQL using LIKE operator
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

```<code>o/p - 1-17
      2-13
</code>```

答:
Is this what you are looking for?

```<code>select length(columnname) from tablename where lower(columnname) like 'animal%';`
</code>```

This gives you the length of the text in the column, columnname when the columnname value contains the word 'animal'

Body:
Example:

Suppose there are following rows:

1- Animal is innocent
 2- Dog is Animal

select length(columnname like %animal%) from tablename

o/p - 1-17
      2-13

Body:
Is this what you are looking for?

select length(columnname) from tablename where lower(columnname) like 'animal%';`

This gives you the length of the text in the column, columnname when the columnname value contains the word 'animal'


问:
If a browser can shows Accept-Encoding of deflate, can it handle .NET gzipped responses?
I'm looking at this method in this HTTPCombiner:

```<code>private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}
</code>```

If this returns true then the response is compressed using a GZipStream. Is this right?

答:
GZip (which is based on Deflate) and Deflate are two different algorithms, so a request for "deflate" should definitely not return gzipped content.

However, this should be easy to fix, by simply using a GZipStream if the accept header contains "gzip" and a DeflateStream for "deflate".

Both are included in System.IO.Compression, so it's not like you'd have to code your own deflate algorithm or use a third party implementation.

Body:
I'm looking at this method in this HTTPCombiner:

private bool CanGZip(HttpRequest request)
{
    string acceptEncoding = request.Headers["Accept-Encoding"];
    if (!string.IsNullOrEmpty(acceptEncoding) &&
         (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
        return true;
    return false;
}

If this returns true then the response is compressed using a GZipStream. Is this right?


问:
In Powershell: Remove lines from a text file if it contains a set words stored in another text file
I know:

```<code>Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt
</code>```

But i need to fetch -pattern from another text file as the patterns are 300k so cannot be piped.

What is the modified command?

答:
Pattern will take an array of patterns, which can just as easily be the result of Get-Content of another file.  Select-String emits objects, so if your're hoping the matched lines are going to be in he file it's going to be wrong.

In that case it will show the filename the line number and the matched line.

To get just the lines try something like:

```<code>$Pattern = Get-Content <SomeFile.txt>
(Select-String -path C:\new\temp_*.txt -Pattern $pattern).Line | Out-File C:\new\newfile.txt
</code>```

Establishing the $Pattern variable as an array of patterns sourced from a file

Instead of piping the files to select string use the -Path parameter with the wildcard pattern.

Then reference & pipe the line property of the match objects instead of piping the objects themselves to the file.

This will result in only the matching lines being present in the output file.

let me know if that helps.

Body:
I know:

Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt

But i need to fetch -pattern from another text file as the patterns are 300k so cannot be piped.

What is the modified command?

Body:
Pattern will take an array of patterns, which can just as easily be the result of Get-Content of another file.  Select-String emits objects, so if your're hoping the matched lines are going to be in he file it's going to be wrong.

In that case it will show the filename the line number and the matched line.

To get just the lines try something like:

$Pattern = Get-Content <SomeFile.txt>
(Select-String -path C:\new\temp_*.txt -Pattern $pattern).Line | Out-File C:\new\newfile.txt

Establishing the $Pattern variable as an array of patterns sourced from a file

Instead of piping the files to select string use the -Path parameter with the wildcard pattern.

Then reference & pipe the line property of the match objects instead of piping the objects themselves to the file.

This will result in only the matching lines being present in the output file.

let me know if that helps.


问:
Loop query through multiple tables
I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:

```<code>select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0
</code>```

and I would like to loop through all the years from 2001 to 2020. So it should look like this:

```<code>select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2002  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2003  p    --Looping trough all the tables until 2020
join products po on p.productID = po.id
where price < 0
</code>```

If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?

Thank you!

答:
This is difficult and costly (looping a SQL statement!) because your schema is bad. You should instead have a single table prices that is identical to your existing tables, but has one extra column called year. Then joining becomes simple and you don't have to create new tables just because the date changed.

Instead though you can UNION your tables together and get the same thing. Something like:

```<code>SELECT p.productID, po.name, p.price, po.year
FROM products p
     INNER JOIN
         (
              SELECT id, name, 2001 as year FROM prices_2001
              UNION ALL SELECT id, name, 2002 FROM prices_2002
              UNION ALL SELECT id, name, 2003 FROM prices_2003
              UNION ALL ... <continue until you have all year tables accounted for>
         ) po
         ON p.productID = po.id
WHERE po.price < 0;
</code>```

Consider writing the results of that UNION subquery to a new table though and just using that from now on.

Title: Loop query through multiple tables

Body:
I would like to the same query which should almost never return any results through multiple tables. The table name is the same except with the addition of the year. So my query looks like this:

select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

and I would like to loop through all the years from 2001 to 2020. So it should look like this:

select p.productID, po.name, p.price from prices_2001  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2002  p
join products po on p.productID = po.id
where price < 0

select p.productID, po.name, p.price from prices_2003  p    --Looping trough all the tables until 2020
join products po on p.productID = po.id
where price < 0

If there are results they can be stored in a temp table. I thought of creating a loop with the table names or creating dynamic sql query. What is the best practice and how can I use this query for all the tables just by executing it once?

Thank you!

Body:
This is difficult and costly (looping a SQL statement!) because your schema is bad. You should instead have a single table prices that is identical to your existing tables, but has one extra column called year. Then joining becomes simple and you don't have to create new tables just because the date changed.

Instead though you can UNION your tables together and get the same thing. Something like:

SELECT p.productID, po.name, p.price, po.year
FROM products p
     INNER JOIN
         (
              SELECT id, name, 2001 as year FROM prices_2001
              UNION ALL SELECT id, name, 2002 FROM prices_2002
              UNION ALL SELECT id, name, 2003 FROM prices_2003
              UNION ALL ... <continue until you have all year tables accounted for>
         ) po
         ON p.productID = po.id
WHERE po.price < 0;

Consider writing the results of that UNION subquery to a new table though and just using that from now on.


问:
How do I replace @click event programmatically?

        Label

```

<pre class="lang-js prettyprint-override"><code>    export default{
        data(){
            ...
        },
        methods:{
            add_filter: function(event){
               this.$refs.filters.appendChild(event.target)
               event.target.removeEventListener('click', this.add_filter)
               event.target.addEventListener('click', this.remove_filter)
            },
            remove_filter: function(event){
               this.$refs.available.appendChild(event.target)
               event.target.removeEventListener('click', this.remove_filter)
               event.target.addEventListener('click', this.add_filter)
            }
        }
</code>```

So, removeEventListener doesn't work is this case. There's any way that I can accomplish to "toggle" the @click event?

答:
Here is an example with a single method. It checks if a list of the HTMLCollection ([...this.$refs.filters.children]) filters contains the clicked item based on innerText. I added a second element with the same class to show you that it works as long as the text is different.

new Vue({
  el: "#app",
  data() {
    return {}
  },
  methods: {
    toggle_filter: function(event){
    if([...this.$refs.filters.children].filter(child=>child.innerText==event.target.innerText).length==0){
        this.$refs.filters.appendChild(event.target)
      }else{
        this.$refs.available.appendChild(event.target)
      }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Filters</h2>
  <div ref="filters"></div>

<h2>Available</h2>
  <div ref="available">
    <span class="badge badge-pill" @click="toggle_filter">Label 1</span>
    <span class="badge badge-pill" @click="toggle_filter">Label 2</span>
  </div>
</div></code>```

Body:
        Label

    export default{
        data(){
            ...
        },
        methods:{
            add_filter: function(event){
               this.$refs.filters.appendChild(event.target)
               event.target.removeEventListener('click', this.add_filter)
               event.target.addEventListener('click', this.remove_filter)
            },
            remove_filter: function(event){
               this.$refs.available.appendChild(event.target)
               event.target.removeEventListener('click', this.remove_filter)
               event.target.addEventListener('click', this.add_filter)
            }
        }

So, removeEventListener doesn't work is this case. There's any way that I can accomplish to "toggle" the @click event?

Body:
Here is an example with a single method. It checks if a list of the HTMLCollection ([...this.$refs.filters.children]) filters contains the clicked item based on innerText. I added a second element with the same class to show you that it works as long as the text is different.

new Vue({
  el: "#app",
  data() {
    return {}
  },
  methods: {
    toggle_filter: function(event){
    if([...this.$refs.filters.children].filter(child=>child.innerText==event.target.innerText).length==0){
        this.$refs.filters.appendChild(event.target)
      }else{
        this.$refs.available.appendChild(event.target)
      }
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Filters</h2>
  <div ref="filters"></div>

<h2>Available</h2>
  <div ref="available">
    <span class="badge badge-pill" @click="toggle_filter">Label 1</span>
    <span class="badge badge-pill" @click="toggle_filter">Label 2</span>
  </div>
</div>


问:
How to switch UIImages in UIViewController from Array by pressing UIButton
So I have a storyboard with UIImageView and two buttons and I need these buttons to change images in UIImageView. UIImages stored in an Array. I tried for in but it can show only only first image. Help would be appreciated :)

class ViewController: UIViewController {

```<code>var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }

// Do any additional setup after loading the view.

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}
</code>```

答:
```<code>var images = [UIImage(named: "2"), UIImage(named: "3"), UIImage(named: "4")]
var actualImage = 0 // counter to know witch image is displayed

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any) {
    imageView.image = images[actualImage]

    if actualImage == images.count - 1 { // check if i'm at the last picture
        actualImage = 0 // reset the counter to the first position
    } else {
        actualImage += 1
    }
}
</code>```

Body:
So I have a storyboard with UIImageView and two buttons and I need these buttons to change images in UIImageView. UIImages stored in an Array. I tried for in but it can show only only first image. Help would be appreciated :)

class ViewController: UIViewController {

var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }

// Do any additional setup after loading the view.

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}


问:
Change border color of donut chart
I made a DONUT chart with APEXCHARTS. It looks like this:

Here is my code:

var options = {
          series: [44, 55, 41, 17, 15],
          labels: ['Apple', 'Mango', 'Orange', 'Watermelon', 'test'],
        chart: {
          type: 'donut',
          foreColor: '#ffffff'
        },
        grid: {
          borderColor: "#EF3252"
        },
        plotOptions: {
          pie: {
            expandOnClick: false
          }
        },
        responsive: [{
          breakpoint: 480,
          options: {
            chart: {
              width: '100%'
            },
            legend: {
              position: 'bottom'
            }
          }
        }],
        datasets: [{
          borderColor: ["#EF3252"]
        }]
        };

   var chart = new ApexCharts(document.getElementById("stats1_chart1"), options);
   chart.render();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="stats1_chart1"></div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script></code>```

I want to achieve to change the border-color. But I can't figure out how this should work.

~Marcus

答:
Just add the stroke attribute:

var options = {
          series: [44, 55, 41, 17, 15],
          labels: ['Apple', 'Mango', 'Orange', 'Watermelon', 'test'],
        chart: {
          type: 'donut',
          foreColor: '#ffffff'
        },
        grid: {
          borderColor: "#EF3252"
        },
        plotOptions: {
          pie: {
            expandOnClick: false
          }
        },
        stroke:{
         colors:['#000']
        },
        responsive: [{
          breakpoint: 480,
          options: {
            chart: {
              width: '100%'
            },
            legend: {
              position: 'bottom'
            }
          }
        }],
        datasets: [{
          borderColor: ["#EF3252"]
        }]
        };

   var chart = new ApexCharts(document.getElementById("stats1_chart1"), options);
   chart.render();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="stats1_chart1"></div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script></code>```

Title: Change border color of donut chart

Body:
I made a DONUT chart with APEXCHARTS. It looks like this:

Here is my code:

var options = {
          series: [44, 55, 41, 17, 15],
          labels: ['Apple', 'Mango', 'Orange', 'Watermelon', 'test'],
        chart: {
          type: 'donut',
          foreColor: '#ffffff'
        },
        grid: {
          borderColor: "#EF3252"
        },
        plotOptions: {
          pie: {
            expandOnClick: false
          }
        },
        responsive: [{
          breakpoint: 480,
          options: {
            chart: {
              width: '100%'
            },
            legend: {
              position: 'bottom'
            }
          }
        }],
        datasets: [{
          borderColor: ["#EF3252"]
        }]
        };

   var chart = new ApexCharts(document.getElementById("stats1_chart1"), options);
   chart.render();

I want to achieve to change the border-color. But I can't figure out how this should work.

~Marcus

Body:
Just add the stroke attribute:

var options = {
          series: [44, 55, 41, 17, 15],
          labels: ['Apple', 'Mango', 'Orange', 'Watermelon', 'test'],
        chart: {
          type: 'donut',
          foreColor: '#ffffff'
        },
        grid: {
          borderColor: "#EF3252"
        },
        plotOptions: {
          pie: {
            expandOnClick: false
          }
        },
        stroke:{
         colors:['#000']
        },
        responsive: [{
          breakpoint: 480,
          options: {
            chart: {
              width: '100%'
            },
            legend: {
              position: 'bottom'
            }
          }
        }],
        datasets: [{
          borderColor: ["#EF3252"]
        }]
        };

   var chart = new ApexCharts(document.getElementById("stats1_chart1"), options);
   chart.render();

<div id="stats1_chart1"></div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>


问:
Exception when parsing xml file using Xerces
I have the following code

```<code>    XercesDOMParser *parser = new XercesDOMParser();
    parser->setExternalNoNamespaceSchemaLocation("personal.xsd");
    parser->setExitOnFirstFatalError(true);
    parser->setValidationConstraintFatal(true);
    parser->setValidationScheme(XercesDOMParser::Val_Auto);
    parser->setDoNamespaces(false);
    parser->setDoSchema(true);
    ErrorHandler* errHandler = (ErrorHandler*) new Error_handler();
    parser->setErrorHandler(errHandler);

    try
    {
        const char *const xmlFile = "personal.xml";
        parser->parse(xmlFile);
    }
    catch (const XMLException& toCatch)
    {
        char* message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n"
            << message << "\n";
        XMLString::release(&message);
    }
    catch (const DOMException& toCatch)
    {
        char* message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n"
            << message << "\n";
        XMLString::release(&message);
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
    }
</code>```

I get an exception in the following line:

```<code>parser->parse(xmlFile);
</code>```

Windows Xp, visual studio 2008, xerces-c-3.1.1.

Any ideas?

答:
The bug was somewhere else afterall.

Always call XMLPlatformUtils::Initialize() in the beginning and XMLPlatformUtils::Terminate() in the end.

Body:
I have the following code

    XercesDOMParser *parser = new XercesDOMParser();
    parser->setExternalNoNamespaceSchemaLocation("personal.xsd");
    parser->setExitOnFirstFatalError(true);
    parser->setValidationConstraintFatal(true);
    parser->setValidationScheme(XercesDOMParser::Val_Auto);
    parser->setDoNamespaces(false);
    parser->setDoSchema(true);
    ErrorHandler* errHandler = (ErrorHandler*) new Error_handler();
    parser->setErrorHandler(errHandler);

    try
    {
        const char *const xmlFile = "personal.xml";
        parser->parse(xmlFile);
    }
    catch (const XMLException& toCatch)
    {
        char* message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n"
            << message << "\n";
        XMLString::release(&message);
    }
    catch (const DOMException& toCatch)
    {
        char* message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n"
            << message << "\n";
        XMLString::release(&message);
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
    }

I get an exception in the following line:

parser->parse(xmlFile);

Windows Xp, visual studio 2008, xerces-c-3.1.1.

Any ideas?


问:
replace a specific character within a list of strings using list comprehension
```<code>my_list = ['"r&d"', '"clinical trial"']
</code>```

my desired output

```<code>my_list = ['"r%26d"', '"clinical trial"']
</code>```

my code attempt 1:

```<code>my_list = [char.replace('&',"%26") for char in item for item in my_list]
</code>```

result 1

```<code>my_list = ['"r&d"', '"clinical trial"']
</code>```

my code attempt 2:

```<code>my_list = [[char.replace('&',"%26") for char in item] for item in my_list]
</code>```

result 2

```<code>[['r', '%26', 'd'], ['c', 'l', 'i', 'n', 'i', 'c', 'a', 'l', ' ', 't', 'r', 'i', 'a', 'l']]
</code>```

I would like to use list comprehension.

答:
A single for is enough in the list comprehension:</p>

```<code>[item.replace('&',"%26") for item in my_list]
# ['"r%26d"', '"clinical trial"']
</code>```

Body:
my_list = ['"r&d"', '"clinical trial"']

my desired output

my_list = ['"r%26d"', '"clinical trial"']

my code attempt 1:

my_list = [char.replace('&',"%26") for char in item for item in my_list]

result 1

my_list = ['"r&d"', '"clinical trial"']

my code attempt 2:

my_list = [[char.replace('&',"%26") for char in item] for item in my_list]

result 2

[['r', '%26', 'd'], ['c', 'l', 'i', 'n', 'i', 'c', 'a', 'l', ' ', 't', 'r', 'i', 'a', 'l']]

I would like to use list comprehension.

Body:
A single for is enough in the list comprehension:

[item.replace('&',"%26") for item in my_list]
# ['"r%26d"', '"clinical trial"']


答:
You want to use a "index" value to determine which image to show from your array of images.

Start at 0 (zero) to show the first image (arrays are zero-based).

When you click the "next" button, increment the index and update the imageView (but don't go beyond the number of images in your array).

When you click the "previous" button, decrement the index and update the imageView (but don't go below 0).

```<code>class ViewController: UIViewController {

    var images: [UIImage] = [
        UIImage.init(named: "2")!,
        UIImage.init(named: "3")!,
        UIImage.init(named: "4")!
    ]

    @IBOutlet weak var imageView: UIImageView!

    var imageIndex: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // updae the imageView with the first image
        imageView.image = images[imageIndex]
    }

    @IBAction func nextButton(_ sender: Any) {
        // if we're at the end of the images array, just return
        if imageIndex == images.count - 1 {
            return
        }
        // increment the index
        imageIndex += 1
        // update the image view
        imageView.image = images[imageIndex]
    }

    @IBAction func prevButton(_ sender: Any) {
        // if we're at the start of the images array, just return
        if imageIndex == 0 {
            return
        }
        // decrement the index
        imageIndex -= 1
        // update the image view
        imageView.image = images[imageIndex]
    }

}
</code>```

Title: How to switch UIImages in UIViewController from Array by pressing UIButton

Body:
You want to use a "index" value to determine which image to show from your array of images.

Start at 0 (zero) to show the first image (arrays are zero-based).

When you click the "next" button, increment the index and update the imageView (but don't go beyond the number of images in your array).

When you click the "previous" button, decrement the index and update the imageView (but don't go below 0).

class ViewController: UIViewController {

    var images: [UIImage] = [
        UIImage.init(named: "2")!,
        UIImage.init(named: "3")!,
        UIImage.init(named: "4")!
    ]

    @IBOutlet weak var imageView: UIImageView!

    var imageIndex: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // updae the imageView with the first image
        imageView.image = images[imageIndex]
    }

    @IBAction func nextButton(_ sender: Any) {
        // if we're at the end of the images array, just return
        if imageIndex == images.count - 1 {
            return
        }
        // increment the index
        imageIndex += 1
        // update the image view
        imageView.image = images[imageIndex]
    }

    @IBAction func prevButton(_ sender: Any) {
        // if we're at the start of the images array, just return
        if imageIndex == 0 {
            return
        }
        // decrement the index
        imageIndex -= 1
        // update the image view
        imageView.image = images[imageIndex]
    }

}


问:
Node.js see where the console was log
For example if I do console.log in Chrome, it will show me where it was log like grant.js:1, can I get similar info in Node.js with some type of flag perhaps while starting the process?

答:
After doing a bit of research on this, it seems to me that you really have to implement this feature yourself. As HarshaHR pointed out, this question has been answered before. You just need to scroll down a bit to see solutions that don't print the full stack trace.

All solutions there rely on splitting and matching the stack trace as a string, which will break if the format of that string is changed in the future. Inspired by this gist on GitHub (and the answers to the similar Stack Overflow question), I want to provide my own solution:

```<code>'use strict';

const path = require('path');

['debug', 'log', 'warn', 'error'].forEach((methodName) => {
    const originalLoggingMethod = console[methodName];
    console[methodName] = (firstArgument, ...otherArguments) => {
        const originalPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = (_, stack) => stack;
        const callee = new Error().stack[1];
        Error.prepareStackTrace = originalPrepareStackTrace;
        const relativeFileName = path.relative(process.cwd(), callee.getFileName());
        const prefix = `${relativeFileName}:${callee.getLineNumber()}:`;
        if (typeof firstArgument === 'string') {
            originalLoggingMethod(prefix + ' ' + firstArgument, ...otherArguments);
        } else {
            originalLoggingMethod(prefix, firstArgument, ...otherArguments);
        }
    };
});

// Tests:
console.log('%s %d', 'hi', 42);
console.log({ a: 'foo', b: 'bar'});
</code>```

Unlike the other solutions I've seen, the above script

outputs no additional lines and

handles string substitutions correctly.

You can color the prefix with chalk or color.js, but I didn't want to introduce dependencies for this here.

The above script uses the V8 API to customize stack traces. The callee is a CallSite object with the following methods in case you want to customize the prefix:

getThis: returns the value of this

getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object’s [[Class]] internal property.

getFunction: returns the current function

getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt is made to infer a name from the function’s context.

getMethodName: returns the name of the property of this or one of its prototypes that holds the current function

getFileName: if this function was defined in a script returns the name of the script

getLineNumber: if this function was defined in a script returns the current line number

getColumnNumber: if this function was defined in a script returns the current column number

getEvalOrigin: if this function was created using a call to eval returns a string representing the location where eval was called

isToplevel: is this a top-level invocation, that is, is this the global object?

isEval: does this call take place in code defined by a call to eval?

isNative: is this call in native V8 code?

isConstructor: is this a constructor call?

isAsync: is this an async call (i.e. await or Promise.all())?

isPromiseAll: is this an async call to Promise.all()?

getPromiseIndex: returns the index of the promise element that was followed in Promise.all() for async stack traces, or null if the CallSite is not a Promise.all() call.

Title: Node.js see where the console was log

Body:
After doing a bit of research on this, it seems to me that you really have to implement this feature yourself. As HarshaHR pointed out, this question has been answered before. You just need to scroll down a bit to see solutions that don't print the full stack trace.

All solutions there rely on splitting and matching the stack trace as a string, which will break if the format of that string is changed in the future. Inspired by this gist on GitHub (and the answers to the similar Stack Overflow question), I want to provide my own solution:

'use strict';

const path = require('path');

['debug', 'log', 'warn', 'error'].forEach((methodName) => {
    const originalLoggingMethod = console[methodName];
    console[methodName] = (firstArgument, ...otherArguments) => {
        const originalPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = (_, stack) => stack;
        const callee = new Error().stack[1];
        Error.prepareStackTrace = originalPrepareStackTrace;
        const relativeFileName = path.relative(process.cwd(), callee.getFileName());
        const prefix = `${relativeFileName}:${callee.getLineNumber()}:`;
        if (typeof firstArgument === 'string') {
            originalLoggingMethod(prefix + ' ' + firstArgument, ...otherArguments);
        } else {
            originalLoggingMethod(prefix, firstArgument, ...otherArguments);
        }
    };
});

// Tests:
console.log('%s %d', 'hi', 42);
console.log({ a: 'foo', b: 'bar'});

Unlike the other solutions I've seen, the above script

outputs no additional lines and

handles string substitutions correctly.

You can color the prefix with chalk or color.js, but I didn't want to introduce dependencies for this here.

The above script uses the V8 API to customize stack traces. The callee is a CallSite object with the following methods in case you want to customize the prefix:

getThis: returns the value of this

getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object’s [[Class]] internal property.

getFunction: returns the current function

getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt is made to infer a name from the function’s context.

getMethodName: returns the name of the property of this or one of its prototypes that holds the current function

getFileName: if this function was defined in a script returns the name of the script

getLineNumber: if this function was defined in a script returns the current line number

getColumnNumber: if this function was defined in a script returns the current column number

getEvalOrigin: if this function was created using a call to eval returns a string representing the location where eval was called

isToplevel: is this a top-level invocation, that is, is this the global object?

isEval: does this call take place in code defined by a call to eval?

isNative: is this call in native V8 code?

isConstructor: is this a constructor call?

isAsync: is this an async call (i.e. await or Promise.all())?

isPromiseAll: is this an async call to Promise.all()?

getPromiseIndex: returns the index of the promise element that was followed in Promise.all() for async stack traces, or null if the CallSite is not a Promise.all() call.


问:
Does Dapper support the like operator?
Using Dapper-dot-net...

The following yields no results in the data object:

```<code>var data = conn.Query(@"
    select top 25
    Term as Label,
    Type,
    ID
    from SearchTerms
    WHERE Term like '%@T%'",
    new { T = (string)term });
</code>```

However, when I just use a regular String Format like:

```<code>string QueryString = String.Format("select top 25 Term as Label, Type, ID from SearchTerms WHERE Term like '%{0}%'", term);
var data = conn.Query(QueryString);
</code>```

I get 25 rows back in the collection.  Is Dapper not correctly parsing the end of the parameter @T?

答:
Try:

```<code>term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");

string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(@"
   select top 25
  Term as Label,
  Type,
  ID
  from SearchTerms
  WHERE Term like @term",
  new { term });
</code>```

There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.

note

The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.

caveat

Any like match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.

Title: Does Dapper support the like operator?

Body:
Using Dapper-dot-net...

The following yields no results in the data object:

var data = conn.Query(@"
    select top 25
    Term as Label,
    Type,
    ID
    from SearchTerms
    WHERE Term like '%@T%'",
    new { T = (string)term });

However, when I just use a regular String Format like:

string QueryString = String.Format("select top 25 Term as Label, Type, ID from SearchTerms WHERE Term like '%{0}%'", term);
var data = conn.Query(QueryString);

I get 25 rows back in the collection.  Is Dapper not correctly parsing the end of the parameter @T?

Body:
Try:

term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");

string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(@"
   select top 25
  Term as Label,
  Type,
  ID
  from SearchTerms
  WHERE Term like @term",
  new { term });

There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.

note

The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.

caveat

Any like match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.


问:
Returning a list of words in alphabetical order - reading from files
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

```<code>    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words
</code>```

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.

答:
First do .lower() and then .split()

```<code>new_word = l.lower().strip().split(' ')
</code>```

You can also add an if statement to catch the whitespace

```<code>if l is ' ' or l is '\n':
  # catch whitespace
</code>```

Body:
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.

Body:
First do .lower() and then .split()

new_word = l.lower().strip().split(' ')

You can also add an if statement to catch the whitespace

if l is ' ' or l is '\n':
  # catch whitespace