问:
configure: error: CGAL library not found
My ultimate goal is to get python package graph_tool working on my system and also on ipynb if possible. I have already brew install graph-tool, as indicated here, but that's still insufficient.

So I follow Anaconda instructions here, and I make decent progress, until the CGAL Library could not be found.

Note: to comply with the Anaconda instructions, I installed anaconda3 and created a new conda environment (named py36env) to conda install all the required packages (packages that must also match with python 3.6)

The entire ./configure output. Below is a snippet:

```<code>(py36env) $ ./configure --prefix=/Users/tamtran/anaconda3/envs/py36env/ --with-python-module-path=/Users/tamtran/anaconda3/envs/py36env/lib/python3.6/site-packages --with-cgal=/Users/tamtran/anaconda3/envs/py36env/
.
.
checking whether CGAL is available in /Users/tamtran/anaconda3/envs/py36env/... no
configure: error: CGAL library not found.
</code>```

The entire config.log. Below is a snippet:

```<code>configure:21200: checking whether CGAL is available in /Users/tamtran/anaconda3/envs/py36env/
configure:21236: g++ -std=gnu++14 -o conftest -fopenmp -O3 -fvisibility=default -fvisibility-inlines-hidden -Wno-deprecated -Wall -Wextra -ftemplate-backtrace-limit=0  -DNDEBUG  -I/Users/tamtran/anaconda3/envs/py36env//include -pthread -I/usr/local/include  -L/Users/tamtran/anaconda3/envs/py36env//lib -lCGAL -lCGAL_Core -lgmp -lboost_thread-mt -lpthread conftest.cpp -lgmp -lgmp  >&5
|       #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
|       #include <CGAL/convex_hull_2.h>
|       typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
|       CGAL::convex_hull_2(points.begin(),points.end(),std::back_inserter(result));
configure:21278: error: CGAL library not found.
CGAL_CPPFLAGS='-I/Users/tamtran/anaconda3/envs/py36env//include'
CGAL_FLAGS=''
CGAL_LDFLAGS='-L/Users/tamtran/anaconda3/envs/py36env//lib -lCGAL -lCGAL_Core -lgmp -lboost_thread-mt -lpthread'
</code>```

Note: Even without the --with-cgal tag, the same issue occurs. It's also important (I think) that the CGAL search directory is within py36env because CGAL matching with python3.6 is in there, whereas CGAL-python3.5 is in conda root environment. The only differences of ./configure output without the CGAL directory are:

```<code>checking whether CGAL is available in /usr... no
checking whether CGAL is available in /usr/local... no
checking whether CGAL is available in /opt... no
checking whether CGAL is available in /opt/local... no
</code>```

答:
on mac os x You must use -lcgal (is using brew)

for example on fedora linux -lCGAL

Body:
My ultimate goal is to get python package graph_tool working on my system and also on ipynb if possible. I have already brew install graph-tool, as indicated here, but that's still insufficient.

So I follow Anaconda instructions here, and I make decent progress, until the CGAL Library could not be found.

Note: to comply with the Anaconda instructions, I installed anaconda3 and created a new conda environment (named py36env) to conda install all the required packages (packages that must also match with python 3.6)

The entire ./configure output. Below is a snippet:

(py36env) $ ./configure --prefix=/Users/tamtran/anaconda3/envs/py36env/ --with-python-module-path=/Users/tamtran/anaconda3/envs/py36env/lib/python3.6/site-packages --with-cgal=/Users/tamtran/anaconda3/envs/py36env/
.
.
checking whether CGAL is available in /Users/tamtran/anaconda3/envs/py36env/... no
configure: error: CGAL library not found.

The entire config.log. Below is a snippet:

configure:21200: checking whether CGAL is available in /Users/tamtran/anaconda3/envs/py36env/
configure:21236: g++ -std=gnu++14 -o conftest -fopenmp -O3 -fvisibility=default -fvisibility-inlines-hidden -Wno-deprecated -Wall -Wextra -ftemplate-backtrace-limit=0  -DNDEBUG  -I/Users/tamtran/anaconda3/envs/py36env//include -pthread -I/usr/local/include  -L/Users/tamtran/anaconda3/envs/py36env//lib -lCGAL -lCGAL_Core -lgmp -lboost_thread-mt -lpthread conftest.cpp -lgmp -lgmp  >&5
|       #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
|       #include <CGAL/convex_hull_2.h>
|       typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
|       CGAL::convex_hull_2(points.begin(),points.end(),std::back_inserter(result));
configure:21278: error: CGAL library not found.
CGAL_CPPFLAGS='-I/Users/tamtran/anaconda3/envs/py36env//include'
CGAL_FLAGS=''
CGAL_LDFLAGS='-L/Users/tamtran/anaconda3/envs/py36env//lib -lCGAL -lCGAL_Core -lgmp -lboost_thread-mt -lpthread'

Note: Even without the --with-cgal tag, the same issue occurs. It's also important (I think) that the CGAL search directory is within py36env because CGAL matching with python3.6 is in there, whereas CGAL-python3.5 is in conda root environment. The only differences of ./configure output without the CGAL directory are:

checking whether CGAL is available in /usr... no
checking whether CGAL is available in /usr/local... no
checking whether CGAL is available in /opt... no
checking whether CGAL is available in /opt/local... no


来源: stackexchange

问:
Change DB design to improve Spring Data JPA soft delete and authentication on queries
I hope this question is not opinion based, but here we go.
I am developing a small API with spring boot, spring data jpa, and JWT Token as the authentication system. The API is pretty straightforward, is an exam generator, where you can register professor, course, question, choice etc.

For example:
[13/11/2017 - edited to include AbstractEntity]

```<code>@MappedSuperclass
public class AbstractEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;
    protected boolean enabled = true;
    //equals, hashcode...
}

public class Professor extends AbstractEntity{
    private String email;
}

public class Course extends AbstractEntity {
    @ManyToOne(optional = false)
    private Professor professor;
}

public class Question extends AbstractEntity {
    @ManyToOne(optional = false)
    private Course course;
}
</code>```

Because the authentication system is JWT token for all queries I have to include the professor's information.

For example

```<code>public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {
    @Query("select c from Course c where c.id = ?1 and c.professor = ?#{principal.professor} and c.enabled = true")
    Course findOne(Long id);
}
</code>```

The problem is that for every crud query I will have to write my own custom query, because of professor's information and also the enabled field.

I know there is a way to extends the PagingAndSortingRepository and write your own custom query, like this:

```<code>public interface CustomPagingAndSortRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
    @Override
    @Query("select e from #{#entityName} e where e.id = ?1 and e.professor = ?#{principal.professor} and e.enabled = true")
    T findOne(ID id);
    //More fields overrided here
}
</code>```

This CustomPagingAndSortRepository would work perfectly for all classes if I only had enabled to worry about. This class will work perfectly for Course because e.professor = ?#{principal.professor} will find the Professor there.  But it will not work for Question, for example, because I need a join with the course class to get the professor, like e.course.professor = ?#{principal.professor}

The point is f I put an association with Professor in all classes I can make that generic code work, save tons of code but sacrificing database design's normalization.
The question is: Is there another way? or maybe is it valid to do it?

PS: The Question, Course etc will never change owner, it means that only the Professor who created will be able to use it.

答:
Why dont you create a class annotated @Service that Autowires your CourseRepository then pass id, principal.professor, enabled into it, then your repository will have the method Course findByIdAndProfessorAndEnabled(Long id, String professor, Boolean enabled).
Code Snippet:

```<code>public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {
    Course findByIdAndProfessorAndEnabled(Long id, Professor professor, Boolean enabled);
}

@Service
public class CourseService{
    @Autowired
    CourseRepository courseRepository;

    //pass in principal.professor from your controller or from wherever this is called
    public Course findByIdAndProfessorAndEnabled(Long id, Professor  professor, Boolean enabled){
        return courseRepository.findByIdAndProfessor(id, professor, enabled);
    }
}
</code>```

EDIT: For Hibernate Models

If you always want enabled set to true in your queries you can use the @Where annotation on your model

```<code>@MappedSuperclass
@Where(clause="is_enabled=true")
public class AbstractEntity implements Serializable {
.
.
.
@Column(name="is_enabled")
protected boolean enabled = true;
...
</code>```

I don't know if this approach would also work for your principal but you can try it

ContentLicense: CC BY-SA 3.0

Body:
I hope this question is not opinion based, but here we go.
I am developing a small API with spring boot, spring data jpa, and JWT Token as the authentication system. The API is pretty straightforward, is an exam generator, where you can register professor, course, question, choice etc.

For example:
[13/11/2017 - edited to include AbstractEntity]

@MappedSuperclass
public class AbstractEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;
    protected boolean enabled = true;
    //equals, hashcode...
}

public class Professor extends AbstractEntity{
    private String email;
}

public class Course extends AbstractEntity {
    @ManyToOne(optional = false)
    private Professor professor;
}

public class Question extends AbstractEntity {
    @ManyToOne(optional = false)
    private Course course;
}

Because the authentication system is JWT token for all queries I have to include the professor's information.

For example

public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {
    @Query("select c from Course c where c.id = ?1 and c.professor = ?#{principal.professor} and c.enabled = true")
    Course findOne(Long id);
}

The problem is that for every crud query I will have to write my own custom query, because of professor's information and also the enabled field.

I know there is a way to extends the PagingAndSortingRepository and write your own custom query, like this:

public interface CustomPagingAndSortRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
    @Override
    @Query("select e from #{#entityName} e where e.id = ?1 and e.professor = ?#{principal.professor} and e.enabled = true")
    T findOne(ID id);
    //More fields overrided here
}

This CustomPagingAndSortRepository would work perfectly for all classes if I only had enabled to worry about. This class will work perfectly for Course because e.professor = ?#{principal.professor} will find the Professor there.  But it will not work for Question, for example, because I need a join with the course class to get the professor, like e.course.professor = ?#{principal.professor}

The point is f I put an association with Professor in all classes I can make that generic code work, save tons of code but sacrificing database design's normalization.
The question is: Is there another way? or maybe is it valid to do it?

PS: The Question, Course etc will never change owner, it means that only the Professor who created will be able to use it.

Body:
Why dont you create a class annotated @Service that Autowires your CourseRepository then pass id, principal.professor, enabled into it, then your repository will have the method Course findByIdAndProfessorAndEnabled(Long id, String professor, Boolean enabled).
Code Snippet:

public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {
    Course findByIdAndProfessorAndEnabled(Long id, Professor professor, Boolean enabled);
}

@Service
public class CourseService{
    @Autowired
    CourseRepository courseRepository;

    //pass in principal.professor from your controller or from wherever this is called
    public Course findByIdAndProfessorAndEnabled(Long id, Professor  professor, Boolean enabled){
        return courseRepository.findByIdAndProfessor(id, professor, enabled);
    }
}

EDIT: For Hibernate Models

If you always want enabled set to true in your queries you can use the @Where annotation on your model

@MappedSuperclass
@Where(clause="is_enabled=true")
public class AbstractEntity implements Serializable {
.
.
.
@Column(name="is_enabled")
protected boolean enabled = true;
...

I don't know if this approach would also work for your principal but you can try it


问:
MVC Framework - Server-side DOM manipulation
I'm building an MVC framework, and I'm looking for native solutions / frameworks / tag libraries to draw from or to replace my framework entirely.

I'm interested in the following features specifically:

server-side DOM manipulation

server-side events (page reload, form submit, node insertion, etc.)

traversing the DOM tree using css selectors

validation of html nodes nesting

validation of html nodes allowed attributes

support for tag libraries / user controls

Pretty much what you get with JavaScript, but on the server-side and  with some little extras.

Any solution will do (even if partial), any language will do, any pointers are appreaciated (even from client-side languages, as long as it's possible to check the source code). Dealing with malformed html is not a prerequisite. Outputting valid markup is a big plus.

Please offer practical solutions by pointing the language/framework that is being discussed and, if possible, what features it provides.

答: Maybe you are looking for ItsNat</p>

OwnerDisplayName: facildelembrar

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: facildelembrar

Body: Maybe you are looking for ItsNat


问:
How to add order by random function in between operator using mysql?
SQL query:</p>

```<code>SELECT *
FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductID;
</code>```

答:
MySQL has a rand function that returns a random number between 0 and 1. You could just order by that:

```<code>SELECT   *
FROM     Products
WHERE    ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY RAND();
</code>```

Body:
SQL query:

SELECT *
FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductID;

Body:
MySQL has a rand function that returns a random number between 0 and 1. You could just order by that:

SELECT   *
FROM     Products
WHERE    ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY RAND();


问:
Route is not matched
I can't figure out why this is not matching my route for the CompanyDetailContainer.  The route for Interview container works fine

```<code>      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
      <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
</code>```

so http://localhost:8080/interviews/companies/10 hits the interview route fine but http://localhost:8080/interviews/companies/501/details does not hit the companydetail route

UPDATE:

I'm using:

```<code>"react-router": "^3.0.0",
"react-router-dom": "^4.2.2",
</code>```

original code:

```<code>import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Switch>
        <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
        <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      </Switch>
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
  </Router>
</code>```

adding just exact to what I had didn't work:

```<code>import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>

  </Router>
</code>```

Then I tried to add switch around it:

```<code>import { Router, Route, Switch, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Switch>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>
    </Switch>
  </Router>
</code>```

And now I get this error: Cannot read property 'createRouteFromReactElement' of undefined.  I noticed my import for Switch is not resolving but that's how you import Switch right?

Also not sure if all those routes should be sub routes of <Route path="/" component={HomePageContainer}>?  Note that I removed the <IndexRoute /> per suggestions too.

答:
There are 2 possible solutions:

Use a Switch, which is used to exclusively render just one route.

Use the exact prop of the Route component, which renders the component only if the path is an exact match.

Eg:

```<code><Switch>
  <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
  <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
</Switch>
</code>```

P.S. I think you wouldn't need IndexedRoute when using Switch ( but you better check it in the docs of the version you are using)

Title: Route is not matched

Body:
I can't figure out why this is not matching my route for the CompanyDetailContainer.  The route for Interview container works fine

      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
      <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />

so http://localhost:8080/interviews/companies/10 hits the interview route fine but http://localhost:8080/interviews/companies/501/details does not hit the companydetail route

UPDATE:

I'm using:

"react-router": "^3.0.0",
"react-router-dom": "^4.2.2",

original code:

import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Switch>
        <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
        <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      </Switch>
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
  </Router>

adding just exact to what I had didn't work:

import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>

  </Router>

Then I tried to add switch around it:

import { Router, Route, Switch, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Switch>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>
    </Switch>
  </Router>

And now I get this error: Cannot read property 'createRouteFromReactElement' of undefined.  I noticed my import for Switch is not resolving but that's how you import Switch right?

Also not sure if all those routes should be sub routes of <Route path="/" component={HomePageContainer}>?  Note that I removed the <IndexRoute /> per suggestions too.

Body:
There are 2 possible solutions:

Use a Switch, which is used to exclusively render just one route.

Use the exact prop of the Route component, which renders the component only if the path is an exact match.

Eg:

<Switch>
  <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
  <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
</Switch>

P.S. I think you wouldn't need IndexedRoute when using Switch ( but you better check it in the docs of the version you are using)


问:
Debugging Windows Kernel from Linux
I used to debug the Windows Kernel using VirtualKD, WinDBG and a single Virtual Machine.

Recently I got a Linux machine, and now I wonder- What's the easiest way to debug the Windows Kernel when your host is unable to run VirtualKD/WinDBG*?

I assume the solution will require two Virtual Machines, but I rather have two instances hosted on my actual machine rather than having an instance residing inside another virtual instance...

Is there anyway to make that work?

Thanks in advance!

*Wine is the last resort for stability reasons...

答:
Another option nowadays is to enable local kernel debugging. This comes with some limitations, however it will enable you to access kernel data while just using one VM.

This approach only works on Windows 8.0 and Windows Server 2012 and later.

Follow these steps:

Open a Command Prompt window as Administrator.

Enter bcdedit /debug on

If the computer is not already configured as the target of a debug transport, enter bcdedit /dbgsettings local

Reboot the computer.

Once the system is rebooted, you can execute WinDBG as Administrator, press ctrl+k or go to File -> Attach to kernel -> Local and press OK.

At that point, you will be able to execute kernel-only commands and access kernel structures:

Tested under Windows 10 and with the new WinDBG version (preview).

Reference: Setting Up Local Kernel Debugging of a Single Computer Manually

Title: Debugging Windows Kernel from Linux


问:
building glib gives error: gfileutils.c:57:25: error: linux/magic.h: No such file or directory
I am on CentOS 5.5 and I am getting the error above when running make in the glib 2.27 directory. What is magic.h and what should I do to correct this?

Also - is there an easier way to get gtk installed on centos?

答: Do you have a /usr/include/linux directory?  Does it contain a magic.h header file?  If not, you probably need to install the "kernel-headers" package.  </p>


问:
Java XML Keeping tabs on Nodes
I am struggling to parse an XML Document with variable fields and nodes.
I either get all the data from the child nodes in one clump or nothing at all.

Imagine this XML Document

```<code><?xml version="1.0" encoding="UTF-8"?>
<GreatGrandParent id="123456" version="5">
    <GrandParent1>
        <Parent1>
            <Child1>Text1</Child1>
            <Child2>Text2</Child2>
            <Child3>Text3</Child3>
        </Parent1>
        <Parent2>
            <Child1 name="something" from="0" to="999" />
            <Child2 name="something" from="0" to="999" />
        </Parent2>
    </GrandParent1>
<GrandParent2>
    <Parent1 id="something else" minv="0" maxv="999" name="name1"/>
</GrandParent2>
</GreatGrandParent>
</code>```

I am only interested in the lines that carry an attribute or text between the tags but want to identify the parents/grandparents etc. I know this is confusing but bear with me. Using the above example, I want Java to produce the following output:

```<code>GreatGrandParent.id="123456"
GreatGrandParent.version="5"
GreatGrandParent.GrandParent1.Parent1.Child1 = "Text1"
GreatGrandParent.GrandParent1.Parent1.Child2 = "Text2"
GreatGrandParent.GrandParent1.Parent1.Child3 = "Text3"
GreatGrandParent.GrandParent1.Parent2.Child1.Name="Something"
GreatGrandParent.GrandParent1.Parent2.Child1.from="0"
GreatGrandParent.GrandParent1.Parent2.Child1.to="999"
etc....
</code>```

The nodes names can vary and don't necessarily follow this pattern but I am trying to explain what it is I am after.

I can do this by reading the file as text and scanning each line one by one but that's not particularly elegant or preferable since the fields can be very variable and I have no idea prior to processing what fields I am going to get or what the relationship of the field is to the ones prior and after, which leads to convoluted code which is difficult to debug.

I am not looking for a solution just an pointer in the right direction. Many of the examples on the internet are based on a static structure and knowing what fields are available which is of no use to me.

I am looking for something along the lines of MKYung's ideas on https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ - specifically the Looping the Node section which does go part of the way, but, the code dumps a lot of superflous code, for example the parent lists all the values of the children in one block, which is not what I want.

Does anyone have a suggestion to this?

答: You could use a SAX-Parser. In the org.xml.sax.helpers.DefaultHandler you must implement startElement() and endElement(). You need both methods to keep a track on the xpath to the actual element and in the startElement() you can check for attributes and print them.</p>

Title: Java XML Keeping tabs on Nodes

Body:
I am struggling to parse an XML Document with variable fields and nodes.
I either get all the data from the child nodes in one clump or nothing at all.

Imagine this XML Document

<?xml version="1.0" encoding="UTF-8"?>
<GreatGrandParent id="123456" version="5">
    <GrandParent1>
        <Parent1>
            <Child1>Text1</Child1>
            <Child2>Text2</Child2>
            <Child3>Text3</Child3>
        </Parent1>
        <Parent2>
            <Child1 name="something" from="0" to="999" />
            <Child2 name="something" from="0" to="999" />
        </Parent2>
    </GrandParent1>
<GrandParent2>
    <Parent1 id="something else" minv="0" maxv="999" name="name1"/>
</GrandParent2>
</GreatGrandParent>

I am only interested in the lines that carry an attribute or text between the tags but want to identify the parents/grandparents etc. I know this is confusing but bear with me. Using the above example, I want Java to produce the following output:

GreatGrandParent.id="123456"
GreatGrandParent.version="5"
GreatGrandParent.GrandParent1.Parent1.Child1 = "Text1"
GreatGrandParent.GrandParent1.Parent1.Child2 = "Text2"
GreatGrandParent.GrandParent1.Parent1.Child3 = "Text3"
GreatGrandParent.GrandParent1.Parent2.Child1.Name="Something"
GreatGrandParent.GrandParent1.Parent2.Child1.from="0"
GreatGrandParent.GrandParent1.Parent2.Child1.to="999"
etc....

The nodes names can vary and don't necessarily follow this pattern but I am trying to explain what it is I am after.

I can do this by reading the file as text and scanning each line one by one but that's not particularly elegant or preferable since the fields can be very variable and I have no idea prior to processing what fields I am going to get or what the relationship of the field is to the ones prior and after, which leads to convoluted code which is difficult to debug.

I am not looking for a solution just an pointer in the right direction. Many of the examples on the internet are based on a static structure and knowing what fields are available which is of no use to me.

I am looking for something along the lines of MKYung's ideas on https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ - specifically the Looping the Node section which does go part of the way, but, the code dumps a lot of superflous code, for example the parent lists all the values of the children in one block, which is not what I want.

Does anyone have a suggestion to this?


问:
Can not set font-weight
I have two fonts:

```<code>font: normal 12px/18px Arial, Helvetica, sans-serif;
font: normal 15px/20px Georgia, "Times New Roman", Times, serif;
</code>```

I need to set font-weight for these fonts with values 400 and 600. Values <=500 makes font normal, >=600 makes font bold. What should I do to get font-weight different from normal or bold?

答:
Some fonts have more than two weights. Values could range from 100-900. Read about it HERE.

100 - Thin

200 - Extra Light (Ultra Light)

300 - Light

400 - Normal

500 - Medium

600 - Semi Bold (Demi Bold)

700 - Bold

800 - Extra Bold (Ultra Bold)

900 - Black (Heavy)

Title: Can not set font-weight

Body:
I have two fonts:

font: normal 12px/18px Arial, Helvetica, sans-serif;
font: normal 15px/20px Georgia, "Times New Roman", Times, serif;

I need to set font-weight for these fonts with values 400 and 600. Values <=500 makes font normal, >=600 makes font bold. What should I do to get font-weight different from normal or bold?


问:
What pandas operation will help me do a groupby and aggregate by column combinations?
Here's an example of what I am trying to do:

```<code>   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
   foo_1_bar_3_o1  foo_1_bar_3_o2  foo_2_bar_3_o1  foo_2_bar_3_o2  \
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

   foo_1_bar_1_o1  foo_1_bar_1_o2  foo_2_bar_1_o1  foo_2_bar_1_o2 thing
0             1.1             7.7             NaN             NaN     a
1             NaN             NaN             NaN             NaN     b
</code>```

The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's).

This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 && bar == 2 for the group 'a'.

I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do.

I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible.

Below is the base Python code for this operation.

```<code>import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({'thing': ['a', 'a', 'b'],
                   'foo': [1, 1, 2],
                   'bar': [1, 1, 3],
                   'o1': [0.0, 1.1, 2.2],
                   'o2': [3.3, 4.4, 5.5]})

key_columns = ['foo', 'bar']

key_value_pairs = [df[key].values.tolist() for key in key_columns]

key_value_pairs = list(set(itertools.product(*key_value_pairs)))

output_columns = ['o1', 'o2']

def aggregate(df):
  new_columns = []
  for pair in key_value_pairs:
    pair = list(zip(key_columns, pair))
    new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair])
    for o in output_columns:
      criteria = list()
      for key, value in pair:
        criterion = (df[key] == value)
        criteria.append(criterion)
      new_columns.append('%s_%s' % (new_column, o))
      df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum()
  return df.head(1)[new_columns + ['thing']]

things = df['thing'].value_counts().index.tolist()

groups = df.groupby('thing')

dfs = []
for thing in things:
  dfs.append(aggregate(groups.get_group(thing).reset_index()))
  #print(aggregate(groups.get_group(thing).reset_index(drop=True)))

print(df)
print(pd.concat(dfs).reset_index(drop=True))
</code>```

答:
I think you'll still have to use itertools.product(), because Pandas isn't designed to think about data that don't exist.  But once you've got those extra combinations defined, you can use groupby() and unstack() to get the output you're looking for.

Using the key_value_pairs you defined:

```<code>for k,v in key_value_pairs:
    if not len(df.loc[df.foo.eq(k) & df.bar.eq(v)]):
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"a"}, ignore_index=True)
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"b"}, ignore_index=True)

df
   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
3    3    1  NaN  NaN     a
4    3    1  NaN  NaN     b
5    1    2  NaN  NaN     a
6    1    2  NaN  NaN     b
</code>```

Now groupby and unstack:

```<code>gb = df.groupby(["thing", "foo", "bar"]).sum().unstack(level=[1,2])
gb.columns = [f"foo_{b}_bar_{c}_{a}" for a,b,c in gb.columns]
</code>```

Output:

```<code>       foo_1_bar_1_o1  foo_1_bar_3_o1  foo_2_bar_1_o1  foo_2_bar_3_o1  \
thing
a                 1.1             NaN             NaN             NaN
b                 NaN             NaN             NaN             2.2

       foo_1_bar_1_o2  foo_1_bar_3_o2  foo_2_bar_1_o2  foo_2_bar_3_o2
thing
a                 7.7             NaN             NaN             NaN
b                 NaN             NaN             NaN             5.5
</code>```

Body:
Here's an example of what I am trying to do:

   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
   foo_1_bar_3_o1  foo_1_bar_3_o2  foo_2_bar_3_o1  foo_2_bar_3_o2  \
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

   foo_1_bar_1_o1  foo_1_bar_1_o2  foo_2_bar_1_o1  foo_2_bar_1_o2 thing
0             1.1             7.7             NaN             NaN     a
1             NaN             NaN             NaN             NaN     b

The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's).

This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 && bar == 2 for the group 'a'.

I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do.

I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible.

Below is the base Python code for this operation.

import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({'thing': ['a', 'a', 'b'],
                   'foo': [1, 1, 2],
                   'bar': [1, 1, 3],
                   'o1': [0.0, 1.1, 2.2],
                   'o2': [3.3, 4.4, 5.5]})

key_columns = ['foo', 'bar']

key_value_pairs = [df[key].values.tolist() for key in key_columns]

key_value_pairs = list(set(itertools.product(*key_value_pairs)))

output_columns = ['o1', 'o2']

def aggregate(df):
  new_columns = []
  for pair in key_value_pairs:
    pair = list(zip(key_columns, pair))
    new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair])
    for o in output_columns:
      criteria = list()
      for key, value in pair:
        criterion = (df[key] == value)
        criteria.append(criterion)
      new_columns.append('%s_%s' % (new_column, o))
      df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum()
  return df.head(1)[new_columns + ['thing']]

things = df['thing'].value_counts().index.tolist()

groups = df.groupby('thing')

dfs = []
for thing in things:
  dfs.append(aggregate(groups.get_group(thing).reset_index()))
  #print(aggregate(groups.get_group(thing).reset_index(drop=True)))

print(df)
print(pd.concat(dfs).reset_index(drop=True))

Body:
I think you'll still have to use itertools.product(), because Pandas isn't designed to think about data that don't exist.  But once you've got those extra combinations defined, you can use groupby() and unstack() to get the output you're looking for.

Using the key_value_pairs you defined:

for k,v in key_value_pairs:
    if not len(df.loc[df.foo.eq(k) & df.bar.eq(v)]):
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"a"}, ignore_index=True)
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"b"}, ignore_index=True)

df
   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
3    3    1  NaN  NaN     a
4    3    1  NaN  NaN     b
5    1    2  NaN  NaN     a
6    1    2  NaN  NaN     b

Now groupby and unstack:

gb = df.groupby(["thing", "foo", "bar"]).sum().unstack(level=[1,2])
gb.columns = [f"foo_{b}_bar_{c}_{a}" for a,b,c in gb.columns]

Output:

       foo_1_bar_1_o1  foo_1_bar_3_o1  foo_2_bar_1_o1  foo_2_bar_3_o1  \
thing
a                 1.1             NaN             NaN             NaN
b                 NaN             NaN             NaN             2.2

       foo_1_bar_1_o2  foo_1_bar_3_o2  foo_2_bar_1_o2  foo_2_bar_3_o2
thing
a                 7.7             NaN             NaN             NaN
b                 NaN             NaN             NaN             5.5


问:
first column outside of kable table with kable_styling()
Why does the first column appear outside of the table in html tags when using kable_styling() in this pipe?

```<code>---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r results='asis'}
  x <- data.frame(v1=c("1", "2"),
                  v2=c("3", "4"))
  library(knitr)
  library(kableExtra)

  x %>%
    kable("html") %>%
    kable_styling()
```
</code>```

答:
You have to remove the current version of package "scales" and install "kableExtra" again.

In my case in helped, have a look at the first screen: R was not able to remove the old version of "scales" package.

Before:

After:

Body:
Why does the first column appear outside of the table in html tags when using kable_styling() in this pipe?

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r results='asis'}
  x <- data.frame(v1=c("1", "2"),
                  v2=c("3", "4"))
  library(knitr)
  library(kableExtra)

  x %>%
    kable("html") %>%
    kable_styling()
```


问:
I have a .osm file, don't know what to do next?
I created an indoor map file in JOSM, with different levels and tags for each room etc. Now I have it as a .osm file. How do I make it operational. Like how do I deploy it so that it can be used for indoor navigation. I also need some other features like calculating path from one place t other and search index.</p>

答: You are basically searching for an offline routing and map drawing solution. This has already been answered multiple times. You could even use a full-featured offline solution such as OsmAnd if you convert your map into a suitable format with the OsmAndMapCreator.</p>


问:
Python- writing json file as list of dictionaries
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

```<code>dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))
</code>```

For example, it currently prints like this:

```<code>[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
</code>```

I would like it to print like this:

```<code>[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]
</code>```

答:
Don't use json, pprint is perfect for this job.

```<code>from pprint import pprint

obj = [{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
with open('dumpfile.json', 'w+') as f:
    pprint(obj, f)
</code>```

There are a few parameters for customization, please check the doc for more details :
https://docs.python.org/3/library/pprint.html

Body:
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))

For example, it currently prints like this:

[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]

I would like it to print like this:

[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]

Body:
Don't use json, pprint is perfect for this job.

from pprint import pprint

obj = [{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
with open('dumpfile.json', 'w+') as f:
    pprint(obj, f)

There are a few parameters for customization, please check the doc for more details :
https://docs.python.org/3/library/pprint.html


问:
How do I gracefully avoid dependencies on infrastructure services from domain entities using DDD?

Background

Suppose I am tasked with building a system in the domain of notification sending using Domain Driven Design (DDD). One of the key requirements of this system is that it needs to support various "types" of notifications, such as SMS, email, etc.

After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes (each being an entity as well).

Notification

public abstract class Notification extends Entity<UUID> {
    //...fields...

    public abstract void send();
}
```

<p><code>SMSNotification</code></p>

<pre class="lang-java prettyprint-override"><code>public class SMSNotification extends Notification {

    public void send(){
         //logic for sending the SMS notification using an infrastructure service.
    }
}
</code>```

EmailNotification

public class EmailNotification extends Notification {

    public void send(){
        //logic for sending the email notification using an infrastructure service.
    }
}
```

<h2>Problem(s)</h2>

<ul>
<li>With this current design approach, each subclass of <code>Notification</code> is interacting with an infrastructure service, where the infrastructure is tasked with interfacing with some external system. </li>
</ul>

<p>Eric Evans dedicates a little page space about this on page 107 in his book Domain-Driven Design when introducing the concept of <code>domain services</code>:</p>

<blockquote>
  <p>..., in most development systems, it is awkward to make a direct interface between a domain object and external resources. We can dress up such external services with a facade that takes inputs in terms of the model, ... but whatever intermediaries we may have, and even though they don't belong to us, those services are carrying out the domain responsibility...</p>
</blockquote>

<ul>
<li>If instead, I procure a <code>SendNotificationService</code> in my domain model using Evans' advice instead of having a <code>send</code> method on each subclass of <code>Notification</code>, I am not sure how I can avoid the need for knowing <em>what type</em> of notification was provided, so that the appropriate infrastructure action can be taken:</li>
</ul>

<p><code>SendNotificationService</code> (Domain Service)</p>

<pre class="lang-java prettyprint-override"><code>public class SendNotificationService {
    public void send(Notification notification){
        //if notification is an SMS notification...
        //    utilize infrastructure services for SMS sending.
        //if notification is an email notification...
        //    utilize infrastructure services for email sending.
        //
        //(╯°□°）╯︵ ┻━┻)
    }
}
</code>```

What am I missing here?

Object oriented design principles are pushing me in favor of having the model first suggested, with the Notification, SMSNotification, and EmailNotification classes. Implementing the send method on each subclass of Notification makes sense, as all notifications need to be sent (justifies its placement in Notification) and each "type" or subclass of Notification will have specialized behavior in how the notification is sent (justifies making send abstract in Notification). This approach also honors Open/Closed Principle (OCP), since the Notification class will be closed to modification, and as new notification types are supported, a new subclass of Notification can be created to extend functionality. Regardless, there seems to be consensus on not having entities interface with external services, as well as not having subclasses of entities at all in DDD.

If the behavior of sending notifications is removed from Notification, then where it is placed must be aware of the "type" of notification, and act accordingly, which I can only conceptualize as chain of if...else... statements, which directly contradicts OCP.

答:
I agree with you that the main responsibility of a Notification should be, that it can send itself. That is the whole reason it exists, so it's a good abstraction.

public interface Notification {
    void send();
}
```

The implementations of this interface are the infrastructure services you are looking for. They will not (should not) be referenced directly by other "business" or "core" classes.

Note about making in an Entity: My own takeaway from reading the blue book is, that DDD is not about using Entity, Services, Aggregate Roots, and things like that. The main points are Ubiquitous Language, Contexts, how to work the Domain itself. Eric Evans himself says that this thinking can be applied to different paradigms. It does not have to always involve the same technical things.

Note about the "conventional" design from the other comment (@VoiceOfUnreason): In object-orientation at least, "holding state" is not a real responsibility. Responsibilities can only directly come from the Ubiquitous Language, in other words from the business. "Conventional" (i.e. procedural) design separates data and function, object-orientation does exactly the opposite. So be sure to decide which paradigm you are aiming for, then it may be easier to choose a solution.

Body:
Background

Suppose I am tasked with building a system in the domain of notification sending using Domain Driven Design (DDD). One of the key requirements of this system is that it needs to support various "types" of notifications, such as SMS, email, etc.

After several iterations on developing the domain model, I continue to land on having a Notification base class as an entity, with subclasses SMSNotification, EmailNotification, etc. as child classes (each being an entity as well).

Notification

public abstract class Notification extends Entity<UUID> {
    //...fields...

    public abstract void send();
}

SMSNotification

public class SMSNotification extends Notification {

    public void send(){
         //logic for sending the SMS notification using an infrastructure service.
    }
}

EmailNotification

public class EmailNotification extends Notification {

    public void send(){
        //logic for sending the email notification using an infrastructure service.
    }
}

Problem(s)

With this current design approach, each subclass of Notification is interacting with an infrastructure service, where the infrastructure is tasked with interfacing with some external system.

Eric Evans dedicates a little page space about this on page 107 in his book Domain-Driven Design when introducing the concept of domain services:

..., in most development systems, it is awkward to make a direct interface between a domain object and external resources. We can dress up such external services with a facade that takes inputs in terms of the model, ... but whatever intermediaries we may have, and even though they don't belong to us, those services are carrying out the domain responsibility...

If instead, I procure a SendNotificationService in my domain model using Evans' advice instead of having a send method on each subclass of Notification, I am not sure how I can avoid the need for knowing what type of notification was provided, so that the appropriate infrastructure action can be taken:

SendNotificationService (Domain Service)

public class SendNotificationService {
    public void send(Notification notification){
        //if notification is an SMS notification...
        //    utilize infrastructure services for SMS sending.
        //if notification is an email notification...
        //    utilize infrastructure services for email sending.
        //
        //(╯°□°）╯︵ ┻━┻)
    }
}

What am I missing here?

Object oriented design principles are pushing me in favor of having the model first suggested, with the Notification, SMSNotification, and EmailNotification classes. Implementing the send method on each subclass of Notification makes sense, as all notifications need to be sent (justifies its placement in Notification) and each "type" or subclass of Notification will have specialized behavior in how the notification is sent (justifies making send abstract in Notification). This approach also honors Open/Closed Principle (OCP), since the Notification class will be closed to modification, and as new notification types are supported, a new subclass of Notification can be created to extend functionality. Regardless, there seems to be consensus on not having entities interface with external services, as well as not having subclasses of entities at all in DDD.

If the behavior of sending notifications is removed from Notification, then where it is placed must be aware of the "type" of notification, and act accordingly, which I can only conceptualize as chain of if...else... statements, which directly contradicts OCP.

Body:
I agree with you that the main responsibility of a Notification should be, that it can send itself. That is the whole reason it exists, so it's a good abstraction.

public interface Notification {
    void send();
}

The implementations of this interface are the infrastructure services you are looking for. They will not (should not) be referenced directly by other "business" or "core" classes.

Note about making in an Entity: My own takeaway from reading the blue book is, that DDD is not about using Entity, Services, Aggregate Roots, and things like that. The main points are Ubiquitous Language, Contexts, how to work the Domain itself. Eric Evans himself says that this thinking can be applied to different paradigms. It does not have to always involve the same technical things.

Note about the "conventional" design from the other comment (@VoiceOfUnreason): In object-orientation at least, "holding state" is not a real responsibility. Responsibilities can only directly come from the Ubiquitous Language, in other words from the business. "Conventional" (i.e. procedural) design separates data and function, object-orientation does exactly the opposite. So be sure to decide which paradigm you are aiming for, then it may be easier to choose a solution.


问:
Creating Buttons Once Press Sounds play C# Xamarin( Visual Studio)
.I have a small Question, making a small app.

Each button plays one sound and I managed to make one button play that one sound, but I just can't figure out how to make the second button to do it. Any ideas?

```<code>using Android.App;
using Android.Widget;
using Android.OS;
using Android.Media;

namespace SoundApp
{
 [Activity(Label = "SoundApp", MainLauncher = true, Icon =      "@mipmap/icon")]
 public class MainActivity : Activity
 {
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);

            playButton = FindViewById<Button>(SoundApp.Resource.Id.playButton);
            playButton.Click += PlayButton_Click;
        }

        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);

            playButton1 = FindViewById<Button>(SoundApp.Resource.Id.playButton1);
            playButton1.Click += PlayButton1_Click;
        }

      }
 }
}
</code>```

答:
As @Jason said, don't assigning event handlers to buttons inside of the event handler. Modify your code like this :

```<code>public class MainActivity : Activity
{
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        playButton = FindViewById<Button>(Resource.Id.playButton);
        playButton.Click += PlayButton_Click;

        playButton = FindViewById<Button>(Resource.Id.playButton1);
        playButton.Click += PlayButton1_Click;

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);
            _player.Start();
        }

        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);
            _player.Start();
        }

    }
}
</code>```

Body:
.I have a small Question, making a small app.

Each button plays one sound and I managed to make one button play that one sound, but I just can't figure out how to make the second button to do it. Any ideas?

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Media;

namespace SoundApp
{
 [Activity(Label = "SoundApp", MainLauncher = true, Icon =      "@mipmap/icon")]
 public class MainActivity : Activity
 {
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);

            playButton = FindViewById<Button>(SoundApp.Resource.Id.playButton);
            playButton.Click += PlayButton_Click;
        }

        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);

            playButton1 = FindViewById<Button>(SoundApp.Resource.Id.playButton1);
            playButton1.Click += PlayButton1_Click;
        }

      }
 }
}

Body:
As @Jason said, don't assigning event handlers to buttons inside of the event handler. Modify your code like this :

public class MainActivity : Activity
{
    MediaPlayer _player;
    Button playButton;
    Button playButton1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        playButton = FindViewById<Button>(Resource.Id.playButton);
        playButton.Click += PlayButton_Click;

        playButton = FindViewById<Button>(Resource.Id.playButton1);
        playButton.Click += PlayButton1_Click;

        void PlayButton_Click(object sender, System.EventArgs e)
        {
            _player = MediaPlayer.Create(this, Resource.Raw.mysound);
            _player.Start();
        }

        void PlayButton1_Click(object sender, System.EventArgs e)
        {
            // Second Button
            _player = MediaPlayer.Create(this, Resource.Raw.A);
            _player.Start();
        }

    }
}