问:
Python Cookbook recipe9.14 Discussion
When I read Python Cookbook recipe 9.14 discussion, it says that I have to convert the OrderedDict to a dict instance when making the final class object. Do I have to do that or using OrderedDict is ok?

I tried this, pass OrderedDict to type constructor, it doesn't raise any exception

```<code>class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        attr_dict['_order'] = order
        return type.__new__(cls, clsname, bases, attr_dict)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()
</code>```

code from book

```<code>class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        d = dict(attr_dict)
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        d['_order'] = order
        return type.__new__(cls, clsname, bases, d)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()
</code>```

enter image description here

答:
No, it is not needed.

type.__new__ can take any mapping - maybe even with fewer methods than the full mapping procotocol - __iter__, __len__ and  __getitem__ should suffice.

This is likely valid since Python 3.0 - the author of the recipe simply took a "safe road" as he was not sure what might ensue with a non-native dict being passed to type.__new__ and calling dict on the OrderedDict is a plain line of code anyway.

But it would not have made much sense to allow any custom mapping to be used in __prepare__ and then do not accept that same mapping on type.__new__ - That is, you don't even need a __new__ method on your metaclass if all you need is a custom mapping - just the __prepare__ method.

That said, this particular recipe is now obsolete anyway, as since Python 3.6 dictionaries used in class construction are ordered by default (and as of Python 3.7, all Python dictionaries are ordered by default).

Title: Python Cookbook recipe9.14 Discussion

Body:
When I read Python Cookbook recipe 9.14 discussion, it says that I have to convert the OrderedDict to a dict instance when making the final class object. Do I have to do that or using OrderedDict is ok?

I tried this, pass OrderedDict to type constructor, it doesn't raise any exception

class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        attr_dict['_order'] = order
        return type.__new__(cls, clsname, bases, attr_dict)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()

code from book

class OrderedMeta(type):
    def __new__(cls, clsname, bases, attr_dict):
        d = dict(attr_dict)
        order = []
        for name, value in attr_dict.items():
            if isinstance(value, Typed):
                value._name = name
                order.append(name)
        d['_order'] = order
        return type.__new__(cls, clsname, bases, d)

    @classmethod
    def __prepare__(cls, clsname, bases):
        return OrderedDict()

enter image description here


来源: stackexchange

问:
Auto-scale content, header and other font sizes
I found the great site with this technique – http://www.informationarchitects.jp/en/
When you change screen width, site auto-scales its content (font-size, position of elements, etc.).

So we have proper view of content on every monitor, not that ugly little font on HD (1980*1280) monitors which can be seen on every 960px wide sites. I mean if you do not zoom in (ctrl + +) 960 px wide site on your HD monitor, font remains very small.

So the question is: is there some common solution to make auto-scaling sites? Or every case must be made in its unique way?

答:
The site is using CSS Media Queries to adapt the layout to screen size. You can read the spec here: http://www.w3.org/TR/css3-mediaqueries/

alistapart had a great article on it a while back that serves as a primer on working with media queries: http://www.alistapart.com/articles/responsive-web-design/

ContentLicense: CC BY-SA 3.0


问:
How to position the label inside the Marker in Google Map?

As shown in the picture, my label '150' is strictly located at the center. But i would like to move up a little bit. Is this possible?
Note that I am using markers clustering. So i have to use 'Markers' type (correct me if I am wrong)

答:
See the documentation for the Icon anonymous object:

labelOrigin

  Type:  Point

  The origin of the label relative to the top-left corner of the icon image, if a label is supplied by the marker. By default, the origin is located in the center point of the image.

To move the label, set the labelOrigin property of the Icon to the required value.

ContentLicense: CC BY-SA 4.0


问:
how to choose parallel computing framework for machine learning?
how to choose parallel computing framework for machine learning? I am a beginner, I saw there are Spark,Hadoop, OpenMP...what should I consider besides the language?</p>

答: Look up Horovod from Uber, it's specifically designed for machine learning, available for several frameworks such as tensorflow/pytorch. It's available in Docker image repository on AWS too. </p>


问:
Capturing KeyDown events in a UserControl
I have a user control with several child controls. I need the user interface to react to keypresses, so I decided to put the handling code in a MainControl_KeyDown event. However, when I press a key in my application, this event does not fire.

I have found a solution through a search engine which relies upon use of the Windows API, which I would like to avoid, as it seems like overkill for what should be a function that is properly supported by the .NET framework.

答:
Since you are in a UserControl, you can simply override OnPreviewKeyDown method as shown below:

```<code>protected override void OnPreviewKeyDown(KeyEventArgs e)
{
    base.OnPreviewKeyDown(e);
    if(e.Key == Key.Escape || e.SystemKey == Key.F10)
    {
        ...
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Since you are in a UserControl, you can simply override OnPreviewKeyDown method as shown below:

protected override void OnPreviewKeyDown(KeyEventArgs e)
{
    base.OnPreviewKeyDown(e);
    if(e.Key == Key.Escape || e.SystemKey == Key.F10)
    {
        ...
    }
}


问:
How to integrate KCFinder inside zend application as standalone
I want to integrate KCFinder inside Zend framework, i want this

http://kcfinder.sunhater.com/demo/kcfinder/browse.php?type=files&dir=files/public

page to be included inside my template without using any iframe, i had tried many things by calling browser.php file inside my view but i am facing issues with file loading and their dependencies, even resolving php file dependency by using autoloader js files are not loading properly

Please help me out on this

答:
I had collaborated  with project like CKfinder called Elrte.org
and i did make a custom ZF form element for it

a sample example on my github account :

https://github.com/tawfekov/Elrte-Element-for-Zend-Framework

the demo has ability to show the rich text editor + file manager

feel free to extend it or to get an example of it


问:
Latex writ only until the middle of the page
am try to type a a pseudo code of an algorithme in latex it work fine but it just writ until the midle . and the rest stay empty .. here is the source

```<code>\documentclass{IEEETran}
\usepackage{algpseudocode}
\usepackage{algorithm}
\begin{document}
\begin{algorithm}
\caption{GPX operator}
\hspace*{\algorithmicindent} \textbf{Input} s1 = $\lbrace V^{1}_{1}; ... ; V^{1}_{k}\rbrace$ and  s2 = $\lbrace V^{2}_{1}; ... ; V^{2}_{k}\rbrace$ - parent solutions. \\
 \hspace*{\algorithmicindent} \textbf{Output} $ s = \lbrace V_{1}; ... ; V_{k}\rbrace$ - offspring solution. \\
\begin{algorithmic}[1]
\For {$l(1\leq l \leq k)$}
\If{($l$ is odd)}
\State A=1

\Else
\State  A=2;
 \EndIf
 \State choose $i$ such that $V^{A}_{i}$  has a maximum cardinality
\State $V_{l}$=$V^{A}_{i}$
\State remove the vertices of  $V_{l}$ from $s1$ and $s2$
\EndFor
\State Assign randomly the vertices of $V - (V_{1} \cup ... \cup V_{k})$
\end{algorithmic}

\end{algorithm}
\end{document}
</code>```

and here is what i get :

答: Default mode of IEEEtran is twocolumn. Compile with \documentclass[onecolumn]{IEEEtran} if it's what you want.

Body:
am try to type a a pseudo code of an algorithme in latex it work fine but it just writ until the midle . and the rest stay empty .. here is the source

\documentclass{IEEETran}
\usepackage{algpseudocode}
\usepackage{algorithm}
\begin{document}
\begin{algorithm}
\caption{GPX operator}
\hspace*{\algorithmicindent} \textbf{Input} s1 = $\lbrace V^{1}_{1}; ... ; V^{1}_{k}\rbrace$ and  s2 = $\lbrace V^{2}_{1}; ... ; V^{2}_{k}\rbrace$ - parent solutions. \\
 \hspace*{\algorithmicindent} \textbf{Output} $ s = \lbrace V_{1}; ... ; V_{k}\rbrace$ - offspring solution. \\
\begin{algorithmic}[1]
\For {$l(1\leq l \leq k)$}
\If{($l$ is odd)}
\State A=1

\Else
\State  A=2;
 \EndIf
 \State choose $i$ such that $V^{A}_{i}$  has a maximum cardinality
\State $V_{l}$=$V^{A}_{i}$
\State remove the vertices of  $V_{l}$ from $s1$ and $s2$
\EndFor
\State Assign randomly the vertices of $V - (V_{1} \cup ... \cup V_{k})$
\end{algorithmic}

\end{algorithm}
\end{document}

and here is what i get :


问:
How to make contaning div not to affect hover on parent div
I have the .img-wrapper parent div that has different divs in it and since div .button-holder is  50px down from bottom and it is also positioned absolutely it results in covering the element after the parent div, in this case, the p element making the hover effect of the parent div active even when hovering on the p element. Hope you get what I mean.
How can I fix this ?

The html:

```<code>  <div class="w-full px-10 md:px-2 py-10 teammember_big text-left">
        <div class="img-wrapper relative hover:cursor-pointer">
          <img class="w-full block" :src="teammember.picture">
          <div class="img-overlay"></div>
          <div class="work-overlay"><div class="work-description"><div class="work-title" v-text="teammember.title"></div><div class="work-phone"><span>M:</span> <a :href="'tel:' + teammember.phone_number"><span v-text="teammember.phone_number"></span></a></div><div class="work-email"><span>E:</span> <a :href="'mailto:' + teammember.email"><span v-text="teammember.email"></span></a></div></div></div>
          <div class="button-holder"><a class="button">BIO & DETAILS</a>
          </div>
          </div>
        <p class="text-black text-center name" v-text="teammember.name"></p>
        <!--<p class="text-black title" v-text="teammember.title"></p>
        <p class="text-black bio" >Bio & Details</p>-->
      </div>
</code>```

and some of the relevant CSS written in SCSS:

```<code>.teammember_big {
 .img-overlay {
  background-color: transparent;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  transition: background-color 0.25s ease-in-out;
}
.work-overlay {
 font-family: National-Book;
 border: none;
 background-color: transparent;
 padding: 0;
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 width: 100%;
 height: 100%;
 opacity: 0;
 backface-visibility: hidden;
 transition: transform 0.15s, opacity 0.15s linear;
 text-align: center;
}
.button-holder {
 opacity: 0;
 position: absolute;
 top: auto;
 bottom: 0;
 left: 0;
 right: 0;
 text-align: center;
 transition: transform 0.35s;
 transform: translate3d(0, 50px, 0);
}
}
.teammember_big .img-wrapper:hover .img-overlay {
  background-color: rgba(37, 37, 39, 0.8);
 }
.teammember_big .img-wrapper:hover .work-overlay {
  opacity: 1;
  transition: transform 0.35s, opacity 0.35s linear;
  transform: translate3d(0, 20%, 0);
 }
 .teammember_big .img-wrapper:hover .button-holder {
  opacity: 1;
  transition: transform 0.45s, opacity 0.45s linear;
  transform: translate3d(0, -30px, 0);
 }
</code>```

答:
I don't quite get the result you want to obtain but why don't you just use a simple margin-top: 50px instead of the translate?
This would prevent the element from overflowing the container.

Body:
I have the .img-wrapper parent div that has different divs in it and since div .button-holder is  50px down from bottom and it is also positioned absolutely it results in covering the element after the parent div, in this case, the p element making the hover effect of the parent div active even when hovering on the p element. Hope you get what I mean.
How can I fix this ?

The html:

M:

E:

BIO & DETAILS

and some of the relevant CSS written in SCSS:

.teammember_big {
 .img-overlay {
  background-color: transparent;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  transition: background-color 0.25s ease-in-out;
}
.work-overlay {
 font-family: National-Book;
 border: none;
 background-color: transparent;
 padding: 0;
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 width: 100%;
 height: 100%;
 opacity: 0;
 backface-visibility: hidden;
 transition: transform 0.15s, opacity 0.15s linear;
 text-align: center;
}
.button-holder {
 opacity: 0;
 position: absolute;
 top: auto;
 bottom: 0;
 left: 0;
 right: 0;
 text-align: center;
 transition: transform 0.35s;
 transform: translate3d(0, 50px, 0);
}
}
.teammember_big .img-wrapper:hover .img-overlay {
  background-color: rgba(37, 37, 39, 0.8);
 }
.teammember_big .img-wrapper:hover .work-overlay {
  opacity: 1;
  transition: transform 0.35s, opacity 0.35s linear;
  transform: translate3d(0, 20%, 0);
 }
 .teammember_big .img-wrapper:hover .button-holder {
  opacity: 1;
  transition: transform 0.45s, opacity 0.45s linear;
  transform: translate3d(0, -30px, 0);
 }


问:
Using npm behind corporate proxy .pac
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

```<code>npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
</code>```

or

```<code>npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac
</code>```

but it doesn't work...

any suggestion? thanks

答:
Just create a file named .npmrc file in a your project folder ,it will avoid proxy setting at system level

```<code>#Without password
proxy=http://ipaddress:80
https-proxy=http://ipaddress:80

#With password
proxy=http://<username>:<pass>@proxyhost:<port>
https-proxy=http://<uname>:<pass>@proxyhost:<port>
</code>```

Comment like this if you don't use the proxy

```<code>#proxy=http://ipaddress:80
#https-proxy=http://ipaddress:80

#With password
#proxy=http://<username>:<pass>@proxyhost:<port>
#https-proxy=http://<uname>:<pass>@proxyhost:<port>
</code>```

Title: Using npm behind corporate proxy .pac

Body:
I need to download several packages through npm but our corporate proxy configuration is a .pac file (i'm on windows)

I have already tried

npm config set proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac
npm config set https-proxy http://mydomain\username:password@1.2.3.4:8181/proxy.pac

or

npm config set proxy http://1.2.3.4:8181/proxy.pac
npm config set https-proxy http://1.2.3.4:8181/proxy.pac

but it doesn't work...

any suggestion? thanks

Body:
Just create a file named .npmrc file in a your project folder ,it will avoid proxy setting at system level

#Without password
proxy=http://ipaddress:80
https-proxy=http://ipaddress:80

#With password
proxy=http://<username>:<pass>@proxyhost:<port>
https-proxy=http://<uname>:<pass>@proxyhost:<port>

Comment like this if you don't use the proxy

#proxy=http://ipaddress:80
#https-proxy=http://ipaddress:80

#With password
#proxy=http://<username>:<pass>@proxyhost:<port>
#https-proxy=http://<uname>:<pass>@proxyhost:<port>


问:
Push key name into an array of object looping over using v-for | Vue.js
I am aiming to store key names of object I'm looping over with v-for in an array within my components data object. I have seen others pass it as props into a separate component, but I instead need to store it in the same component where I'm running my v-for loop.

<div v-for="(fieldData, fieldName, index) in fieldset.fields" :key="`c-form__field--${index + 1}`">

```

I need to push each fieldName into an array called currentFields in my data object.

答:
You can add a computed method to do that.</p>
```<code>computed: {
    // a computed getter
    currentFields:
      let arr = [];
      this.fieldset.forEach(fields => {
         arr.push(//whatever you need to save)
      });
      return arr;
    }
  }
</code>```

Body:
I am aiming to store key names of object I'm looping over with v-for in an array within my components data object. I have seen others pass it as props into a separate component, but I instead need to store it in the same component where I'm running my v-for loop.

<div v-for="(fieldData, fieldName, index) in fieldset.fields" :key="`c-form__field--${index + 1}`">

I need to push each fieldName into an array called currentFields in my data object.

Body:
You can add a computed method to do that.

computed: {
    // a computed getter
    currentFields:
      let arr = [];
      this.fieldset.forEach(fields => {
         arr.push(//whatever you need to save)
      });
      return arr;
    }
  }


问:
Horizontal List that wraps without overlapping
I'm trying to create a list (UL) which is displayed horizontally. Each item has some padding around it. The problem I'm having is that when the list gets to the end of the line and starts wrapping to the next line, it doesn't render low enough and starts overlapping the first line. Can someone help me figure out how to get the wrapping to go on to the next line without overlapping?

Here's the CSS

```<code>.letterlist ul {
   margin: 0; padding: 0;
    list-style-type: none; list-style-image: none;
}

.letterlist li
{
    display:inline;
}

.letterlist li a
{
    margin: 4px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;
    border-radius: 5px;
}
</code>```

Here's the HTML

```<code><p>
<ul class="letterlist">
    <li><a href="/list/A">A</a></li>
    <li><a href="/list/B">B</a></li>
    <li><a href="/list/C">C</a></li>
    <li><a href="/list/D">D</a></li>
    <li><a href="/list/E">E</a></li>
    <li><a href="/list/F">F</a></li>
    <li><a href="/list/G">G</a></li>
    <li><a href="/list/H">H</a></li>
    <li><a href="/list/I">I</a></li>
    <li><a href="/list/J">J</a></li>
    <li><a href="/list/K">K</a></li>
    <li><a href="/list/L">L</a></li>
    <li><a href="/list/M">M</a></li>
    <li><a href="/list/N">N</a></li>
    <li><a href="/list/O">O</a></li>
    <li><a href="/list/P">P</a></li>
    <li><a href="/list/Q">Q</a></li>
    <li><a href="/list/R">R</a></li>
    <li><a href="/list/S">S</a></li>
    <li><a href="/list/T">T</a></li>
    <li><a href="/list/U">U</a></li>
    <li><a href="/list/V">V</a></li>
    <li><a href="/list/W">W</a></li>
    <li><a href="/list/X">X</a></li>
    <li><a href="/list/Y">Y</a></li>
    <li><a href="/list/Z">Z</a></li>
</ul>
</p>
</code>```

I'm using blueprint CSS if that matters.

答:
Yi Jiang's answer can be simplified by using a flex box

.letterlist {
  display: flex;
  flex-wrap: wrap;
  gap: 6px
}

.letterlist a {
    margin-bottom: 10px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;

    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="letterlist">
    A
    B
    C
    D
    E
    F
    G
    H
    I
    J
    K
    L
    M
    N
    O
    P
    Q
    R
    S
    T
    U
    V
    W
    X
    Y
    Z
</div></code>```

Body:
I'm trying to create a list (UL) which is displayed horizontally. Each item has some padding around it. The problem I'm having is that when the list gets to the end of the line and starts wrapping to the next line, it doesn't render low enough and starts overlapping the first line. Can someone help me figure out how to get the wrapping to go on to the next line without overlapping?

Here's the CSS

.letterlist ul {
   margin: 0; padding: 0;
    list-style-type: none; list-style-image: none;
}

.letterlist li
{
    display:inline;
}

.letterlist li a
{
    margin: 4px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;
    border-radius: 5px;
}

Here's the HTML

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

I'm using blueprint CSS if that matters.

Body:
Yi Jiang's answer can be simplified by using a flex box

.letterlist {
  display: flex;
  flex-wrap: wrap;
  gap: 6px
}

.letterlist a {
    margin-bottom: 10px;
    color:#eee;
    padding: 10px 20px;
    background:#3c66ad;
    font-size:16px;
    font-weight: bold;

    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}

<div class="letterlist">
    <a href="/list/A">A</a>
    <a href="/list/B">B</a>
    <a href="/list/C">C</a>
    <a href="/list/D">D</a>
    <a href="/list/E">E</a>
    <a href="/list/F">F</a>
    <a href="/list/G">G</a>
    <a href="/list/H">H</a>
    <a href="/list/I">I</a>
    <a href="/list/J">J</a>
    <a href="/list/K">K</a>
    <a href="/list/L">L</a>
    <a href="/list/M">M</a>
    <a href="/list/N">N</a>
    <a href="/list/O">O</a>
    <a href="/list/P">P</a>
    <a href="/list/Q">Q</a>
    <a href="/list/R">R</a>
    <a href="/list/S">S</a>
    <a href="/list/T">T</a>
    <a href="/list/U">U</a>
    <a href="/list/V">V</a>
    <a href="/list/W">W</a>
    <a href="/list/X">X</a>
    <a href="/list/Y">Y</a>
    <a href="/list/Z">Z</a>
</div>


问:
Can I secure my cloud function using Firebase Auth, but without using callable cloud functions. (HTTP request only)
In my project I use a bunch of GCP services, including Firestore, Cloud Functions and Firebase auth.

Taking the fact that users are able to login via Firebase auth service, I assume that it should be possible to check and authenticate users calling my cloud function. Issue is that I can not find any docs or example of how to do that.

I understand that there are special callable functions but it doesn't suit me. I am using express for handling requests.

Is it possible to retrieve some kind of JWT token from user logged in on client side (firebase auth) then send it with request to my cloud function and then check it somehow there? Or is there any other mechanism to achieve CF protection described above?

P.S.
I saw this question, but it is not about what I am asking, because it is related to Firebase Functions and I am talking about Cloud Functions which is very similar but not exact same thing.

答:
So, according to Dougs suggestion and after some additional googling I found out the way which should work for me.

On client side we need to retrieve id token of authenticated user:

```<code>const token = await firebase.auth().currentUser.getIdToken(true);
</code>```

Now we can actually add this token to any request we need. I am going to put in request headers while calling my HTTP triggered cloud function. For example:

```<code>...
const headers = {
    'Authorization': token
}
const response = await fetch('CF_URL', {headers});
....
</code>```

The last and most important thing here is to have verification logic on the serverside (Cloud functions in my case):

```<code>try {
    const userData = await admin.auth().verifyIdToken(tokenFromHeaders);
    console.log(userData.uid) // here we have uid of verified user
    // check user access or do whatever we need here
} catch (e) {
    // something go wrong
}
</code>```

Body:
So, according to Dougs suggestion and after some additional googling I found out the way which should work for me.

On client side we need to retrieve id token of authenticated user:

const token = await firebase.auth().currentUser.getIdToken(true);

Now we can actually add this token to any request we need. I am going to put in request headers while calling my HTTP triggered cloud function. For example:

...
const headers = {
    'Authorization': token
}
const response = await fetch('CF_URL', {headers});
....

The last and most important thing here is to have verification logic on the serverside (Cloud functions in my case):

try {
    const userData = await admin.auth().verifyIdToken(tokenFromHeaders);
    console.log(userData.uid) // here we have uid of verified user
    // check user access or do whatever we need here
} catch (e) {
    // something go wrong
}


问:
how to find out all properties of an object in lua?
Is there any way of getting all the non-nil parameters / properties
of an object? I found this: getmetadata(self.xxxx) and i am looking for something like: getalldata(self).

I'm currently working on a project where lua is involved. Unfortunately, there is no complete reference and i have to use precompiled stuff.

I hope you are able to understand what I am trying to say.

答:
I'm going to assume that when you are referring to "objects" you are meaning "lua tables with an __index metatable pointing to other tables". If that is not the case, this answer will not help you.

If your object structure is made with tables (this is, all __indexes are tables) then you can "parse them up" to obtain all the properties and inherited properties.

If you have any function as __index then what you ask is impossible; there's no way to get the "list of values for which a function returns a non-nil value".

In the first case, the code would look like this:

```<code>function getAllData(t, prevData)
  -- if prevData == nil, start empty, otherwise start with prevData
  local data = prevData or {}

  -- copy all the attributes from t
  for k,v in pairs(t) do
    data[k] = data[k] or v
  end

  -- get t's metatable, or exit if not existing
  local mt = getmetatable(t)
  if type(mt)~='table' then return data end

  -- get the __index from mt, or exit if not table
  local index = mt.__index
  if type(index)~='table' then return data end

  -- include the data from index into data, recursively, and return
  return getAllData(index, data)
end
</code>```

But remember, if any of your __indexes is a function, there is no way to get all the properties; at least not from Lua.

Body:
I'm going to assume that when you are referring to "objects" you are meaning "lua tables with an __index metatable pointing to other tables". If that is not the case, this answer will not help you.

If your object structure is made with tables (this is, all __indexes are tables) then you can "parse them up" to obtain all the properties and inherited properties.

If you have any function as __index then what you ask is impossible; there's no way to get the "list of values for which a function returns a non-nil value".

In the first case, the code would look like this:

function getAllData(t, prevData)
  -- if prevData == nil, start empty, otherwise start with prevData
  local data = prevData or {}

  -- copy all the attributes from t
  for k,v in pairs(t) do
    data[k] = data[k] or v
  end

  -- get t's metatable, or exit if not existing
  local mt = getmetatable(t)
  if type(mt)~='table' then return data end

  -- get the __index from mt, or exit if not table
  local index = mt.__index
  if type(index)~='table' then return data end

  -- include the data from index into data, recursively, and return
  return getAllData(index, data)
end

But remember, if any of your __indexes is a function, there is no way to get all the properties; at least not from Lua.


问:
Apache Commons CSV Mapping not found
I am trying to read a CSV file with certain headers into a Java object using Apache Commons CSV. However, when I run the code, I get the following exeption:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Mapping for Color not found, expected one of [Color, Name, Price, House Cost, Rent, 1 House, 2 Houses, 3 Houses, 4 Houses, Hotel, Mortgage]
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:102)
at GameBoard.<init>(GameBoard.java:25)
at Game.main(Game.java:3)
</code>```

Can someone explain where the exception is coming from? It appears to me that Apache Commons somehow is not matching my input to a column. Is there something wrong on my part or is something else broken? Here is my code snippet:

```<code>Reader in;
    Iterable<CSVRecord> records = null;
    try {
        in = new FileReader(new File(Objects.requireNonNull(getClass().getClassLoader().getResource("Properties.csv")).getFile()));
        records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
    } catch (IOException | NullPointerException e) {
        e.printStackTrace();
        System.exit(1);
    }
    for (CSVRecord record :
            records) {
        spaces.add(new Property(
                record.get("Color"),
                record.get("Name"),
                Integer.parseInt(record.get("Price")),
</code>```

And here are my csv headers (sorry, one was cut off but that's not the point):

Thanks!

答:
I got the same weird exception.  It actually said "Expecting one of ..." and then listed the field it said it could not find - just like in your case.

The reason was that I had set the wrong CSVFormat:

```<code>CSVFormat csvFormat = CSVFormat.newFormat(';');
</code>```

This meant that my code was trying to separate fields on semi-colons in a file that actually had comma separators.

Once I used the DEFAULT CSVFormat, everything started to work.

```<code>CSVFormat csvFormat = CSVFormat.DEFAULT;
</code>```

So the answer is that probably you must set CSVFormat correctly for your file.

Title: Apache Commons CSV Mapping not found

Body:
I am trying to read a CSV file with certain headers into a Java object using Apache Commons CSV. However, when I run the code, I get the following exeption:

Exception in thread "main" java.lang.IllegalArgumentException: Mapping for Color not found, expected one of [Color, Name, Price, House Cost, Rent, 1 House, 2 Houses, 3 Houses, 4 Houses, Hotel, Mortgage]
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:102)
at GameBoard.<init>(GameBoard.java:25)
at Game.main(Game.java:3)

Can someone explain where the exception is coming from? It appears to me that Apache Commons somehow is not matching my input to a column. Is there something wrong on my part or is something else broken? Here is my code snippet:

Reader in;
    Iterable<CSVRecord> records = null;
    try {
        in = new FileReader(new File(Objects.requireNonNull(getClass().getClassLoader().getResource("Properties.csv")).getFile()));
        records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
    } catch (IOException | NullPointerException e) {
        e.printStackTrace();
        System.exit(1);
    }
    for (CSVRecord record :
            records) {
        spaces.add(new Property(
                record.get("Color"),
                record.get("Name"),
                Integer.parseInt(record.get("Price")),

And here are my csv headers (sorry, one was cut off but that's not the point):

Thanks!

Body:
I got the same weird exception.  It actually said "Expecting one of ..." and then listed the field it said it could not find - just like in your case.

The reason was that I had set the wrong CSVFormat:

CSVFormat csvFormat = CSVFormat.newFormat(';');

This meant that my code was trying to separate fields on semi-colons in a file that actually had comma separators.

Once I used the DEFAULT CSVFormat, everything started to work.

CSVFormat csvFormat = CSVFormat.DEFAULT;

So the answer is that probably you must set CSVFormat correctly for your file.


问:
Parse an HTML template as you require it in JavaScript
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

```<code>   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]
</code>```

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

答:
To me it seems like the posthtml-loader is primarily a tool that helps to "prepare" your HTML during the build. Its parser options allow you to break in to the string -> PostHTML AST Tree step, and its plugin options allow you to modify the tree. Then, it stringifies back to HTML.

I couldn't find an option in the webpack plugin to return the interim tree format.

You could write a small custom loader to parse HTML strings to DOM objects:

```<code>// custom-loader.js
module.exports = function(content) {
  return `module.exports = (function() {
    const parser = new DOMParser();
    const doc = parser.parseFromString("${content}", "text/html");
    return doc.body.children;
  }())`;
};
</code>```

Then, in your webpack.config.js, you can tell webpack to make .html files pass this loader:

```<code>// webpack.config.js
module.exports = {
  mode: 'development',
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.bundle.js'
  },
  devtool: "eval-source-map",
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [ './custom-loader' ]
      }
    ]
  }
};
</code>```

Now, whenever you type something like const template = require('./template.html'); you'll get an HTMLCollection instance rather than just a string.

Note that this loader adds a dependency to DOMParser, which is only available in the browser. You could replace it by something like jsdom if you want to run in non-browser environments.

Body:
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

Body:
To me it seems like the posthtml-loader is primarily a tool that helps to "prepare" your HTML during the build. Its parser options allow you to break in to the string -> PostHTML AST Tree step, and its plugin options allow you to modify the tree. Then, it stringifies back to HTML.

I couldn't find an option in the webpack plugin to return the interim tree format.

You could write a small custom loader to parse HTML strings to DOM objects:

// custom-loader.js
module.exports = function(content) {
  return `module.exports = (function() {
    const parser = new DOMParser();
    const doc = parser.parseFromString("${content}", "text/html");
    return doc.body.children;
  }())`;
};

Then, in your webpack.config.js, you can tell webpack to make .html files pass this loader:

// webpack.config.js
module.exports = {
  mode: 'development',
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.bundle.js'
  },
  devtool: "eval-source-map",
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [ './custom-loader' ]
      }
    ]
  }
};

Now, whenever you type something like const template = require('./template.html'); you'll get an HTMLCollection instance rather than just a string.

Note that this loader adds a dependency to DOMParser, which is only available in the browser. You could replace it by something like jsdom if you want to run in non-browser environments.


问:
No material widget found textfield widgets require a material widget ancestor
Hi I am trying to build a login screen in flutter but I am getting below error when opening it.

No material widget found textfield widgets require a material widget ancestor

```<code> import 'package:flutter/material.dart';

 Widget LoginPage() {
    return new Container(
      height: MediaQuery.of(context).size.height,
      decoration: BoxDecoration(
        color: Colors.white,
        image: DecorationImage(
          colorFilter: new ColorFilter.mode(
              Colors.black.withOpacity(0.05), BlendMode.dstATop),
          image: AssetImage('assets/images/mountains.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      child: new Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(120.0),
            child: Center(
              child: Icon(
                Icons.headset_mic,
                color: Colors.redAccent,
                size: 50.0,
              ),
            ),
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "EMAIL",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'samarthagarwal@live.com',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "PASSWORD",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '*********',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 20.0),
                child: new FlatButton(
                  child: new Text(
                    "Forgot Password?",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                    textAlign: TextAlign.end,
                  ),
                  onPressed: () => {},
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            alignment: Alignment.center,
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new FlatButton(
                    shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(30.0),
                    ),
                    color: Colors.redAccent,
                    onPressed: () => {},
                    child: new Container(
                      padding: const EdgeInsets.symmetric(
                        vertical: 20.0,
                        horizontal: 20.0,
                      ),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Expanded(
                            child: Text(
                              "LOGIN",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            alignment: Alignment.center,
            child: Row(
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.all(8.0),
                    decoration: BoxDecoration(border: Border.all(width: 0.25)),
                  ),
                ),
                Text(
                  "OR CONNECT WITH",
                  style: TextStyle(
                    color: Colors.grey,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.all(8.0),
                    decoration: BoxDecoration(border: Border.all(width: 0.25)),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.only(right: 8.0),
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new FlatButton(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30.0),
                            ),
                            color: Color(0Xff3B5998),
                            onPressed: () => {},
                            child: new Container(
                              child: new Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(
                                        top: 20.0,
                                        bottom: 20.0,
                                      ),
                                      child: new Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                        children: <Widget>[
                                          Icon(
                                            const IconData(0xea90,
                                                fontFamily: 'icomoon'),
                                            color: Colors.white,
                                            size: 15.0,
                                          ),
                                          Text(
                                            "FACEBOOK",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.only(left: 8.0),
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new FlatButton(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30.0),
                            ),
                            color: Color(0Xffdb3236),
                            onPressed: () => {},
                            child: new Container(
                              child: new Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(
                                        top: 20.0,
                                        bottom: 20.0,
                                      ),
                                      child: new Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                        children: <Widget>[
                                          Icon(
                                            const IconData(0xea88,
                                                fontFamily: 'icomoon'),
                                            color: Colors.white,
                                            size: 15.0,
                                          ),
                                          Text(
                                            "GOOGLE",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
</code>```

Does anyone know how to resolve it ?

答: I encountered your same problem. Always remember to enter Scaffold remembering that it must be included as a parent who creates the page, inside it after, you will insert all the widgets you want, but Scaffold after MaterialApp is the second component that must be added if you are creating a new page.</p>

Body:
Hi I am trying to build a login screen in flutter but I am getting below error when opening it.

No material widget found textfield widgets require a material widget ancestor

 import 'package:flutter/material.dart';

 Widget LoginPage() {
    return new Container(
      height: MediaQuery.of(context).size.height,
      decoration: BoxDecoration(
        color: Colors.white,
        image: DecorationImage(
          colorFilter: new ColorFilter.mode(
              Colors.black.withOpacity(0.05), BlendMode.dstATop),
          image: AssetImage('assets/images/mountains.jpg'),
          fit: BoxFit.cover,
        ),
      ),
      child: new Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(120.0),
            child: Center(
              child: Icon(
                Icons.headset_mic,
                color: Colors.redAccent,
                size: 50.0,
              ),
            ),
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "EMAIL",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'samarthagarwal@live.com',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            children: <Widget>[
              new Expanded(
                child: new Padding(
                  padding: const EdgeInsets.only(left: 40.0),
                  child: new Text(
                    "PASSWORD",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                    color: Colors.redAccent,
                    width: 0.5,
                    style: BorderStyle.solid),
              ),
            ),
            padding: const EdgeInsets.only(left: 0.0, right: 10.0),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                new Expanded(
                  child: TextField(
                    obscureText: true,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '*********',
                      hintStyle: TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 24.0,
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 20.0),
                child: new FlatButton(
                  child: new Text(
                    "Forgot Password?",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.redAccent,
                      fontSize: 15.0,
                    ),
                    textAlign: TextAlign.end,
                  ),
                  onPressed: () => {},
                ),
              ),
            ],
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            alignment: Alignment.center,
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new FlatButton(
                    shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(30.0),
                    ),
                    color: Colors.redAccent,
                    onPressed: () => {},
                    child: new Container(
                      padding: const EdgeInsets.symmetric(
                        vertical: 20.0,
                        horizontal: 20.0,
                      ),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Expanded(
                            child: Text(
                              "LOGIN",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            alignment: Alignment.center,
            child: Row(
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.all(8.0),
                    decoration: BoxDecoration(border: Border.all(width: 0.25)),
                  ),
                ),
                Text(
                  "OR CONNECT WITH",
                  style: TextStyle(
                    color: Colors.grey,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.all(8.0),
                    decoration: BoxDecoration(border: Border.all(width: 0.25)),
                  ),
                ),
              ],
            ),
          ),
          new Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.only(right: 8.0),
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new FlatButton(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30.0),
                            ),
                            color: Color(0Xff3B5998),
                            onPressed: () => {},
                            child: new Container(
                              child: new Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(
                                        top: 20.0,
                                        bottom: 20.0,
                                      ),
                                      child: new Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                        children: <Widget>[
                                          Icon(
                                            const IconData(0xea90,
                                                fontFamily: 'icomoon'),
                                            color: Colors.white,
                                            size: 15.0,
                                          ),
                                          Text(
                                            "FACEBOOK",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                new Expanded(
                  child: new Container(
                    margin: EdgeInsets.only(left: 8.0),
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new FlatButton(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30.0),
                            ),
                            color: Color(0Xffdb3236),
                            onPressed: () => {},
                            child: new Container(
                              child: new Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(
                                        top: 20.0,
                                        bottom: 20.0,
                                      ),
                                      child: new Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                        children: <Widget>[
                                          Icon(
                                            const IconData(0xea88,
                                                fontFamily: 'icomoon'),
                                            color: Colors.white,
                                            size: 15.0,
                                          ),
                                          Text(
                                            "GOOGLE",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontWeight: FontWeight.bold),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

Does anyone know how to resolve it ?


问:
Compare two MySQL databases
I'm currently developing an application using a MySQL database.

The database-structure is still in flux and changes while development progresses (I change my local copy, leaving the one on the test-server alone).

Is there a way to compare the two instances of the database to see if there were any changes?

While currently simply discarding the previous test server database is fine, as testing starts entering test data it could get a bit tricky.

The same though more so will happen again later in production...

Is there an easy way to incrementally make changes to the production database, preferably by automatically creating a script to modify it?

Tools mentioned in the answers:

Red-Gate's MySQL Schema & Data Compare (Commercial)

Maatkit (now Percona)

liquibase

Toad

Nob Hill Database Compare (Commercial)

MySQL Diff

SQL EDT (Commercial)

答:
check: http://schemasync.org/
the schemasync tool works for me, it is a command line tool works easily in linux command line</p>

OwnerDisplayName: Vincent Ramdhanie

Title: Compare two MySQL databases

LastEditorDisplayName: Vincent Ramdhanie


问:
Restrict enum values by user role
I have an enum of actions. The actions are partitioned by two user roles. The users make requests to an app via Web API. How can I restrict the values accepted by the Web API action based on user role?

At the moment I have two roles and I'm using two enums and two Web API methods. When a value is passed to a database repository it's cast to an integer. This isn't ideal - I'd prefer to use an amalgamation of the enums in the repository interface.

So...

Admins can request that actions from Enum1 are performed and non-admins can do likewise for the actions in Enum2. But the repository method that performs the work can work with integer values from both because authorisation has been handled.

Enum inheritance would fix this if enums were inheritable.

```<code>enum EnumAdmin { Action1 = 1, Action2 = 2 }
enum EnumNotAdmin { Action3 = 3, Action4 = 4 }

void DoAction(int action);

[Authorize(Roles = "Admin")]
public IActionResult AdminMethod(EnumAdmin param)
{
   repos.DoAction((int) param);
}

[Authorize(Roles = "NotAdmin")]
public IActionResult AdminMethod(EnumNotAdmin param)
{
   repos.DoAction((int) param);
}
</code>```

EDIT: Well, nothing to see here as my scheme doesn't work anyway.

Able to assign an invalid Enum value via reflection

答:
You have updated the question for problem definition. I think you can use the flyweight design pattern for the problem. Not very good but I sampled below. I used class for the role. Because the enum type is sealed.</p>

```<code>   public class User
    {
        public string Name { get; set; }
    }

    public class RoleBase
    {

    }

    public class RoleAdmin: RoleBase
    {
     public bool Action1 { get; set; }
     public bool Action2 { get; set; }
    }

    public class RoleNotAdmin: RoleBase
    {
        public bool Action3 { get; set; }
        public bool Action4 { get; set; }
    }

    public interface IPermission
    {
        bool IsAuthorization(RoleBase role, User user);
    }

    public class PermissionAdmin : IPermission
    {
        public bool IsAuthorization(RoleBase roleBase, User user)
        {
            var roleAdmin = roleBase as RoleAdmin;

            return true;
        }
    }
</code>```

Title: Restrict enum values by user role

Body:
I have an enum of actions. The actions are partitioned by two user roles. The users make requests to an app via Web API. How can I restrict the values accepted by the Web API action based on user role?

At the moment I have two roles and I'm using two enums and two Web API methods. When a value is passed to a database repository it's cast to an integer. This isn't ideal - I'd prefer to use an amalgamation of the enums in the repository interface.

So...

Admins can request that actions from Enum1 are performed and non-admins can do likewise for the actions in Enum2. But the repository method that performs the work can work with integer values from both because authorisation has been handled.

Enum inheritance would fix this if enums were inheritable.

enum EnumAdmin { Action1 = 1, Action2 = 2 }
enum EnumNotAdmin { Action3 = 3, Action4 = 4 }

void DoAction(int action);

[Authorize(Roles = "Admin")]
public IActionResult AdminMethod(EnumAdmin param)
{
   repos.DoAction((int) param);
}

[Authorize(Roles = "NotAdmin")]
public IActionResult AdminMethod(EnumNotAdmin param)
{
   repos.DoAction((int) param);
}

EDIT: Well, nothing to see here as my scheme doesn't work anyway.

Able to assign an invalid Enum value via reflection

Body:
You have updated the question for problem definition. I think you can use the flyweight design pattern for the problem. Not very good but I sampled below. I used class for the role. Because the enum type is sealed.

   public class User
    {
        public string Name { get; set; }
    }

    public class RoleBase
    {

    }

    public class RoleAdmin: RoleBase
    {
     public bool Action1 { get; set; }
     public bool Action2 { get; set; }
    }

    public class RoleNotAdmin: RoleBase
    {
        public bool Action3 { get; set; }
        public bool Action4 { get; set; }
    }

    public interface IPermission
    {
        bool IsAuthorization(RoleBase role, User user);
    }

    public class PermissionAdmin : IPermission
    {
        public bool IsAuthorization(RoleBase roleBase, User user)
        {
            var roleAdmin = roleBase as RoleAdmin;

            return true;
        }
    }


问:
How to prevent of converting header name into lower case - Spring boot?
I am developing a java based web application in spring-boot where I am sending http-header from server to client end.

Server-side I have used Spring-boot in form of REST API, whereas at client end we have simple plain HTML5/Angular framework.

My query is, while I am sending any header from server then at client end I always get it into lowercase vs actual.
For example, I am setting header something like,

```<code>header.add("KK-ACTUAL-VALUE", "sfsfjDFFDHTsdfJKKA");
</code>```

At client end, it gives,

kk-actual-value : "sfsfjDFFDHTsdfJKKA"; (Header name converts into lower case!)

Now, the question is, how to prevent it ?

I want to have the same header name what is actually passed by Server/API.

答:
Looks like tomcat container turns the headers to lowercase. Since spring boot uses an embedded tomcat is been affected by it. More info here: https://github.com/mitre/HTTP-Proxy-Servlet/issues/65

As the Http standard specifies:

Each header field consists of a case-insensitive field name followed
by a colon (":") ...

https://www.rfc-editor.org/rfc/rfc7230#section-3.2

Body:
I am developing a java based web application in spring-boot where I am sending http-header from server to client end.

Server-side I have used Spring-boot in form of REST API, whereas at client end we have simple plain HTML5/Angular framework.

My query is, while I am sending any header from server then at client end I always get it into lowercase vs actual.
For example, I am setting header something like,

header.add("KK-ACTUAL-VALUE", "sfsfjDFFDHTsdfJKKA");

At client end, it gives,

kk-actual-value : "sfsfjDFFDHTsdfJKKA"; (Header name converts into lower case!)

Now, the question is, how to prevent it ?

I want to have the same header name what is actually passed by Server/API.


问:
how to find no of attributes in an entity class
```<code> public int getColumnCount() {
            return getClass().getDeclaredFields().length;
        }
    this is the code which return no of attributes of same class,but not anaother class
</code>```

In my service class,I want to know the number of attributes of a
    particular entity class.

I have tried a method,which tells the no of attributes present in the
    same class.But i want to know attributes of another class.

could you please help me to reach the requirement.

答:
Thanks a lot jonK,it worked helped me.

```<code>here is the code.
public int getAttributes() {
        EmployeeDO employeeDo=new EmployeeDO();
        Class<?> e=employeeDo.getClass();
        return getAllAttributes(e);
    }

    private int getAllAttributes(Class<?> entityClass) {

        return entityClass.getDeclaredFields().length;
    }
</code>```

Body:
 public int getColumnCount() {
            return getClass().getDeclaredFields().length;
        }
    this is the code which return no of attributes of same class,but not anaother class

In my service class,I want to know the number of attributes of a
    particular entity class.

I have tried a method,which tells the no of attributes present in the
    same class.But i want to know attributes of another class.

could you please help me to reach the requirement.

Body:
Thanks a lot jonK,it worked helped me.

here is the code.
public int getAttributes() {
        EmployeeDO employeeDo=new EmployeeDO();
        Class<?> e=employeeDo.getClass();
        return getAllAttributes(e);
    }

    private int getAllAttributes(Class<?> entityClass) {

        return entityClass.getDeclaredFields().length;
    }


问:
Set a custom identity value on a auto increment field
I have in my DB (Sql server 2008) a id column with auto numeric set on.
I'm using EF and linq2entities

In some specific scenario I would like to be able to set a custom Id number (obviously I'm totally sure this value is not repeated), for example I would use it to "fill" missing Id numbers caused by deletions.  I want to keep the auto increment prop in database, the problem is that when I do the linq sentence, the database assign the next Id number, not the one that I like.

Maybe it's a little weird but is it possible to do using linq2entities ?

Thanks in advance!

答:
I believe Its not possible unless there is some way to turn off "SET Identity_Insert TableName ON" within Entity Framework.

Basically in SQL Server when you sent Identity on a field it cannot be populated manually unless you run the following statement

```<code>SET Identity_Insert TableName ON
</code>```

After running this statement you will be able to populate Identity Fields manually.

The only other options I can think of is to remove the Identity attribute from the column and create your own incrementer for the field in the Entity Framework using a partial Class

Something like this

```<code>public partial class EntityClassName : global::System.Data.Objects.DataClasses.EntityObject, IEntity
{
    partial void InitializeFields();

    Int64 IEntity.IdentityColumn
    {
        get { return IdentityColumn; }
        set { //some code for an incrementer
              //and the ability to set manually
              //if value provide is not null
            }
    }

}
</code>```

Body:
I believe Its not possible unless there is some way to turn off "SET Identity_Insert TableName ON" within Entity Framework.

Basically in SQL Server when you sent Identity on a field it cannot be populated manually unless you run the following statement

SET Identity_Insert TableName ON

After running this statement you will be able to populate Identity Fields manually.

The only other options I can think of is to remove the Identity attribute from the column and create your own incrementer for the field in the Entity Framework using a partial Class

Something like this

public partial class EntityClassName : global::System.Data.Objects.DataClasses.EntityObject, IEntity
{
    partial void InitializeFields();

    Int64 IEntity.IdentityColumn
    {
        get { return IdentityColumn; }
        set { //some code for an incrementer
              //and the ability to set manually
              //if value provide is not null
            }
    }

}


问:
Handle bar Template in React
Currently we are migrating one application from jquery to react.
In existing app, handlebar is used for few html generation which further send to server for pdf generation .
is it possible to re use the handlebar in the REact app. Basically we would like to  use the handlebar template and pouplate it with the Json from the backend in React app , is it possible, if so any pointers?</p>

答:
It doesnt have anything to do with React really. If I understand your question correctly, you are looking to running handlebar on the client side (in the browser). The answer is yes you can definitely import Handlebar in your react app and compile the template.

```<code>import Handlebars from "handlebars";

const hbr = `
<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
"{{kids.length}} kids:</p>" +
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>
`;

const template = Handlebars.compile(hbr);
const htmlString = template(data);
</code>```

Take a look at https://codesandbox.io/s/sweet-http-c4565 as an example.

Title: Handle bar Template in React

Body:
It doesnt have anything to do with React really. If I understand your question correctly, you are looking to running handlebar on the client side (in the browser). The answer is yes you can definitely import Handlebar in your react app and compile the template.

import Handlebars from "handlebars";

const hbr = `
<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
"{{kids.length}} kids:</p>" +
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>
`;

const template = Handlebars.compile(hbr);
const htmlString = template(data);

Take a look at https://codesandbox.io/s/sweet-http-c4565 as an example.


问:
Finding and Installing Latest file in directory with specific extension
I'm trying to search for the latest .msi file, and install it in the background.

I have tried following the help from this link but it did not help.

This is what I currently have:

```<code>  @echo off
setlocal

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::

FOR /F "eol=| delims=" %%I IN ('DIR "directory" /A-D /B /S /O-D /TW 2^>nul')
DO (
    ECHO %%~I
    SET "NewestFile=%%~I"
    GOTO FoundFile
)
ECHO No *.msi file found!
GOTO :EOF

:FoundFile
msiexec.exe /I "%NewestFile%" /Q

::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.
</code>```

I'm guessing the problem is with the :FoundFile and the execution part or finding the correct file based off of time.

I was thinking maybe I have to use:

```<code>forfiles /p "dir" /m *.msi /S /D +%Date%
</code>```

but I'm not entirely sure.

答:
A proposal for a solution using Powershell:

```<code>Get-ChildItem *msi | Sort-Object -Property LastWriteTime | Select -Last 1 | %{Start-Process $_.FullName -WindowStyle Hidden}
</code>```

This will launch in the background the .msi file with the most recent write time in your current folder.

Body:
I'm trying to search for the latest .msi file, and install it in the background.

I have tried following the help from this link but it did not help.

This is what I currently have:

  @echo off
setlocal

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::

FOR /F "eol=| delims=" %%I IN ('DIR "directory" /A-D /B /S /O-D /TW 2^>nul')
DO (
    ECHO %%~I
    SET "NewestFile=%%~I"
    GOTO FoundFile
)
ECHO No *.msi file found!
GOTO :EOF

:FoundFile
msiexec.exe /I "%NewestFile%" /Q

::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.

I'm guessing the problem is with the :FoundFile and the execution part or finding the correct file based off of time.

I was thinking maybe I have to use:

forfiles /p "dir" /m *.msi /S /D +%Date%

but I'm not entirely sure.

Body:
A proposal for a solution using Powershell:

Get-ChildItem *msi | Sort-Object -Property LastWriteTime | Select -Last 1 | %{Start-Process $_.FullName -WindowStyle Hidden}

This will launch in the background the .msi file with the most recent write time in your current folder.


问:
Input type hidden passes the same value from foreach in javascript
I have a code with foreach which prints the image and then it will stores the image id in hidden form field. I want to get the particular image id when user clicks the particular image . But it returns the first value of foreach image id . Sorry for bad english . Somebody please help me with this. </p>

```<code><div id="gallery_09" >
    <?php foreach ($hair['hair_color_media'] as $key => $row){?>
   <input type = "hidden" name = "hair_color_slug" value = "<?=$row->hair_color_slug?>">
   <a href="#" class="elevatezoom-gallery" data-toggle="tooltip" title="<?=$row->hair_color?>" data-update="" data-image="<?=base_url('assets/img/products/large/'.$row->media_images);?>" data-zoom-image="<?=base_url('assets/img/products/large/'.$row->media_images);?>" onclick = "getPrice();">
      <img data-toggle="tooltip" title="<?=$row->hair_color?>" src="<?=base_url('assets/img/products/pin/'.$row->media_images);?>" width="50" style = "border-radius: 50%;">
  </a>
<?php }?>
  </div>
<input type = "text" readonly="" id ="color" name = "color"/>

</code>```

```<code><script type="text/javascript">
        function getPrice()
        {
            var color = $('input:hidden[name=hair_color_slug]').val();

            document.getElementById('color').value = color;
        }
    </script>
</code>```

答:
pass the handler 'this' keyword within getPrice function to obtain the current element which fired the event.

```<code>onclick = "getPrice(this);
</code>```

On click will get the previous hidden value of clicks element and put in the color field.

```<code>function getPrice(getprice)
{
    var color = $(getprice).prev().val();

    document.getElementById('color').value = color;
}
</code>```

Body:
I have a code with foreach which prints the image and then it will stores the image id in hidden form field. I want to get the particular image id when user clicks the particular image . But it returns the first value of foreach image id . Sorry for bad english . Somebody please help me with this.

    <?php foreach ($hair['hair_color_media'] as $key => $row){?>
   <input type = "hidden" name = "hair_color_slug" value = "<?=$row->hair_color_slug?>">
   <a href="#" class="elevatezoom-gallery" data-toggle="tooltip" title="<?=$row->hair_color?>" data-update="" data-image="<?=base_url('assets/img/products/large/'.$row->media_images);?>" data-zoom-image="<?=base_url('assets/img/products/large/'.$row->media_images);?>" onclick = "getPrice();">
      <img data-toggle="tooltip" title="<?=$row->hair_color?>" src="<?=base_url('assets/img/products/pin/'.$row->media_images);?>" width="50" style = "border-radius: 50%;">

<?php }?>

<input type = "text" readonly="" id ="color" name = "color"/>

Body:
pass the handler 'this' keyword within getPrice function to obtain the current element which fired the event.

onclick = "getPrice(this);

On click will get the previous hidden value of clicks element and put in the color field.

function getPrice(getprice)
{
    var color = $(getprice).prev().val();

    document.getElementById('color').value = color;
}


问:
Multiple scatter plots in a single figure from multiple data frame in R using ggplot?
I want to generate a figure that display all the scatter plots on this single figure using data from the two data frame (i.e., regressing column-A of Data1 against Column-A of Data2). Each plot in the figure should show R-square and p-value. I am more interested to know how I can use the fact_wrap function of ggplot while grabing data from multiple data frame.
I tried a couple of method but did not succeeded.

```<code>library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

#method-1: using plot functions
par(mfrow=c(3,1))
plot(Data1$A, Data2$A)
abline(lm(Data1$A ~ Data2$A))
plot(Data1$B, Data2$B)
abline(lm(Data1$B ~ Data2$B))
plot(Data1$C, Data2$C)
abline(lm(Data1$C ~ Data2$C))
dev.off()

#method-2: using ggplot
ggplot()+
  geom_point(aes(Data1$A,Data2$A))
</code>```

I want a Figure like the one below

答:
@Jordo82, here is what I get when I try to insert the text on the figures. Is there a way to free-up the Y-axis in a way that the added text do not depends on the y-scale rather it appears on the top left corner of each plot. The reason why I used annotate_custom was that it do not depends on the y-scale but the downside is that I would take only the first text in the labels. my real values are so different then each other- see the Y-scale of attached Figure.

I used your code while editing the placement coordinate

```<code> annotate("text", -1.5, 800, label = c("P = 0.6", "P = 0.5", "P = 0.9", "P = 0.9"),
             color = "red", fontface = "italic")
</code>```

Body:
I want to generate a figure that display all the scatter plots on this single figure using data from the two data frame (i.e., regressing column-A of Data1 against Column-A of Data2). Each plot in the figure should show R-square and p-value. I am more interested to know how I can use the fact_wrap function of ggplot while grabing data from multiple data frame.
I tried a couple of method but did not succeeded.

library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

#method-1: using plot functions
par(mfrow=c(3,1))
plot(Data1$A, Data2$A)
abline(lm(Data1$A ~ Data2$A))
plot(Data1$B, Data2$B)
abline(lm(Data1$B ~ Data2$B))
plot(Data1$C, Data2$C)
abline(lm(Data1$C ~ Data2$C))
dev.off()

#method-2: using ggplot
ggplot()+
  geom_point(aes(Data1$A,Data2$A))

I want a Figure like the one below

Body:
@Jordo82, here is what I get when I try to insert the text on the figures. Is there a way to free-up the Y-axis in a way that the added text do not depends on the y-scale rather it appears on the top left corner of each plot. The reason why I used annotate_custom was that it do not depends on the y-scale but the downside is that I would take only the first text in the labels. my real values are so different then each other- see the Y-scale of attached Figure.

I used your code while editing the placement coordinate

 annotate("text", -1.5, 800, label = c("P = 0.6", "P = 0.5", "P = 0.9", "P = 0.9"),
             color = "red", fontface = "italic")


问:
Setting IsCheckable seems to prevent submenus from showing up
I'm trying to bind IsChecked to the Selected DependancyProperty on the object I'm displaying, this code appears to work, but submenus don't show up if I use it. Is this the right way to go about it, and how do I fix the problem?</p>

```<code><MenuItem Header="Window" Name="windowMenu" ItemsSource="{Binding}">
    <MenuItem.ItemContainerStyle>
        <Style>
             <Setter Property="MenuItem.IsChecked" Value="{Binding Path=Selected}" />
             <Setter Property="MenuItem.IsCheckable" Value="true" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>
</code>```

答:
A quick test reveals that if a MenuItem's IsCheckable property is set to True, it will not display its child items.

```<code>    <Menu>
        <MenuItem Header="File">
            <MenuItem Header="Exit" />
        </MenuItem>
        <MenuItem Header="Tools">
            <MenuItem Header="Options" IsCheckable="True">
                <MenuItem Header="one" IsCheckable="True" />
                <MenuItem Header="two" IsCheckable="True" />
            </MenuItem>
        </MenuItem>
    </Menu>
</code>```

In the example above, Options will have no children displaying.

Edit: The reason this is the case is that from a user experience standpoint, this is not a case that really makes sense. The only case I can think of is checking an item which checks all of its subitems, but I'd suppose you'd be better off using checkboxes for that.

Redefining the ControlTemplate is certainly an option. Blend can usually tell you what the default control template it and you can go from there.

OwnerDisplayName: Eric

Body:
I'm trying to bind IsChecked to the Selected DependancyProperty on the object I'm displaying, this code appears to work, but submenus don't show up if I use it. Is this the right way to go about it, and how do I fix the problem?

<MenuItem Header="Window" Name="windowMenu" ItemsSource="{Binding}">
    <MenuItem.ItemContainerStyle>

    </MenuItem.ItemContainerStyle>
</MenuItem>

Body:
A quick test reveals that if a MenuItem's IsCheckable property is set to True, it will not display its child items.

    <Menu>
        <MenuItem Header="File">
            <MenuItem Header="Exit" />
        </MenuItem>
        <MenuItem Header="Tools">
            <MenuItem Header="Options" IsCheckable="True">
                <MenuItem Header="one" IsCheckable="True" />
                <MenuItem Header="two" IsCheckable="True" />
            </MenuItem>
        </MenuItem>
    </Menu>

In the example above, Options will have no children displaying.

Edit: The reason this is the case is that from a user experience standpoint, this is not a case that really makes sense. The only case I can think of is checking an item which checks all of its subitems, but I'd suppose you'd be better off using checkboxes for that.

Redefining the ControlTemplate is certainly an option. Blend can usually tell you what the default control template it and you can go from there.

OwnerDisplayName: siz

LastEditorDisplayName: siz