问:
Dynamic ROOT With SQL Server For JSON PATH
I have a keyword table that I want to render to a Json object:

```<code>ID  Keyword     Text    Value
4   Category    A       10
5   Category    B       20
1   Season      Winter  1
2   Season      Spring  2
3   Season      Summer  3
9   Season      Fall    4
6   UnitType    Ft      Feet
7   UnitType    Set     Set
8   UnitType    $   Dollar
</code>```

that groups each category into it's own object.

I've being able to create this:

```<code>{"Keywords":[
{"Keyword":"Category","Values":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Keyword":"Season","Values":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"Keyword":"UnitType","Values":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}
</code>```

using:

```<code>SELECT T.Keyword AS 'Keyword',
(SELECT [subT].[Value] AS 'Value', [subT].[Text] AS 'Text'
FROM tblKeywords subT WHERE subT.Keyword=T.Keyword
ORDER BY [subT].[Value]
FOR JSON PATH) AS 'Values'
FROM tblKeywords T
GROUP BY T.Keyword
FOR JSON PATH, ROOT('Keywords')
</code>```

But I'd like to be able to set the ROOT for the sub query to be keyword itself. Is this even possible?

The desired result is:

```<code>{"Keywords":[
{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"UnitType":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}
</code>```

答:
Initial data:

```<code>DROP TABLE IF EXISTS #tblKeywords;
CREATE TABLE #tblKeywords (ID INT, Keyword NVARCHAR(255), [Text] NVARCHAR(255), Value NVARCHAR(255));
INSERT INTO #tblKeywords(ID,Keyword,Text,[Value])VALUES
     (4,'Category','A','10')
    ,(5,'Category','B','20')
    ,(1,'Season','Winter','1')
    ,(2,'Season','Spring','2')
    ,(3,'Season','Summer','3')
    ,(9,'Season','Fall','4')
    ,(6,'UnitType','Ft','Feet')
    ,(7,'UnitType','Set','Set')
    ,(8,'UnitType','$','Dollar')
;
</code>```

I know, Dynamic SQL, however:

```<code>DECLARE @DynSql NVARCHAR(MAX) = (
    SELECT 'SELECT ' + STUFF((
            SELECT DISTINCT N',(SELECT [subT].[Value] AS [Value], [subT].[Text] AS [Text]
            FROM #tblKeywords subT
            WHERE subT.Keyword = ''' + t.Keyword + N'''
            ORDER BY [subT].[Value]
            FOR JSON PATH
            ) AS [' + t.Keyword + N']' + CHAR(13) + '   '
            FROM #tblKeywords t
            FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
        + 'FOR JSON PATH, ROOT(''Keywords'')'
)
;
--PRINT @DynSql;
EXEC (@DynSql);
</code>```

Body:
I have a keyword table that I want to render to a Json object:

ID  Keyword     Text    Value
4   Category    A       10
5   Category    B       20
1   Season      Winter  1
2   Season      Spring  2
3   Season      Summer  3
9   Season      Fall    4
6   UnitType    Ft      Feet
7   UnitType    Set     Set
8   UnitType    $   Dollar

that groups each category into it's own object.

I've being able to create this:

{"Keywords":[
{"Keyword":"Category","Values":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Keyword":"Season","Values":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"Keyword":"UnitType","Values":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}

using:

SELECT T.Keyword AS 'Keyword',
(SELECT [subT].[Value] AS 'Value', [subT].[Text] AS 'Text'
FROM tblKeywords subT WHERE subT.Keyword=T.Keyword
ORDER BY [subT].[Value]
FOR JSON PATH) AS 'Values'
FROM tblKeywords T
GROUP BY T.Keyword
FOR JSON PATH, ROOT('Keywords')

But I'd like to be able to set the ROOT for the sub query to be keyword itself. Is this even possible?

The desired result is:

{"Keywords":[
{"Category":[{"Value":"10","Text":"A"},{"Value":"20","Text":"B"}]},
{"Season":[{"Value":"1","Text":"Winter"},{"Value":"2","Text":"Spring"},{"Value":"3","Text":"Summer"},{"Value":"4","Text":"Fall"}]},
{"UnitType":[{"Value":"Dollar","Text":"$"},{"Value":"Feet","Text":"Ft"},{"Value":"Set","Text":"Set"}]}
]}

Body:
Initial data:

DROP TABLE IF EXISTS #tblKeywords;
CREATE TABLE #tblKeywords (ID INT, Keyword NVARCHAR(255), [Text] NVARCHAR(255), Value NVARCHAR(255));
INSERT INTO #tblKeywords(ID,Keyword,Text,[Value])VALUES
     (4,'Category','A','10')
    ,(5,'Category','B','20')
    ,(1,'Season','Winter','1')
    ,(2,'Season','Spring','2')
    ,(3,'Season','Summer','3')
    ,(9,'Season','Fall','4')
    ,(6,'UnitType','Ft','Feet')
    ,(7,'UnitType','Set','Set')
    ,(8,'UnitType','$','Dollar')
;

I know, Dynamic SQL, however:

DECLARE @DynSql NVARCHAR(MAX) = (
    SELECT 'SELECT ' + STUFF((
            SELECT DISTINCT N',(SELECT [subT].[Value] AS [Value], [subT].[Text] AS [Text]
            FROM #tblKeywords subT
            WHERE subT.Keyword = ''' + t.Keyword + N'''
            ORDER BY [subT].[Value]
            FOR JSON PATH
            ) AS [' + t.Keyword + N']' + CHAR(13) + '   '
            FROM #tblKeywords t
            FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
        + 'FOR JSON PATH, ROOT(''Keywords'')'
)
;
--PRINT @DynSql;
EXEC (@DynSql);


来源: stackexchange

问:
Object.fromEntries only available on iOS? (react native - NOT WEB)
The title is pretty self explanatory but still, consider this sample code:

```<code>import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}
</code>```

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?

答:
just add the babel preset to your babel config:
https://www.npmjs.com/package/babel-plugin-transform-object-from-entries</p>

ContentLicense: CC BY-SA 4.0

Body:
The title is pretty self explanatory but still, consider this sample code:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?


问:
Page title in stateless functional components
How do you do this in stateless functional components? I tried this but it doesn't work:
ComponentName.componentDidMount = () => document.title = "Who's Marco?"
Where the ComponentName is something like this:

```<code>export const Life = ({sayHello="Ciao"}) => (

)
</code>```

答:
With a functional component, you can use useEffect.

For example,

```<code>useEffect(() => {
  document.title = "Who's Marco?"
}, []);
</code>```

Adding the empty array in useEffect calls the function only once, just like a componentDidMount life cycle method.

ContentLicense: CC BY-SA 3.0

Body:
How do you do this in stateless functional components? I tried this but it doesn't work:
ComponentName.componentDidMount = () => document.title = "Who's Marco?"
Where the ComponentName is something like this:

export const Life = ({sayHello="Ciao"}) => (

)

Body:
With a functional component, you can use useEffect.

For example,

useEffect(() => {
  document.title = "Who's Marco?"
}, []);

Adding the empty array in useEffect calls the function only once, just like a componentDidMount life cycle method.


问:
JQuery Form success callback not being called
I have searched and can't find an answer that matches my exact situation so first off, apologies if this is a duplicate.

I am using ASP.Net MVC 3, and am submitting a form using the JQuery form plugin.  The form submits correctly and I am able to step through the code behind etc however the success callback is never called - I've stripped back my code to as simple as possible:

```<code>$(document).ready(function () {
    BindForm();
});

function BindForm() {
    $('#PaydayForm').ajaxForm({
        error:  function() { alert("Error");},
        success: function() { alert("Success");},
    });
}
</code>```

The form submits but neither error or success is called!

答: Are you submitting cross-domain with ajax? That's one reason I can think where you will receive the data on the server but your JavaScript code will either not receive a success callback at all (Firefox) or will get the call but never the response data (Chrome).</p>

Body:
I have searched and can't find an answer that matches my exact situation so first off, apologies if this is a duplicate.

I am using ASP.Net MVC 3, and am submitting a form using the JQuery form plugin.  The form submits correctly and I am able to step through the code behind etc however the success callback is never called - I've stripped back my code to as simple as possible:

$(document).ready(function () {
    BindForm();
});

function BindForm() {
    $('#PaydayForm').ajaxForm({
        error:  function() { alert("Error");},
        success: function() { alert("Success");},
    });
}

The form submits but neither error or success is called!


问:
Terraform resource with count 0 and a variable depending on the resource
I'm trying to create s3 buckets on aws using Terraform, few buckets exist in all environments (dev, qa and prod) whereas most buckets exist in only 1 or 2 environments. I'm using count to define resources selectively

So in the below code, I'm creating a bucket in S3 only if the environment is dev or qa using count and conditionals. But when I run the code for prod environment, I'm getting Error: module 's3-bucket-example': unknown variable referenced: 'lifecycle_rule_s3_bucket_example'; define it with a 'variable' block

lifecycle_rule for each bucket is defined in corresponding var file for each environment like lifecycle_rule_s3_bucket_example is defined in var-file.dev and var-file.qa but not in var-file.prod as the bucket exists in dev and qa. But since the bucket doesn't exist in prod, why am i getting the error to define lifecycle_rule variable ? My guess was that since the count = 0 for prod, none of the remaining variables should matter in the module.

```<code>module "s3-bucket-example" {
  source             = "./modules/s3"
  count              = "${var.aws-account == "dev"|| var.aws-account == "qa" ? 1 :0}"
  bucketname         = "${local.this_env_prefix}-s3-bucket-example"
  versioning-enabled = "true"
  lifecycle_rule     = "${var.lifecycle_rule_s3_bucket_example}"
  aws_account        = "${var.aws-account}"
}
</code>```

答:
Prior to actually creating any resource in AWS (or any other provider for that matter), Terraform performs a validation to check wether all variables etc. are defined.

This way the chance of running into an error during resource creation is reduced.

Guess you have to define the variable for your prod env as well with a dummy value...

Body:
I'm trying to create s3 buckets on aws using Terraform, few buckets exist in all environments (dev, qa and prod) whereas most buckets exist in only 1 or 2 environments. I'm using count to define resources selectively

So in the below code, I'm creating a bucket in S3 only if the environment is dev or qa using count and conditionals. But when I run the code for prod environment, I'm getting Error: module 's3-bucket-example': unknown variable referenced: 'lifecycle_rule_s3_bucket_example'; define it with a 'variable' block

lifecycle_rule for each bucket is defined in corresponding var file for each environment like lifecycle_rule_s3_bucket_example is defined in var-file.dev and var-file.qa but not in var-file.prod as the bucket exists in dev and qa. But since the bucket doesn't exist in prod, why am i getting the error to define lifecycle_rule variable ? My guess was that since the count = 0 for prod, none of the remaining variables should matter in the module.

module "s3-bucket-example" {
  source             = "./modules/s3"
  count              = "${var.aws-account == "dev"|| var.aws-account == "qa" ? 1 :0}"
  bucketname         = "${local.this_env_prefix}-s3-bucket-example"
  versioning-enabled = "true"
  lifecycle_rule     = "${var.lifecycle_rule_s3_bucket_example}"
  aws_account        = "${var.aws-account}"
}


问:
How to write a string algorithm
given a FASTA text file (Rosalind_gc.txt), I am supposed to go through each DNA record and identify the percentage (%) of Guanine-Cytosine (GC) content.

Example of this is :

Sample Dataset:

```<code>>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT
</code>```

Sample output:

Rosalind_0808
60.919540

So basically go through each string, count the amt of times G/C show up and then divide that total by the length of each string. My issue is learning how to identify the breaks in code (i.e. >Rosalind_6404 ). I would like an example of this code without using Biopython and also with the biopython approach.

答:
You may want to make use of precompiled C modules as much as possible for performance issue. There's one solution using regex:

```<code>seq = 'CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCCTCCCACTAATAATTCTGAGG'

import re
perc = re.subn(r'[GC]', '', seq) / len(seq)
</code>```

And also handle the ">" lines:

```<code>seq = []
name = ''

for line in open('Rosalind_gc.txt'):
    if not line.startswith('>'):
        seq.append(line.strip())
    else:
        if seq:
            seq = ''.join(seq)
            perc = re.subn(r'[GC]', '', seq) / len(seq)
            print('{} has GC percent: {}'.format(name, perc * 100))
            seq = []
        name = line.strip()
</code>```

Title: How to write a string algorithm

Body:
given a FASTA text file (Rosalind_gc.txt), I am supposed to go through each DNA record and identify the percentage (%) of Guanine-Cytosine (GC) content.

Example of this is :

Sample Dataset:

>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT

Sample output:

Rosalind_0808
60.919540

So basically go through each string, count the amt of times G/C show up and then divide that total by the length of each string. My issue is learning how to identify the breaks in code (i.e. >Rosalind_6404 ). I would like an example of this code without using Biopython and also with the biopython approach.

Body:
You may want to make use of precompiled C modules as much as possible for performance issue. There's one solution using regex:

seq = 'CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCCTCCCACTAATAATTCTGAGG'

import re
perc = re.subn(r'[GC]', '', seq) / len(seq)

And also handle the ">" lines:

seq = []
name = ''

for line in open('Rosalind_gc.txt'):
    if not line.startswith('>'):
        seq.append(line.strip())
    else:
        if seq:
            seq = ''.join(seq)
            perc = re.subn(r'[GC]', '', seq) / len(seq)
            print('{} has GC percent: {}'.format(name, perc * 100))
            seq = []
        name = line.strip()


问:
Detecting enter key on a svg element
I am trying to make my web site more accessible by making navigable with keyboard input only. To do so I need to be able to tab to a dynamically created SVG element, g, and then press enter to open a modal with more information.

I can detect when any key is pressed but not specifically enter. I have seen lots of people describing how to detect an enter keypress on a input element, but that does not fix my issue. The problem I have run into is that myEvent is just a normal event and not a keyboard event. So it does not have a keycode. I have also seen it suggested to use myEvent.key or myEvent.which, which it also does not have. So I don't know how to get the information of what key was pressed.

I don't know it this info is helpful but my website is a family history tree viewing web app so each SVG element is the visual representation of a node in a tree. I am trying to tab across every node and display more information about the focused node's person when enter is pressed.

```<code> var g:Element = document.createElementNS("http://www.w3.org/2000/svg", "g");

 g.setAttribute('tabindex', "0"); // So I can tab to the element

 g.addEventListener("keypress",  function (myEvent) {
      // To this point everything works.

      // The next line gives an error.
      if(myEvent.keyCode === 13) { // 13 is enter
           // Open my modal
      }
 });
</code>```

答:
Try to do a cast.

var container:Element = document.createElement("div");
var svg:Element = document.createElementNS("http://www.w3.org/2000/svg", "svg");

 var g:Element = document.createElementNS("http://www.w3.org/2000/svg", "g");

 g.setAttribute('tabindex', "0"); // So I can tab to the element

 g.addEventListener("keypress",  function (myEvent:KeyboardEvent) {
      // To this point everything works.

     console.log(myEvent);
      // The next line gives an error.
      if(myEvent.keyCode === 13) { // 13 is enter
          alert('enter');
      }
 });

var circle:Element = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");

g.appendChild(circle);
svg.appendChild(g);
container.appendChild(svg);
document.body.appendChild(container);```

Title: Detecting enter key on a svg element

Body:
I am trying to make my web site more accessible by making navigable with keyboard input only. To do so I need to be able to tab to a dynamically created SVG element, g, and then press enter to open a modal with more information.

I can detect when any key is pressed but not specifically enter. I have seen lots of people describing how to detect an enter keypress on a input element, but that does not fix my issue. The problem I have run into is that myEvent is just a normal event and not a keyboard event. So it does not have a keycode. I have also seen it suggested to use myEvent.key or myEvent.which, which it also does not have. So I don't know how to get the information of what key was pressed.

I don't know it this info is helpful but my website is a family history tree viewing web app so each SVG element is the visual representation of a node in a tree. I am trying to tab across every node and display more information about the focused node's person when enter is pressed.

 var g:Element = document.createElementNS("http://www.w3.org/2000/svg", "g");

 g.setAttribute('tabindex', "0"); // So I can tab to the element

 g.addEventListener("keypress",  function (myEvent) {
      // To this point everything works.

      // The next line gives an error.
      if(myEvent.keyCode === 13) { // 13 is enter
           // Open my modal
      }
 });


问:
Java: How to create new child class instance from abstract parent class?
Here is the gist of what I am trying to do:

```<code>abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

答:
public abstract class Animal {

    abstract List<? extends Animal> makeFive();

}

class Dog extends Animal {

    @Override
    List<Dog> makeFive() {
        return null;
    }
}

class Cat extends Animal {

    @Override
    List<Cat> makeFive() {
        return null;
    }
}
```

Body:
Here is the gist of what I am trying to do:

abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.


问:
how to use n model in one root in reactjs?
hi i have one root like this code

```<code><body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<button >Platform</button>
<button >Game</button>
<button >Score</button>
<hr />

<div id="root"></div>
</code>```

index.js code

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();
</code>```

app.js code

```<code>    import React ,{Component} from 'react';
import axios from 'axios';
import { Modal,ModalHeader,ModalBody,ModalFooter,FormGroup,Label,Input,Table ,Button} from 'reactstrap';

class App extends Component{
  state={
    books:[],
    NewBookData:{
      Title:'',
      Rating:''
    },
    EditBookData:{
      Id:'',
      Title:'',
      Rating:''
    },

    NewBookModal:false,
    EditBookModal:false
  }
....
</code>```

this root is ok for default jobs,but i want ovveride this root base on platform ,game , ...
how i can this work?

答:
you must use Route like this code

1.create 3 js file for Platform,game,score,... in Component Folder like this code

```<code>import React,{Component} from 'react';
class Game extends Component {
    render(){
    return (
     <h1>this is game page</h1>
    );
    }
  }
  export default Game;
</code>```

2.import this code to app.js

```<code>import React,{Component} from 'react';
import {BrowserRouter as Router,NavLink} from 'react-router-dom';
import Route from 'react-router-dom/Route';
import gamePage from './Component/game';
import platformPage from './Component/platform';
import scorePage from './Component/score';
</code>```

3.use Route to send to models

```<code>  <Router>
<div className="App">
  <ul>
    <li>
  <NavLink to="/platform" exact activeStyle={{color:'violet'}}>Platform</NavLink>
  </li>
  <li>
  <NavLink to="/game" exact activeStyle={{color:'violet'}}>Game</NavLink>
  </li>
  <li>
  <NavLink to="/score" exact activeStyle={{color:'violet'}}>Score</NavLink>
  </li>
  </ul>
  <Route path="/platform" exact strict component={platformPage}/>

  <Route path="/game" exact strict component={gamePage}/>

  <Route path="/score" exact strict component={scorePage}  />

</div>
</Router>
</code>```

Body:
hi i have one root like this code

You need to enable JavaScript to run this app.
<button >Platform</button>
<button >Game</button>
<button >Score</button>

index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

app.js code

    import React ,{Component} from 'react';
import axios from 'axios';
import { Modal,ModalHeader,ModalBody,ModalFooter,FormGroup,Label,Input,Table ,Button} from 'reactstrap';

class App extends Component{
  state={
    books:[],
    NewBookData:{
      Title:'',
      Rating:''
    },
    EditBookData:{
      Id:'',
      Title:'',
      Rating:''
    },

    NewBookModal:false,
    EditBookModal:false
  }
....

this root is ok for default jobs,but i want ovveride this root base on platform ,game , ...
how i can this work?

Body:
you must use Route like this code

1.create 3 js file for Platform,game,score,... in Component Folder like this code

import React,{Component} from 'react';
class Game extends Component {
    render(){
    return (
     <h1>this is game page</h1>
    );
    }
  }
  export default Game;

2.import this code to app.js

import React,{Component} from 'react';
import {BrowserRouter as Router,NavLink} from 'react-router-dom';
import Route from 'react-router-dom/Route';
import gamePage from './Component/game';
import platformPage from './Component/platform';
import scorePage from './Component/score';

3.use Route to send to models

  <Router>
<div className="App">
  <ul>
    <li>
  <NavLink to="/platform" exact activeStyle={{color:'violet'}}>Platform</NavLink>
  </li>
  <li>
  <NavLink to="/game" exact activeStyle={{color:'violet'}}>Game</NavLink>
  </li>
  <li>
  <NavLink to="/score" exact activeStyle={{color:'violet'}}>Score</NavLink>
  </li>
  </ul>
  <Route path="/platform" exact strict component={platformPage}/>

  <Route path="/game" exact strict component={gamePage}/>

  <Route path="/score" exact strict component={scorePage}  />

</div>
</Router>


问:
How can I elegantly implement multiple string replacements in the same file?
Currently I have some code to replace strings in a file that looks like this:

```<code>File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));
</code>```

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

答: A better practice would be to read the contents of the file once, storing it into a local variable.  Then performing any changes you need (in your case, two regular expressions), and then writing that output to the file.  File IO is one of the most expensive operations a computer can perform, and in-memory computation is much cheaper.  Hit the disk as little as possible, as long as you can avoid it.</p>

Body:
Currently I have some code to replace strings in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.


问:
RegEx for replacing multiple HTML tags
I am trying to find a regex that will match multiple html tags, exclude the content in between so that the wrapping tags can be replaced by a different html tag. This replacement needs to work on a large HTML document where there are many instances of the same
...
 format.

Current HTML

```<code><div>
  <div><strong>Heading</strong></div>
  <div>Some other content<div>
  <div><strong>Heading Title 2</strong></div>
  <div>Some more content</div>
</div>
</code>```

Desired HTML

```<code><div>
  <div class="heading">Heading</div>
  <div>Some other content<div>
  <div class="heading">Heading Title 2</div>
  <div>Some more content</div>
</div>
</code>```

I've managed to find a regex that will match the full string but am unsure how to exclude the Heading content and then how to best replace the outer tags.

The best regex I have so far is: /
]*>(.*?)<\/strong><\/div>/g

答:
Use replaceWith to replace the div with a newly formatted div.

[...document.querySelectorAll('div > strong')].forEach(item => {
  // item is the 'strong' element
  // Create a new div
  let div = document.createElement('div')

  // Add a heading class to the div
  div.classList.add('heading')

  // Set the text of the div
  div.innerHTML = item.innerHTML

  // Replace the 'strong' elements parent with the new div
  item.parentNode.replaceWith(div)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.heading {
  font-size: 20px;
  font-weight: bold;
}</code>```

Heading

Some other content

Heading Title 2

Some more content

```

Title: RegEx for replacing multiple HTML tags

Body:
I am trying to find a regex that will match multiple html tags, exclude the content in between so that the wrapping tags can be replaced by a different html tag. This replacement needs to work on a large HTML document where there are many instances of the same
...
 format.

Current HTML

Heading

Some other content

Heading Title 2

Some more content

Desired HTML

Heading

Some other content

Heading Title 2

Some more content

I've managed to find a regex that will match the full string but am unsure how to exclude the Heading content and then how to best replace the outer tags.

The best regex I have so far is: /
]*>(.*?)<\/strong><\/div>/g

Body:
Use replaceWith to replace the div with a newly formatted div.

[...document.querySelectorAll('div > strong')].forEach(item => {
  // item is the 'strong' element
  // Create a new div
  let div = document.createElement('div')

  // Add a heading class to the div
  div.classList.add('heading')

  // Set the text of the div
  div.innerHTML = item.innerHTML

  // Replace the 'strong' elements parent with the new div
  item.parentNode.replaceWith(div)
})

.heading {
  font-size: 20px;
  font-weight: bold;
}

<div>
  <div><strong>Heading</strong></div>
  <div>Some other content<div>
  <div><strong>Heading Title 2</strong></div>
  <div>Some more content</div>
</div>


答:
The regexp you use should work. You can use $1 to copy the capture group to the result.

const html = `

Heading

Some other content

Heading Title 2

Some more content

`;

const new_html = html.replace(/
]*>(.*?)<\/strong><\/div>/g, '
$1
');
console.log(new_html);```

Note that this is a bad approach if you're trying to update the DOM of the entire document. Replacing all the HTML will discard any dynamic state, such as user inputs, event listeners, since all the HTML is re-parsed from scratch. It's better to use DOM element methods, as in @GetOffMyLawn's answer.

Title: RegEx for replacing multiple HTML tags

Body:
The regexp you use should work. You can use $1 to copy the capture group to the result.

const html = `<div>
  <div><strong>Heading</strong></div>
  <div>Some other content<div>
  <div><strong>Heading Title 2</strong></div>
  <div>Some more content</div>
</div>`;

const new_html = html.replace(/<div><strong\b[^>]*>(.*?)<\/strong><\/div>/g, '<div class="heading">$1</div>');
console.log(new_html);

Note that this is a bad approach if you're trying to update the DOM of the entire document. Replacing all the HTML will discard any dynamic state, such as user inputs, event listeners, since all the HTML is re-parsed from scratch. It's better to use DOM element methods, as in @GetOffMyLawn's answer.


问:
How to find list of missing characters in a column from another column
I have two tables. Tab_1.col_2 has characters and Tab2.col_2 has strings

```<code>Tab_1
col_1   col_2
1       A
2       B
3       C
4       N

Tab_2
col_1   col_2
101     CCNCCN
102     ABCNSN
103     TABGNN
</code>```

I want to be able to search Tab2.col_2 using Tab_1.col_2 and identify all the missing characters

There is no join condition available between these two table. I tried to substring each character on Tab_2.col_2 and then do a simple not in function.

Expected result:

I expect the output to give two characters that are missing from Tab_1.col_2 - T and G as two rows

```<code>Output:
T
G
</code>```

答:
One way is to use a recursive CTE stripping of leftmost char for leftmost char. The get the distinct set of that chars where the char doesn't exist in the set of single chars.

```<code>WITH
cte (c, r)
AS
(
SELECT substr(t2.col_2, 1, 1) c,
       substr(t2.col_2, 2, length(t2.col_2) - 1) r
       FROM tab_2 t2
UNION ALL
SELECT substr(c.r, 1, 1) c,
       substr(c.r, 2, length(c.r) - 1) r
       FROM cte c
       WHERE substr(c.r, 1, 1) IS NOT NULL
)
SELECT DISTINCT
       c.c
       FROM cte c
       WHERE NOT EXISTS (SELECT *
                                FROM tab_1 t1
                                WHERE t1.col_2 = c.c);
</code>```

db<>fiddle

Maybe you can combine the idea of Gordon removing the existing chars with translate() first with the idea of stripping off the leftmost chars one by one to even get a shortcut without the need of the NOT EXISTS.

Body:
I have two tables. Tab_1.col_2 has characters and Tab2.col_2 has strings

Tab_1
col_1   col_2
1       A
2       B
3       C
4       N

Tab_2
col_1   col_2
101     CCNCCN
102     ABCNSN
103     TABGNN

I want to be able to search Tab2.col_2 using Tab_1.col_2 and identify all the missing characters

There is no join condition available between these two table. I tried to substring each character on Tab_2.col_2 and then do a simple not in function.

Expected result:

I expect the output to give two characters that are missing from Tab_1.col_2 - T and G as two rows

Output:
T
G

Body:
One way is to use a recursive CTE stripping of leftmost char for leftmost char. The get the distinct set of that chars where the char doesn't exist in the set of single chars.

WITH
cte (c, r)
AS
(
SELECT substr(t2.col_2, 1, 1) c,
       substr(t2.col_2, 2, length(t2.col_2) - 1) r
       FROM tab_2 t2
UNION ALL
SELECT substr(c.r, 1, 1) c,
       substr(c.r, 2, length(c.r) - 1) r
       FROM cte c
       WHERE substr(c.r, 1, 1) IS NOT NULL
)
SELECT DISTINCT
       c.c
       FROM cte c
       WHERE NOT EXISTS (SELECT *
                                FROM tab_1 t1
                                WHERE t1.col_2 = c.c);

db<>fiddle

Maybe you can combine the idea of Gordon removing the existing chars with translate() first with the idea of stripping off the leftmost chars one by one to even get a shortcut without the need of the NOT EXISTS.


问:
using match to check both character and function type objects
I am writing a custom function that plots a smoothing line and displays subtitle as "linear model" only when the geom_smooth parameters are all linear (i.e. method = "lm" and formula = y ~ x). This involves checking what the user inputs for these two arguments. The complicated aspect of checking the input is that the method argument can be entered either as a character ("lm") or as a function (MASS::rlm) and this is where the function fails.

How can I get this to work?

Here is a reprex:

# for reproducibility
set.seed(123)
library(tidyverse)
library(mgcv)

# defining a function to plot smooth line
scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
  if (as.character(deparse(formula)) != "y ~ x" ||
    !any(method %in% c("lm", stats::lm))) {
    subtitle <- "non-linear model"
  } else {
    subtitle <- "linear model"
  }

  # creating the plot
  ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
    geom_smooth(formula = formula, method = method) +
    labs(subtitle = subtitle)
}

# different `formula` (works)
scatter_lm(mtcars, wt, mpg, y ~ log(x))
```

<p><img src="https://i.imgur.com/JOgV3vn.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code># `method` entered as a character (works)
scatter_lm(mtcars, wt, mpg, y ~ x, "gam")
</code>```

# `method` entered as a function (doesn't work)
scatter_lm(mtcars, wt, mpg, y ~ x, MASS::rlm)
#> Error in match(x, table, nomatch = 0L): 'match' requires vector arguments
```

Created on 2019-05-30 by the reprex package (v0.3.0)

答:
this solution is a bit convoluted, but it works:</p>

```<code>scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
  a <- paste(deparse(method), collapse = "")
  if (as.character(deparse(formula)) != "y ~ x" ||
      if (class(method) == "function") {
        a != paste(deparse(lm), collapse = "")
      } else method != "lm") {
    subtitle <- "non-linear model"
  } else {
    subtitle <- "linear model"
  }

  #creating the plot
  ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
    geom_smooth(formula = formula, method = method) +
    labs(subtitle = subtitle)
}
</code>```

Body:
I am writing a custom function that plots a smoothing line and displays subtitle as "linear model" only when the geom_smooth parameters are all linear (i.e. method = "lm" and formula = y ~ x). This involves checking what the user inputs for these two arguments. The complicated aspect of checking the input is that the method argument can be entered either as a character ("lm") or as a function (MASS::rlm) and this is where the function fails.

How can I get this to work?

Here is a reprex:

# for reproducibility
set.seed(123)
library(tidyverse)
library(mgcv)

# defining a function to plot smooth line
scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
  if (as.character(deparse(formula)) != "y ~ x" ||
    !any(method %in% c("lm", stats::lm))) {
    subtitle <- "non-linear model"
  } else {
    subtitle <- "linear model"
  }

  # creating the plot
  ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
    geom_smooth(formula = formula, method = method) +
    labs(subtitle = subtitle)
}

# different `formula` (works)
scatter_lm(mtcars, wt, mpg, y ~ log(x))

# `method` entered as a character (works)
scatter_lm(mtcars, wt, mpg, y ~ x, "gam")

# `method` entered as a function (doesn't work)
scatter_lm(mtcars, wt, mpg, y ~ x, MASS::rlm)
#> Error in match(x, table, nomatch = 0L): 'match' requires vector arguments

Created on 2019-05-30 by the reprex package (v0.3.0)

Body:
this solution is a bit convoluted, but it works:

scatter_lm <- function(df, x, y, formula = y ~ x, method = "lm") {
  a <- paste(deparse(method), collapse = "")
  if (as.character(deparse(formula)) != "y ~ x" ||
      if (class(method) == "function") {
        a != paste(deparse(lm), collapse = "")
      } else method != "lm") {
    subtitle <- "non-linear model"
  } else {
    subtitle <- "linear model"
  }

  #creating the plot
  ggplot(df, aes(!!rlang::enquo(x), !!rlang::enquo(y))) +
    geom_smooth(formula = formula, method = method) +
    labs(subtitle = subtitle)
}


问:
How to make C# application crash with an AccessViolationException
How to intentionally crash an application with an AccessViolationException in c#?

I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions. Because of that, I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.

Besides that, it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.

Surprisingly, this does not work:

public static void Crash()
{
    throw new AccessViolationException();
}
```

<p>Neither this:</p>

```public static unsafe void Crash()
{
    for (int i = 1; true; i++)
    {
        var ptr = (int*)i;
        int value = *ptr;
    }
}
```

答:
A Deterministic approach is to have Windows throw it for you:

From Петър Петров's answer to: How to make C# application crash

```<code>[DllImport("kernel32.dll")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags,  uint nNumberOfArguments, IntPtr lpArguments);

void start()
{
    RaiseException(0xC0000005, 0, 0, new IntPtr(1));
}
</code>```

Body:
How to intentionally crash an application with an AccessViolationException in c#?

I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions. Because of that, I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.

Besides that, it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.

Surprisingly, this does not work:

public static void Crash()
{
    throw new AccessViolationException();
}

Neither this:

public static unsafe void Crash()
{
    for (int i = 1; true; i++)
    {
        var ptr = (int*)i;
        int value = *ptr;
    }
}

Body:
A Deterministic approach is to have Windows throw it for you:

From Петър Петров's answer to: How to make C# application crash

[DllImport("kernel32.dll")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags,  uint nNumberOfArguments, IntPtr lpArguments);

void start()
{
    RaiseException(0xC0000005, 0, 0, new IntPtr(1));
}


答: Sounds like you should be doing your all your string replacements on a string residing in memory, then write your final resulting string to disk.</p>

Title: How can I elegantly implement multiple string replacements in the same file?


问:
Spring Data Repository @Query - Update and return modified entity
let's assume we have a Spring Data repository interface with a custom method...

```<code>@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
void markAsSoftDeleted(long id);
</code>```

This method simply sets the deletedAt field of the entity, ok. Is there any way to allow this method to return an updated version of the MyEntity?

Obviously...

```<code>@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
MyEntity markAsSoftDeleted(long id);
</code>```

...does not work, since...

java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!

Does anyon know another way to easily allow that, except of course the obvious "add a service layer between repository and caller for such things"...

答:
```<code>@Modifying(clearAutomatically=true)
</code>```

Its works for me.

Body:
let's assume we have a Spring Data repository interface with a custom method...

@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
void markAsSoftDeleted(long id);

This method simply sets the deletedAt field of the entity, ok. Is there any way to allow this method to return an updated version of the MyEntity?

Obviously...

@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
MyEntity markAsSoftDeleted(long id);

...does not work, since...

java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!

Does anyon know another way to easily allow that, except of course the obvious "add a service layer between repository and caller for such things"...

Body:
@Modifying(clearAutomatically=true)

Its works for me.


问:
regular expression - find a letter in by a specific template
I need to write a code about DNA.

I need to find between a str of multipal letters a seqence of 6 letters that need to be a match to the template.

For example: in index 0 it can be the letter A or T, that it, only those letters. What do I use to do this? Which type of function in regular expression ?

```<code>the_str = "AAATAAAATAAATAATAAAGAGCCAGAGGCCCTTGAAGAATGGATGGAAT\
TTGGACTTTAGCGGGGCTGGGGGACCCCGGAAATGGACGAGAAGCAGAAC\
CGAGGCCCTTTAGGGCTCAGCGGAGGCCTGCCTGTCTCTCTAAGGTCCCT\
CTTGGAGCAACTGAAGAAACTCCAGGCCATTGTGGTGCAGTCCACCAGCA\
AGTCAGCCCAGACAGGCACCTGTGTCGCAGTGAGTCCTGGTGCCCCCAGG\
CAAGCCGGGGACCTAGGCTTCTGTAGAGGGGCCCATAGGGAGGTGACAAT\
GAGTCCAAGCTCTCCTTGTGCCCCAGCTCAAGTATGATCCAGTCTGGTCT\
TTGGGGCCTCAGTTTCCCTGCCTGTGGGATGGAGATGCTTGCAGGGGAGG\
GGAGGGAGGGGGTGACTCTGCCGCTGTCTCCACCAGGTCCTGTTGCTGTC"
</code>```

答:
It sounds like maybe you need something like this?

(A|T)AGCGG

That would match either AAGCGG or TAGCGG.

If the fourth character could be any of C, A, G then it might look like this:

(A|T)AG(C|A|G)GG

Body:
I need to write a code about DNA.

I need to find between a str of multipal letters a seqence of 6 letters that need to be a match to the template.

For example: in index 0 it can be the letter A or T, that it, only those letters. What do I use to do this? Which type of function in regular expression ?

the_str = "AAATAAAATAAATAATAAAGAGCCAGAGGCCCTTGAAGAATGGATGGAAT\
TTGGACTTTAGCGGGGCTGGGGGACCCCGGAAATGGACGAGAAGCAGAAC\
CGAGGCCCTTTAGGGCTCAGCGGAGGCCTGCCTGTCTCTCTAAGGTCCCT\
CTTGGAGCAACTGAAGAAACTCCAGGCCATTGTGGTGCAGTCCACCAGCA\
AGTCAGCCCAGACAGGCACCTGTGTCGCAGTGAGTCCTGGTGCCCCCAGG\
CAAGCCGGGGACCTAGGCTTCTGTAGAGGGGCCCATAGGGAGGTGACAAT\
GAGTCCAAGCTCTCCTTGTGCCCCAGCTCAAGTATGATCCAGTCTGGTCT\
TTGGGGCCTCAGTTTCCCTGCCTGTGGGATGGAGATGCTTGCAGGGGAGG\
GGAGGGAGGGGGTGACTCTGCCGCTGTCTCCACCAGGTCCTGTTGCTGTC"


问:
How can I send command line arguments to a malloc array, and then send those arguments from a parent process to a child process
This is for a school assignment, and I know this is about a simple problem as there is, but for the life of me I can't figure out what I am doing wrong.

In the parent process, I need to convert cmdline arguments to integers, then store the arguments in a malloc array. I then need to send each integer to the child process one at a time. The child process will then sum all of the integers passed from the parent process. Once the summation is complete, it will return the sum to the parent process. The parent process then prints out the sum.

There are 3 things I do not understand about this code.

Taking command line arguments, converting them into integers, and storing them using a pointer to a malloc array. I do not understand why I can't just write this in my parent process:

```<code>  int* numArray = (int*) malloc (argc * sizeof(int));
  for(int i = 0; i < argc; ++i){
     numArray[i] = atoi(argv[i+1]);
  }
</code>```

How can I send individual values to child process for summation? I can read them one at a time, and then increment sum by the value in sumBuf. Then sumBuf gets overwritten with the next value, and increments sum by sumBuf again. How can I do this?

How can I access the child's return value in the parent process?

Storing the integers in the malloc array yields a segmentation fault, and I do not understand how to correct this. also, since fork returns the child's PID, if the child returns a sum, shouldn't the sum be the child's PID?

For the malloc array I have tried de-referencing numArray inside the for loop like:

```<code>   *numArray[i] = atoi(argv[i+1])
</code>```

I have tried writing individual values to the pipe within a for loop

I know that fork returns the child PID value, so if child returns sum, shouldn't sum = p, store sum into the parent's sum value?

```<code>int main(int argc, char **argv){
  int *numArray = (int*) malloc (argc * sizeof(int));
  pid_t p;
  int fd[2];
  pipe(fd);
  p = fork()
  //error checks

  if(p == 0){//child process
       int sum = 0;
       int sumBuf = 0;
       close(fd[1]);//close write end
       for(int i = 0; i < argc; ++i){
           read(fd[0], sumBuf, sizeof(int));
           sum += sumBuf;
       }
       close(fd[0]);//close read end
       return sum;//return sum from child process
   }
   else{//parent process
       int sum = 0;
       close(fd[0]);//close read end
       for(int i = 0; i < argc; ++i){
           numArray[i] = atoi(argv[i+1]);
           write(fd[1], numArray[i], sizeof(int));
       }
       close(fd[1]);//close write end of pipe
       sum = p;
       printf("Sum = %d", sum);
       return 0;
   }
   free(numArray);
   return 0;
}
</code>```

I get a segmentation fault message when I try to run this program. Please don't call me stupid, I understand the idea of what to do, but I don't understand how to implement it..

答:
I do not understand why I can't just write this in my parent process -- that is exactly what you have done and it should work. There is nothing wrong with it.

The read and the write functions take the address of the buffer as the second argument. You have tried to pass the value of the variables. Change the following lines as -

```<code>read(fd[0], sumBuf, sizeof(int));
</code>```

to

```<code>read(fd[0], &sumBuf, sizeof(int));
</code>```

and

```<code>write(fd[1], numArray[i], sizeof(int));
</code>```

to

```<code>write(fd[1], &(numArray[i]), sizeof(int));
</code>```

This should solve the problem for you. Also, your compiler must have warned you about these. Please treat all warnings as errors.

You can access the child's process id in the parent by looking at the return value of fork. In your case, the variable p.

You also seem to be having a confusion between PID and the value the process returns. PID is a process identifier. It is unique to a process. The return value is what the main function of that process returns. This can be integer (two processes can also return the same value). The parent can access the value it's child returns using the wait function.

Body:
This is for a school assignment, and I know this is about a simple problem as there is, but for the life of me I can't figure out what I am doing wrong.

In the parent process, I need to convert cmdline arguments to integers, then store the arguments in a malloc array. I then need to send each integer to the child process one at a time. The child process will then sum all of the integers passed from the parent process. Once the summation is complete, it will return the sum to the parent process. The parent process then prints out the sum.

There are 3 things I do not understand about this code.

Taking command line arguments, converting them into integers, and storing them using a pointer to a malloc array. I do not understand why I can't just write this in my parent process:

  int* numArray = (int*) malloc (argc * sizeof(int));
  for(int i = 0; i < argc; ++i){
     numArray[i] = atoi(argv[i+1]);
  }

How can I send individual values to child process for summation? I can read them one at a time, and then increment sum by the value in sumBuf. Then sumBuf gets overwritten with the next value, and increments sum by sumBuf again. How can I do this?

How can I access the child's return value in the parent process?

Storing the integers in the malloc array yields a segmentation fault, and I do not understand how to correct this. also, since fork returns the child's PID, if the child returns a sum, shouldn't the sum be the child's PID?

For the malloc array I have tried de-referencing numArray inside the for loop like:

   *numArray[i] = atoi(argv[i+1])

I have tried writing individual values to the pipe within a for loop

I know that fork returns the child PID value, so if child returns sum, shouldn't sum = p, store sum into the parent's sum value?

int main(int argc, char **argv){
  int *numArray = (int*) malloc (argc * sizeof(int));
  pid_t p;
  int fd[2];
  pipe(fd);
  p = fork()
  //error checks

  if(p == 0){//child process
       int sum = 0;
       int sumBuf = 0;
       close(fd[1]);//close write end
       for(int i = 0; i < argc; ++i){
           read(fd[0], sumBuf, sizeof(int));
           sum += sumBuf;
       }
       close(fd[0]);//close read end
       return sum;//return sum from child process
   }
   else{//parent process
       int sum = 0;
       close(fd[0]);//close read end
       for(int i = 0; i < argc; ++i){
           numArray[i] = atoi(argv[i+1]);
           write(fd[1], numArray[i], sizeof(int));
       }
       close(fd[1]);//close write end of pipe
       sum = p;
       printf("Sum = %d", sum);
       return 0;
   }
   free(numArray);
   return 0;
}

I get a segmentation fault message when I try to run this program. Please don't call me stupid, I understand the idea of what to do, but I don't understand how to implement it..

Body:
I do not understand why I can't just write this in my parent process -- that is exactly what you have done and it should work. There is nothing wrong with it.

The read and the write functions take the address of the buffer as the second argument. You have tried to pass the value of the variables. Change the following lines as -

read(fd[0], sumBuf, sizeof(int));

to

read(fd[0], &sumBuf, sizeof(int));

and

write(fd[1], numArray[i], sizeof(int));

to

write(fd[1], &(numArray[i]), sizeof(int));

This should solve the problem for you. Also, your compiler must have warned you about these. Please treat all warnings as errors.

You can access the child's process id in the parent by looking at the return value of fork. In your case, the variable p.

You also seem to be having a confusion between PID and the value the process returns. PID is a process identifier. It is unique to a process. The return value is what the main function of that process returns. This can be integer (two processes can also return the same value). The parent can access the value it's child returns using the wait function.


问:
ASP.Net and log4Net - Compatible Framework error on adding of Dll
I cannot add log4Net as a reference to my new .Net project.  I've researched this, and all the answers say to change the Target framework from ".Net Framework 4 (Client Profile)" to ".Net Framework 4" or some variation.

Well, my project is already ".Net Framework 4".  And I don't even have the Client Profile type in my target framework drop down.

To be clear, I DO have this option on other projects, but just not on the last one that I made.  I can't remember if I made this a new "Project" or "Website" -- I'm assuming I chose "Project" when I made it.

When I try to add log4net, I get this error:

```<code>"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" is incompatible with .NET Framework 4

In order to add it you should to change the project's target to a compatible framework first.
</code>```

Yes, even that incorrect grammar is from the message "you should to change"

I'm missing something fundamental, but for the life of me I can't tell between my projects what is different about this one.

答: I suggest that you install NuGet and let it add the reference for you.  NuGet is a much more standardized way to install components like log4net and keep them up to date.  It kind of unscrews this sort of thing for you.</p>

Body:
I cannot add log4Net as a reference to my new .Net project.  I've researched this, and all the answers say to change the Target framework from ".Net Framework 4 (Client Profile)" to ".Net Framework 4" or some variation.

Well, my project is already ".Net Framework 4".  And I don't even have the Client Profile type in my target framework drop down.

To be clear, I DO have this option on other projects, but just not on the last one that I made.  I can't remember if I made this a new "Project" or "Website" -- I'm assuming I chose "Project" when I made it.

When I try to add log4net, I get this error:

"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" is incompatible with .NET Framework 4

In order to add it you should to change the project's target to a compatible framework first.

Yes, even that incorrect grammar is from the message "you should to change"

I'm missing something fundamental, but for the life of me I can't tell between my projects what is different about this one.


问:
I am trying to auto focus to the next text input on submit
I am rendering text inputs for player names by mapping the components and passing down the player number. I want the user to hit enter and the screen to focus on the next input.

I've tried this

```<code><TextInput style={styles.nameBox} placeholder="Enter Name" onChangeText={(text) => this.setState({text})} ref={`input-${this.props.number}`}
  onSubmitEditing={value => {
   this.setState({ value })
   if (value) this.refs.input_2.focus();
}} />
</code>```

The problem is that I cant hardcode input_2 because it will then be that way for all of my inputs. I want it to focus on "input-this.props.number++", Basically the following input.

答:
You could develop a function to be triggered on return, and pass the id of the input type that you want to get focus as an argument.

The following sample code is written by Aung Myint Thein from medium.com:

```<code>//sample text fields

<TextField
  label={"Field 1"}
  blurOnSubmit={ false }
  returnKeyType={ 'next' }
  onSubmitEditing={() => { this.focusTheField('field2'); }}
/>
<TextField
  ref={input => { this.inputs['field2'] = input }}
  label={"Field 2"}
/>

//function

// variable to hold the references of the textfields
inputs = {};
 // function to focus the field
focusTheField = (id) => {
   this.inputs[id].focus();
}
</code>```

Hope this helps

Body:
I am rendering text inputs for player names by mapping the components and passing down the player number. I want the user to hit enter and the screen to focus on the next input.

I've tried this

<TextInput style={styles.nameBox} placeholder="Enter Name" onChangeText={(text) => this.setState({text})} ref={`input-${this.props.number}`}
  onSubmitEditing={value => {
   this.setState({ value })
   if (value) this.refs.input_2.focus();
}} />

The problem is that I cant hardcode input_2 because it will then be that way for all of my inputs. I want it to focus on "input-this.props.number++", Basically the following input.

Body:
You could develop a function to be triggered on return, and pass the id of the input type that you want to get focus as an argument.

The following sample code is written by Aung Myint Thein from medium.com:

//sample text fields

<TextField
  label={"Field 1"}
  blurOnSubmit={ false }
  returnKeyType={ 'next' }
  onSubmitEditing={() => { this.focusTheField('field2'); }}
/>
<TextField
  ref={input => { this.inputs['field2'] = input }}
  label={"Field 2"}
/>

//function

// variable to hold the references of the textfields
inputs = {};
 // function to focus the field
focusTheField = (id) => {
   this.inputs[id].focus();
}

Hope this helps


问:
Deserialize JSON into struct with duplicate JSON mapping
I am trying to deserialize JSON which looks like this:

```<code>{
  "pattern": {"@odata.type": "microsoft.graph.recurrencePattern"},
  "range": {"@odata.type": "microsoft.graph.recurrenceRange"}
}
</code>```

For this I created several structs where the first one looks like this:

```<code>type MSPatternedRecurrence struct {
    Pattern MSRecurrencePattern `json:"@odata.type"`
    Range   MSRecurrenceRange   `json:"@odata.type"`
}
</code>```

However go vet throws an error like this:

```<code>struct field Range repeats json tag "@odata.type"
</code>```

What is the right way to create a struct in this situation?

type MSPatternedRecurrence struct {
    Pattern MSRecurrencePattern json:"@odata.type"
    Range   MSRecurrenceRange   json:"@odata.type"
}

```<code>type MSRecurrencePattern struct {
    DayOfMonth     int      `json:"dayOfMonth"`
    DayOfWeek      []string `json:"daysOfWeek"`
    FirstDayOfWeek string   `json:"firstDayOfWeek"`
    Index          string   `json:"index"`
    Interval       int      `json:"interval"`
    Month          int      `json:"month"`
    Type           string   `json:"type"`
}

type MSRecurrenceRange struct {
    EndDate             string `json:"endDate"`
    NumberOfOccurrences int    `json:"numberOfOccurrences"`
    RecurrenceTimeZone  string `json:"recurrenceTimeZone"`
    StartDate           string `json:"startDate"`
    Type                string `json:"type"`
}
</code>```

答:
No; the error clearly states you're trying to map two struct fields to the same JSON field name, which you cannot do; also, the definitions for the types used for those fields aren't given, but it seems unlikely they're correct given that the JSON has them both as simple strings.

You have two fields, pattern and range. Each's value is an object. Those objects each have a field named @odata.type. I.e.:

```<code>type Odata struct {
    Type string `json:"@odata.type"`
}

type MSPatternedRecurrence struct {
    Pattern Odata
    Range   Odata
}
</code>```

You might find the JSON-to-Go tool useful. For this JSON, it outputs:

```<code>type AutoGenerated struct {
    Pattern struct {
        OdataType string `json:"@odata.type"`
    } `json:"pattern"`
    Range struct {
        OdataType string `json:"@odata.type"`
    } `json:"range"`
}
</code>```

Body:
I am trying to deserialize JSON which looks like this:

{
  "pattern": {"@odata.type": "microsoft.graph.recurrencePattern"},
  "range": {"@odata.type": "microsoft.graph.recurrenceRange"}
}

For this I created several structs where the first one looks like this:

type MSPatternedRecurrence struct {
    Pattern MSRecurrencePattern `json:"@odata.type"`
    Range   MSRecurrenceRange   `json:"@odata.type"`
}

However go vet throws an error like this:

struct field Range repeats json tag "@odata.type"

What is the right way to create a struct in this situation?

type MSPatternedRecurrence struct {
    Pattern MSRecurrencePattern json:"@odata.type"
    Range   MSRecurrenceRange   json:"@odata.type"
}

type MSRecurrencePattern struct {
    DayOfMonth     int      `json:"dayOfMonth"`
    DayOfWeek      []string `json:"daysOfWeek"`
    FirstDayOfWeek string   `json:"firstDayOfWeek"`
    Index          string   `json:"index"`
    Interval       int      `json:"interval"`
    Month          int      `json:"month"`
    Type           string   `json:"type"`
}

type MSRecurrenceRange struct {
    EndDate             string `json:"endDate"`
    NumberOfOccurrences int    `json:"numberOfOccurrences"`
    RecurrenceTimeZone  string `json:"recurrenceTimeZone"`
    StartDate           string `json:"startDate"`
    Type                string `json:"type"`
}

Body:
No; the error clearly states you're trying to map two struct fields to the same JSON field name, which you cannot do; also, the definitions for the types used for those fields aren't given, but it seems unlikely they're correct given that the JSON has them both as simple strings.

You have two fields, pattern and range. Each's value is an object. Those objects each have a field named @odata.type. I.e.:

type Odata struct {
    Type string `json:"@odata.type"`
}

type MSPatternedRecurrence struct {
    Pattern Odata
    Range   Odata
}

You might find the JSON-to-Go tool useful. For this JSON, it outputs:

type AutoGenerated struct {
    Pattern struct {
        OdataType string `json:"@odata.type"`
    } `json:"pattern"`
    Range struct {
        OdataType string `json:"@odata.type"`
    } `json:"range"`
}


问:
Where is the variable "code" in SKError defined?
I am seeing examples of code using SKError "code" property or variable.
I cannot seem to define any definition for this property.
How is xcode / Swift able to access this property?
I am using SwiftyStoreKit with this issue.
Thanks

Tried looking in the documentation for SKError, nothing there.
Tried debugging in xcode, live, cannot understand from xcode where is this thing coming from.

```<code>    SwiftyStoreKit.purchaseProduct("X", quantity: 1, atomically: true) { result in
        switch result {
        case .success(let purchase):
            print("Purchase Success: \(purchase.productId)")
            let defaults = UserDefaults.standard
            defaults.set(true, forKey: "Y")
        case .error(let error):
            switch error.code {
            case .unknown: self.Alert("Z")
</code>```

Just want to know how xcode can access this property.

答:
See SKError.Code documentation, found in the SKError documentation. In Xcode you can also press shift+command+o (the letter “oh”) and type SKError and jump right to the definition.

These are the values at this point:

case unknown

  Error code indicating that an unknown or unexpected error occurred.

case clientInvalid

  Error code indicating that the client is not allowed to perform the attempted action.

case paymentCancelled

  Error code indicating that the user canceled a payment request.

case paymentInvalid

  Error code indicating that one of the payment parameters was not recognized by the App Store.

case paymentNotAllowed

  Error code indicating that the user is not allowed to authorize payments.

case storeProductNotAvailable

  Error code indicating that the requested product is not available in the store.

case cloudServicePermissionDenied

  Error code indicating that the user has not allowed access to Cloud service information.

case cloudServiceNetworkConnectionFailed

  Error code indicating that the device could not connect to the network.

case cloudServiceRevoked

  Error code indicating that the user has revoked permission to use this cloud service.

case privacyAcknowledgementRequired

  Error code indicating that the user has not yet acknowledged Apple’s privacy policy for Apple Music.

case unauthorizedRequestData

  Error code indicating that the app is attempting to use a property for which it does not have the required entitlement.

case invalidOfferIdentifier

  Error code indicating that the offer identifier is invalid.

case invalidOfferPrice

  Error code indicating that the price you specified in App Store Connect is no longer valid.

case invalidSignature

  Error code indicating that the signature in a payment discount is not valid.

case missingOfferParams

  Error code indicating that parameters are missing in a payment discount.

Body:
I am seeing examples of code using SKError "code" property or variable.
I cannot seem to define any definition for this property.
How is xcode / Swift able to access this property?
I am using SwiftyStoreKit with this issue.
Thanks

Tried looking in the documentation for SKError, nothing there.
Tried debugging in xcode, live, cannot understand from xcode where is this thing coming from.

    SwiftyStoreKit.purchaseProduct("X", quantity: 1, atomically: true) { result in
        switch result {
        case .success(let purchase):
            print("Purchase Success: \(purchase.productId)")
            let defaults = UserDefaults.standard
            defaults.set(true, forKey: "Y")
        case .error(let error):
            switch error.code {
            case .unknown: self.Alert("Z")

Just want to know how xcode can access this property.


问:
How to retain millisecond information while using mktime in awk?
I have a date string of the format 2012-12-20T01:16:02.05 and i want to convert to the format  2011-12-20-01.16.02.050000

Currently i am doing it as follows

```<code>format = "%F-%H.%M.%S.%N"
split(stringinput,input,"T");
split(input[1],date,"-")
split(input[2],time,":")

 return strftime(format,mktime(date[1] " " date[2] " " date[3] " " time[1] " " time[2] " " time[3] " " time[4]));
</code>```

But i am losing the microsecond information or the millisecond information. How can i get that. It is returning 2011-12-20-01.16.02.%N

Also any suggestions to make the string parsing more generic. Currently it support only one format.

Thanks.

答:
Because I wanted my GNU date precision to match with awk, I had to do it in the following:

```<code>x='2019-05-30 14:09:20.074'
echo $x | awk '{split($1,a,"-");;split($2,b,".");split(b[1],c,":");s=a[1]" "a[2]" "a[3]" "c[1]" "c[2]" "c[3];tt=mktime(s);print tt b[2] "000000"}'
1559196560074000000

date --date=$x +'%s%N'
1559196560074000000
</code>```

Now, that I am able to bring these two into agreement, I am now able to do comparison logic inside awk.

Body:
I have a date string of the format 2012-12-20T01:16:02.05 and i want to convert to the format  2011-12-20-01.16.02.050000

Currently i am doing it as follows

format = "%F-%H.%M.%S.%N"
split(stringinput,input,"T");
split(input[1],date,"-")
split(input[2],time,":")

 return strftime(format,mktime(date[1] " " date[2] " " date[3] " " time[1] " " time[2] " " time[3] " " time[4]));

But i am losing the microsecond information or the millisecond information. How can i get that. It is returning 2011-12-20-01.16.02.%N

Also any suggestions to make the string parsing more generic. Currently it support only one format.

Thanks.

Body:
Because I wanted my GNU date precision to match with awk, I had to do it in the following:

x='2019-05-30 14:09:20.074'
echo $x | awk '{split($1,a,"-");;split($2,b,".");split(b[1],c,":");s=a[1]" "a[2]" "a[3]" "c[1]" "c[2]" "c[3];tt=mktime(s);print tt b[2] "000000"}'
1559196560074000000

date --date=$x +'%s%N'
1559196560074000000

Now, that I am able to bring these two into agreement, I am now able to do comparison logic inside awk.


问:
MutationObserver on iFrame javascript
I have an iframe containing a source www.abc/main.html

```<code><iframe id="my-iframe" src="http://www.abc/main.html"></iframe>
</code>```

abc/main.html imports and executes some js files.
I want to use a MutationObserver to get the name of the js files it is importing.

```<code>var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                [].filter.call(mutation.addedNodes, function (node) {
                    return node.nodeName == 'IFRAME';
                }).forEach(function (node) {
                    node.addEventListener('load', function (e) {
                        console.log('loaded', node.src);
                    });
                });
            });
        });
observer.observe(document.body, { childList: true, subtree: true });
</code>```

This is what I am using. Referring: SO answer

But I am unable to get the name of the js file. Does it have to do with the CSP set on the source of the iframe?

Note: The iframe content is not of the same origin as the parent document.

答:
MutationObserver only observes your own document.

Without explicit CORS support from the remote site, it is completely impossible to observe or interact with a frame from a different origin.

Title: MutationObserver on iFrame javascript

Body:
I have an iframe containing a source www.abc/main.html

abc/main.html imports and executes some js files.
I want to use a MutationObserver to get the name of the js files it is importing.

var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                [].filter.call(mutation.addedNodes, function (node) {
                    return node.nodeName == 'IFRAME';
                }).forEach(function (node) {
                    node.addEventListener('load', function (e) {
                        console.log('loaded', node.src);
                    });
                });
            });
        });
observer.observe(document.body, { childList: true, subtree: true });

This is what I am using. Referring: SO answer

But I am unable to get the name of the js file. Does it have to do with the CSP set on the source of the iframe?

Note: The iframe content is not of the same origin as the parent document.


问:
Why is the rails_12factor gem necessary on Heroku?
I noticed that the new version of Michael Hartl's  Ruby on Rails Tutorial says to include the following to serving static assets on Heroku

gem 'rails_12factor', group: :production

The previous version of his book did not have that. Can someone explain the details of what happened with Heroku that requires this gem?

答: As of Rails 5, you no longer need to include this gem in your Gemfile. They've removed it from their documentation also: https://github.com/railsbridge/docs/issues/569


问:
TypeScript: Declaring a callable type as a class method type
I have a callable type alias or interface such as

```<code>type MyCallable = (n: number) => string

</code>```

Then I have a class and one of its methods is of that callable type:

```<code>class MyClass {
  myMethod(n: number): string {
    return ''
  }
}
</code>```

I want instead to declare its typing using that MyCallable type:

```<code>class MyClass {
  myMethod(n): MyCallable {
    return ''
  }
}
</code>```

Obviously this approach doesn't work because myMethod doesn't return a MyCallable, but is itself a MyCallable.

Is this even possible in TS?

答:
A slightly wordy way is to declare and implement an interface:</p>

```<code>type MyCallable = (n: number) => string

type WithCallable = {
    myMethod: MyCallable
}
class MyClass implements WithCallable {
  myMethod(n) {
    return ''
  }
}
</code>```

Body:
I have a callable type alias or interface such as

type MyCallable = (n: number) => string

Then I have a class and one of its methods is of that callable type:

class MyClass {
  myMethod(n: number): string {
    return ''
  }
}

I want instead to declare its typing using that MyCallable type:

class MyClass {
  myMethod(n): MyCallable {
    return ''
  }
}

Obviously this approach doesn't work because myMethod doesn't return a MyCallable, but is itself a MyCallable.

Is this even possible in TS?

Body:
A slightly wordy way is to declare and implement an interface:

type MyCallable = (n: number) => string

type WithCallable = {
    myMethod: MyCallable
}
class MyClass implements WithCallable {
  myMethod(n) {
    return ''
  }
}


问:
TestNG - How to run setup once before all tests in a class for each parallel run
I am trying to see if it is possible to have a setup run once for each parallel class instantiated.

If I have the following test class, because of the DataFactory (CSV has 2 rows of data, one for each test), two tests are started in parallel

Is it possible to get testSetup() to run once for each instance of the TestFu class.  BeforeClass seems to run it once before both parallel test instances.

TestXML

```<code><suite name="SomeTest" parallel="none" thread-count="20" verbose="2">
    <test name="Graph+APITests" parallel="instances" thread-count="5">
        <classes>
            <class name="TestFu" />
        </classes>
    </test>
</suite>
</code>```

Test Class

```<code>public class TestFu {

    String var1;

    @Factory(dataProvider = "testStuff")
    public TestFu(String var1, String var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    @DataProvider(name = "testStuff")
    public static Object[][] stuff() {

        return methodThatLoadsVarsFromCSV;
    }

    @BeforeClass
    public void testSetup() {
        System.out.println("Doing setup");
    }

    @Test
    public void testOne() {
        System.out.println("Test 1 " + this.var1);
    }

    @Test
    public void testTwo() {
        System.out.println("Test 2 " + this.var2);
    }
}
</code>```

答:
Use static flag like this:

```<code>    static boolean initialized = false;

    @BeforeClass
    public void testSetup() {
        if (!initialized) {
            initialized = true;
            System.out.println("Doing setup");
        }
    }
</code>```

Body:
I am trying to see if it is possible to have a setup run once for each parallel class instantiated.

If I have the following test class, because of the DataFactory (CSV has 2 rows of data, one for each test), two tests are started in parallel

Is it possible to get testSetup() to run once for each instance of the TestFu class.  BeforeClass seems to run it once before both parallel test instances.

TestXML

<suite name="SomeTest" parallel="none" thread-count="20" verbose="2">
    <test name="Graph+APITests" parallel="instances" thread-count="5">
        <classes>
            <class name="TestFu" />
        </classes>
    </test>
</suite>

Test Class

public class TestFu {

    String var1;

    @Factory(dataProvider = "testStuff")
    public TestFu(String var1, String var2) {
        this.var1 = var1;
        this.var2 = var2;
    }

    @DataProvider(name = "testStuff")
    public static Object[][] stuff() {

        return methodThatLoadsVarsFromCSV;
    }

    @BeforeClass
    public void testSetup() {
        System.out.println("Doing setup");
    }

    @Test
    public void testOne() {
        System.out.println("Test 1 " + this.var1);
    }

    @Test
    public void testTwo() {
        System.out.println("Test 2 " + this.var2);
    }
}

Body:
Use static flag like this:

    static boolean initialized = false;

    @BeforeClass
    public void testSetup() {
        if (!initialized) {
            initialized = true;
            System.out.println("Doing setup");
        }
    }


问:
How can I elegantly implement multiple string replacements in the same file?
Currently I have some code to replace strings in a file that looks like this:

```<code>File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));
</code>```

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

答:
```<code>string contents = File.ReadAllText(filePath);
contents = Regex.Replace(contents,
    "( " + column.Key + " )",
    " " + column.Value + " ");
contents = Regex.Replace(contents,
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]");
File.WriteAllText(filePath, contents);
</code>```

Body:
Currently I have some code to replace strings in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.


问:
How to fail the build pipeline if "Tests Failed" in azure pipelines?
I want to fail the build pipeline if a single test failed with azure pipelines.

Azure can successfully detect that my tests entered a failed state however it gives a success state to the entire build pipeline:

The question is how to make azure give a failed build state if the tests stage failed?

Here's my azure-pipelines.yml :

```<code># Build ASP.NET Core project using Azure Pipelines
# https://learn.microsoft.com/azure/devops/pipelines/languages/dotnet-core?view=vsts

pool:
  vmImage: 'Ubuntu 16.04'

variables:
  buildConfiguration: 'Release'

steps:
- script: |
    dotnet build --configuration $(buildConfiguration)
    dotnet test dotnetcore-tests --configuration $(buildConfiguration) --logger trx
    dotnet publish --configuration $(buildConfiguration) --output $BUILD_ARTIFACTSTAGINGDIRECTORY

- task: PublishTestResults@2
  inputs:
    testRunner: VSTest
    testResultsFiles: '**/*.trx'

- task: PublishBuildArtifacts@1
</code>```

答:
The original answer didn't work for me, but it looks like there was a lot of discussion on this, and there's now a failTaskOnFailedTests param for the task. That seems to work.

```<code>
- task: PublishTestResults@2
  inputs:
    testRunner: VSTest
    testResultsFiles: '**/*.trx'
    failTaskOnFailedTests: true
</code>```

I'm still surprised this wasn't default behavior.

Body:
I want to fail the build pipeline if a single test failed with azure pipelines.

Azure can successfully detect that my tests entered a failed state however it gives a success state to the entire build pipeline:

The question is how to make azure give a failed build state if the tests stage failed?

Here's my azure-pipelines.yml :

# Build ASP.NET Core project using Azure Pipelines
# https://learn.microsoft.com/azure/devops/pipelines/languages/dotnet-core?view=vsts

pool:
  vmImage: 'Ubuntu 16.04'

variables:
  buildConfiguration: 'Release'

steps:
- script: |
    dotnet build --configuration $(buildConfiguration)
    dotnet test dotnetcore-tests --configuration $(buildConfiguration) --logger trx
    dotnet publish --configuration $(buildConfiguration) --output $BUILD_ARTIFACTSTAGINGDIRECTORY

- task: PublishTestResults@2
  inputs:
    testRunner: VSTest
    testResultsFiles: '**/*.trx'

- task: PublishBuildArtifacts@1

Body:
The original answer didn't work for me, but it looks like there was a lot of discussion on this, and there's now a failTaskOnFailedTests param for the task. That seems to work.

- task: PublishTestResults@2
  inputs:
    testRunner: VSTest
    testResultsFiles: '**/*.trx'
    failTaskOnFailedTests: true

I'm still surprised this wasn't default behavior.


问:
How do you set the document title in React?
I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.

答:
For React 16.8, you can do this with a functional component using useEffect.

For Example:

```<code>useEffect(() => {
   document.title = "new title"
}, []);
</code>```

Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.

Body:
For React 16.8, you can do this with a functional component using useEffect.

For Example:

useEffect(() => {
   document.title = "new title"
}, []);

Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.


问:
Vuetify - How to set background color
I am using Vuetify with the Light theme. By default this sets the background of the main content to a light grey. I need it to be white.

I'd like to override this by modifying the stylus variables, but I can't seem to figure out which variable sets the background color.

I followed all the steps in the docs, and I can change the font throughout the app by setting $body-font-family = 'Open Sans' in my main.styl file (so I know I have the webpack build set up correctly)

I have tried $body-bg-light = '#fff' in my main.styl, but that doesn't seem to change anything at all. If I set $material-light.background = '#fff' I get an error.

答:
To change the background colour simply...

```<code><v-app class="white">
</code>```

for text color

```<code><v-app class="grey--text text--darken-2">
</code>```

Title: Vuetify - How to set background color

Body:
To change the background colour simply...

<v-app class="white">

for text color

<v-app class="grey--text text--darken-2">


答:
```<code>var fileContents = File.ReadAllText(filePath);
fileContents = Regex.Replace(fileContents,
    "( " + column.Key + " )",
    " " + column.Value + " "
);
fileContents = Regex.Replace(fileContents ,
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
);
File.WriteAllText(filePath, fileContents);
</code>```


问:
How to turn off default domain in firebase hosting
I am hosting a site on Firebase hosting. It has a default URL of myapp.firebaseapp.com. I have configured a custom URL for my app and it is sub.domain.com. The issue i am having is that both are still accessible. Users can access the app from myapp.firebaseapp.com and sub.domain.com. I need users to only be able to access sub.domain.com.

Is there a way to turn off the default domain within the Firebase console or do i need to accomplish this with a rewrite or a redirect?

Any help would be greatly appreciated. I searched around and was not able to find any information regarding this issue. Below is a screenshot showing that both domains are configured correctly.

答: I think your only option (at least for now) is to use to redirect the users. You could redirect your users from default to the custom url using simple Javascript. That could be done by getting the host (window.host), checking if it is the default or the custom url and redirecting if necessary.</p>


问:
How do I fix this script that I've written?
I'm getting error codes every time I change just a piece of my code. I'm trying to run a statement that will count the number of CADS.
Error message ~ "Incorrect syntax near the keyword 'from'"
Also, trying to add a Group by dbo.uneTablePTX.PropertyName
When I remove the count function my query will run flawlessly

```<code>select dbo.ptx_CADS.cad_name, dbo.uneTablePTX.PropertyName, (SELECT count(*)
from dbo.ptx_CADS.cad_id  AS "TotalAccounts"
from dbo.ptx_CADS
Inner Join dbo.uneTablePTX on dbo.ptx_CADS.cad_id=dbo.uneTablePTX.cad_id
Group bydbo.uneTablePTX.PropertyName
</code>```

I expect the columns name to change and for it to add them up. I don't understand the error message.

答:
I think you just want a basic aggregation query:</p>

```<code>select c.cad_name, p.PropertyName, count(*) as TotalAccounts
from dbo.ptx_CADS c Inner Join
     dbo.uneTablePTX p
     on c.cad_id = p.cad_id
group by c.cad_name, p.PropertyName;
</code>```

Body:
I'm getting error codes every time I change just a piece of my code. I'm trying to run a statement that will count the number of CADS.
Error message ~ "Incorrect syntax near the keyword 'from'"
Also, trying to add a Group by dbo.uneTablePTX.PropertyName
When I remove the count function my query will run flawlessly

select dbo.ptx_CADS.cad_name, dbo.uneTablePTX.PropertyName, (SELECT count(*)
from dbo.ptx_CADS.cad_id  AS "TotalAccounts"
from dbo.ptx_CADS
Inner Join dbo.uneTablePTX on dbo.ptx_CADS.cad_id=dbo.uneTablePTX.cad_id
Group bydbo.uneTablePTX.PropertyName

I expect the columns name to change and for it to add them up. I don't understand the error message.

Body:
I think you just want a basic aggregation query:

select c.cad_name, p.PropertyName, count(*) as TotalAccounts
from dbo.ptx_CADS c Inner Join
     dbo.uneTablePTX p
     on c.cad_id = p.cad_id
group by c.cad_name, p.PropertyName;


问:
clearing rails app database on heroku production site
So I'm new to ROR and Heroku and need a little help. I've created an app and have deployed it; however, I'd like to clear out the database associated with it. Meaning I'd like to clear any users (and their attached data) that have been created thus far.

I've basically created several phony accounts to test out whether the database on the production site works, but now i'd like to clear this out, and start with a fresh database.

Is this possible without deleting the database entirely?

Any help would be sincerely appreciated. Thank you very much for your time!

答:
Databases can be reset from the web dashboard as well:

Find your database and click on the link:

On the database page click on "Settings"

Then click on, "Reset Database" and follow the instructions to confirm.

You'll of course need to use rake to migrate to get your tables back.


问:
Count occurrences of factor in R, with zero counts reported
I want to count the number of occurrences of a factor in a data frame. For example, to count the number of events of a given type in the code below:

```<code>library(plyr)
events <- data.frame(type = c('A', 'A', 'B'),
                       quantity = c(1, 2, 1))
ddply(events, .(type), summarise, quantity = sum(quantity))
</code>```

The output is the following:

```<code>     type quantity
1    A        3
2    B        1
</code>```

However, what if I know that there are three types of events A, B and C, and I also want to see the count for C which is 0? In other words, I want the output to be:

```<code>     type quantity
1    A        3
2    B        1
3    C        0
</code>```

How do I do this? It feels like there should be a function defined to do this somewhere.

The following are my two not-so-good ideas about how to go about this.

Idea #1: I know I could do this by using a for loop, but I know that it is widely said that if you are using a for loop in R, then you are doing something wrong, there must be a better way to do it.

Idea #2: Add dummy entries to the original data frame. This solution works but it feels like there should be a more elegant solution.

```<code>events <- data.frame(type = c('A', 'A', 'B'),
                       quantity = c(1, 2, 1))
events <- rbind(events, data.frame(type = 'C', quantity = 0))
ddply(events, .(type), summarise, quantity = sum(quantity))
</code>```

答:
In data you put your dataframe and into levels your categories.</p>

```<code>table(factor(data, levels = 1:5))
</code>```

Body:
I want to count the number of occurrences of a factor in a data frame. For example, to count the number of events of a given type in the code below:

library(plyr)
events <- data.frame(type = c('A', 'A', 'B'),
                       quantity = c(1, 2, 1))
ddply(events, .(type), summarise, quantity = sum(quantity))

The output is the following:

     type quantity
1    A        3
2    B        1

However, what if I know that there are three types of events A, B and C, and I also want to see the count for C which is 0? In other words, I want the output to be:

     type quantity
1    A        3
2    B        1
3    C        0

How do I do this? It feels like there should be a function defined to do this somewhere.

The following are my two not-so-good ideas about how to go about this.

Idea #1: I know I could do this by using a for loop, but I know that it is widely said that if you are using a for loop in R, then you are doing something wrong, there must be a better way to do it.

Idea #2: Add dummy entries to the original data frame. This solution works but it feels like there should be a more elegant solution.

events <- data.frame(type = c('A', 'A', 'B'),
                       quantity = c(1, 2, 1))
events <- rbind(events, data.frame(type = 'C', quantity = 0))
ddply(events, .(type), summarise, quantity = sum(quantity))

Body:
In data you put your dataframe and into levels your categories.

table(factor(data, levels = 1:5))


问:
SMTP server correct email routing
I'm trying to implement a SMTP server at the moment and I've question regarding the routing...
Imagine, a client (foo@bar.com) sends a mail to foo1@bar1.com, foo2@bar2.com and foo3@bar3.com.
What happens when the SMTP server sees the message? Now, I'm not sure if the following sequence is correct:

The SMTP server will put the mail into the outbox of foo@bar.com

For each recipient (except foo@bar.com) in the envelope, the SMTP server will do:

Retrieve the MX record

Connect to the SMTP server determined by the MX record

Send HELO/EHLO command

Send MAIL FROM command (foo@bar.com)

Send RCPT TO command (e.g. foo1@bar1.com)

Send DATA command

Send QUIT command

Are these steps correct? For me it makes sense that the SMTP of the sender processes all the communication, but I've found some pages (e.g. https://www.msxfaq.de/internet/envelope.htm) where a mail server only forwards the message to the next SMTP server and each SMTP server removes one recipient from envelop's rcpt-to list, e.g.

So, what's correct...?

Sender's SMTP handles all the routing

Sender's SMTP removes one recipient (in this case foo@bar.com) and then forwards the message to the next SMTP server

答:
The steps you listed are basically correct.

The complexity arises when you compose an email and try to send it to a lot of different domains, e.g. steve@apple.com, woz@apple.com, and bill@microsoft.com.

In this case, the server must do MX lookups on each one of these domains and split the email.  Steve and Woz are both at the same domain, so the server can send an email with those two recipients to the MX record for apple.com.  The server must open a separate connection to the MX record for microsoft.com and attempt to send the email to Bill over that connection.

Title: SMTP server correct email routing


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
What is inside of that loops? Similar problems can appear if you will check some field in a loop to synchronize multiple threads:

```<code>while (_field); // waiting for _field change in another thread
</code>```

This solution will work very slow and calls to Thread.Sleep(0) is not a solution, but can be a hack in some cases. This can be fixed properly if you change that synchronization loop by call to WaitHandle.WaitOne() method of some synchronization object (ManualResetEvent for example) and place a signal to this handle in another thread. Maybe your problem is something like that? Please provide some part of your code.

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

Body:
What is inside of that loops? Similar problems can appear if you will check some field in a loop to synchronize multiple threads:

while (_field); // waiting for _field change in another thread

This solution will work very slow and calls to Thread.Sleep(0) is not a solution, but can be a hack in some cases. This can be fixed properly if you change that synchronization loop by call to WaitHandle.WaitOne() method of some synchronization object (ManualResetEvent for example) and place a signal to this handle in another thread. Maybe your problem is something like that? Please provide some part of your code.

OwnerDisplayName: Dmitriy Matveev