问:
Drag and drop between several lists
I have 4 lists of four different objects (A, B, C, D).

Is there a way to associate a name with each of these lists? In other words, list A being A, B being B ...

I intend to drag and drop an object and at the same time know which list it came from and where it went.

I used this to find out the automatically generated list value console.log ("FROM" + event.previousContainer.id)
    console.log ("TO" + event.container.id), the problem is that these values sometimes vary, they are not always the same and if you use conditions it can stop working.

Is there a way to assign or always get the same name from the list where it is object and the one in which it was dropped?

Thanks

Demo- Stackblitz

.ts

```<code>  drop(event: CdkDragDrop<string[]>) {
    console.log("FROM" + event.previousContainer.id)
    console.log("TO" + event.container.id)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
</code>```

Title: Drag and drop between several lists

Body:
I have 4 lists of four different objects (A, B, C, D).

Is there a way to associate a name with each of these lists? In other words, list A being A, B being B ...

I intend to drag and drop an object and at the same time know which list it came from and where it went.

I used this to find out the automatically generated list value console.log ("FROM" + event.previousContainer.id)
    console.log ("TO" + event.container.id), the problem is that these values sometimes vary, they are not always the same and if you use conditions it can stop working.

Is there a way to assign or always get the same name from the list where it is object and the one in which it was dropped?

Thanks

Demo- Stackblitz

.ts

  drop(event: CdkDragDrop<string[]>) {
    console.log("FROM" + event.previousContainer.id)
    console.log("TO" + event.container.id)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

Body:
Inside your drop function call this event data:

For the previous container:

event.previousContainer.element.nativeElement.id

For your current container:

event.container.element.nativeElement.id

Then in your HTML add an ID to the list element like that:

<div ... #activeList="cdkDropList" id="list-A" ...>


来源: stackexchange

问:
on setState render a new component
I have an analog clock
using

https://github.com/zackargyle/react-analog-clock

I have a textbox that fetches city name and timezone on autocomplete,

Default clock2 loaded with offset +8

On select of city in textbox

Fetch City Name

Fetch Timezone

Re-render the clock2

How can I code that?

```<code> public render(): React.ReactElement<Props> {
    return (
 <div className={styles.time}>
            <AnalogClock theme={Themes.light} width={120} gmtOffset=${this.state.gmtoffset} /><br/>
            {this.state.wxLoc}

 </div>
);
</code>```

I attempted

```<code>
this.showClock2(this.state.gmtoffset);
////////////////////////

private showClock2(offset="+8"){
  let show=`<AnalogClock theme={Themes.light} width={120} gmtOffset=${offset} /><br/>
  {this.state.wxLoc}`;
  return show;

}
//other codes

public render(): React.ReactElement<Props> {
    return (
 <div className={styles.time}>
            {this.showClock2()}

 </div>
);

</code>```

it shows Literal Code, Is it possible to Render the <AnalogClock/> ?

答:
```<code>private showClock2(offset="+8") {

 ReactDOM.render(<AnalogClock theme={Themes.light} width={120} gmtOffset={offset} />, document.getElementById('root'))

}
</code>```

<p>Add  in the public render and it works </p>

ContentLicense: CC BY-SA 4.0

Title: on setState render a new component

Body:
I have an analog clock
using

https://github.com/zackargyle/react-analog-clock

I have a textbox that fetches city name and timezone on autocomplete,

Default clock2 loaded with offset +8

On select of city in textbox

Fetch City Name

Fetch Timezone

Re-render the clock2

How can I code that?

 public render(): React.ReactElement<Props> {
    return (

            <AnalogClock theme={Themes.light} width={120} gmtOffset=${this.state.gmtoffset} />

            {this.state.wxLoc}

);

I attempted

this.showClock2(this.state.gmtoffset);
////////////////////////

private showClock2(offset="+8"){
  let show=`<AnalogClock theme={Themes.light} width={120} gmtOffset=${offset} />

  {this.state.wxLoc}`;
  return show;

}
//other codes

public render(): React.ReactElement<Props> {
    return (

            {this.showClock2()}

);

it shows Literal Code, Is it possible to Render the <AnalogClock/> ?

Body:
private showClock2(offset="+8") {

 ReactDOM.render(<AnalogClock theme={Themes.light} width={120} gmtOffset={offset} />, document.getElementById('root'))

}

Add  in the public render and it works


问:
TSQL show only first row
I have the following TSQL query:

```<code>SELECT DISTINCT MyTable1.Date
  FROM MyTable1
INNER JOIN MyTable2
ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' ORDER BY MyTable1.Date DESC
</code>```

It retrieves a long list of Dates, but I only need the first one, the one in the first row.

How can I get it?

Thanks a ton!

答:
There are several options here. You can use TOP(1) as Taryn mentioned. But according to docs for the purposes of limiting the rows returned it is better to use OFFSET and FETCH.

We recommend that you use the OFFSET and FETCH clauses instead of the TOP clause to implement a query paging solution and limit the number of rows sent to a client application.

Using OFFSET and FETCH as a paging solution requires running the query one time for each "page" of data returned to the client application. For example, to return the results of a query in 10-row increments, you must execute the query one time to return rows 1 to 10 and then run the query again to return rows 11 to 20 and so on.

Assuming, the solution for your problem using OFFSET and FETCH approach could be:

```<code>SELECT DISTINCT MyTable1.Date
  FROM MyTable1
INNER JOIN MyTable2
ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' ORDER BY MyTable1.Date DESC
OFFSET 0 ROWS
FETCH NEXT 1 ROW ONLY
</code>```

ContentLicense: CC BY-SA 3.0

Title: TSQL show only first row

Body:
I have the following TSQL query:

SELECT DISTINCT MyTable1.Date
  FROM MyTable1
INNER JOIN MyTable2
ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' ORDER BY MyTable1.Date DESC

It retrieves a long list of Dates, but I only need the first one, the one in the first row.

How can I get it?

Thanks a ton!

Body:
There are several options here. You can use TOP(1) as Taryn mentioned. But according to docs for the purposes of limiting the rows returned it is better to use OFFSET and FETCH.

We recommend that you use the OFFSET and FETCH clauses instead of the TOP clause to implement a query paging solution and limit the number of rows sent to a client application.

Using OFFSET and FETCH as a paging solution requires running the query one time for each "page" of data returned to the client application. For example, to return the results of a query in 10-row increments, you must execute the query one time to return rows 1 to 10 and then run the query again to return rows 11 to 20 and so on.

Assuming, the solution for your problem using OFFSET and FETCH approach could be:

SELECT DISTINCT MyTable1.Date
  FROM MyTable1
INNER JOIN MyTable2
ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' ORDER BY MyTable1.Date DESC
OFFSET 0 ROWS
FETCH NEXT 1 ROW ONLY


问:
Black background slide up
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

```<code><div class="wrapper">
  <div class="sliding-background"></div>
</div>
</code>```

CSS:

```<code>.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}
</code>```

See on Codepen here

Thank you !

答:
Thank you all for the help the clean code is this one :

Html

```<code><div class="wrapper">
  <div class="sliding-background"></div>
</div>
</code>```

CSS

```<code>.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  width: 100%;
  height: 100vh;
  animation: slide 0.6s ease-out forwards;
  animation-delay: 2000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);
  }
  100%{
    transform: translate3d(0px, -100%, 0px);
  }
}
</code>```

Title: Black background slide up

Body:
It is probably very simple but i'm stuck trying to make a homepage automatic background slider like here : https://www.jackdavison.co.uk

That's probably Jquery but I found a way to have something similar with html and Css, only it keeps repeating.

Any help ?

You can see my code here:

HTML

CSS:

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  height: 560px;
  width: 100%;
  animation: slide 2s linear infinite;
  animation-delay: 4000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);

  }
  100%{
    transform: translate3d(0px, -2000px, 0px);

  }

}

See on Codepen here

Thank you !

Body:
Thank you all for the help the clean code is this one :

Html

<div class="wrapper">
  <div class="sliding-background"></div>
</div>

CSS

.wrapper {
  overflow: hidden;
}

.sliding-background {
  background-color: black;
  width: 100%;
  height: 100vh;
  animation: slide 0.6s ease-out forwards;
  animation-delay: 2000ms;
}

@keyframes slide{
  0%{
    transform: translate3d(0, 0, 0);
  }
  100%{
    transform: translate3d(0px, -100%, 0px);
  }
}


问:
Pushing empty commits to remote
I have pushed one commit to remote but now I realized that the commit message is not correct. I would like to change the commit message but AFAIK it is not possible. So i decided to create empty commit with correct message:

```<code>git commit --allow-empty
</code>```

Are there any disadvantages/consequences of pushing empty commits? Is there any problem I might face in future because of this empty commit??

答:
What about this; </p>

```<code> git commit --allow-empty-message -m ''
</code>```

Title: Pushing empty commits to remote

Body:
I have pushed one commit to remote but now I realized that the commit message is not correct. I would like to change the commit message but AFAIK it is not possible. So i decided to create empty commit with correct message:

git commit --allow-empty

Are there any disadvantages/consequences of pushing empty commits? Is there any problem I might face in future because of this empty commit??

Body:
What about this;

 git commit --allow-empty-message -m ''


问:
In Slurm, is there a quick command to determine the total number of jobs (pending and active) at a given moment?
In slurm, calling the command squeue -u <username> will list all the jobs that are pending or active for a given user. I am wondering if there was a quick way to tally them all so that I know how many outstanding jobs there are, including pending and actively running jobs. Thanks!

答:
I would interprete "quick command" differently. Additionally I would add -r for cases when you are using job arrays:

```<code>squeue -u <username> -h -t pending,running -r | wc -l
</code>```

option -h removes the header "wc -l" (word count) counts the line of the output.
Eventually I am using it with watch

```<code>watch 'squeue -u <username> -h -t pending,running -r | wc -l'
</code>```

Body:
I would interprete "quick command" differently. Additionally I would add -r for cases when you are using job arrays:

squeue -u <username> -h -t pending,running -r | wc -l

option -h removes the header "wc -l" (word count) counts the line of the output.
Eventually I am using it with watch

watch 'squeue -u <username> -h -t pending,running -r | wc -l'


问:
Git ignore changeset
Hi
I'm currently using SVN. Let's say I have some files with some changes that should be locally presented on my pc (I need them to run it on my configuration) but they shouldn't be committed to server.
I case of SVN it is ok to add them to .ignore and just do not commit them, but this works only in case of changing other files during my work. If I need to change something in files that are marked as ignore - I need before commit to backup these files, revert ignored changes, commit and restore them after backup. Sometimes this can be very annoying.

I heard about git, that it is built upon changesets not files. Can I use git-svn to ignore some changeset?

答:
If you're using git-svn, you might be interested in its create-ignore and show-ignore options, which will create a .gitignore file matching the existing svn:ignore settings.

If the files you want to ignore are purely local and not even known by svn:ignore, putting their names/patterns in .gitignore should be enough for them to be ignored by git and git-svn (unless you've added them explicitly to the index).

If you want to ignore a changeset (which is different to ignore a file as part of your git commits), you should put them on a different branch, one that you don't "dcommit" with git-svn.

Title: Git ignore changeset


问:
How to initialize a const std vector in old c++?
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

```<code>const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};
</code>```

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

答:
You've already gotten two good answers. This is just a combination of both:</p>

```<code>namespace detail {
    template<typename T, size_t N>
    size_t size(const T (&)[N]) { return N; }

    std::vector<int> vecinit() {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        return std::vector<int>(arr, arr+size(arr));
    }
}

//...

const std::vector<int> myVector(detail::vecinit());
</code>```

Body:
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

Body:
You've already gotten two good answers. This is just a combination of both:

namespace detail {
    template<typename T, size_t N>
    size_t size(const T (&)[N]) { return N; }

    std::vector<int> vecinit() {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        return std::vector<int>(arr, arr+size(arr));
    }
}

//...

const std::vector<int> myVector(detail::vecinit());


问:
Delphi: TabStop problems of TRadioButton
When TRadioButton has TabStop=True, it's acting very strange.

If you will try to switch focus between many radio buttons on a form using Tab key, you would do it only 1 time per app session. The tabulation is one-way, never returning back to the first radio button. Also when the focus is moving across radio buttons, they becoming "checked" automatically.

Can this behavior be fixed without creating my own component?

I want standard radio buttons to

switch focus cyclically

prevent radio button from checking when the focus comes into it (I want my users to check them using Space key)

答:
You can put code in the OnEnter event to prevent the checkbox from selecting.

You'll need to store the previously selected RadioButton somehow though.

```<code>var
  SelectedRadioButton: TRadioButton;

//event shared by all radiobuttons
procedure TForm1.RadioButton1Enter(Sender: TObject);
begin
  if Sender <> SelectedRadioButton then begin
    SelectedRadioButton.Checked:= true;
  end;
end;

procedure TFrameOrder.RadioButton1Click(Sender: TObject);
begin
  SelectedRadioButton:= (Sender as TRadioButton);
end;

procedure TFrameOrder.RadioButton1KeyPress(Sender: TObject; var Key: Char);
var
  MyRadioButton: TRadioButton;
begin
  MyRadioButton:= (Sender as TRadioButton);
  if Key in [#32,#13] then begin
    MyRadioButton.Checked:= true;
    RadioButton1Click(MyRadioButton);
  end; {if}
end;
</code>```

It probably clearer to create a new TMyRadioButton component though because this will clutter up your regular code.

Body:
You can put code in the OnEnter event to prevent the checkbox from selecting.

You'll need to store the previously selected RadioButton somehow though.

var
  SelectedRadioButton: TRadioButton;

//event shared by all radiobuttons
procedure TForm1.RadioButton1Enter(Sender: TObject);
begin
  if Sender <> SelectedRadioButton then begin
    SelectedRadioButton.Checked:= true;
  end;
end;

procedure TFrameOrder.RadioButton1Click(Sender: TObject);
begin
  SelectedRadioButton:= (Sender as TRadioButton);
end;

procedure TFrameOrder.RadioButton1KeyPress(Sender: TObject; var Key: Char);
var
  MyRadioButton: TRadioButton;
begin
  MyRadioButton:= (Sender as TRadioButton);
  if Key in [#32,#13] then begin
    MyRadioButton.Checked:= true;
    RadioButton1Click(MyRadioButton);
  end; {if}
end;

It probably clearer to create a new TMyRadioButton component though because this will clutter up your regular code.


问:
how to add a script to script js
how to add a:

Tawk_API.hideWidget();

//Example

Tawk_API.onLoad = function(){
    Tawk_API.hideWidget();
};

Tawk_API.toggleVisibility();

//Example

Tawk_API.onLoad = function(){
    Tawk_API.toggleVisibility();
};```
</div>
</div>
</p>

<p>to</p>

<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><script type="text/javascript">

document.querySelector("#print").addEventListener("click", function() {

 window.print();
});
    </script></code>```

I need hide a chat widget on print page. When i print a page i have a small widget with chat in right bottom corner.

答:
if hiding a widget on the print page means when you click on the print button is only your concern then it will work for you because as I can see in your code you add an event listener to a #print. so I am assuming that works as a print button for you.
you can uncomment the code if you required that I marked as a comment.
write the following code as you required. Please vote up and accept the answer if it helps you.

```

Title: how to add a script to script js

Body:
how to add a:

Tawk_API.hideWidget();

//Example

Tawk_API.onLoad = function(){
    Tawk_API.hideWidget();
};

Tawk_API.toggleVisibility();

//Example

Tawk_API.onLoad = function(){
    Tawk_API.toggleVisibility();
};

to

I need hide a chat widget on print page. When i print a page i have a small widget with chat in right bottom corner.

Body:
if hiding a widget on the print page means when you click on the print button is only your concern then it will work for you because as I can see in your code you add an event listener to a #print. so I am assuming that works as a print button for you.
you can uncomment the code if you required that I marked as a comment.
write the following code as you required. Please vote up and accept the answer if it helps you.

<script type="text/javascript">

document.querySelector("#print").addEventListener("click", function() {
     Tawk_API.hideWidget();

//i dont know why you write below code so i mark it as comment you can uncomment if you need it.
//Example
/*
Tawk_API.onLoad = function(){
    Tawk_API.hideWidget();
};

Tawk_API.toggleVisibility();

//Example

Tawk_API.onLoad = function(){
    Tawk_API.toggleVisibility();
};*/
 window.print();
});
    </script>


问:
Is there a library that can handle LIDAR data in Windows Python?
I'm looking for a library that can manipulate .liblas data in windows. I'm using windows 10, and my anaconda python version is 3.7. Any help will be appreciated.</p>

答: If by .liblas data you mean the ASPRS LAS file format, you can use laspy.


问:
Customize grid lines in d3 bar chart
I am developing a two-way bar chart using d3. I want to add grid lines to the bar chart, how to customize those grid lines. I've used d3fc to draw the grid lines. It looks something like

```<code>var x = d3.scaleLinear()
    .rangeRound([0, width])

var y = d3.scaleBand()
    .rangeRound([0, height]).padding(0.5);

var xAxis = d3.axisBottom(x)
    .ticks(8)
    .tickSize(0)
    .tickFormat(function(d){
        return d3.format('.00s')(Math.abs(d));   // Use Math.abs() to get the absolute value
    });

var yAxis = d3.axisLeft(y)
    .ticks(5)
    .tickSize(0);
//draw grid lines
const gridline = fc.annotationSvgGridline()
    .xScale(x)
    .yScale(y);
var svg = d3.select("#ageSexNotif").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

x.domain([-d3.max(data, function(d){
    return d.female
})*1.2,d3.max(data, function(d){
    return d.female
})*1.2])
y.domain(data.map(function (d) {
    return d.age;
}));

svg.append("g")
    .attr("class", "x axis")
    .call(xAxis)
    .call(gridline);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);
    // .call(gridline);

var barsRight = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")

barsRight.append("rect")
    .attr("class", "bar")
    .attr("x", function (d) {
        return x(Math.min(0, d.female));
    })
    .attr("y", function (d) {
        return y(d.age);
    })
    .attr("width", function (d) {
        return Math.abs(x(d.female) - x(0));
    })
    .transition()
    .duration(1500)
    .delay(200)
    .style("margin-top", "10px")
    .attr("height", y.bandwidth())
    .attr("fill", "#F293C9")
    .attr("text", "label");

barsRight.append("text")
    .attr("class", "label")
    //y position of the label is halfway down the bar
    .attr("y", function (d) {
        return y(d.age) + y.bandwidth()- 6;
    })
    //x position is 3 pixels to the right of the bar
    .attr("x", function (d) {
        return x(d.female) + 10;
    })
    .text(function (d) {
        return (d.female/1000)+'k';
    })
    .style("font-family", "Source Sans Pro")
    .style("font-size", "14px")
    .style("font-weight", "bold")
    .attr("fill", "#F293C9");

var barsLeft = svg.selectAll(".bar2")
    .data(data)
    .enter().append("g")

barsLeft.append("rect")
    .attr("class", "bar2")
    .attr("x", function (d) {
        return x(Math.min(0, -d.male));
    })
    .attr("y", function (d) {
        return y(d.age);
    })
    .attr("width", function (d) {
        return Math.abs(x(-d.male) - x(0));
    })
    .transition()
    .duration(1500)
    .delay(200)
    .style("margin-top", "10px")
    .attr("height", y.bandwidth())
    .attr("fill", "#4880FF");

barsLeft.append("text")
    .attr("class", "label")
    .style("font-family", "Source Sans Pro")
    .style("font-size", "14px")
    .style("font-weight", "bold")
    .attr("fill","#4880FF")
    //y position of the label is halfway down the bar
    .attr("y", function (d) {
        return y(d.age) + y.bandwidth()- 6;
    })
    //x position is 3 pixels to the right of the bar
    .attr("x", function (d) {
        return x(-d.male) - 40;
    })
    .text(function (d) {
        return (d.male/1000)+'k';
    });
</code>```

The result of my chart is

My chart should look like this

How to join the edges in x-axis and highlight the base axis as shown in the image? Any help for customizing the grid lines is appreciated.
Link to my example link

Thanks in advance!

答: You can add class name to your grid lines using attr('class', 'class-name'), and add your effect by CSS.

Title: Customize grid lines in d3 bar chart

Body:
I am developing a two-way bar chart using d3. I want to add grid lines to the bar chart, how to customize those grid lines. I've used d3fc to draw the grid lines. It looks something like

var x = d3.scaleLinear()
    .rangeRound([0, width])

var y = d3.scaleBand()
    .rangeRound([0, height]).padding(0.5);

var xAxis = d3.axisBottom(x)
    .ticks(8)
    .tickSize(0)
    .tickFormat(function(d){
        return d3.format('.00s')(Math.abs(d));   // Use Math.abs() to get the absolute value
    });

var yAxis = d3.axisLeft(y)
    .ticks(5)
    .tickSize(0);
//draw grid lines
const gridline = fc.annotationSvgGridline()
    .xScale(x)
    .yScale(y);
var svg = d3.select("#ageSexNotif").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

x.domain([-d3.max(data, function(d){
    return d.female
})*1.2,d3.max(data, function(d){
    return d.female
})*1.2])
y.domain(data.map(function (d) {
    return d.age;
}));

svg.append("g")
    .attr("class", "x axis")
    .call(xAxis)
    .call(gridline);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);
    // .call(gridline);

var barsRight = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")

barsRight.append("rect")
    .attr("class", "bar")
    .attr("x", function (d) {
        return x(Math.min(0, d.female));
    })
    .attr("y", function (d) {
        return y(d.age);
    })
    .attr("width", function (d) {
        return Math.abs(x(d.female) - x(0));
    })
    .transition()
    .duration(1500)
    .delay(200)
    .style("margin-top", "10px")
    .attr("height", y.bandwidth())
    .attr("fill", "#F293C9")
    .attr("text", "label");

barsRight.append("text")
    .attr("class", "label")
    //y position of the label is halfway down the bar
    .attr("y", function (d) {
        return y(d.age) + y.bandwidth()- 6;
    })
    //x position is 3 pixels to the right of the bar
    .attr("x", function (d) {
        return x(d.female) + 10;
    })
    .text(function (d) {
        return (d.female/1000)+'k';
    })
    .style("font-family", "Source Sans Pro")
    .style("font-size", "14px")
    .style("font-weight", "bold")
    .attr("fill", "#F293C9");

var barsLeft = svg.selectAll(".bar2")
    .data(data)
    .enter().append("g")

barsLeft.append("rect")
    .attr("class", "bar2")
    .attr("x", function (d) {
        return x(Math.min(0, -d.male));
    })
    .attr("y", function (d) {
        return y(d.age);
    })
    .attr("width", function (d) {
        return Math.abs(x(-d.male) - x(0));
    })
    .transition()
    .duration(1500)
    .delay(200)
    .style("margin-top", "10px")
    .attr("height", y.bandwidth())
    .attr("fill", "#4880FF");

barsLeft.append("text")
    .attr("class", "label")
    .style("font-family", "Source Sans Pro")
    .style("font-size", "14px")
    .style("font-weight", "bold")
    .attr("fill","#4880FF")
    //y position of the label is halfway down the bar
    .attr("y", function (d) {
        return y(d.age) + y.bandwidth()- 6;
    })
    //x position is 3 pixels to the right of the bar
    .attr("x", function (d) {
        return x(-d.male) - 40;
    })
    .text(function (d) {
        return (d.male/1000)+'k';
    });

The result of my chart is

My chart should look like this

How to join the edges in x-axis and highlight the base axis as shown in the image? Any help for customizing the grid lines is appreciated.
Link to my example link

Thanks in advance!


问:
How to transform a bipartite Network and use node attributes from one level as edge weights in the second level in igraph (R)
Im trying right now to transfer a bipartite two-mode graph to its one-mode representation. The issue is that I want to conserve node atrributes from the two-mode graph to the one-mode representations. For example a dataframe is given by:

Person EventLocation DurationEvent
 Peter  Bar           90
 Jack   Bar           90
 Franz  Train         20
 Franz  Bar           90
 Laurie Train         20
 Jack   Train         20
 ...

Now I want to get persons network using the igraph function bipartite_projection() on the Person and EventLocation columns but I see no ways how to presafe additional node attributes (duration) that might be transfer to edge weights between Persons, e.g. Peter-Jack with weight 90 or Franz-Laurie with weight 20.

Edit: I´ve added the last row to be more precise. The edge "Jack-Franz" would now correspond to 90+20 = 110. But basically my issue is just related how to implement a bipartite_projection which transfers the node attribute of a bipartite igraph-network to the correspoding edge attribute in the one-mode igraph-network.

Edit 2: I just added another example. First, I create a network among persons then I want to add the budget informations to the persons edges implying how much project budget did the both attracted together (the sum of budgets only from different unique projects as weights). Then I wanted to do some further weighted centrality calculations:

```<code>person_id <- c("X","Y","Z","Q","W","E","R","X","Y")
project <- c("a","b","c","a","a","b","c","b","a")
budget <- c(100,200,300,100,100,200,300,200,100)
employ.data <- data.frame(person_id, project, budget)
View(employ.data)
sna.complete.list <- employ.data
sna.list.complete.igraph.calc <- graph.data.frame(sna.complete.list)
V(sna.list.complete.igraph.calc)$type <- V(sna.list.complete.igraph.calc)$name%in%sna.complete.list$person_id
sna.list.complete.igraph.calc.one <- try(bipartite.projection(sna.list.complete.igraph.calc, type=V(sna.list.complete.igraph.calc)$type))
sna.statistics.persons <- sna.list.complete.igraph.calc.one[[2]]
plot.igraph(sna.statistics.persons)
</code>```

EDIT3: I try to reformulate my concern:

Overall Goal:
Get an weighted graph (edge values between nodes weighted with some values)

Outline/Data:

Data on people participating in different projects that differ in budget size

Convert bipartite connection graph (People-Project) to one-mode-People-People-graph

Use the budget sizes as weights for the edges between the people.

BUT for two people this value should only account for the sum of participating at unique projects. Thus, if A and B are only connected by project x of budget size 100 should result in an edge-weight of 100. If they also participate in another project with value 20, the result should be 120 etc.

I tried to transfer this information during using bipartite.projection but failed or couldn´t implement this information afterwards.

答:
The bipartite_projection() can collect only structural weights of edges, that is to say, Peter and Jack are both affiliated to both Train and Bar. To handle edge-attributes is trickier.

If you only want to perserve the node-attributes, as you write above bipartite_projection() absolutely does that for you already. Just re-project and find your attributes preserved like so:

```<code>V(unipartite_graph)$your_attributee
</code>```

If you need to preserve edge-attributes when re-projecting, however, there are several questions to ask before.

How should multiple paths be treated when Franz-Train-Jack also has Franz-Bar_Jack?

What role does directionality have in the calculation

I needed the exact same thing some years back, and solved it by writing my own extended re-projection function. It is perhaps not the shortest way around this, but calculates sums of a given edge-attribute by the shortest path between each unipartite-vertex-pair in the bipartite graph and returns an graph with one edge-attribute preserved (and summarised).

Note that the function does not calculate the unipartite Laurie-Peter. You could manipulate the function to your liking.

This reproduces your example data and applies my function

```<code># Reproduce your data
df <- data.frame(Person = c("Peter","Jack","Franz","Franz","Laurie","Jack"),
                 EventLocation = c("Bar","Bar","Train","Bar","Train","Train"),
                 DurationEvent = c(90,90,20,90,20,20), stringsAsFactors = F)

## Make bipartite graph from example data
g <- graph_from_data_frame(df, directed=FALSE)
# Set vertex type using bipartite.mapping() (OBS type should be boolean for bipartite_projection())
V(g)$type <- bipartite.mapping(g)$type

## Plot Bipartite graph
E(g)$label <- E(g)$DurationEvent
V(g)$color <- ifelse(V(g)$type, "red", "yellow")
V(g)$size <- ifelse(V(g)$type, 40, 20)
plot(g, edge.label.color="gray", vertex.label.color="black")

# Function to reproject a bipartite graph to unipartite projection while
# calculating an attribute-value sum between reprojected vertecies.
unipartite_projection_attr <- function(graph_bi, attribute, projection=FALSE){

  ## Make initial unipartite projection
  graph_uni <- bipartite_projection(graph_bi, which=FALSE)

  ## List paths in bipartite-graph along which to summarise selected attribute
  el <- as_edgelist(graph_uni)
  el <- matrix(sapply(el, function(x) as.numeric(which(x == V(graph_bi)$name))), ncol=2)

  ## Function to summarise given atribute-value
  summarise_graph_attribute_along_path <- function(source, target, attribute){
    attr_value <- edge_attr(g, attribute)
    path <- get.shortest.paths(g, source, target, output="epath")$epath[[1]]
    sum(E(g)$DurationEvent[path])
  }

  attr_uni <- mapply(summarise_graph_attribute_along_path, el[,1], el[,2], attribute)
  graph_uni <- set_edge_attr(graph_uni, attribute, value=attr_uni)

  (graph_uni)
}

# Use function to make unipartite projection
gg <- unipartite_projection_attr(g, "DurationEvent", FALSE)

# Visualise
V(gg)$color <- "yellow"
E(gg)$label <- E(gg)$DurationEvent
plot(gg, edge.label.color="gray", vertex.label.color="black")
</code>```

Best of luck

Body:
Im trying right now to transfer a bipartite two-mode graph to its one-mode representation. The issue is that I want to conserve node atrributes from the two-mode graph to the one-mode representations. For example a dataframe is given by:

Person EventLocation DurationEvent
 Peter  Bar           90
 Jack   Bar           90
 Franz  Train         20
 Franz  Bar           90
 Laurie Train         20
 Jack   Train         20
 ...

Now I want to get persons network using the igraph function bipartite_projection() on the Person and EventLocation columns but I see no ways how to presafe additional node attributes (duration) that might be transfer to edge weights between Persons, e.g. Peter-Jack with weight 90 or Franz-Laurie with weight 20.

Edit: I´ve added the last row to be more precise. The edge "Jack-Franz" would now correspond to 90+20 = 110. But basically my issue is just related how to implement a bipartite_projection which transfers the node attribute of a bipartite igraph-network to the correspoding edge attribute in the one-mode igraph-network.

Edit 2: I just added another example. First, I create a network among persons then I want to add the budget informations to the persons edges implying how much project budget did the both attracted together (the sum of budgets only from different unique projects as weights). Then I wanted to do some further weighted centrality calculations:

person_id <- c("X","Y","Z","Q","W","E","R","X","Y")
project <- c("a","b","c","a","a","b","c","b","a")
budget <- c(100,200,300,100,100,200,300,200,100)
employ.data <- data.frame(person_id, project, budget)
View(employ.data)
sna.complete.list <- employ.data
sna.list.complete.igraph.calc <- graph.data.frame(sna.complete.list)
V(sna.list.complete.igraph.calc)$type <- V(sna.list.complete.igraph.calc)$name%in%sna.complete.list$person_id
sna.list.complete.igraph.calc.one <- try(bipartite.projection(sna.list.complete.igraph.calc, type=V(sna.list.complete.igraph.calc)$type))
sna.statistics.persons <- sna.list.complete.igraph.calc.one[[2]]
plot.igraph(sna.statistics.persons)

EDIT3: I try to reformulate my concern:

Overall Goal:
Get an weighted graph (edge values between nodes weighted with some values)

Outline/Data:

Data on people participating in different projects that differ in budget size

Convert bipartite connection graph (People-Project) to one-mode-People-People-graph

Use the budget sizes as weights for the edges between the people.

BUT for two people this value should only account for the sum of participating at unique projects. Thus, if A and B are only connected by project x of budget size 100 should result in an edge-weight of 100. If they also participate in another project with value 20, the result should be 120 etc.

I tried to transfer this information during using bipartite.projection but failed or couldn´t implement this information afterwards.

Body:
The bipartite_projection() can collect only structural weights of edges, that is to say, Peter and Jack are both affiliated to both Train and Bar. To handle edge-attributes is trickier.

If you only want to perserve the node-attributes, as you write above bipartite_projection() absolutely does that for you already. Just re-project and find your attributes preserved like so:

V(unipartite_graph)$your_attributee

If you need to preserve edge-attributes when re-projecting, however, there are several questions to ask before.

How should multiple paths be treated when Franz-Train-Jack also has Franz-Bar_Jack?

What role does directionality have in the calculation

I needed the exact same thing some years back, and solved it by writing my own extended re-projection function. It is perhaps not the shortest way around this, but calculates sums of a given edge-attribute by the shortest path between each unipartite-vertex-pair in the bipartite graph and returns an graph with one edge-attribute preserved (and summarised).

Note that the function does not calculate the unipartite Laurie-Peter. You could manipulate the function to your liking.

This reproduces your example data and applies my function

# Reproduce your data
df <- data.frame(Person = c("Peter","Jack","Franz","Franz","Laurie","Jack"),
                 EventLocation = c("Bar","Bar","Train","Bar","Train","Train"),
                 DurationEvent = c(90,90,20,90,20,20), stringsAsFactors = F)

## Make bipartite graph from example data
g <- graph_from_data_frame(df, directed=FALSE)
# Set vertex type using bipartite.mapping() (OBS type should be boolean for bipartite_projection())
V(g)$type <- bipartite.mapping(g)$type

## Plot Bipartite graph
E(g)$label <- E(g)$DurationEvent
V(g)$color <- ifelse(V(g)$type, "red", "yellow")
V(g)$size <- ifelse(V(g)$type, 40, 20)
plot(g, edge.label.color="gray", vertex.label.color="black")

# Function to reproject a bipartite graph to unipartite projection while
# calculating an attribute-value sum between reprojected vertecies.
unipartite_projection_attr <- function(graph_bi, attribute, projection=FALSE){

  ## Make initial unipartite projection
  graph_uni <- bipartite_projection(graph_bi, which=FALSE)

  ## List paths in bipartite-graph along which to summarise selected attribute
  el <- as_edgelist(graph_uni)
  el <- matrix(sapply(el, function(x) as.numeric(which(x == V(graph_bi)$name))), ncol=2)

  ## Function to summarise given atribute-value
  summarise_graph_attribute_along_path <- function(source, target, attribute){
    attr_value <- edge_attr(g, attribute)
    path <- get.shortest.paths(g, source, target, output="epath")$epath[[1]]
    sum(E(g)$DurationEvent[path])
  }

  attr_uni <- mapply(summarise_graph_attribute_along_path, el[,1], el[,2], attribute)
  graph_uni <- set_edge_attr(graph_uni, attribute, value=attr_uni)

  (graph_uni)
}

# Use function to make unipartite projection
gg <- unipartite_projection_attr(g, "DurationEvent", FALSE)

# Visualise
V(gg)$color <- "yellow"
E(gg)$label <- E(gg)$DurationEvent
plot(gg, edge.label.color="gray", vertex.label.color="black")

Best of luck


问:
Bootstrap 4 font size em differs in Mozilla Firefox and Google Chrome
I'm using Angular 8 with bootstrap v4.4.1 (package.json -> "@ng-bootstrap/ng-bootstrap": "^5.2.1",). My requirements:

support responsive design (accomplished with bootstrap)

make browsers render all elements consistently

I thought that the second point is solved by bootstrap as well. The problem is this:

```<code><button type="button" class="btn btn-outline-dark menu-item">
  <i class="fas fa-align-center"></i>
</button>
</code>```

Chrome shows button twice as large as Mozilla Firefox. I then added Bootstrap Reboot (as a normalizes, but it doesn't change anything)

This is my whole global styles.scss:

```<code>@import "~bootstrap/dist/css/bootstrap-reboot.css";
@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~@fortawesome/fontawesome-free/css/all.css";
@import "variables.scss";

html,
body {
  height: 100%;
  background-color: $gray-light;
}

.menu-item {
  font-size: 1.5em;
}
</code>```

How do I get that font size renders equally in Firefox and Chrome. Specifying px works, but latest trends go to em or rem. Doesn't Reboot overrides the em?

Setting this works, but not really sure this is the best approach:

```<code>html,
body {
  height: 100%;
  background-color: $gray-light;
  font-size: 16px;
}
</code>```

答:
The problem is default font size defined by Mozilla Firefox browser.

If you set font-size: 100% it will use default size defined by the browser. You have to set font-size in pixels. From there on you just use  or <rem>.

```<code>   html,
body {
  height: 100%;
  background-color: $gray-light;
  /* Browser settings can override font-size, therefore we set it here. This is also
  with accordance with bootstrap https://getbootstrap.com/docs/4.0/content/typography/ */
  font-size: 16px;
}

.my-div {
  font-size: 2em;
}
</code>```

Body:
I'm using Angular 8 with bootstrap v4.4.1 (package.json -> "@ng-bootstrap/ng-bootstrap": "^5.2.1",). My requirements:

support responsive design (accomplished with bootstrap)

make browsers render all elements consistently

I thought that the second point is solved by bootstrap as well. The problem is this:

<button type="button" class="btn btn-outline-dark menu-item">

</button>

Chrome shows button twice as large as Mozilla Firefox. I then added Bootstrap Reboot (as a normalizes, but it doesn't change anything)

This is my whole global styles.scss:

@import "~bootstrap/dist/css/bootstrap-reboot.css";
@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~@fortawesome/fontawesome-free/css/all.css";
@import "variables.scss";

html,
body {
  height: 100%;
  background-color: $gray-light;
}

.menu-item {
  font-size: 1.5em;
}

How do I get that font size renders equally in Firefox and Chrome. Specifying px works, but latest trends go to em or rem. Doesn't Reboot overrides the em?

Setting this works, but not really sure this is the best approach:

html,
body {
  height: 100%;
  background-color: $gray-light;
  font-size: 16px;
}

Body:
The problem is default font size defined by Mozilla Firefox browser.

If you set font-size: 100% it will use default size defined by the browser. You have to set font-size in pixels. From there on you just use <em> or <rem>.

   html,
body {
  height: 100%;
  background-color: $gray-light;
  /* Browser settings can override font-size, therefore we set it here. This is also
  with accordance with bootstrap https://getbootstrap.com/docs/4.0/content/typography/ */
  font-size: 16px;
}

.my-div {
  font-size: 2em;
}


问:
flutter command not found on Jenkins
I successfully installed Flutter on my local pc. But when add to Jenkins, said flutter command not found

Pipeline script

```<code>stage('Build Release APK') {
            //  sh 'export PATH="$PATH:/Users/bhanukaisuru/Documents/flutter/bin"'//after said, flutter command not found I added this line, but not working
              sh "flutter clean"
              sh "flutter build apk --split-per-abi"
         }
</code>```

Before Adding Flutter command, I added this line.

```<code>sh "./gradlew clean assembleRelease"
</code>```

also said, gradlew not found

答:
Try setting the path of flutter in environment within your stage like this:</p>

```<code>    environment {
        flutter = "/Library/Flutter/bin/flutter"
    }
    steps {
        sh '$flutter clean'
    }
</code>```

Title: flutter command not found on Jenkins

Body:
I successfully installed Flutter on my local pc. But when add to Jenkins, said flutter command not found

Pipeline script

stage('Build Release APK') {
            //  sh 'export PATH="$PATH:/Users/bhanukaisuru/Documents/flutter/bin"'//after said, flutter command not found I added this line, but not working
              sh "flutter clean"
              sh "flutter build apk --split-per-abi"
         }

Before Adding Flutter command, I added this line.

sh "./gradlew clean assembleRelease"

also said, gradlew not found

Body:
Try setting the path of flutter in environment within your stage like this:

    environment {
        flutter = "/Library/Flutter/bin/flutter"
    }
    steps {
        sh '$flutter clean'
    }


问:
How to mount folder with files in kubernetes
I am running a docker image that has certain configuration files within it. I need to persist/mount the same folder to the disk as new files will get added later on. When I use standard volume mount in kubernetes, it mounts an empty directory without the intial configuration files. How do I make sure my initial files are copied to the volume while mounting?</p>

```<code>        - mountPath: /tmp
          name: my-vol
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - name: my-vol
        persistentVolumeClaim:
          claimName: wso2-disk2```
</code>```

答:
The suggested way to provide configurations to your pod is by creating a configmap for your configurations and mount it in your pod using volumes. This guide ( https://kubernetes.io/docs/concepts/storage/volumes/#configmap) descibes how to do that.

Other ways are to create a persistent volume and persistent volume claim in your cluster and copy your configuration file in that path. Mount the persistent volume in your pod.

You can also copy your configuration on one of the nodes in your cluster and mount that path using hostPath but this requires that your pod should also run on the same node as it tries to look for the path in that node. (Not a recommended approach)

Body:
I am running a docker image that has certain configuration files within it. I need to persist/mount the same folder to the disk as new files will get added later on. When I use standard volume mount in kubernetes, it mounts an empty directory without the intial configuration files. How do I make sure my initial files are copied to the volume while mounting?

        - mountPath: /tmp
          name: my-vol
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - name: my-vol
        persistentVolumeClaim:
          claimName: wso2-disk2```


问:
"WSMan Initialization failed with error code: -2144108171" error
I have MVC web app controller to connect exchange server powershell with the following codes:

```<code>  enter connectionInfo = new WSManConnectionInfo(new Uri(ConfigurationManager.AppSettings.Get   ("WSManConnectionInfo").ToString()), "http://schemas.microsoft.com/powershell/Microsoft.Exchange",  newCred);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
string rspace = "space is OK";
        try
        {
            //--create remote runspace
            runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        } catch (Exception ex2)
        {
            rspace = ex2.Message.ToString();
        }
        ViewBag.rspace = rspace; //show the above error message on client side view
</code>```

The above codes works fine from my local machine, but I got the above error after publishing to production server, please note I can see the "Microsoft.Management.Infrustructure.dll" is existed on the bin folder of production server.

Please advise if how to fix this error, much appreciated,

Edit: I even tried to add these 3 lines codes, but same error;

connectionInfo.SkipCACheck = true;

connectionInfo.SkipCNCheck = true;

connectionInfo.MaximumConnectionRedirectionCount = 4;code here

Edit: the  System.Management.Automation.dll is also added in the Reference folder

答:
It seems the problem has been resolved, I think it was caused by the System.Management.Automation installation, this is what I did:

1.First make sure the System.Management.Automation.dll is added in the References folder from  C:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll , this dll file was there, but it still causesthe error,

2.Go to Manage Nuget package and install System.Management.Automation from there, although they have the same name, but I think this file is different than the System.Management.Automation.dll added on the first step.  but after installing this file, thenthe problem is gone. there is nothing changes for the C# codes,

Body:
I have MVC web app controller to connect exchange server powershell with the following codes:

  enter connectionInfo = new WSManConnectionInfo(new Uri(ConfigurationManager.AppSettings.Get   ("WSManConnectionInfo").ToString()), "http://schemas.microsoft.com/powershell/Microsoft.Exchange",  newCred);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
string rspace = "space is OK";
        try
        {
            //--create remote runspace
            runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        } catch (Exception ex2)
        {
            rspace = ex2.Message.ToString();
        }
        ViewBag.rspace = rspace; //show the above error message on client side view

The above codes works fine from my local machine, but I got the above error after publishing to production server, please note I can see the "Microsoft.Management.Infrustructure.dll" is existed on the bin folder of production server.

Please advise if how to fix this error, much appreciated,

Edit: I even tried to add these 3 lines codes, but same error;

connectionInfo.SkipCACheck = true;

connectionInfo.SkipCNCheck = true;

connectionInfo.MaximumConnectionRedirectionCount = 4;code here

Edit: the  System.Management.Automation.dll is also added in the Reference folder


问:
How do we add an element to JSON string using Json path?
I have a use case where i will initially have a JSON object with few elements and I want to add few more new elements to this object using JSON path with the help of Javascript.

Eg:

JSON object:

{
    "article": {
        "title": "Article Title",
        "sect1": {
            "title": "Section1 Title",
            "para": "Text"
        }
    }
}

I would like to set  'article.sect1.subsection.subtitle' as 'Test Title' and 'article.sect1.subsection.para' as 'Number'.

Could you please suggest any solution?

I could add element inside existing section as below
JSONObject.article.sect1.sect1.newElement = 'newelementvalue';

But this is not working for above scenario.

答:
You can easily convert the string to a JSON object and then manipulate it as you would normally. Once you are done, stringify it back and you can persist it how you wish.

const json = `{ "article": { "title": "Article Title", "sect1": { "title": "Section1 Title", "para": "Text" } } }`;
const obj = JSON.parse(json);
obj.article.sect1.subtitle = 'Test Title';
obj.article.sect1.subsection = {para: 'Number'};
const str = JSON.stringify(obj);

console.log(str)```


问:
C++ prevent access to a temporary
I am working on a class that acts like a std::variant, in that, it stores another object using a union along with an error code. Like std::variant, there is a get_if() function that can be used to access to the object in the class. So something like this

```<code>template<typename T>
class result final
{
    ...
    [[nodiscard]] constexpr T const *
    get_if() const noexcept
    {
        if (details::result_type::contains_t == m_which) {
            return &m_t;
        }

        return nullptr;
    }
    ...
};
</code>```

Now... suppose you have a function that returns an object using this class like this:

```<code>[[nodiscard]] static bsl::result<example_implementation>
make(bsl::int32 const answer) noexcept
{
    constexpr bsl::int32 valid_answer{42};

    if (answer == valid_answer) {
        return {bsl::in_place, valid_answer};
    }

    return {bsl::errc_failure, bsl::here()};
}
</code>```

All of this works great. The problem that I cam concerned about is if the user does something like this:

```<code>if (auto const impl = example_implementation::make(valid_answer).get_if()) {
    example_bind_apis_type enforced_impl{*impl};

    if (enforced_impl.member_func_example(valid_answer)) {
        bsl::print("success\n");
    }

    if (!enforced_impl.member_func_example(invalid_answer)) {
        bsl::print("success\n");
    }
}
else {
    bsl::print("failure\n");
}
</code>```

In the example above, the user is creating an example_implementation, and then using get_if() to get a pointer to the object wrapped by the result object. That pointer is then dereferenced and used. ASAN detects that the stack was used after destruction of an object, which is due to the fact that the "if" statement created a temporary result object, and then returned a pointer to something inside that temporary, which is deleted after the call to get_if(). This is similar to an issue with QString that I remember years ago, when people would get a pointer to the C style string inside the QString from a temporary.

Is there a way, in C++ to prevent the user from being able to call get_if() on a temporary like this? I tried reference qualifying get_if(), but that doesn't seem to work as the make function above returns an lvalue, not an rvalue (even though RVO will likely remove the copy). All I want to do is prevent the user from making this mistake accidentally.

Update:
As stated in the comments, make() is returning an rvalue, not an lvalue as I stated above, so a ref qualifier should work.

答:
You might use reference qualifier to your method:

```<code>template<typename T>
class result final
{
    // ...
    [[nodiscard]] constexpr T const* get_if() const & noexcept;

    constexpr void get_if() && noexcept = delete;

    // ...
};
</code>```

Demo

Title: C++ prevent access to a temporary

Body:
I am working on a class that acts like a std::variant, in that, it stores another object using a union along with an error code. Like std::variant, there is a get_if() function that can be used to access to the object in the class. So something like this

template<typename T>
class result final
{
    ...
    [[nodiscard]] constexpr T const *
    get_if() const noexcept
    {
        if (details::result_type::contains_t == m_which) {
            return &m_t;
        }

        return nullptr;
    }
    ...
};

Now... suppose you have a function that returns an object using this class like this:

[[nodiscard]] static bsl::result<example_implementation>
make(bsl::int32 const answer) noexcept
{
    constexpr bsl::int32 valid_answer{42};

    if (answer == valid_answer) {
        return {bsl::in_place, valid_answer};
    }

    return {bsl::errc_failure, bsl::here()};
}

All of this works great. The problem that I cam concerned about is if the user does something like this:

if (auto const impl = example_implementation::make(valid_answer).get_if()) {
    example_bind_apis_type enforced_impl{*impl};

    if (enforced_impl.member_func_example(valid_answer)) {
        bsl::print("success\n");
    }

    if (!enforced_impl.member_func_example(invalid_answer)) {
        bsl::print("success\n");
    }
}
else {
    bsl::print("failure\n");
}

In the example above, the user is creating an example_implementation, and then using get_if() to get a pointer to the object wrapped by the result object. That pointer is then dereferenced and used. ASAN detects that the stack was used after destruction of an object, which is due to the fact that the "if" statement created a temporary result object, and then returned a pointer to something inside that temporary, which is deleted after the call to get_if(). This is similar to an issue with QString that I remember years ago, when people would get a pointer to the C style string inside the QString from a temporary.

Is there a way, in C++ to prevent the user from being able to call get_if() on a temporary like this? I tried reference qualifying get_if(), but that doesn't seem to work as the make function above returns an lvalue, not an rvalue (even though RVO will likely remove the copy). All I want to do is prevent the user from making this mistake accidentally.

Update:
As stated in the comments, make() is returning an rvalue, not an lvalue as I stated above, so a ref qualifier should work.

Body:
You might use reference qualifier to your method:

template<typename T>
class result final
{
    // ...
    [[nodiscard]] constexpr T const* get_if() const & noexcept;

    constexpr void get_if() && noexcept = delete;

    // ...
};

Demo


问:
Angular AEM integration usecase?
AEM itself is self reliant WCMS and can be used to generate very rich digital experiences over multiple channels.

Often there is talk of using Angular as front end and moving AEM to backseat. What is point of doing so?

Using angular will add additional complexity and developer has to deal with it, increasing efforts for building system.

It will undermine core AEM features e.g. HTL & clientlibs

Multi channel experience can still be achieved without angular.

答:
Using AEM as an integration layer is a challenging decision. AEM is a content management system and works well for static content (content is cached at Dispatcher layer).
However, it use the Jetty server under the hood. Jetty uses thread pools for handling requests. It means that when the number of users increases, it use more and more resources. The situation is the same for time-consuming operations - think about API's unavailability or delays.
Instead of using AEM as an integration layer, you delegate this integration logic to more reactive systems such as Knot.x. Then AEM may serve only static pages (templates), Knot.x would fill all required data from external APIs.

See more here.

Title: Angular AEM integration usecase?


问:
D3 V5 Word Wrapping in Circle
I'm fairly new to D3 and made some progress, but this problem has completely stumped me.  I can't seem to get my text to fit inside circles.  I don't anything too fancy, I think just simple line breaks would even pass.

Here's my sample code to generate circles and text.

```<code>graph
.selectAll('circle')
.data(this.nodes)
.enter()
.append('circle')
.attr('r', 30)

graph
.selectAll('text')
.data(this.nodes)
.enter()
.append('text')
.attr('x', 0)
.attr('y', '.31em')
.attr('text-anchor', 'middle')
.text((d: Vertex) => d.name)
</code>```

I have tried adding tspans but I couldn't get it to work.

答:
I suggest you try to use d3plus plugin for D3, here is an example:

// Wrap text in a rectangle.
  d3plus.textwrap()
    .container(d3.select("#rectWrap"))
    .draw();

  // Wrap text in a rectangle, and size the text to fit.
  d3plus.textwrap()
    .container(d3.select("#rectResize"))
    .resize(true)
    .draw();

  // Wrap text in a circle.
  d3plus.textwrap()
    .container(d3.select("#circleWrap"))
    .draw();

  // Wrap text in a circle, and size the text to fit.
  d3plus.textwrap()
    .container(d3.select("#circleResize"))
    .resize(true)
    .draw();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  font-family: "Helvetica", "Arial", sans-serif;
  height: 425px;
  margin: 25px;
  width: 900px;
}

.type {
  fill: #888;
  text-anchor: middle;
}

.shape {
  fill: #eee;
  stroke: #ccc;
}</code>```

<!DOCTYPE html>
<meta charset="utf-8">

<svg>

  <text class="type" dy="15px" x="75px">Wrapped</text>

  <rect class="shape" height="150px" width="150px" y="50px"></rect>
  <text id="rectWrap" class="wrap" y="50px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="75px" cy="300px"></circle>
  <text id="circleWrap" class="wrap" y="225px" x="0px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <text class="type" dy="15px" x="275px">Resized</text>

  <rect class="shape" height="150px" width="150px" y="50px" x="200px"></rect>
  <text id="rectResize" class="wrap" y="50px" x="200px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="275px" cy="300px"></circle>
  <text id="circleResize" class="wrap" y="225px" x="200px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <text class="type" dy="15px" x="475px">Default Behavior</text>

  <rect class="shape" height="150px" width="150px" y="50px" x="400px"></rect>
  <text class="wrap" y="50px" x="400px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="475px" cy="300px"></circle>
  <text class="wrap" y="225px" x="400px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

</svg>```

Title: D3 V5 Word Wrapping in Circle

Body:
I'm fairly new to D3 and made some progress, but this problem has completely stumped me.  I can't seem to get my text to fit inside circles.  I don't anything too fancy, I think just simple line breaks would even pass.

Here's my sample code to generate circles and text.

graph
.selectAll('circle')
.data(this.nodes)
.enter()
.append('circle')
.attr('r', 30)

graph
.selectAll('text')
.data(this.nodes)
.enter()
.append('text')
.attr('x', 0)
.attr('y', '.31em')
.attr('text-anchor', 'middle')
.text((d: Vertex) => d.name)

I have tried adding tspans but I couldn't get it to work.

Body:
I suggest you try to use d3plus plugin for D3, here is an example:

// Wrap text in a rectangle.
  d3plus.textwrap()
    .container(d3.select("#rectWrap"))
    .draw();

  // Wrap text in a rectangle, and size the text to fit.
  d3plus.textwrap()
    .container(d3.select("#rectResize"))
    .resize(true)
    .draw();

  // Wrap text in a circle.
  d3plus.textwrap()
    .container(d3.select("#circleWrap"))
    .draw();

  // Wrap text in a circle, and size the text to fit.
  d3plus.textwrap()
    .container(d3.select("#circleResize"))
    .resize(true)
    .draw();

svg {
  font-family: "Helvetica", "Arial", sans-serif;
  height: 425px;
  margin: 25px;
  width: 900px;
}

.type {
  fill: #888;
  text-anchor: middle;
}

.shape {
  fill: #eee;
  stroke: #ccc;
}

<!DOCTYPE html>
<meta charset="utf-8">

<script src="//d3plus.org/js/d3.js"></script>
<script src="//d3plus.org/js/d3plus.js"></script>

<svg>

  <!-- Text that will use the D3plus default wrapping. -->
  <text class="type" dy="15px" x="75px">Wrapped</text>

  <rect class="shape" height="150px" width="150px" y="50px"></rect>
  <text id="rectWrap" class="wrap" y="50px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="75px" cy="300px"></circle>
  <text id="circleWrap" class="wrap" y="225px" x="0px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <!-- Text that D3plus will resize to fit the available space. -->
  <text class="type" dy="15px" x="275px">Resized</text>

  <rect class="shape" height="150px" width="150px" y="50px" x="200px"></rect>
  <text id="rectResize" class="wrap" y="50px" x="200px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="275px" cy="300px"></circle>
  <text id="circleResize" class="wrap" y="225px" x="200px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <!-- For comparison, how SVG would display the text without D3plus. -->
  <text class="type" dy="15px" x="475px">Default Behavior</text>

  <rect class="shape" height="150px" width="150px" y="50px" x="400px"></rect>
  <text class="wrap" y="50px" x="400px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

  <circle class="shape" r="75px" cx="475px" cy="300px"></circle>
  <text class="wrap" y="225px" x="400px" font-size="12">
    Here is a long text string that SVG should wrap by default, but it does not.
  </text>

</svg>


问:
Store last created model's row in memory
I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB.

In general, all changes are stored in DB as history, but I want the recent change duplicated in memory.

So the problem is: i want one variable to be stored in memory instead of DB.

答:
Unfortunately I don't believe you can do this unless you only have one instance of Python running, in which case you can use a global variable.  With most web implementations you have a threaded server so this would not work.  You would have to do a fetch from the database to get the latest copy of the record.

If this is a very high-usage situation, you may want to look into memcached (or similar) as a way of lowering the performance overhead of hitting the database for each request.

OwnerDisplayName: slatvick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jack M.


答:
This is not really related to git or svn specifically.

The usual practice in the case you're in is put under version control a template of this file (config.in for example) and to ignore the real config file. When cloning the repository all  you have to do is to copy the template, and the real file that will be used is ignored by your version control system.

Title: Git ignore changeset

Body:
Hi
I'm currently using SVN. Let's say I have some files with some changes that should be locally presented on my pc (I need them to run it on my configuration) but they shouldn't be committed to server.
I case of SVN it is ok to add them to .ignore and just do not commit them, but this works only in case of changing other files during my work. If I need to change something in files that are marked as ignore - I need before commit to backup these files, revert ignored changes, commit and restore them after backup. Sometimes this can be very annoying.

I heard about git, that it is built upon changesets not files. Can I use git-svn to ignore some changeset?


问:
How to write User stories in Data Warehouse project
In my Data Warehouse(More like data logistics because of we just transport data with a minimal transformation to a central HUB) project(which is said to be Agile-SCRUM) team have been writing User stories like

As an analyst, I want to prepare the specification sheet so the development can start

As a Developer, I want to develop the Transformation layer so that the HUB can be loaded

As a tester, I want to test the table so the same can be moved to production

Now for a fact I know that this is not how you write User stories since none of these represent functionality, they just represent a technical task.

I proposed something like,

As a data consumer, I want the table to be tested so there will not be any issues during consumption

And for this I got questions like "The consumer never asked the table to be tested, we test it because of the process we follow. The consumer only asked for data so why should we say as a consumer in the User story"

I do not know how to answer that and also I feel the User stories can still be composed in a better way but still sticking to the principle that "User stories are chunks that can be completed within 1-2 days"

I need some help to understand how others do it in a SCRUM Data logistic project and any suggestion on how this can be composed better

答:
This is a tricky situation as the data warehouse sound like it is may be a component rather than a product.

I can think of two possible approaches and the one you chose would depend on the setup of your organisation.

Write stories for end-user features

I'm guessing the data warehouse will be used for reports, etc. As such, a user story might be something like:

As a sales director I want a report on monthly sales so that I can plan my sales strategy

This story may then have several sub-tasks, such as:

Import sales data using SQL script

Create warehouse schema

Validate data

...and so on.

The challenge here will be if the work your team is doing is kept separate from the end-user features. In other words, you are implementing the data warehouse component and it does not include the reporting front-end.

Reframe the stories to focus on the users of the data warehouse

If the warehouse is a component to be used elsewhere in the organisation you could reflect this in your stories.

For example:

As a report writer I want the data in the data warehouse to be reliable so that I can write my reports with the confidence that the data is valid

This may then have a sub-task like:

Ensure all tables are tested


问:
Select Text in DIV with specific range using JavaScript
I want to select the text inside
 with a specific range ex.

```<code><div>This is a sample text.</div>
selectText(3, 12);
</code>```

it will select text from s to m(s is a sam) inside div and the user can copy the text by pressing ctrl + c

答:
This is a sample text.

slice(3, 12);

Body:
I want to select the text inside
 with a specific range ex.

This is a sample text.

selectText(3, 12);

it will select text from s to m(s is a sam) inside div and the user can copy the text by pressing ctrl + c

Body:
This is a sample text.

slice(3, 12);


问:
How to obtain all possible words from given hunspell dictionary?
I would like to parse open office supporting hunspell formatted aff and dic files.

English aff and dic files can be downloaded from here for example : http://extensions.openoffice.org/en/project/english-dictionaries-apache-openoffice

I want to scan each line of the given .dic file and generate every possible word of the each line with the provided .aff file

How can i do that?

I have installed NHunspell framework but it does not have that feature : https://www.nuget.org/packages/NHunspell/

For example for the english language lets consider

```<code>make/UAGS
</code>```

make can be make, made, makes, making etc

Now i need parser to give me all these combinations. How can i obtain them? Ty very much

So basically i want to scan each line of the dictionary and generate all possible words from the word of that line and i dont know how can i do that

I can also write my own parsers, but it seems to me rules are pretty complex and there are no detailed and easy documentation about this

Here what i want basically. The image explains very clearly

Giving analyze/ADSG, en.dic and en.aff file and obtaining all the following words

```<code>analyze, analyzes, analyzing, analyzed, reanalyze, reanalyzes, reanalyzing, reanalyzed
</code>```

答:
If you want the entire database you may execute unmunch:

```<code>unmunch dictionary.dic dictionary.aff
</code>```

Note that the current implementation of unmunch in hunspell has a limitation of maximum number of words, affs, and length of generated words. So, unmunch may fail if the target language is beyond the limits of unmunch.

If you want just the list of possible words that can be generated from an entry, you may use wordforms:

```<code>wordforms dictionary.aff dictionary.dic word
</code>```

Body:
I would like to parse open office supporting hunspell formatted aff and dic files.

English aff and dic files can be downloaded from here for example : http://extensions.openoffice.org/en/project/english-dictionaries-apache-openoffice

I want to scan each line of the given .dic file and generate every possible word of the each line with the provided .aff file

How can i do that?

I have installed NHunspell framework but it does not have that feature : https://www.nuget.org/packages/NHunspell/

For example for the english language lets consider

make/UAGS

make can be make, made, makes, making etc

Now i need parser to give me all these combinations. How can i obtain them? Ty very much

So basically i want to scan each line of the dictionary and generate all possible words from the word of that line and i dont know how can i do that

I can also write my own parsers, but it seems to me rules are pretty complex and there are no detailed and easy documentation about this

Here what i want basically. The image explains very clearly

Giving analyze/ADSG, en.dic and en.aff file and obtaining all the following words

analyze, analyzes, analyzing, analyzed, reanalyze, reanalyzes, reanalyzing, reanalyzed

Body:
If you want the entire database you may execute unmunch:

unmunch dictionary.dic dictionary.aff

Note that the current implementation of unmunch in hunspell has a limitation of maximum number of words, affs, and length of generated words. So, unmunch may fail if the target language is beyond the limits of unmunch.

If you want just the list of possible words that can be generated from an entry, you may use wordforms:

wordforms dictionary.aff dictionary.dic word


问:
Remove an item from a list of objects - Typescript
I want to remove a specific object from a list. The object model looks like this:

```<code>export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}
</code>```

I created a list of Task objects and I want to delete a Task that has a specific taskId.

```<code> moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }
</code>```

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

答:
there is spelling mistake use tasks.tasskId instead of task.</p>

```<code>
tasks: Task[]; // here I received some objects from a HTTP request.
filteredList: Task[];
filteredList = listOfTasks.filter(item => item.taskId !== tasks.taskId);

</code>```

Body:
I want to remove a specific object from a list. The object model looks like this:

export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}

I created a list of Task objects and I want to delete a Task that has a specific taskId.

 moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

Body:
there is spelling mistake use tasks.tasskId instead of task.

tasks: Task[]; // here I received some objects from a HTTP request.
filteredList: Task[];
filteredList = listOfTasks.filter(item => item.taskId !== tasks.taskId);


问:
How to run FFMPEG in laravel project
I can run this code via cmd. And my question is how can I run this command to my laravel project locally and also to my live server?

ffmpeg -i input1.webm -i input2.webm output.mp3

Thanks in advance.

答:
public function store(Request $request) {</p>

```<code>    $rules =  [
        'title' => 'required',
        'description' => 'required',
        'meta_title' => 'required',
        'category_id' => 'required',
        'video_file' => 'required',
        'tags' => 'required',
    ];
    $messages = [
        'category_id.required' => 'Category field required.',
        'tags.required' => 'Tag field required',

    ];
    $validator = Validator::make($request->all(),$rules, $messages);

    $validator->sometimes('file', 'nullable|mimes:csv,xlsx|max:1024000', function ($request) {
        $messages = ['file.mimes'=>'file type must be csv or xlsx.'];
        return ($request->category_id == 2 || $request->category_id == 4);
    });
    $validator->sometimes('file', 'nullable|mimes:pdf|max:1024000', function ($request) {
        $messages = ['file.mimes'=>'file type must be pdf.'];
        return ($request->category_id == 1);
    });
    if($validator->fails()) {
        return response()->json(['error'=>$validator->errors(),'status'=>false]);
    }else {
        DB::beginTransaction();
        try {

            $formData = new Video();
            $formData->title = $request->title;
            $formData->user_id = Auth::id();
            $formData->description = $request->description;
            $formData->upload_date = Carbon::now();
            //$formData->meta_title = implode(",",$request->meta_title);
            $formData->meta_description =isset($formData->meta_description)?implode(",", $request->meta_description):'';
            //$formData->tags = implode(",",$request->tags);

           $formData->category_id = $request->category_id[0];

            if($request->hasFile('image_file')) {
                $uploadedFile = $request->file('image_file');
                $filename = time().$uploadedFile->getClientOriginalName();
                $imagePath =  Storage::disk('public')->putFileAs(
                    'images',
                    $uploadedFile,
                    $filename
                  );
                $formData->image_file = $imagePath;
            }

             if($request->hasFile('video_file')) {
                $uploadedFile = $request->file('video_file');
                $filename = trim(time().$uploadedFile->getClientOriginalName());
                $removeSpaceFromFile = preg_replace('/[^A-Za-z0-9\-]/', '', $filename);
                $filePath =  Storage::disk('public')->putFileAs(
                    'videos',
                    $uploadedFile,
                    $removeSpaceFromFile
                  );
                $formData->video_file = $filePath;

                $video_id = DB::getPdo()->lastInsertId();
                $filefullPath = asset('storage').'/'.$filePath;
                $getOutputFilePath = Mp3AndTumbnails::where('id',1)->first();
                $outputMp3File =  $getOutputFilePath->mp3_output_path;
                $outputImageFile =  $getOutputFilePath->thumbnails_path;
                // $mp3Filename = $video_id.'.mp3';
                // $imageFileName = $video_id;
                $mp3Filename = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title).'.mp3';
                $imageFileName = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title);

                $output = shell_exec('ffmpeg -i '. $filefullPath.' -vn -ar 44100 -ac 2 -ab 192 -f mp3 '. $outputMp3File.'/'.$mp3Filename);
                $imageOutput = shell_exec('ffmpeg -i '.$filefullPath.' -ss 00:00:10 -vframes 1 -s 370x220 '.$outputImageFile.'/'.$imageFileName.'.jpg -hide_banner');
                $formData->mp3_file = $mp3Filename;
                $formData->image_file = 'images/'.$imageFileName.'.jpg';
                $dur = shell_exec("ffmpeg -i ".$filefullPath." 2>&1");
                preg_match("/Duration: (.{2}):(.{2}):(.{2})/", $dur, $duration);
                if(isset($duration[1])) {

                    $hours = $duration[1];
                    $minutes = $duration[2];
                    $seconds = $duration[3];
                    $video_length = $hours.':'.$minutes.':'.$seconds;
                    $formData->video_length = $video_length;
                }
            }
            if($request->hasFile('file')) {
                $lyricsFile = $request->file('file');
                $categoryInfo = Category::where('id',$request->category_id[0])->first();
                $filename = time().$lyricsFile->getClientOriginalName();
                $lyricsFile->move(public_path("download".'/'.$categoryInfo->name), $filename);
                $path = $filename;
                $formData->lyrics_file = $path;
            }
            $formData->save();
            foreach ($request->category_id as $key => $value) {
                $category = new VideoCategoryUpload();
                $category->video_id = $formData->id;
                $category->category_id = $value;
                $category->save();
            }
            $updateEncodeVideoId = Video::where('id',$formData->id)
                                    ->update(['base64_encode_video_id'=>base64_encode($formData->id)]);

            foreach ($request->tags as $key => $value) {
                $tagData = new TagModel();
                $tagData->user_id = Auth::id();
                $tagData->video_id = $formData->id;
                $tagData->name = $value;
                $tagData->slug_name = $value;

                $tagData->save();
            }

             foreach ($request->meta_title as $key => $value) {
                $metaTitleData = new MetaTitleModel();
                $metaTitleData->user_id = Auth::id();
                $metaTitleData->video_id = $formData->id;
                $metaTitleData->title_name = $value;
                $metaTitleData->title_slug_name = $value;

                $metaTitleData->save();
            }

            DB::commit();
            return response()->json(['status'=>true,'msg'=>'File uploaded successfully !!.']);
        }catch(\Exception $e) {
            DB::rollback();
            return response()->json(['status'=>'exception','msg'=>'Something Went Wrong !!.']);
        }
    }
}
</code>```

Title: How to run FFMPEG in laravel project

Body:
public function store(Request $request) {

    $rules =  [
        'title' => 'required',
        'description' => 'required',
        'meta_title' => 'required',
        'category_id' => 'required',
        'video_file' => 'required',
        'tags' => 'required',
    ];
    $messages = [
        'category_id.required' => 'Category field required.',
        'tags.required' => 'Tag field required',

    ];
    $validator = Validator::make($request->all(),$rules, $messages);

    $validator->sometimes('file', 'nullable|mimes:csv,xlsx|max:1024000', function ($request) {
        $messages = ['file.mimes'=>'file type must be csv or xlsx.'];
        return ($request->category_id == 2 || $request->category_id == 4);
    });
    $validator->sometimes('file', 'nullable|mimes:pdf|max:1024000', function ($request) {
        $messages = ['file.mimes'=>'file type must be pdf.'];
        return ($request->category_id == 1);
    });
    if($validator->fails()) {
        return response()->json(['error'=>$validator->errors(),'status'=>false]);
    }else {
        DB::beginTransaction();
        try {

            $formData = new Video();
            $formData->title = $request->title;
            $formData->user_id = Auth::id();
            $formData->description = $request->description;
            $formData->upload_date = Carbon::now();
            //$formData->meta_title = implode(",",$request->meta_title);
            $formData->meta_description =isset($formData->meta_description)?implode(",", $request->meta_description):'';
            //$formData->tags = implode(",",$request->tags);

           $formData->category_id = $request->category_id[0];

            if($request->hasFile('image_file')) {
                $uploadedFile = $request->file('image_file');
                $filename = time().$uploadedFile->getClientOriginalName();
                $imagePath =  Storage::disk('public')->putFileAs(
                    'images',
                    $uploadedFile,
                    $filename
                  );
                $formData->image_file = $imagePath;
            }

             if($request->hasFile('video_file')) {
                $uploadedFile = $request->file('video_file');
                $filename = trim(time().$uploadedFile->getClientOriginalName());
                $removeSpaceFromFile = preg_replace('/[^A-Za-z0-9\-]/', '', $filename);
                $filePath =  Storage::disk('public')->putFileAs(
                    'videos',
                    $uploadedFile,
                    $removeSpaceFromFile
                  );
                $formData->video_file = $filePath;

                $video_id = DB::getPdo()->lastInsertId();
                $filefullPath = asset('storage').'/'.$filePath;
                $getOutputFilePath = Mp3AndTumbnails::where('id',1)->first();
                $outputMp3File =  $getOutputFilePath->mp3_output_path;
                $outputImageFile =  $getOutputFilePath->thumbnails_path;
                // $mp3Filename = $video_id.'.mp3';
                // $imageFileName = $video_id;
                $mp3Filename = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title).'.mp3';
                $imageFileName = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title);

                $output = shell_exec('ffmpeg -i '. $filefullPath.' -vn -ar 44100 -ac 2 -ab 192 -f mp3 '. $outputMp3File.'/'.$mp3Filename);
                $imageOutput = shell_exec('ffmpeg -i '.$filefullPath.' -ss 00:00:10 -vframes 1 -s 370x220 '.$outputImageFile.'/'.$imageFileName.'.jpg -hide_banner');
                $formData->mp3_file = $mp3Filename;
                $formData->image_file = 'images/'.$imageFileName.'.jpg';
                $dur = shell_exec("ffmpeg -i ".$filefullPath." 2>&1");
                preg_match("/Duration: (.{2}):(.{2}):(.{2})/", $dur, $duration);
                if(isset($duration[1])) {

                    $hours = $duration[1];
                    $minutes = $duration[2];
                    $seconds = $duration[3];
                    $video_length = $hours.':'.$minutes.':'.$seconds;
                    $formData->video_length = $video_length;
                }
            }
            if($request->hasFile('file')) {
                $lyricsFile = $request->file('file');
                $categoryInfo = Category::where('id',$request->category_id[0])->first();
                $filename = time().$lyricsFile->getClientOriginalName();
                $lyricsFile->move(public_path("download".'/'.$categoryInfo->name), $filename);
                $path = $filename;
                $formData->lyrics_file = $path;
            }
            $formData->save();
            foreach ($request->category_id as $key => $value) {
                $category = new VideoCategoryUpload();
                $category->video_id = $formData->id;
                $category->category_id = $value;
                $category->save();
            }
            $updateEncodeVideoId = Video::where('id',$formData->id)
                                    ->update(['base64_encode_video_id'=>base64_encode($formData->id)]);

            foreach ($request->tags as $key => $value) {
                $tagData = new TagModel();
                $tagData->user_id = Auth::id();
                $tagData->video_id = $formData->id;
                $tagData->name = $value;
                $tagData->slug_name = $value;

                $tagData->save();
            }

             foreach ($request->meta_title as $key => $value) {
                $metaTitleData = new MetaTitleModel();
                $metaTitleData->user_id = Auth::id();
                $metaTitleData->video_id = $formData->id;
                $metaTitleData->title_name = $value;
                $metaTitleData->title_slug_name = $value;

                $metaTitleData->save();
            }

            DB::commit();
            return response()->json(['status'=>true,'msg'=>'File uploaded successfully !!.']);
        }catch(\Exception $e) {
            DB::rollback();
            return response()->json(['status'=>'exception','msg'=>'Something Went Wrong !!.']);
        }
    }
}


问:
Get most upper descendant descendant(s) in jQuery
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

```<code><div id="page">
    <div ...>
        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>
    </div>
    <div ...>
        <div ...>
            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>
        </div>
   </div>
</div>
</code>```

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

答:
If you know it's always going to have a
 parent, you could do this (which avoids having to know how many elements are between #page and div):

```<code>#page div>svg
</code>```

Body:
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>

            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

Body:
If you know it's always going to have a <div> parent, you could do this (which avoids having to know how many elements are between #page and div):

#page div>svg


问:
loading external scala scripts into a scala file
i originally made scripts with many functions on 2 individual scala worksheets. i got them working and now want to tie these individual scripts together by importing and using them into a third file. from what i have read you can not simply import external scripts you must first make them into a class and put them into a package. so i tried that but i still couldn't import it

i know this may be a bit basic for this site but im struggling to find much scala documentation.

i think my problem might span from a missunderstanding of how packages work. the picture below might help.

my program example

adder.scala

```<code>package adder
class adder {
  def add_to_this(AA:Int):Int={
    var BB = AA + 1;
    return BB
    }
}
</code>```

build.scala

```<code>package builder
class build {
  def make_numbers(){
  var a = 0;
  var b = 0;}
}
</code>```

main.sc

```<code>import adder
import builder
object main {
 adder.adder.add_to_this(10);

}
</code>```

the errors i get are

object  is not a member of package adder
object  is not a member of package builder

答:
Classes in scala slightly differ from classes in java. If you need something like singleton, you'll want to use object instead of class i.e.:

package com.example
object Main extends App {
  object Hide{
    object Adder{
      def addToThis(AA:Int):Int = AA + 1
    }
  }
 object Example{
   import com.example.Main.Hide.Adder
   def run(): Unit = println(Adder.addToThis(10))
 }
 Example.run()
}
```

Consider objects like packages/modules which are also regular values. You can import an object by its full path, i.e. com.example.Main.Hide.Adder you can also import contents of an object by adding .{addToThis}, or import anything from object by adding ._ after an object.

Note that classes, traits and case classes could not be used as objects, you can't do anything with it unless you have an instance - there are no static modifier.

Body:
i originally made scripts with many functions on 2 individual scala worksheets. i got them working and now want to tie these individual scripts together by importing and using them into a third file. from what i have read you can not simply import external scripts you must first make them into a class and put them into a package. so i tried that but i still couldn't import it

i know this may be a bit basic for this site but im struggling to find much scala documentation.

i think my problem might span from a missunderstanding of how packages work. the picture below might help.

my program example

adder.scala

package adder
class adder {
  def add_to_this(AA:Int):Int={
    var BB = AA + 1;
    return BB
    }
}

build.scala

package builder
class build {
  def make_numbers(){
  var a = 0;
  var b = 0;}
}

main.sc

import adder
import builder
object main {
 adder.adder.add_to_this(10);

}

the errors i get are

object  is not a member of package adder
object  is not a member of package builder

Body:
Classes in scala slightly differ from classes in java. If you need something like singleton, you'll want to use object instead of class i.e.:

package com.example
object Main extends App {
  object Hide{
    object Adder{
      def addToThis(AA:Int):Int = AA + 1
    }
  }
 object Example{
   import com.example.Main.Hide.Adder
   def run(): Unit = println(Adder.addToThis(10))
 }
 Example.run()
}

Consider objects like packages/modules which are also regular values. You can import an object by its full path, i.e. com.example.Main.Hide.Adder you can also import contents of an object by adding .{addToThis}, or import anything from object by adding ._ after an object.

Note that classes, traits and case classes could not be used as objects, you can't do anything with it unless you have an instance - there are no static modifier.


问:
Problem importing with read.csv (NULL in database manager is not recognized)
I'm trying to import a dataframe to r with read.csv. I exported from my database manager (DBeaver) with UTF-8 encoding.

In some factor vectors what is NULL in the database manager is not recognized as so. I think NULL is replaced by blank space(s) and I when I try, can't turn them to NULL or NA.

I'm using:

```<code>tb1 <- read.csv("pacientes.csv", header = TRUE, sep = ",", dec = ".")
</code>```

I identified the problem when I use

```<code>table(tb1$var2, useNA="ifany")
</code>```

With factor variables I know have missing values and I get a table with "blank space(s)" as a category (along with the correct categories)

I have 59 columns, so using some features of read.csv is unpractical. And I really believe there's an easier way to fix the problem. Can anyone help me? thank you very much!

答:
Try</p>

```<code>read.csv("pacientes.csv", header = TRUE, sep = ",", dec = ".", na.strings = c("NA", "", " "))
</code>```

Body:
I'm trying to import a dataframe to r with read.csv. I exported from my database manager (DBeaver) with UTF-8 encoding.

In some factor vectors what is NULL in the database manager is not recognized as so. I think NULL is replaced by blank space(s) and I when I try, can't turn them to NULL or NA.

I'm using:

tb1 <- read.csv("pacientes.csv", header = TRUE, sep = ",", dec = ".")

I identified the problem when I use

table(tb1$var2, useNA="ifany")

With factor variables I know have missing values and I get a table with "blank space(s)" as a category (along with the correct categories)

I have 59 columns, so using some features of read.csv is unpractical. And I really believe there's an easier way to fix the problem. Can anyone help me? thank you very much!

Body:
Try

read.csv("pacientes.csv", header = TRUE, sep = ",", dec = ".", na.strings = c("NA", "", " "))