问:
c# mvc project DB data backward compability
I have encountered a problem in the project that I am developing and I would like to consult about the solution.The app must support more than one version.Versions of the web page related to the number of parameters  and the name can vary in the database.We can make the web page dynamic by using the entity framework but when the version is upgraded, the cost of making old tables compatible with new tables comes up.
How can I get rid of this cost?Can you help me?

project :c# mvc project
DB : Mssql

答:
This is a well known problem in environments where more than one version of the website is supported.  It is also a well known problem in the microservices world, where multiple different versions of the same microservice must be supported.

Unfortunately, there is no easy way out. You have to write the code that does the mapping of functionality between different versions, and you have to be prepared to keep writing this version mapping code forever.

That's why the concept of breaking changes vs. non-breaking changes has been invented.  When new functionality is introduced which is so different from the old functionality that we cannot really map the old to the new, we say that we have a breaking change, we increment the major version number, and we put the new version of code and data separately from the old, thus breaking support of the old stuff.  When the change is not breaking, then we write the mapping code and we only increment the minor version number, indicating that the new stuff retains backwards compatibility with the old stuff.

Some non-technical decision maker within your company may think that being backwards-compatible should not be a big deal, and may have promised it to customers, but he has to be informed that the sad reality is that every once in a while there will be breaking changes.


来源: stackexchange

问:
Ionic 3 how to use textarea ngModel and default value?
I am new in ionic and have a problem with textarea.
This is my code:

```<code><textarea  [(ngModel)]="userData.aboutme" name="" id="" cols="30" rows="20"
    value="{{ about_me}}" style="width:100%; padding: 10px; margin-top: 3px;" >
</textarea>
</code>```

The problem is that the value is not showing inside textarea. It's show only if i remove the [(ngModel)].
I need help for this thanks a lot

答:
You need to use ion-textarea.

Note: This is just an example.Adjust it as you wish.

Working stackblitz

html

```<code> <ion-item>
  <ion-textarea placeholder="Tap here"
      [(ngModel)]="note" name="note" autocomplete="on" autocorrect="on"></ion-textarea>
 </ion-item>
</code>```

.ts

```<code>  note: string = "My Default Text";
  constructor(public navCtrl: NavController) {

  }
</code>```

Offical doc about ion-textarea

ContentLicense: CC BY-SA 3.0

Body:
I am new in ionic and have a problem with textarea.
This is my code:

<textarea  [(ngModel)]="userData.aboutme" name="" id="" cols="30" rows="20"
    value="{{ about_me}}" style="width:100%; padding: 10px; margin-top: 3px;" >
</textarea>

The problem is that the value is not showing inside textarea. It's show only if i remove the [(ngModel)].
I need help for this thanks a lot

Body:
You need to use ion-textarea.

Note: This is just an example.Adjust it as you wish.

Working stackblitz

html

 <ion-item>
  <ion-textarea placeholder="Tap here"
      [(ngModel)]="note" name="note" autocomplete="on" autocorrect="on"></ion-textarea>
 </ion-item>

.ts

  note: string = "My Default Text";
  constructor(public navCtrl: NavController) {

  }

Offical doc about ion-textarea


问:
Xampp is not starting on ubuntu 17.10
I have installed xampp on my ubuntu 17.10, it has been successfully installed but when i start the xampp using sudo /opt/lampp/lampp start it throw errors

Starting XAMPP for Linux 5.6.32-0... XAMPP: Starting
  Apache.../opt/lampp/share/xampp/xampplib: line 22: netstat: command
  not found

/opt/lampp/share/xampp/xampplib: line 22: netstat: command not found
  fail.

XAMPP:  Starting diagnose...   XAMPP:  Sorry, I've no idea what's
  going wrong.   XAMPP:  Please contact our forum
  http://www.apachefriends.org/f

and more errors

答:
Maybe you have to install netstat command as prompt said.

sudo apt-get install net-tools

Title: Xampp is not starting on ubuntu 17.10

ContentLicense: CC BY-SA 4.0


问:
Sort SparseArray in Android
How can I sort android.util.SparseArray?
E.g. I have SparseArray with:

1 - 2.33

5 - 1.5

Result:

5 - 1.5

1 - 2.33

Thanks!!!

-- EDITED

I've used the Map. Thanks for help.

答:
Updated:

```<code>private SparseIntArray void sortMap(SparseIntArray unsorted) {
    SparseIntArray sortedSparseIntArray = new SparseIntArray();
    while (unsorted.size() > 0) {
        int min = Integer.MAX_VALUE;
        int minIndex = 0;
        for (int i = 0; i < unsorted.size(); i++) {
            if (unsorted.keyAt(i) <= min) {
                min = unsorted.keyAt(i);
                minIndex = i;
            }
        }
        sortedSparseIntArray.put(min, unsorted.get(min));
        sFactorsMap.removeAt(minIndex);
    }
    return sortedSparseIntArray;
}
</code>```

Title: Sort SparseArray in Android

Body:
Updated:

private SparseIntArray void sortMap(SparseIntArray unsorted) {
    SparseIntArray sortedSparseIntArray = new SparseIntArray();
    while (unsorted.size() > 0) {
        int min = Integer.MAX_VALUE;
        int minIndex = 0;
        for (int i = 0; i < unsorted.size(); i++) {
            if (unsorted.keyAt(i) <= min) {
                min = unsorted.keyAt(i);
                minIndex = i;
            }
        }
        sortedSparseIntArray.put(min, unsorted.get(min));
        sFactorsMap.removeAt(minIndex);
    }
    return sortedSparseIntArray;
}


问:
removing black border around user icon blue coloring
I have these images that I've colored blue, but they have a black outline around the images. Can anyone tell me how I can remove the black outline in MS paint? Or another tool that is easy to use and free?

答:
Try with miniPaint. It's a online site.

Use Tool->Replace Color and replace Black with Transparent and Power ~25 like so:

The final result is quite good i think

Note slide Alpha to 0 in order to replace with Transparent color


问:
xmlstarlet: get exact value
input:

```<code>  <ReferenceTitle>
    <TitleText>Mozart - Don Giovanni</TitleText>
  </ReferenceTitle>
</code>```

my code:

```<code>for /R %%a in (*.xml) do (
    for /f %%i in ('%root%\files\xml.exe sel -v "/ernm:NewReleaseMessage/ResourceList/SoundRecording/ReferenceTitle/TitleText[1]" %%a') do set titel=%%i
    )
</code>```

I would like to get the exact (entire) value of  using XML-starlet, however all i'm getting is 'Mozart '. What am I missing?

答: Try for /f "delims=" %%i in etc... otherwise the default delimiter is a space, hence you only get the first word. The /f "delims=" option says there is no delimiter and you get the whole line. Type for /? for more details.

Title: xmlstarlet: get exact value

Body:
input:

  <ReferenceTitle>
    <TitleText>Mozart - Don Giovanni</TitleText>
  </ReferenceTitle>

my code:

for /R %%a in (*.xml) do (
    for /f %%i in ('%root%\files\xml.exe sel -v "/ernm:NewReleaseMessage/ResourceList/SoundRecording/ReferenceTitle/TitleText[1]" %%a') do set titel=%%i
    )

I would like to get the exact (entire) value of  using XML-starlet, however all i'm getting is 'Mozart '. What am I missing?


问:
Convert video file to TIFF with ffmpeg.dll or avcodec.dll? Is "on-the-fly" possible?
I want to create a program, which gets a video-file from Qt, converts that video file to TIFF-files and sends them to an algorithm which handles these TIFF-Files.

My questions:

is it possible with ffmpeg or avcodec not to convert a video-file to TIFF-files first on harddrive and send them to the algorithm after that, but to convert frame for frame and send it to the algorithm right away?

The more important question: Is it possible to do that not with an external process with ffmpeg.exe, but with ffmpeg.dll? Or is it only possible with avcodec.dll? (It doesn't have to be "on-the-fly" like at my point above) How can I create a ffmpeg.dll with header and lib?

答:
for exporting tif :
http://www.repaire.net/forums/cinema-numerique/215306-projet-dencodage-dcp.html</p>

ContentLicense: CC BY-SA 2.5


问:
Find valid time period for given date
I issue is to find valid price for given date using two SQL tables.
First table columns look like:

```<code>Item_ID | Date
</code>```

and the second is like:

```<code>Item_ID | FromDate1 | Price1 | FromDate2 | Price2 | FromDate3 | Price3 | FromDate4 | Price4 | EndDate
</code>```

I want to write Query, where the result will be like :

```<code>Item_ID | Date | Valid_Price
</code>```

As you probably guessed Valid_Price depends on the date. E.g.

If first.FromDate(x) < second.Date < first.FromDate(x+1)

result.Valid_Price = first.Price(x)

Of course Item_ID must be the same in both tables, but I know i can do it with WHERE or ON. Do You have any ideas how to include above conditions in SQL query?

P.S. sometimes only few columns are filled. E.g. there might be only FromDate1, Price1, EndDate, and rest of values are NULLs.

答:
I assume this is not the best solution regarding the query, but this might be functional :

```<code>  SELECT Item_ID, first.date,
         CASE WHEN first.date <= FromDate1 THEN Price1
              WHEN first.date <= FromDate2 THEN Price2
              WHEN first.date <= FromDate3 THEN Price3
              WHEN first.date <= FromDate4 THEN Price4
         ELSE 0
         END AS price
    FROM first JOIN second USING (Item_ID);
</code>```

Hope this help. But not sure to understand your "first.FromDate(x+1)"

Title: Find valid time period for given date

Body:
I issue is to find valid price for given date using two SQL tables.
First table columns look like:

Item_ID | Date

and the second is like:

Item_ID | FromDate1 | Price1 | FromDate2 | Price2 | FromDate3 | Price3 | FromDate4 | Price4 | EndDate

I want to write Query, where the result will be like :

Item_ID | Date | Valid_Price

As you probably guessed Valid_Price depends on the date. E.g.

If first.FromDate(x) < second.Date < first.FromDate(x+1)

result.Valid_Price = first.Price(x)

Of course Item_ID must be the same in both tables, but I know i can do it with WHERE or ON. Do You have any ideas how to include above conditions in SQL query?

P.S. sometimes only few columns are filled. E.g. there might be only FromDate1, Price1, EndDate, and rest of values are NULLs.

Body:
I assume this is not the best solution regarding the query, but this might be functional :

  SELECT Item_ID, first.date,
         CASE WHEN first.date <= FromDate1 THEN Price1
              WHEN first.date <= FromDate2 THEN Price2
              WHEN first.date <= FromDate3 THEN Price3
              WHEN first.date <= FromDate4 THEN Price4
         ELSE 0
         END AS price
    FROM first JOIN second USING (Item_ID);

Hope this help. But not sure to understand your "first.FromDate(x+1)"


问:
Type mismatch resolving iterator Item to a pointer with an explicit lifetime
I'm trying to add functions to Iterator where the associated type Item is a reference to a struct with an explicit lifetime.

When I've wanted to modify the iterator state or return a new value I've had no problems, but when I attempt to return a new Iterator where Item is a reference with an explicit lifetime, the compiler complains.

Example

```<code>use std::marker::PhantomData;

/// First, an "Inner" struct to be contained in my custom iterator
pub struct Inner {
    text: String,
}

/// Then, the "CustomIterator" in question.  Notice that `Item` is `&'a Inner`.
pub struct CustomIterator<'a, I: Iterator<Item = &'a Inner>> {
    iter: I,
    _marker: PhantomData<&'a i8>,
}

/// Implementing Iterator for CustomIterator so as to define the `next()` function, as you do...
impl<'a, I: Iterator<Item = &'a Inner>> Iterator for CustomIterator<'a, I> {
    type Item = &'a Inner;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

/// Now, creating a custom trait definition called IterateMore that:
///   1. inherits Iterator
///   2. includes a default method called `more` which returns a `CustomIterator`
pub trait IterateMore<'a>: Iterator {
    type Item;
    fn more(self) -> CustomIterator<'a, Self>
    where
        Self: Sized;
}

/// Implementing `IterateMore` for an iterator of the specific type `Iterator<Item=&'a Inner>`
impl<'a, I: Iterator<Item = &'a Inner>> IterateMore<'a> for I
where
    I: Iterator,
{
    type Item = &'a Inner;
    fn more(self) -> CustomIterator<'a, Self>
    where
        Self: Sized,
    {
        CustomIterator {
            iter: self,
            _marker: PhantomData,
        }
    }
}

fn main() {
    let inner = Inner {
        text: "Hello world".to_string(),
    };
    let inners = vec![&inner];
    inners.iter().more().next();
}
</code>```

(See it on repl.it)

Error

error[E0271]: type mismatch resolving `<Self as std::iter::Iterator>::Item == &'a Inner`
  --> src/main.rs:28:5
   |
28 | /     fn more(self) -> CustomIterator<'a, Self>
29 | |     where
30 | |         Self: Sized;
   | |____________________^ expected associated type, found reference
   |
   = note: expected type `<Self as std::iter::Iterator>::Item`
              found type `&'a Inner`
   = note: required by `CustomIterator`
```

<p>Why is <code>Item</code> not being resolved here?  It is a bit frustrating as the compiler also complains if I try to set <code>&'a Inner</code> as the default <code>Item</code> type in the trait definition, saying:</p>

<pre class="lang-none prettyprint-override"><code>error: associated type defaults are unstable (see issue #29661)
</code>```

How could this be fixed or done differently?

答:
It is unclear to me why you'd want to restrict the wrapped iterator to some custom type (given that you still have to write down the restriction every time you use the type, although that might change).  But perhaps your "real" next function does something funny.

PhantomData doesn't seem to be necessary (anymore) to "use" the lifetime when it is used in a where-clause.

IterateMore shouldn't have an Item associated type, given Iterator already has it.  (If you'd really need a new type pick a different name)

As IterateMore uses the CustomIterator type it needs to repeat the requirements, in this case Iterator<Item = &'a Inner> (that is what the type mismatch error is about); this is not the same as saying type Item = &'a Inner in the trait definition.

Playground

```<code>/// an "Inner" struct to be contained in my custom iterator
pub struct Inner {
    text: String,
}

pub struct CustomIterator<'a, I>
where
    I: Iterator<Item = &'a Inner>,
{
    iter: I,
}

impl<'a, I> Iterator for CustomIterator<'a, I>
where
    I: Iterator<Item = &'a Inner>,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

pub trait IterateMore<'a>: Iterator<Item = &'a Inner> + Sized {
    fn more(self) -> CustomIterator<'a, Self>;
}

impl<'a, I> IterateMore<'a> for I
where
    I: Iterator<Item = &'a Inner>,
{
    fn more(self) -> CustomIterator<'a, Self> {
        CustomIterator { iter: self }
    }
}

fn main() {
    let inner = Inner {
        text: "Hello world".to_string(),
    };
    let inners = vec![inner];
    inners.iter().more().next();
}
</code>```

You could also remove the type restrictions everywhere like this (and only add it back in the place you actually need/want it):

Playground

```<code>pub struct CustomIterator<I> {
    iter: I,
}

impl<I> Iterator for CustomIterator<I>
where
    I: Iterator,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

pub trait IterateMore: Iterator + Sized {
    fn more(self) -> CustomIterator<Self>;
}

impl<I> IterateMore for I
where
    I: Iterator,
{
    fn more(self) -> CustomIterator<Self>
    {
        CustomIterator { iter: self }
    }
}

fn main() {
    let inners = vec!["Hello world".to_string()];
    inners.iter().more().next();
}
</code>```

Body:
I'm trying to add functions to Iterator where the associated type Item is a reference to a struct with an explicit lifetime.

When I've wanted to modify the iterator state or return a new value I've had no problems, but when I attempt to return a new Iterator where Item is a reference with an explicit lifetime, the compiler complains.

Example

use std::marker::PhantomData;

/// First, an "Inner" struct to be contained in my custom iterator
pub struct Inner {
    text: String,
}

/// Then, the "CustomIterator" in question.  Notice that `Item` is `&'a Inner`.
pub struct CustomIterator<'a, I: Iterator<Item = &'a Inner>> {
    iter: I,
    _marker: PhantomData<&'a i8>,
}

/// Implementing Iterator for CustomIterator so as to define the `next()` function, as you do...
impl<'a, I: Iterator<Item = &'a Inner>> Iterator for CustomIterator<'a, I> {
    type Item = &'a Inner;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

/// Now, creating a custom trait definition called IterateMore that:
///   1. inherits Iterator
///   2. includes a default method called `more` which returns a `CustomIterator`
pub trait IterateMore<'a>: Iterator {
    type Item;
    fn more(self) -> CustomIterator<'a, Self>
    where
        Self: Sized;
}

/// Implementing `IterateMore` for an iterator of the specific type `Iterator<Item=&'a Inner>`
impl<'a, I: Iterator<Item = &'a Inner>> IterateMore<'a> for I
where
    I: Iterator,
{
    type Item = &'a Inner;
    fn more(self) -> CustomIterator<'a, Self>
    where
        Self: Sized,
    {
        CustomIterator {
            iter: self,
            _marker: PhantomData,
        }
    }
}

fn main() {
    let inner = Inner {
        text: "Hello world".to_string(),
    };
    let inners = vec![&inner];
    inners.iter().more().next();
}

(See it on repl.it)

Error

error[E0271]: type mismatch resolving `<Self as std::iter::Iterator>::Item == &'a Inner`
  --> src/main.rs:28:5
   |
28 | /     fn more(self) -> CustomIterator<'a, Self>
29 | |     where
30 | |         Self: Sized;
   | |____________________^ expected associated type, found reference
   |
   = note: expected type `<Self as std::iter::Iterator>::Item`
              found type `&'a Inner`
   = note: required by `CustomIterator`

Why is Item not being resolved here?  It is a bit frustrating as the compiler also complains if I try to set &'a Inner as the default Item type in the trait definition, saying:

error: associated type defaults are unstable (see issue #29661)

How could this be fixed or done differently?

Body:
It is unclear to me why you'd want to restrict the wrapped iterator to some custom type (given that you still have to write down the restriction every time you use the type, although that might change).  But perhaps your "real" next function does something funny.

PhantomData doesn't seem to be necessary (anymore) to "use" the lifetime when it is used in a where-clause.

IterateMore shouldn't have an Item associated type, given Iterator already has it.  (If you'd really need a new type pick a different name)

As IterateMore uses the CustomIterator type it needs to repeat the requirements, in this case Iterator<Item = &'a Inner> (that is what the type mismatch error is about); this is not the same as saying type Item = &'a Inner in the trait definition.

Playground

/// an "Inner" struct to be contained in my custom iterator
pub struct Inner {
    text: String,
}

pub struct CustomIterator<'a, I>
where
    I: Iterator<Item = &'a Inner>,
{
    iter: I,
}

impl<'a, I> Iterator for CustomIterator<'a, I>
where
    I: Iterator<Item = &'a Inner>,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

pub trait IterateMore<'a>: Iterator<Item = &'a Inner> + Sized {
    fn more(self) -> CustomIterator<'a, Self>;
}

impl<'a, I> IterateMore<'a> for I
where
    I: Iterator<Item = &'a Inner>,
{
    fn more(self) -> CustomIterator<'a, Self> {
        CustomIterator { iter: self }
    }
}

fn main() {
    let inner = Inner {
        text: "Hello world".to_string(),
    };
    let inners = vec![inner];
    inners.iter().more().next();
}

You could also remove the type restrictions everywhere like this (and only add it back in the place you actually need/want it):

Playground

pub struct CustomIterator<I> {
    iter: I,
}

impl<I> Iterator for CustomIterator<I>
where
    I: Iterator,
{
    type Item = I::Item;
    fn next(&mut self) -> Option<Self::Item> {
        println!("Custom next called");
        self.iter.next()
    }
}

pub trait IterateMore: Iterator + Sized {
    fn more(self) -> CustomIterator<Self>;
}

impl<I> IterateMore for I
where
    I: Iterator,
{
    fn more(self) -> CustomIterator<Self>
    {
        CustomIterator { iter: self }
    }
}

fn main() {
    let inners = vec!["Hello world".to_string()];
    inners.iter().more().next();
}


问:
php function to make plain line breaks into a list
I have a variable $boo that contains lines of plain text like (with singular line breaks):

a

b

c

I want a function to format it into a bullet list. Have come up with the following, but can't quiet get anything to output:

```<code><?php
function listformat ($list) {
    $listformat = explode("\n", $listformat);
    foreach ($listformat as $test => $line) {
        return "<li>".$line."</li>";
    };
};
?>

<ul>
<?php
listformat ($boo);
?>
</ul>
</code>```

It works if I use echo in place of "return" and remove the function.

答:
Simplest way:</p>

```<code>function ln2ul($string) {
  return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}
</code>```

Body:
I have a variable $boo that contains lines of plain text like (with singular line breaks):

a

b

c

I want a function to format it into a bullet list. Have come up with the following, but can't quiet get anything to output:

<?php
function listformat ($list) {
    $listformat = explode("\n", $listformat);
    foreach ($listformat as $test => $line) {
        return "
".$line."
";
    };
};
?>

<?php
listformat ($boo);
?>

It works if I use echo in place of "return" and remove the function.

Body:
Simplest way:

function ln2ul($string) {
  return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}


问:
Updating state on first render only?
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

```<code>import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}
</code>```

// Draggable

```<code>import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;
</code>```

// Output of console.log

```<code>START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}
</code>```

答:
According to the information provided by you, your onLayout function is called by the  component so its not included in the  component lifecycle process, so when the  component completes its lifecycle it goes into componentDidMount after mounting (which is not calling onLayout func) & thus changed the firstRender state to false and hence when you drag the component each time it goes from true to false.
I hope this explains</p>

Title: Updating state on first render only?

Body:
Using react-native, I'm creating sub-Components within the parent App and providing their position to the array this.state.objLocation within the parent App.

I can get the initial location data into the array straight after the render, but because my subcomponents are draggable, each time they re-render on drag, it adds a new position object to the array.

I'd like to avoid this, and I thought that creating this.state = { firstRender: true } in the constructor and then using componentDidMount = () => { this.setState({ firstRender: false }) } after the first render would allow me to create a 'gate' to stop the addition of the extra position objects.

I can see that if I comment out //componentDidMount = () => { this.setState({ firstRender: false }) } then I will get multiple entries to my array but if it's included in the class I get absolutely none.

So possibly my interpretation of the render lifecycle and componentDidMount is incorrect?

Here is my code.

// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

const dataArray = [{num: 1,id: 'A',},{num: 2,id: 'B',},{num: 3,id: 'Z',}]

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
            objLocation: [],
            firstRender: true,
        };
    }
    render(){
        return (
            <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                    <Text>Draggable Container</Text> {dataArray.map( d => { return(
                    <Draggable
                        id={d.id}
                        onLayout={ e=> this.onLayout(e)}
                        onPanResponderGrant={(dID) =>this.setState({ dID })}
                        onPanResponderRelease={() => this.setState({dID: null})} /> ) })}
                        <View style={[styles.findPoint ]} />
                </View>
                <View style={styles.infoBar}>
                    <Text>{this.state.dID ? this.state.dID : ''}</Text>{this.compFrame()}
                </View>
            </View>
        );
    }
    onLayout = (e) => {
      if ( e && this.state.firstRender) {
        const n = e.nativeEvent.layout;
            const position = {
              width: n.width,
              height: n.height,
              x: n.x,
              y: n.y
            }
        console.log(position);
        this.setState({
          objLocation: this.state.objLocation.concat([position])
        });
      }
    }
    componentWillMount = () => {
      console.log("START");
    }
    compFrame = () => {
      return(
        this.state.objLocation.map( d => {<View style={[styles.findPoint2,{left: d.x, top: d.y, width: d.width, height: d.height} ]} ></View>})
        )
    }
    componentDidMount = () => {
      this.setState({firstRender: true })
      console.log(this.state.objLocation.length);
    }
}

// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated } from 'react-native';
import styles from './styles';

class Draggable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.props.onPanResponderGrant(this.props.id);
      },
      onPanResponderMove: Animated.event([ null, {
          dx: this.state.pan.x,
          dy: this.state.pan.y,
        },
      ]),
      onPanResponderRelease: () => {
        Animated.spring(this.state.pan, { toValue: { x: 0, y: 0 } }).start();
        this.props.onPanResponderRelease();
      },
    });
  }
  render() {
    return (
      <Animated.View
        onLayout={ (e) => this.props.onLayout(e) }
        {...this.panResponder.panHandlers}
        style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
        <Text style={styles.textAlt}>Drag me!</Text>
        <Text style={styles.textNum}>{this.props.id}</Text>
      </Animated.View>
    );
  }
  componentDidMount = () => {
    this.props.onLayout(this.props.dragEvent)
  }
}
export default Draggable;

// Output of console.log

START xxx
0
{width:108,height:108,x:133.5,y:376.5}
{width:108,height:108,x:133.5,y:78.5}
{width:108,height:108,x:133.5,y:227.5}


问:
RCTBatchedBridge is deprecated and will be removed in a future React Native release
I am facing this warning in my react Native App, How to solve this any suggestion would be helpful.</p>

答:
I guess the ideal way is to refactor the module that uses RCTBatchedBridge to avoid the warning, but if this is out of your control you can hide the it with console.ignoredYellowBox:

```<code>console.ignoredYellowBox = ["RCTBatchedBridge is deprecated and will be removed in a future React Native release."];
</code>```

You can read more about it at: https://facebook.github.io/react-native/docs/debugging.html#warnings

Body:
I guess the ideal way is to refactor the module that uses RCTBatchedBridge to avoid the warning, but if this is out of your control you can hide the it with console.ignoredYellowBox:

console.ignoredYellowBox = ["RCTBatchedBridge is deprecated and will be removed in a future React Native release."];

You can read more about it at: https://facebook.github.io/react-native/docs/debugging.html#warnings


问:
JMS sending message
I want to publish message for which I am writing a JMS application which will publish messages to Tibco EMS queues. There are two queues one is for normal logging and another for exception logging. Now how to send message to two different queues in JMS. Can anyone help me with this as it is very critical?</p>

答:
The very basic JMS API code to send message to queue is shown below. You need to adjust the connection factory as well queue name as per your environment. Also need to adjust initial context settings.</p>

```<code>void sendMessage() {
    Connection con = null;
    try {

        // Get the initial context
        Hashtable<String, String> hTable = new Hashtable<String, String>();
        hTable.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        hTable.put(Context.PROVIDER_URL, "t3://localhost:7001");
        Context ctx = new InitialContext(hTable);

        // Create ConnectionFactory
        ConnectionFactory cf = (ConnectionFactory) ctx.lookup("JMS-JNDI-ConFactory");

        // Create connection
        con = cf.createConnection();

        // Create Non transacted Session with auto ack
        Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination
        Queue queue = (Queue) ctx.lookup("JMS-JNDI-Queue");

        // Create MessageProducer for the destination
        MessageProducer producer = session.createProducer(queue);

        // Create empty Message with header and properties only
        TextMessage message = session.createTextMessage();

        // set the message body
        message.setText("Message-1");

        // Send the message
        producer.send(message);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

Title: JMS sending message

Body:
The very basic JMS API code to send message to queue is shown below. You need to adjust the connection factory as well queue name as per your environment. Also need to adjust initial context settings.

void sendMessage() {
    Connection con = null;
    try {

        // Get the initial context
        Hashtable<String, String> hTable = new Hashtable<String, String>();
        hTable.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        hTable.put(Context.PROVIDER_URL, "t3://localhost:7001");
        Context ctx = new InitialContext(hTable);

        // Create ConnectionFactory
        ConnectionFactory cf = (ConnectionFactory) ctx.lookup("JMS-JNDI-ConFactory");

        // Create connection
        con = cf.createConnection();

        // Create Non transacted Session with auto ack
        Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination
        Queue queue = (Queue) ctx.lookup("JMS-JNDI-Queue");

        // Create MessageProducer for the destination
        MessageProducer producer = session.createProducer(queue);

        // Create empty Message with header and properties only
        TextMessage message = session.createTextMessage();

        // set the message body
        message.setText("Message-1");

        // Send the message
        producer.send(message);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}


问:
Robot keys not working when using it after implicit wait
Robot keys not working when using it after implicit wait. If I use thread.sleep instead of implicit sleep the same code working fine. But it is not best practice to use thread.sleep. So give me a solution for this problem.

```<code>searchbox.sendKeys(sFirstName);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
Utils.keyEnter();
</code>```

The code in Utils package is:

```<code>public static void keyEnter() throws Exception
{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_ENTER);
    r.keyRelease(KeyEvent.VK_ENTER);
}
</code>```

答:
You are mixing two entirely different testdrivers. Selenium Webdriver and java.awt.Robot which is hardly a good idea. The driver object does not know anything about the robot object and vice versa. This means that calling an implicit wait on driver, does not affect the robot object at all.

Also, note that the empty constructor on java.awt.Robot

Constructs a Robot object in the coordinate system of the primary
  screen.

And the primary screen in your case is most probably not the browser window the driver object operates on. That is why nothing seems to happen.

Body:
Robot keys not working when using it after implicit wait. If I use thread.sleep instead of implicit sleep the same code working fine. But it is not best practice to use thread.sleep. So give me a solution for this problem.

searchbox.sendKeys(sFirstName);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
Utils.keyEnter();

The code in Utils package is:

public static void keyEnter() throws Exception
{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_ENTER);
    r.keyRelease(KeyEvent.VK_ENTER);
}


问:
Cursor pointer not showing when using an SVG image in Internet Explorer
When using this html:

```<code><a href="http://www.wikipedia.com">
    <object data="http://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg" type="image/svg+xml">
        <img src="http://herdeirodocaos.files.wordpress.com/2007/11/wikipedia-logo.jpg" alt="Logo" />
    </object>
</a>
</code>```

Combined with this css:

```<code>a {
    display: block;
}
object, img {
    width: 200px;
    height: 200px;
}

object:hover {
    cursor: pointer;
}
</code>```

JsFiddle

The cursor doesn't change to a pointer (hand) when the mouse is over the image in Internet Explorer only

Any idea?

答:
Try adding this to your CSS:

```<code>object{
    pointer-events: none;
}
</code>```

Body:
When using this html:

    <object data="http://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg" type="image/svg+xml">

    </object>

Combined with this css:

a {
    display: block;
}
object, img {
    width: 200px;
    height: 200px;
}

object:hover {
    cursor: pointer;
}

JsFiddle

The cursor doesn't change to a pointer (hand) when the mouse is over the image in Internet Explorer only

Any idea?

Body:
Try adding this to your CSS:

object{
    pointer-events: none;
}


问:
Organize list of object in java
I have a class

```<code>public class ProductStock {

   private Long id;
   private Integer quantity;

}
</code>```

and a list like

```<code>List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}
</code>```

I want to group productStocks by id.
What is the best way to convert this list like bellow

```<code>productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
</code>```

答:
You can group the products by iterating the List and add products to LinkedHashMap to preserve order:</p>

```<code>void mergeProducts() {
    Map<Long, Integer> pMap = new HashMap<Long, Integer>();
    for (ProductStock ps :  productStocks) {
        if (pMap.containsKey(ps.getId())) {
            int qty = pMap.get(ps.getId());
            qty += ps.getQuantity();
            pMap.put(ps.getId(), qty);
        } else {
            pMap.put(ps.getId(), ps.getQuantity());
        }
    }

    System.out.println("Product grouping: ");
    for (Map.Entry<Long, Integer> entry : pMap.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}
</code>```

Title: Organize list of object in java

Body:
I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and a list like

List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}

I want to group productStocks by id.
What is the best way to convert this list like bellow

productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}

Body:
You can group the products by iterating the List and add products to LinkedHashMap to preserve order:

void mergeProducts() {
    Map<Long, Integer> pMap = new HashMap<Long, Integer>();
    for (ProductStock ps :  productStocks) {
        if (pMap.containsKey(ps.getId())) {
            int qty = pMap.get(ps.getId());
            qty += ps.getQuantity();
            pMap.put(ps.getId(), qty);
        } else {
            pMap.put(ps.getId(), ps.getQuantity());
        }
    }

    System.out.println("Product grouping: ");
    for (Map.Entry<Long, Integer> entry : pMap.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}


问:
Android studio Firebase and Github pushing and cloning
I have created a small project for user register and login in(Authentication) android studio using firebase and it was working fine. Basically i need to keep this project on github, I have moved to project to my desktop and then pushed it to github. My version of the project works, however, the cloned project doesn't seem to work as it just keeps loading when the user wants to register or login.

Also, it comes up with some errors like missing iml's or that the app has multiple slice apk's and need to uninstall.

My question is what steps do I need to undertake to make sure that the application will work when pushed to a github repo and then cloned back from the repo, so that the application runs when downloaded on any pc, and do i have to do anything to the firebase?

since what i see is that everything is in place, package name hasnt changed, all files and dependencies are present.

答:
First of all you didn't specify what authentication you are using. For example if you are using facebook you need to add to the Facebook developers page the sha1 key fingerprint for each device you are going to install the app.

Secondly I have deployed my firebase project to github and working from my mac and windows machine without any problem syncing with Firebase. In firebase project settings as I can see I haven't added any SHA certificate fingerprint.

Make sure that you have added on Github all the SHA certificate fingerprint from any pc that you are planning to clone the project.


问:
Make child height update height of his siblings
Is there any way to define childHeight as more important than its siblings and propagate its size to (less important) siblings.

Consider this layout

```<code><RelativeLayout
  match_parent,match_parent>

    <FrameLayout
      match_parent,match_parent>

        <ViewA
          this view size is important and its siblings should have same size, set on Runtime.
          layout_gravity="center"/>

        <ViewB
          match_parent,match_parent
          layout_gravity="center"
          (should have the size of ViewB)  />

    </FrameLayout>

</RelativeLayout>
</code>```

I know how to do it using ConstrainLayout but I am asking just out of curiosity

```<code><ConstraintLayout>
      <ViewA
       wrap_content,wrap_content
       constraint_to="parent"/>

       <ViewB
          0dp,0dp
          constraint_to="ViewA"
          layout_gravity="center"
          (should have the size of ViewA)  />
</ConstraintLayout>
</code>```

Use case I have cameraView (ViewA) and cameraOverlay (ViewB). ViewA changes it's size according to user preference (16:9 | 4:3...) and ViewB (has some alpha) must always overlap whole ViewA.

Edit: Forgot to add that I don't want to change size of viewB manually

答:
I understand that you change the height/width of viewA programmatically. So you have the height and width resources available.

To others who have the same problem, to set the height of the View:

```<code>viewB.getLayoutParams().height = heightViewA;
viewB.getLayoutParams().width = widthViewB;
</code>```

Hope this helps.

Important. If you're setting the height after the layout has already been 'laid out', make sure you also call:

```<code>viewB.requestLayout()
</code>```

Another option is to use
RelativeLayout

```<code><RelativeLayout
       wrap_content,wrap_content
>
      <ViewA
       wrap_content,wrap_content
       constraint_to="parent"/>

       <ViewB
          match_parent,match_parent
          constraint_to="ViewA"
          layout_gravity="center"
          (should have the size of ViewA)  />
</RelativeLayout>
</code>```

And in RelativeLayout  you can overlay them.

Body:
Is there any way to define childHeight as more important than its siblings and propagate its size to (less important) siblings.

Consider this layout

<RelativeLayout
  match_parent,match_parent>

    <FrameLayout
      match_parent,match_parent>

        <ViewA
          this view size is important and its siblings should have same size, set on Runtime.
          layout_gravity="center"/>

        <ViewB
          match_parent,match_parent
          layout_gravity="center"
          (should have the size of ViewB)  />

    </FrameLayout>

</RelativeLayout>

I know how to do it using ConstrainLayout but I am asking just out of curiosity

<ConstraintLayout>
      <ViewA
       wrap_content,wrap_content
       constraint_to="parent"/>

       <ViewB
          0dp,0dp
          constraint_to="ViewA"
          layout_gravity="center"
          (should have the size of ViewA)  />
</ConstraintLayout>

Use case I have cameraView (ViewA) and cameraOverlay (ViewB). ViewA changes it's size according to user preference (16:9 | 4:3...) and ViewB (has some alpha) must always overlap whole ViewA.

Edit: Forgot to add that I don't want to change size of viewB manually

Body:
I understand that you change the height/width of viewA programmatically. So you have the height and width resources available.

To others who have the same problem, to set the height of the View:

viewB.getLayoutParams().height = heightViewA;
viewB.getLayoutParams().width = widthViewB;

Hope this helps.

Important. If you're setting the height after the layout has already been 'laid out', make sure you also call:

viewB.requestLayout()

Another option is to use
RelativeLayout

<RelativeLayout
       wrap_content,wrap_content
>
      <ViewA
       wrap_content,wrap_content
       constraint_to="parent"/>

       <ViewB
          match_parent,match_parent
          constraint_to="ViewA"
          layout_gravity="center"
          (should have the size of ViewA)  />
</RelativeLayout>

And in RelativeLayout  you can overlay them.


问:
Add column to the right jQuery table
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body></code>```

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

```<code>Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds
</code>```

and not like this :

```<code>Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg
</code>```

Can someone please give me a little help with this.

答:
Your code is not working because you have to add the new td´s for each existing tr, to make this you could make an array and then loop it, like this:

$(document).ready(function() {
  $(".get_attr").click(function() {
    var cont = 1;
    var val = ["sdfg1	", "sdfg2	", "sdf3g	", "sdfg4	"];

    $("tr:first").append("Class	");
    for(var i in val){
      $("tr").eq(cont).append(val[i]);
      cont++;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table border="1" class='optionsForm'>
  <tr><th>Name</th></tr>
  <tr><td>sdg</td></tr>
  <tr><td>sdfg</td></tr>
  <tr><td>sdgds</td></tr>
</table>

<button type="button" data-id="5" class="get_attr" >Click Me</button></code>```

Title: Add column to the right jQuery table

Body:
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});

Name

sdg

sdfg

sdgds

  <button type="button" data-id="5" class="get_attr" >Click Me</button>

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds

and not like this :

Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg

Can someone please give me a little help with this.

Body:
Your code is not working because you have to add the new td´s for each existing tr, to make this you could make an array and then loop it, like this:

$(document).ready(function() {
  $(".get_attr").click(function() {
    var cont = 1;
    var val = ["<td>sdfg1</td>", "<td>sdfg2</td>", "<td>sdf3g</td>", "<td>sdfg4</td>"];

    $("tr:first").append("<th>Class</th>");
    for(var i in val){
      $("tr").eq(cont).append(val[i]);
      cont++;
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table border="1" class='optionsForm'>
  <tr><th>Name</th></tr>
  <tr><td>sdg</td></tr>
  <tr><td>sdfg</td></tr>
  <tr><td>sdgds</td></tr>
</table>

<button type="button" data-id="5" class="get_attr" >Click Me</button>


问:
mysql query returns undefined in nodeJS
This code returns an error because 'results(mysql.query)' returns undefined value. I have created a database table of 7~10 rows using mysql command shell and the database works perfectly from both workbench and command shell. is it because I have installed mysql in a wrong way? or code fault? I have tested the very same stuff in a  different computer and it worked perfectly from there and suddenly it doesn't work. I didn't copy the file, just wrote/typed the same stuff from memory.

I have searched stackoverflow already and it seems everybody talks about async problem, which isn't really the one in my case.(same thing worked before)

used npm install mysql,
mysql version is community 5.7

crudserver.js(main file)

```<code>const fs = require("fs"); //filesystem
const ejs = require("ejs");
const mysql = require("mysql");
const express = require("express"); //handles all the middlewares
const bodyParser = require("body-parser"); //handles "POST"

const client = mysql.createConnection({
  user:"****",
  password:"****",
  database:"testdb"
});

let app = express();
app.use(bodyParser.urlencoded({
  extended:false
}));

app.listen(52273, function(){
  console.log("server running at http://127.0.0.1:52273");
});

app.get("/",function (request,response){
  fs.readFile("crudlist.ejs","utf8",function(error,data){
    client.query("SELECT * FROM products", function(error,results){
      response.send(ejs.render(data,{
        data:results,
        mytitle:"title1",
        mytitlesub:"title2"
      }));
    });
  });
});
</code>```

crudlist.ejs

```<code> <% data.forEach(function (itm,index){ %>
 some codes....
 <% } >
</code>```

and it says the 'data' is undefined.

Cannot read property 'forEach' of undefined
    at eval (eval at compile (F:\mycoding\node_modules\ejs\lib\ejs.js:549:12), :17:12)
    at returnedFn (F:\mycoding\node_modules\ejs\lib\ejs.js:580:17)
    at Object.exports.render (F:\mycoding\node_modules\ejs\lib\ejs.js:384:37)
    at Query._callback (F:\mycoding\crudserver.js:25:25)
    at Query.Sequence.end (F:\mycoding\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:398:18
    at Array.forEach (native)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:397:13
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

答:
If data is undefined, you most likely have an error that you decided not to handle:

```<code>// note the first parameter of callback function - "error"
client.query("SELECT * FROM products", function(error,results){
</code>```

You should test whether or not the error exists, and render the results only if it doesn't.

Title: mysql query returns undefined in nodeJS

Body:
This code returns an error because 'results(mysql.query)' returns undefined value. I have created a database table of 7~10 rows using mysql command shell and the database works perfectly from both workbench and command shell. is it because I have installed mysql in a wrong way? or code fault? I have tested the very same stuff in a  different computer and it worked perfectly from there and suddenly it doesn't work. I didn't copy the file, just wrote/typed the same stuff from memory.

I have searched stackoverflow already and it seems everybody talks about async problem, which isn't really the one in my case.(same thing worked before)

used npm install mysql,
mysql version is community 5.7

crudserver.js(main file)

const fs = require("fs"); //filesystem
const ejs = require("ejs");
const mysql = require("mysql");
const express = require("express"); //handles all the middlewares
const bodyParser = require("body-parser"); //handles "POST"

const client = mysql.createConnection({
  user:"****",
  password:"****",
  database:"testdb"
});

let app = express();
app.use(bodyParser.urlencoded({
  extended:false
}));

app.listen(52273, function(){
  console.log("server running at http://127.0.0.1:52273");
});

app.get("/",function (request,response){
  fs.readFile("crudlist.ejs","utf8",function(error,data){
    client.query("SELECT * FROM products", function(error,results){
      response.send(ejs.render(data,{
        data:results,
        mytitle:"title1",
        mytitlesub:"title2"
      }));
    });
  });
});

crudlist.ejs

 <% data.forEach(function (itm,index){ %>
 some codes....
 <% } >

and it says the 'data' is undefined.

Cannot read property 'forEach' of undefined
    at eval (eval at compile (F:\mycoding\node_modules\ejs\lib\ejs.js:549:12), :17:12)
    at returnedFn (F:\mycoding\node_modules\ejs\lib\ejs.js:580:17)
    at Object.exports.render (F:\mycoding\node_modules\ejs\lib\ejs.js:384:37)
    at Query._callback (F:\mycoding\crudserver.js:25:25)
    at Query.Sequence.end (F:\mycoding\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:398:18
    at Array.forEach (native)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:397:13
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Body:
If data is undefined, you most likely have an error that you decided not to handle:

// note the first parameter of callback function - "error"
client.query("SELECT * FROM products", function(error,results){

You should test whether or not the error exists, and render the results only if it doesn't.


问:
How to do paging on Object that isn't Entity?
I'm trying to do paging, very similar to the option of @RepositoryRestResource
but only on object that isn't Entity.

the code:

```<code>public class FloorplanDevice {

private String FloorplanName;
private Long FloorplanId;

private Long DeviceId;
private String DeviceName;
private String macAddress;
private Long groupId;
private LocatableType deviceType;

public String getFloorplanName() {
    return FloorplanName;
}

public void setFloorplanName(String floorplanName) {
    FloorplanName = floorplanName;
}

public Long getFloorplanId() {
    return FloorplanId;
}

public void setFloorplanId(Long floorplanId) {
    FloorplanId = floorplanId;
}

public Long getDeviceId() {
    return DeviceId;
}

public void setDeviceId(Long deviceId) {
    DeviceId = deviceId;
}

public String getDeviceName() {
    return DeviceName;
}

public void setDeviceName(String deviceName) {
    DeviceName = deviceName;
}

public String getMacAddress() {
    return macAddress;
}

public void setMacAddress(String macAddress) {
    this.macAddress = macAddress;
}

public Long getGroupId() {
    return groupId;
}

public void setGroupId(Long groupId) {
    this.groupId = groupId;
}

public LocatableType getDeviceType() {
    return deviceType;
}

public void setDeviceType(LocatableType deviceType) {
    this.deviceType = deviceType;
}

public FloorplanDevice() {
}

public FloorplanDevice(String floorplanName, Long floorplanId, Long deviceId, String deviceName, String macAddress, Long groupId, LocatableType deviceType) {
    FloorplanName = floorplanName;
    FloorplanId = floorplanId;
    DeviceId = deviceId;
    DeviceName = deviceName;
    this.macAddress = macAddress;
    this.groupId = groupId;
    this.deviceType = deviceType;
  }
}
</code>```

This object doesn't have Repository but it has controller:

```<code>   @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}", "/floorplanDevice/{groupId}/"),
      method = arrayOf(RequestMethod.GET))
 open fun getFloorplanDevice(@PathVariable("groupId") groupId: Long): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
return ResponseEntity(floorplanDevice, HttpStatus.OK)

 }
</code>```

So how can I do Paging to this object with page number and size (if it possible sorting also)?

I'm using java Spring

Thank you

答:
Solution:
This is my solution by using PageListHolder.

```<code>     @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}/page/{pageNum}/size/{sizeNum}", "/floorplanDevice/{groupId}/page/{pageNum}/size/{sizeNum}/"),
      method = arrayOf(RequestMethod.GET))
open fun getFloorplanDevicePage(@PathVariable("groupId") groupId: Long, @PathVariable("pageNum") pageNum: Int,@PathVariable("sizeNum") sizeNum: Int): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
var paging= PagedListHolder<FloorplanDevice>(floorplanDevice)
var setsize= paging.setPageSize(sizeNum)
if(paging.pageCount>pageNum){
var setpage=paging.setPage(pageNum)}
else{
  return throw RuntimeException("page: $pageNum is too big, insert smaller page from 0 to ${paging.pageCount-1}")
  }
var pageList= paging.pageList
return ResponseEntity(pageList, HttpStatus.OK)

}
</code>```

Body:
I'm trying to do paging, very similar to the option of @RepositoryRestResource
but only on object that isn't Entity.

the code:

public class FloorplanDevice {

private String FloorplanName;
private Long FloorplanId;

private Long DeviceId;
private String DeviceName;
private String macAddress;
private Long groupId;
private LocatableType deviceType;

public String getFloorplanName() {
    return FloorplanName;
}

public void setFloorplanName(String floorplanName) {
    FloorplanName = floorplanName;
}

public Long getFloorplanId() {
    return FloorplanId;
}

public void setFloorplanId(Long floorplanId) {
    FloorplanId = floorplanId;
}

public Long getDeviceId() {
    return DeviceId;
}

public void setDeviceId(Long deviceId) {
    DeviceId = deviceId;
}

public String getDeviceName() {
    return DeviceName;
}

public void setDeviceName(String deviceName) {
    DeviceName = deviceName;
}

public String getMacAddress() {
    return macAddress;
}

public void setMacAddress(String macAddress) {
    this.macAddress = macAddress;
}

public Long getGroupId() {
    return groupId;
}

public void setGroupId(Long groupId) {
    this.groupId = groupId;
}

public LocatableType getDeviceType() {
    return deviceType;
}

public void setDeviceType(LocatableType deviceType) {
    this.deviceType = deviceType;
}

public FloorplanDevice() {
}

public FloorplanDevice(String floorplanName, Long floorplanId, Long deviceId, String deviceName, String macAddress, Long groupId, LocatableType deviceType) {
    FloorplanName = floorplanName;
    FloorplanId = floorplanId;
    DeviceId = deviceId;
    DeviceName = deviceName;
    this.macAddress = macAddress;
    this.groupId = groupId;
    this.deviceType = deviceType;
  }
}

This object doesn't have Repository but it has controller:

   @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}", "/floorplanDevice/{groupId}/"),
      method = arrayOf(RequestMethod.GET))
 open fun getFloorplanDevice(@PathVariable("groupId") groupId: Long): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
return ResponseEntity(floorplanDevice, HttpStatus.OK)

 }

So how can I do Paging to this object with page number and size (if it possible sorting also)?

I'm using java Spring

Thank you

Body:
Solution:
This is my solution by using PageListHolder.

     @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}/page/{pageNum}/size/{sizeNum}", "/floorplanDevice/{groupId}/page/{pageNum}/size/{sizeNum}/"),
      method = arrayOf(RequestMethod.GET))
open fun getFloorplanDevicePage(@PathVariable("groupId") groupId: Long, @PathVariable("pageNum") pageNum: Int,@PathVariable("sizeNum") sizeNum: Int): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
var paging= PagedListHolder<FloorplanDevice>(floorplanDevice)
var setsize= paging.setPageSize(sizeNum)
if(paging.pageCount>pageNum){
var setpage=paging.setPage(pageNum)}
else{
  return throw RuntimeException("page: $pageNum is too big, insert smaller page from 0 to ${paging.pageCount-1}")
  }
var pageList= paging.pageList
return ResponseEntity(pageList, HttpStatus.OK)

}


问:
modify checkbox using javascript
I had declared 5 checkboxes with name and id attribute in a html:

```<code><input type="checkbox" name="category" value="One" id=11>One<br/>
<input type="checkbox" name="category" value="Two" id=12>Two<br/>
<input type="checkbox" name="category" value="Three" id=13>Three<br/>
<input type="checkbox" name="category" value="Four" id=14>Four<br/>
</code>```

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.

答:
try

```<code>   document.myform.box1.checked = true;
</code>```

or

```<code>document.getElementById('myid').checked = true;
</code>```

see an full example : http://www.rgagnon.com/jsdetails/js-0007.html

Title: modify checkbox using javascript

Body:
I had declared 5 checkboxes with name and id attribute in a html:

<input type="checkbox" name="category" value="One" id=11>One

<input type="checkbox" name="category" value="Two" id=12>Two

<input type="checkbox" name="category" value="Three" id=13>Three

<input type="checkbox" name="category" value="Four" id=14>Four

After declaration, I want to run a javascript that would enable the checkbox1 using that checkbox id.

Let me know to clarify something.

Body:
try

   document.myform.box1.checked = true;

or

document.getElementById('myid').checked = true;

see an full example : http://www.rgagnon.com/jsdetails/js-0007.html


问:
How do I map an array field to multiple columns in a WinForms DataGridView using a DataSource binding?
I have a class like this:

```<code>public class PricingRecord
{
    private string _name;
    private float[] _prices;

    public PricingRecord(string name, float[] prices)
    {
        _name = name;
        _prices = prices;
    }

    [DisplayName("Name")]
    public string PricingName => _name;

    public float[] Prices => _prices;
}
</code>```

I want to map "Prices" to "Price 1", "Price 2", etc. columns in a DataGridView. I can get the columns to appear, but don't know how to make the mapping work.

Here's the main window:

```<code>public partial class MainForm : Form
{
    private int _numPricingColumns;
    private BindingList<PricingRecord> _records;

    public MainForm()
    {
        InitializeComponent();

        SetupPricingData();
        SetupGridView();
    }

    private void SetupPricingData()
    {
        _records = new BindingList<PricingRecord>();

        for (int i = 0; i < 100; i++)
        {
            var pricing = new PricingRecord($"Name {i + 1}", new [] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f });
            _records.Add(pricing);
        }

        _numPricingColumns = _records[0].Prices.Length;

        GridView.DataSource = _records;
    }

    private void SetupGridView()
    {
        //GridView.AutoGenerateColumns = false;

        //DataGridViewColumn column = new DataGridViewTextBoxColumn
        //{
        //    Name = "Name",
        //    DataPropertyName = "PricingName"
        //};
        //GridView.Columns.Add(column);

        for (int i = 0; i < _numPricingColumns; i++)
        {
            DataGridViewColumn column = new DataGridViewTextBoxColumn
            {
                Name = $"Price {i + 1}",
                DataPropertyName = $"Price{i + 1}"
            };
            GridView.Columns.Add(column);
        }
    }
}
</code>```

If I don't use BindingView I can set it up all by hand, but then I have to maintain the rows and columns myself. I'd like to use BindingView but this doesn't seem to support mapping many columns to an array.

答: A faster and more flexible solution proved to be dropping BindingList and directly poking the cells in the grid. The need to map an array field to multiple columns becomes moot as it's done by hand.</p>

Body:
I have a class like this:

public class PricingRecord
{
    private string _name;
    private float[] _prices;

    public PricingRecord(string name, float[] prices)
    {
        _name = name;
        _prices = prices;
    }

    [DisplayName("Name")]
    public string PricingName => _name;

    public float[] Prices => _prices;
}

I want to map "Prices" to "Price 1", "Price 2", etc. columns in a DataGridView. I can get the columns to appear, but don't know how to make the mapping work.

Here's the main window:

public partial class MainForm : Form
{
    private int _numPricingColumns;
    private BindingList<PricingRecord> _records;

    public MainForm()
    {
        InitializeComponent();

        SetupPricingData();
        SetupGridView();
    }

    private void SetupPricingData()
    {
        _records = new BindingList<PricingRecord>();

        for (int i = 0; i < 100; i++)
        {
            var pricing = new PricingRecord($"Name {i + 1}", new [] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f });
            _records.Add(pricing);
        }

        _numPricingColumns = _records[0].Prices.Length;

        GridView.DataSource = _records;
    }

    private void SetupGridView()
    {
        //GridView.AutoGenerateColumns = false;

        //DataGridViewColumn column = new DataGridViewTextBoxColumn
        //{
        //    Name = "Name",
        //    DataPropertyName = "PricingName"
        //};
        //GridView.Columns.Add(column);

        for (int i = 0; i < _numPricingColumns; i++)
        {
            DataGridViewColumn column = new DataGridViewTextBoxColumn
            {
                Name = $"Price {i + 1}",
                DataPropertyName = $"Price{i + 1}"
            };
            GridView.Columns.Add(column);
        }
    }
}

If I don't use BindingView I can set it up all by hand, but then I have to maintain the rows and columns myself. I'd like to use BindingView but this doesn't seem to support mapping many columns to an array.


问:
Django - Reducing duplicate context code in the view
Say I have a view function like so:

```<code>def check_view(request):
    if user.is_authenticated:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variablec':c}
    else:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variabled':d}
</code>```

Is there any way to only write the context variables just one time (given that there some similar variables for both conditions), but the variables that are different can be written under their own parent conditions?

So variable C will belong to the if statement and D to the else, whereas both variables A and B can be written once but apply to both the if and else statement....

Note how the last variable for each condition is different (c and d)

Thanks

答:
It's just a dictionary, so set the ones that are consistent across all of the conditions, and then add the other one in in your if/else logic. </p>

```<code>def check_view(request):
    context = {'variablea':a, 'variableb':b}
    if user.is_authenticated:
        context['variablec'] = c
    else:
        context['variabled'] = d

    return render(request, 'user-template.html', context)
</code>```

Body:
Say I have a view function like so:

def check_view(request):
    if user.is_authenticated:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variablec':c}
    else:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variabled':d}

Is there any way to only write the context variables just one time (given that there some similar variables for both conditions), but the variables that are different can be written under their own parent conditions?

So variable C will belong to the if statement and D to the else, whereas both variables A and B can be written once but apply to both the if and else statement....

Note how the last variable for each condition is different (c and d)

Thanks

Body:
It's just a dictionary, so set the ones that are consistent across all of the conditions, and then add the other one in in your if/else logic.

def check_view(request):
    context = {'variablea':a, 'variableb':b}
    if user.is_authenticated:
        context['variablec'] = c
    else:
        context['variabled'] = d

    return render(request, 'user-template.html', context)


问:
Formatting Floating Point Numbers
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

```<code>2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120
</code>```

I tried using DecimalFormatter, Am i doing it wrong?

```<code>DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
</code>```

Thanks. :)

答:
Use NumberFormat class.

Example:

```<code>    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));
</code>```

Output will be 2.5, not 2.500.

Title: Formatting Floating Point Numbers

Body:
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

I tried using DecimalFormatter, Am i doing it wrong?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)

Body:
Use NumberFormat class.

Example:

    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));

Output will be 2.5, not 2.500.


问:
Is Inline adding of a row is possible in Primeng Datatable
I need to enable inline adding of a row to primeng datatble. Please help. I need to add new row of text boxes or combination of text boxes and selection lists as a new row to prime ng datatable upon clicking add new button instead of opening pop up and accepting values

App.component.html:-

```<code><div>
    <p-dataTable [value]="cars" [editable]="true" [paginator]="true" [rows]="10" [responsive]="true">
       <header>CRUD for Cars</header>
        <p-column field="vin" header="Vin" [sortable]="true" [editable]="true"></p-column>
        <p-column field="year" header="Year" [sortable]="true" [editable]="true"></p-column>
        <p-column field="brand" header="Brand" [sortable]="true" [editable]="true"></p-column>
        <p-column field="color" header="Color" [sortable]="true" [editable]="true"></p-column>
        <footer><div class="ui-helper-clearfix" style="width:100%"><button type="button" pButton icon="fa-plus" style="float:left" (click)="showDialogToAdd()" label="Add"></button></div></footer>
    </p-dataTable>

    <p-dialog header="Car Details" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true">
        <div class="ui-grid ui-grid-responsive ui-fluid ui-grid-pad" *ngIf="car">
            <div class="ui-grid-row">
                <div class="ui-grid-col-4"><label for="vin">Vin</label></div>
                <div class="ui-grid-col-8"><input pInputText id="vin" [(ngModel)]="car.vin" /></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-4"><label for="brand">Year</label></div>
                <div class="ui-grid-col-8"><input pInputText id="brand" [(ngModel)]="car.year" /></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-4"><label for="brand">Brand</label></div>
                <div class="ui-grid-col-8"><input pInputText id="brand" [(ngModel)]="car.brand" /></div>
            </div>
            <div class="ui-grid-row">
                <div class="ui-grid-col-4"><label for="color">Color</label></div>
                <div class="ui-grid-col-8"><input pInputText id="color" [(ngModel)]="car.color" /></div>
            </div>
        </div>
        <footer>
            <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
                <button type="button" pButton icon="fa-close" (click)="delete()" label="Delete"></button>
                <button type="button" pButton icon="fa-check" (click)="save()" label="Save"></button>
            </div>
        </footer>
    </p-dialog>
</div>
</code>```

app.component.ts:-

```<code>import {Component} from '@angular/core';
import {Car} from './cars/car';
import {CarService} from './cars/carservice';

class PrimeCar implements Car {
    constructor(public vin?, public year?, public brand?, public color?) {}
}

@Component({
    templateUrl: 'app/app.component.html',
    selector: 'my-app'
})
export class AppComponent {

    displayDialog: boolean;

    car: Car = new PrimeCar();

    selectedCar: Car;

    newCar: boolean;

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars = cars);
    }

    showDialogToAdd() {
        this.newCar = true;
        this.car = new PrimeCar();
        this.displayDialog = true;
    }

    save() {
        if(this.newCar)
            this.cars.push(this.car);
        else
            this.cars[this.findSelectedCarIndex()] = this.car;

        this.car = null;
        this.displayDialog = false;
    }

    delete() {
        this.cars.splice(this.findSelectedCarIndex(), 1);
        this.car = null;
        this.displayDialog = false;
    }

    onRowSelect(event) {
        this.newCar = false;
        this.car = this.cloneCar(event.data);
        this.displayDialog = true;
    }

    cloneCar(c: Car): Car {
        let car = new PrimeCar();
        for(let prop in c) {
            car[prop] = c[prop];
        }
        return car;
    }

    findSelectedCarIndex(): number {
        return this.cars.indexOf(this.selectedCar);
    }
}
</code>```

答:
You can programmatically add an item to the array that you're using behind the scenes, which in your case is cars.

```<code>addRow() {
    const newCar = {
      vin: '123',
      year: '1902',
      brand: 'Ford',
      color: 'brown'
    };
    this.cars.push(newCar);
    this.cars = this.cars.slice();
  }
</code>```

I found that I had to add the .slice() operation at the end in order to get the data-table to refresh in the browser.  I believe the issue there had to do with change detection, but I don't recall 100%.

Footnote: I believe there is probably a more elegant and controlled way of adding items "inline" like you're looking for, but I'm still working on coming up with a solution on that myself.

Body:
I need to enable inline adding of a row to primeng datatble. Please help. I need to add new row of text boxes or combination of text boxes and selection lists as a new row to prime ng datatable upon clicking add new button instead of opening pop up and accepting values

App.component.html:-

       CRUD for Cars

<button type="button" pButton icon="fa-plus" style="float:left" (click)="showDialogToAdd()" label="Add"></button>

Vin

<input pInputText id="vin" [(ngModel)]="car.vin" />

Year

<input pInputText id="brand" [(ngModel)]="car.year" />

Brand

<input pInputText id="brand" [(ngModel)]="car.brand" />

Color

<input pInputText id="color" [(ngModel)]="car.color" />

                <button type="button" pButton icon="fa-close" (click)="delete()" label="Delete"></button>
                <button type="button" pButton icon="fa-check" (click)="save()" label="Save"></button>

app.component.ts:-

import {Component} from '@angular/core';
import {Car} from './cars/car';
import {CarService} from './cars/carservice';

class PrimeCar implements Car {
    constructor(public vin?, public year?, public brand?, public color?) {}
}

@Component({
    templateUrl: 'app/app.component.html',
    selector: 'my-app'
})
export class AppComponent {

    displayDialog: boolean;

    car: Car = new PrimeCar();

    selectedCar: Car;

    newCar: boolean;

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars = cars);
    }

    showDialogToAdd() {
        this.newCar = true;
        this.car = new PrimeCar();
        this.displayDialog = true;
    }

    save() {
        if(this.newCar)
            this.cars.push(this.car);
        else
            this.cars[this.findSelectedCarIndex()] = this.car;

        this.car = null;
        this.displayDialog = false;
    }

    delete() {
        this.cars.splice(this.findSelectedCarIndex(), 1);
        this.car = null;
        this.displayDialog = false;
    }

    onRowSelect(event) {
        this.newCar = false;
        this.car = this.cloneCar(event.data);
        this.displayDialog = true;
    }

    cloneCar(c: Car): Car {
        let car = new PrimeCar();
        for(let prop in c) {
            car[prop] = c[prop];
        }
        return car;
    }

    findSelectedCarIndex(): number {
        return this.cars.indexOf(this.selectedCar);
    }
}

Body:
You can programmatically add an item to the array that you're using behind the scenes, which in your case is cars.

addRow() {
    const newCar = {
      vin: '123',
      year: '1902',
      brand: 'Ford',
      color: 'brown'
    };
    this.cars.push(newCar);
    this.cars = this.cars.slice();
  }

I found that I had to add the .slice() operation at the end in order to get the data-table to refresh in the browser.  I believe the issue there had to do with change detection, but I don't recall 100%.

Footnote: I believe there is probably a more elegant and controlled way of adding items "inline" like you're looking for, but I'm still working on coming up with a solution on that myself.


问:
jqPlot - bar chart - always color only highest value
I have a page that has a bar chart that updates when a user clicks on table rows from a data table that is updated via ajax calls.

EG: the plot data is not fixed.

I need to always color the largest value / highest bar, in orange. Obviously, the highest bar could be any one of the bars in the plot.

How is this possible to do, in an efficient way with jqplot?

I have seen examples with bars colored in various series colors, but I need one color only, with all bars being blue except for the largest value, which needs to be orange.

I cant see any way to do this.

答:
I came up with a solution to this and got this working. It isn't very elegant, but it works!

The bar colours are just an array, so how I did this was to...

1) Colour all bars the same

```<code> var colorArray = ['#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5'];
</code>```

2) Find the max data value

```<code> var maxValue = Math.max(data01,data02,data03,data04,data05,data06,data07);
</code>```

3) Change the colour array value if the data is the maximum value

```<code>if (data01 == maxValue) { colorArray[0] = '#fbbc05'; }
else if (data02 == maxValue) { colorArray[1] = '#fbbc05'; }
else if (data03 == maxValue) { colorArray[2] = '#fbbc05'; }
else if (data04 == maxValue) { colorArray[3] = '#fbbc05'; }
else if (data05 == maxValue) { colorArray[4] = '#fbbc05'; }
else if (data06 == maxValue) { colorArray[5] = '#fbbc05'; }
else if (data07 == maxValue) { colorArray[6] = '#fbbc05'; }
</code>```

4) Set up the bar chart plot

```<code>var bar_options = {
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesColors: colorArray,
 seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { highlightMouseOver:false, barMargin:5, shadowOffset:1, varyBarColor:true } },
 axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer } }
 };
</code>```

And it works!

Hope this helps someone else!

Body:
I came up with a solution to this and got this working. It isn't very elegant, but it works!

The bar colours are just an array, so how I did this was to...

1) Colour all bars the same

 var colorArray = ['#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5','#4bb2c5'];

2) Find the max data value

 var maxValue = Math.max(data01,data02,data03,data04,data05,data06,data07);

3) Change the colour array value if the data is the maximum value

if (data01 == maxValue) { colorArray[0] = '#fbbc05'; }
else if (data02 == maxValue) { colorArray[1] = '#fbbc05'; }
else if (data03 == maxValue) { colorArray[2] = '#fbbc05'; }
else if (data04 == maxValue) { colorArray[3] = '#fbbc05'; }
else if (data05 == maxValue) { colorArray[4] = '#fbbc05'; }
else if (data06 == maxValue) { colorArray[5] = '#fbbc05'; }
else if (data07 == maxValue) { colorArray[6] = '#fbbc05'; }

4) Set up the bar chart plot

var bar_options = {
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesColors: colorArray,
 seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { highlightMouseOver:false, barMargin:5, shadowOffset:1, varyBarColor:true } },
 axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer } }
 };

And it works!

Hope this helps someone else!


问:
How to retrieve invisible elements form list on the page in Xamarin.UITest?
I have a list of 20 elements and when I use app.Query on the page, Xamarin.UITest gives me only 3 elements as only 3 elements are visible in UI.  How can I retrieve all 20 elements from the list inside of my UITest?</p>

答: Try writing a backdoor method to expose whatever information you need (in this case the total count of list items) and then call it via Invoke</p>


问:
Accessing Bloomberg's API through Excel vs. Python / Java / other programming languages
I've used Excel in the past to fetch daily price data on more than 1000 equity securities over a period of a month and it was a really slow experience (1 hour wait in some circumstances) since I was making a large amount of calls using the Bloomberg Excel Plugin.

I've always wondered if there was a substantial performance improvement to do the same task if I was using Python or Java to pull data from Bloomberg's API instead.

Would like to know from those who have had experience with both Excel and a programming language before I dive head first into trying to implement a Python or Java solution.

答:
I have only used the Python API, and via wrappers. As such I imagine there are ways to get data faster than what I currently do.
But for what I do, I'd say I can get a few years of daily data for roughly 50 securities in a matter of seconds.
So I imagine it could improve your workflow to move to a more robust API.
Regarding intraday data on the other hand I don't find much improvement. But I am not using concurrent calls (which I'm sure would help my speed on that front).</p>


答:
Yes. Define the variables dict once, and then update it in a single if-block if you need to.</p>

```<code>def check_view(request):
    variables = {'variablea': a, 'variableb': b, 'variablec': d}
    if user.is_authenticated:
        variables['variablec'] = c
    return render(request, 'user-template.html', variables)
</code>```

Title: Django - Reducing duplicate context code in the view

Body:
Yes. Define the variables dict once, and then update it in a single if-block if you need to.

def check_view(request):
    variables = {'variablea': a, 'variableb': b, 'variablec': d}
    if user.is_authenticated:
        variables['variablec'] = c
    return render(request, 'user-template.html', variables)


问:
How to highlight region enclosed by parentheses in vim?
Is there a way to automatically highlight the region enclosed by parentheses when the cursor goes over that region?

Take the following text as an example:

```<code>(define (example x)
  (cond ((string? x) (display x))
             (else (error "Bad" x))))
</code>```

when the cursor goes above the cond, this particular region should be immediately highlighted (i.e. there should be no need to press any keys to achieve highlighting):

```<code>(cond ((string? x) (display x))
           (else (error "Bad" x))))
</code>```

Useful screenshot from something similar in emacs: https://www.emacswiki.org/emacs/HighlightSexps

I believe this highlighting feature will make reading s-expressions (basically Racket, Scheme, Clojure, Common Lisp code) a lot easier.

How can this highlighting be achieved in vim?

答:
You can use va( (start visual mode, select from the previous opening ( to the corresponding closing ), including (with i(: excluding) the parentheses themselves). To remove the highlighting and go back to where you were, use <Esc>``.

I know that this is only a partial solution, but this is what you can get with built-in functions. More than that would require a plugin, but I don't know whether such exists.

Body:
Is there a way to automatically highlight the region enclosed by parentheses when the cursor goes over that region?

Take the following text as an example:

(define (example x)
  (cond ((string? x) (display x))
             (else (error "Bad" x))))

when the cursor goes above the cond, this particular region should be immediately highlighted (i.e. there should be no need to press any keys to achieve highlighting):

(cond ((string? x) (display x))
           (else (error "Bad" x))))

Useful screenshot from something similar in emacs: https://www.emacswiki.org/emacs/HighlightSexps

I believe this highlighting feature will make reading s-expressions (basically Racket, Scheme, Clojure, Common Lisp code) a lot easier.

How can this highlighting be achieved in vim?


问:
Node Red TI sensortag
I use the Node Red node from the following link:
https://github.com/node-red/node-red-nodes/tree/master/hardware/sensorTag

It works great, but I can't find an option to change the read interval time. Is there a possibility to change this time (for example to 500ms)?

答: No. The node does not expose any options to change the interval it sends readings from the SensorTag.</p>

Title: Node Red TI sensortag