问:
Pug (Jade) HTML form
I'm trying to create the following simple form with Pug:

     <form action="/add_movie" method="POST">

         title: <input type="text" name="title" value=""/>
         year: <input type="text" name="year" value=""/>
         imdb: <input type="text" name="imdb" value=""/>

       <input type="submit" value="Submit"/>
     </form>
  ```
</div>
</div>
</p>

<p>But I can't make the form work with only one <code>p</code> tag. Here is what I came up with instead: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>body
    h1= "Add a movie!"
    form(action="/new_movie" method="POST")
    p Title:
      input(type="text" name="title" placeholder="")
    p Year:
      input(type="text" name="year" placeholder="")
    p imdb:
      input(type="text" name="imdb" placeholder="")
    input(type="submit")</code>```

Is there a way, to re-create the original HTML form in Pug within one p tag?

答:
Use piped text to mark content as text within an existing block.

```<code>body
  form(action='/add_movie', method='POST')
    p
      | title:
      input(type='text', name='title', value='')
      |          year:
      input(type='text', name='year', value='')
      |          imdb:
      input(type='text', name='imdb', value='')
    input(type='submit', value='Submit')
</code>```

… but you should only use paragraphs when you actually have a paragraph and you should learn to love labels.

Title: Pug (Jade) HTML form

Body:
I'm trying to create the following simple form with Pug:

     <form action="/add_movie" method="POST">

         title: <input type="text" name="title" value=""/>
         year: <input type="text" name="year" value=""/>
         imdb: <input type="text" name="imdb" value=""/>

       <input type="submit" value="Submit"/>
     </form>

But I can't make the form work with only one p tag. Here is what I came up with instead:

body
    h1= "Add a movie!"
    form(action="/new_movie" method="POST")
    p Title:
      input(type="text" name="title" placeholder="")
    p Year:
      input(type="text" name="year" placeholder="")
    p imdb:
      input(type="text" name="imdb" placeholder="")
    input(type="submit")

Is there a way, to re-create the original HTML form in Pug within one p tag?

Body:
Use piped text to mark content as text within an existing block.

body
  form(action='/add_movie', method='POST')
    p
      | title:
      input(type='text', name='title', value='')
      |          year:
      input(type='text', name='year', value='')
      |          imdb:
      input(type='text', name='imdb', value='')
    input(type='submit', value='Submit')

… but you should only use paragraphs when you actually have a paragraph and you should learn to love labels.


来源: stackexchange

问:
Rails: Adding an index after adding column
Suppose I created a table table in a Rails app. Some time later, I add a column running:

```<code>rails generate migration AddUser_idColumnToTable user_id:string.
</code>```

Then I realize I need to add user_id as an index. I know about the add_index method, but where should this method be called? Am I supposed to run a migration (if yes, which one ?), then adding by hand this method?

答:
For references you can call

```<code>rails generate migration AddUserIdColumnToTable user:references
</code>```

If in the future you need to add a general index you can launch this

```<code>rails g migration AddOrdinationNumberToTable ordination_number:integer:index
</code>```

Generated code:

```<code>class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I created a table table in a Rails app. Some time later, I add a column running:

rails generate migration AddUser_idColumnToTable user_id:string.

Then I realize I need to add user_id as an index. I know about the add_index method, but where should this method be called? Am I supposed to run a migration (if yes, which one ?), then adding by hand this method?

Body:
For references you can call

rails generate migration AddUserIdColumnToTable user:references

If in the future you need to add a general index you can launch this

rails g migration AddOrdinationNumberToTable ordination_number:integer:index

Generated code:

class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end

ContentLicense: CC BY-SA 4.0


问:
Add values from another react component
I created a component. Code can be seen here: http://codepen.io/anon/pen/zZmyyd

```<code>class Add extends React.Component  {
  constructor () {
    super();
    this.state = {
      inItems: ["aaa", "bbb", "ccc", "ddd"]
    }
     this.state.items= this.state.inItems;
  }

  add () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems,
            value: newVal
        });
  }

  render () {
    return (
        <div>
        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
            <List items= {this.state.items} />
         </div>
     )
  }
}

class List extends React.Component {
    render () {
        return (
            <ul>
                {
                    this.props.items.map(function(item) {
                        return <li key={item}>{item}</li>
                    })
                }
            </ul>
        )
    }
}

ReactDOM.render(
  <Add />,
  document.getElementById('root')
);
</code>```

How can I add value from Addnews component?

```<code>class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems,
            value: newVal
        });
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}
</code>```

答:
You have to render the Addnew component in Add component.

And then pass the add function as props to Addnew Component:

```<code>render () {
    return (
        <div>
        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
        <List items= {this.state.items} />
        <Addnew add={this.add.bind(this)} />
     </div>
 )
}
</code>```

And in Addnew component:

```<code>class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
       this.props.add();
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}
</code>```

here's the modified code: http://codepen.io/anon/pen/OpBdpV?editors=0010#0

Title: Add values from another react component

Body:
I created a component. Code can be seen here: http://codepen.io/anon/pen/zZmyyd

class Add extends React.Component  {
  constructor () {
    super();
    this.state = {
      inItems: ["aaa", "bbb", "ccc", "ddd"]
    }
     this.state.items= this.state.inItems;
  }

  add () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems,
            value: newVal
        });
  }

  render () {
    return (

        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
            <List items= {this.state.items} />

     )
  }
}

class List extends React.Component {
    render () {
        return (

                {
                    this.props.items.map(function(item) {
                        return
{item}

                    })
                }

        )
    }
}

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

How can I add value from Addnews component?

class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems,
            value: newVal
        });
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}

Body:
You have to render the Addnew component in Add component.

And then pass the add function as props to Addnew Component:

render () {
    return (
        <div>
        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
        <List items= {this.state.items} />
        <Addnew add={this.add.bind(this)} />
     </div>
 )
}

And in Addnew component:

class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
       this.props.add();
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}

here's the modified code: http://codepen.io/anon/pen/OpBdpV?editors=0010#0


问:
How to find all permissions for all users in a sql?
```<code>CREATE TABLE Users(UserId int,UserName nvarchar(15), Permisions int)
CREATE TABLE Permissions(PermissionId int,Title NVARCHAR(15))
</code>```

I Have this Permissions Table with this data:

```<code>Id  Title
--------------
1   'Read'
2   'Write'
4   'Update'
8   'Delete'
</code>```

And Users Table

```<code>Id  UserName    Permission
-----------------------------------
1   'David'     3
2   'Sara'      12
3   'Maryam'    15
</code>```

in this case 'David' has 'Read' and 'Write' Access (1+2=3)
'Sara' has 'Update' and 'Delete' Access(4+8=12)
and 'Maryam' has 'Read', 'Write', 'Update' and 'Delete' Access(1+2+4+8=15)

How to Join this tables in sql and query with following result

```<code>UserName        Title
------------------------------
'David'         'Read'
'David'         'Write'
'Sara'          'Update'
'Sara'          'Delete'
'Maryam'        'Read'
'Maryam'        'Write'
'Maryam'        'Update'
'Maryam'        'Delete'
</code>```

答:
Can you try this?

```<code>CREATE TABLE P (ID INT, TITLE VARCHAR(20));
CREATE TABLE U (ID INT, UNAME VARCHAR(20), PERM INT);

INSERT INTO P VALUES (1,'Read');
INSERT INTO P VALUES (2,'Write');
INSERT INTO P VALUES (4,'Update');
INSERT INTO P VALUES (8,'Delete');
INSERT INTO U VALUES (1,'DAvid', 3);
INSERT INTO U VALUES (1,'Sara', 12);
INSERT INTO U VALUES (1,'Maryam', 15);

    SELECT *
    FROM U
    CROSS JOIN P
    WHERE U.PERM & P.ID>0;
</code>```

Output:

```<code>ID          UNAME                PERM        ID          TITLE
----------- -------------------- ----------- ----------- --------------------
1           DAvid                3           1           Read
1           DAvid                3           2           Write
1           Sara                 12          4           Update
1           Sara                 12          8           Delete
1           Maryam               15          1           Read
1           Maryam               15          2           Write
1           Maryam               15          4           Update
1           Maryam               15          8           Delete
</code>```

Body:
CREATE TABLE Users(UserId int,UserName nvarchar(15), Permisions int)
CREATE TABLE Permissions(PermissionId int,Title NVARCHAR(15))

I Have this Permissions Table with this data:

Id  Title
--------------
1   'Read'
2   'Write'
4   'Update'
8   'Delete'

And Users Table

Id  UserName    Permission
-----------------------------------
1   'David'     3
2   'Sara'      12
3   'Maryam'    15

in this case 'David' has 'Read' and 'Write' Access (1+2=3)
'Sara' has 'Update' and 'Delete' Access(4+8=12)
and 'Maryam' has 'Read', 'Write', 'Update' and 'Delete' Access(1+2+4+8=15)

How to Join this tables in sql and query with following result

UserName        Title
------------------------------
'David'         'Read'
'David'         'Write'
'Sara'          'Update'
'Sara'          'Delete'
'Maryam'        'Read'
'Maryam'        'Write'
'Maryam'        'Update'
'Maryam'        'Delete'

Body:
Can you try this?

CREATE TABLE P (ID INT, TITLE VARCHAR(20));
CREATE TABLE U (ID INT, UNAME VARCHAR(20), PERM INT);

INSERT INTO P VALUES (1,'Read');
INSERT INTO P VALUES (2,'Write');
INSERT INTO P VALUES (4,'Update');
INSERT INTO P VALUES (8,'Delete');
INSERT INTO U VALUES (1,'DAvid', 3);
INSERT INTO U VALUES (1,'Sara', 12);
INSERT INTO U VALUES (1,'Maryam', 15);

    SELECT *
    FROM U
    CROSS JOIN P
    WHERE U.PERM & P.ID>0;

Output:

ID          UNAME                PERM        ID          TITLE
----------- -------------------- ----------- ----------- --------------------
1           DAvid                3           1           Read
1           DAvid                3           2           Write
1           Sara                 12          4           Update
1           Sara                 12          8           Delete
1           Maryam               15          1           Read
1           Maryam               15          2           Write
1           Maryam               15          4           Update
1           Maryam               15          8           Delete


问:
Generic Methods in Java: "Object does not take parameters"
I want to create a generic method inside a class which takes an array of given type objects and sorts them to return a pair object containing the minimum array item and the maximum array item.

At the moment I get 3 compiler errors:

type Object does not take parameters: public <FirstType> Pair sortMinMax(Object<FirstType>[] array)

type Object does not take parameters: Object<FirstType> minimum = array[0]

type Object does not take parameters: Object<FirstType> maximum = array[0]

Here is my Class:

```<code>public class MinMaxArray {

  // takes an array of a given object and returns a pair
  // of the min and max array elements
  public <FirstType> Pair sortMinMax(Object<FirstType>[] array) {
    Object<FirstType> minimum = array[0];
    Object<FirstType> maximum = array[0];

    // loop through all array items and perform sort
    for (int counter = 1; counter < array.length; counter++) {
      // if this element is less than current min, set as min
      // else if this element is greater than current max, set as max
      if (array[counter].compareTo(minimum) < 0) {
        minimum = array[counter];
      } else if (array[counter].comparTo(maximum) > 0) {
        maximum = array[counter];
      } // end if else new min, max
    } // end for (all array items)

    return new Pair<FirstType, FirstType>(minimum, maximum);
  } // end compare()

} // end MinMaxArray
</code>```

答:
```<code>type Object does not take parameters
</code>```

This is what tells you most. Simply, you can write things like Object<T>. The class Object is not parameterized. Lists for example, are.

Also, in order to use the compareTo() method, you need to have something like this:

```<code>public <FirstType extends Comparable> Pair sortMinMax(FirstType[] array)
</code>```

Body:
I want to create a generic method inside a class which takes an array of given type objects and sorts them to return a pair object containing the minimum array item and the maximum array item.

At the moment I get 3 compiler errors:

type Object does not take parameters: public <FirstType> Pair sortMinMax(Object<FirstType>[] array)

type Object does not take parameters: Object<FirstType> minimum = array[0]

type Object does not take parameters: Object<FirstType> maximum = array[0]

Here is my Class:

public class MinMaxArray {

  // takes an array of a given object and returns a pair
  // of the min and max array elements
  public <FirstType> Pair sortMinMax(Object<FirstType>[] array) {
    Object<FirstType> minimum = array[0];
    Object<FirstType> maximum = array[0];

    // loop through all array items and perform sort
    for (int counter = 1; counter < array.length; counter++) {
      // if this element is less than current min, set as min
      // else if this element is greater than current max, set as max
      if (array[counter].compareTo(minimum) < 0) {
        minimum = array[counter];
      } else if (array[counter].comparTo(maximum) > 0) {
        maximum = array[counter];
      } // end if else new min, max
    } // end for (all array items)

    return new Pair<FirstType, FirstType>(minimum, maximum);
  } // end compare()

} // end MinMaxArray

Body:
type Object does not take parameters

This is what tells you most. Simply, you can write things like Object<T>. The class Object is not parameterized. Lists for example, are.

Also, in order to use the compareTo() method, you need to have something like this:

public <FirstType extends Comparable> Pair sortMinMax(FirstType[] array)


问:
Two XAML pages with same code behind
I'm creating an Windows Universal App (WinRT and WP8.1).
What I want is to have an user choose between two different layouts for the same page.
Below is a simple representation.
I'd like to find the simplest, laziest approach (I know I could just create two pages, but there must be a better way.)
I have already created 1 page (500 lines of C# code behind to handle control interactions) and now need to add the second layout to it. The two layouts have the exact same functions and the controls have the same names, they are just arranged differently.

In Android I could do:

```<code>if(IsLayout1Selected)
    setContentView(R.layout.activity_d2p_layout1);

else
    setContentView(R.layout.activity_d2p_layout2);
</code>```

Thank you in advance for your help!

Layout1:

```<code><Page x:Name="d2pPageLayout1"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="mainGrid">
        <Button x:Name="button1" VerticalAlignment="Top" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>
        <!-- Of course there are a lot more elements and they have many layout properties that differ -->
    </Grid>
</Page>
</code>```

Layout2:

```<code><Page x:Name="d2pPageLayout2"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="mainGrid">
        <Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>
        <!-- Of course there are a lot more elements and they have many layout properties that differ -->
    </Grid>
</Page>
</code>```

Code behind (same for Layout 1 and Layout 2):

```<code>namespace _MyApp
{
    public sealed partial class D2P : Page
    {
    public D2P()
        {
            this.InitializeComponent();
        }

    private void PageLoaded(object sender, RoutedEventArgs e)
        {
            // do stuff here
        }

    private void PageUnloaded(object sender, RoutedEventArgs e)
        {
            // do some other stuff here
        }

    private void buttonClick(object sender, RoutedEventArgs e)
        {
            // handle buttonClick here
            // a lot of this code also references the controls directly e.g.
            textblock1.Text = "Button 1 was clicked";
        }
    }
}
</code>```

EDIT:

Thanks to the tip from Akshay Soam I came pretty close to what I wanted by using DataTemplate and ContentControl, but now this results in another problem, breaking my code. My code accesses a lot of elements directly.
Example:

```<code>textblock1.Text = "Button 1 was clicked";
</code>```

Since my entire page content is now wrapped inside the DataTemplate I cannot access the elements anymore. How do I do this?

Current implementation is:

XAML:

```<code><Page.Resources>
    <DataTemplate x:Key="template1">
        <Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>
    </DataTemplate>
</Page.Resources>
<ContentControl x:Name="contentControl" Content="{Binding}"/>
</code>```

Code behind:

```<code>contentControl.ContentTemplate = template1;
this.DataContext = template1;
</code>```

答:
You can Build more than one xaml for the same page like here:
I built 8 xaml for the same MainPage for different screen size

```<code>public sealed partial class MainPage : Page
{

    public MainPage()
    {

        Rect bounds = ApplicationView.GetForCurrentView().VisibleBounds;
        double scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
        Size size = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

        string resourceName;

        if (size.Width >= 1920 && size.Height >= 1080) resourceName = "ms-appx:///MainPage.layout-1920x1080.xaml";
        else if (size.Width >= 1680 && size.Height >= 1050) resourceName = "ms-appx:///MainPage.layout-1680x1050.xaml";
        else if (size.Width >= 1600 && size.Height >= 1200) resourceName = "ms-appx:///MainPage.layout-1600x1200.xaml";
        else if (size.Width >= 1360 && size.Height >= 768) resourceName = "ms-appx:///MainPage.layout-1360x768.xaml";
        else if (size.Width >= 1280 && size.Height >= 1024) resourceName = "ms-appx:///MainPage.layout-1280x1024.xaml";
        else if (size.Width >= 1024 && size.Height >= 768) resourceName = "ms-appx:///MainPage.layout-1024x768.xaml";
        else if (size.Width >= 720 && size.Height >= 480) resourceName = "ms-appx:///MainPage.layout-720x480.xaml";
        else resourceName = "ms-appx:///MainPage.layout-640x480.xaml";

        this.InitializeComponent(new Uri(resourceName, UriKind.Absolute));

    }

}
</code>```

}

These are the links for the code that you can use it for your scenario

https://developer.microsoft.com/en-us/windows/iot/samples/digitalsign

https://github.com/ms-iot/samples/tree/develop/DigitalSign

Title: Two XAML pages with same code behind

Body:
I'm creating an Windows Universal App (WinRT and WP8.1).
What I want is to have an user choose between two different layouts for the same page.
Below is a simple representation.
I'd like to find the simplest, laziest approach (I know I could just create two pages, but there must be a better way.)
I have already created 1 page (500 lines of C# code behind to handle control interactions) and now need to add the second layout to it. The two layouts have the exact same functions and the controls have the same names, they are just arranged differently.

In Android I could do:

if(IsLayout1Selected)
    setContentView(R.layout.activity_d2p_layout1);

else
    setContentView(R.layout.activity_d2p_layout2);

Thank you in advance for your help!

Layout1:

<Page x:Name="d2pPageLayout1"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="mainGrid">
        <Button x:Name="button1" VerticalAlignment="Top" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>

    </Grid>
</Page>

Layout2:

<Page x:Name="d2pPageLayout2"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="mainGrid">
        <Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>

    </Grid>
</Page>

Code behind (same for Layout 1 and Layout 2):

namespace _MyApp
{
    public sealed partial class D2P : Page
    {
    public D2P()
        {
            this.InitializeComponent();
        }

    private void PageLoaded(object sender, RoutedEventArgs e)
        {
            // do stuff here
        }

    private void PageUnloaded(object sender, RoutedEventArgs e)
        {
            // do some other stuff here
        }

    private void buttonClick(object sender, RoutedEventArgs e)
        {
            // handle buttonClick here
            // a lot of this code also references the controls directly e.g.
            textblock1.Text = "Button 1 was clicked";
        }
    }
}

EDIT:

Thanks to the tip from Akshay Soam I came pretty close to what I wanted by using DataTemplate and ContentControl, but now this results in another problem, breaking my code. My code accesses a lot of elements directly.
Example:

textblock1.Text = "Button 1 was clicked";

Since my entire page content is now wrapped inside the DataTemplate I cannot access the elements anymore. How do I do this?

Current implementation is:

XAML:

<Page.Resources>
    <DataTemplate x:Key="template1">
        <Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
        <TextBlock x:Name="textblock1" Text="Hello"/>
    </DataTemplate>
</Page.Resources>
<ContentControl x:Name="contentControl" Content="{Binding}"/>

Code behind:

contentControl.ContentTemplate = template1;
this.DataContext = template1;

Body:
You can Build more than one xaml for the same page like here:
I built 8 xaml for the same MainPage for different screen size

public sealed partial class MainPage : Page
{

    public MainPage()
    {

        Rect bounds = ApplicationView.GetForCurrentView().VisibleBounds;
        double scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
        Size size = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

        string resourceName;

        if (size.Width >= 1920 && size.Height >= 1080) resourceName = "ms-appx:///MainPage.layout-1920x1080.xaml";
        else if (size.Width >= 1680 && size.Height >= 1050) resourceName = "ms-appx:///MainPage.layout-1680x1050.xaml";
        else if (size.Width >= 1600 && size.Height >= 1200) resourceName = "ms-appx:///MainPage.layout-1600x1200.xaml";
        else if (size.Width >= 1360 && size.Height >= 768) resourceName = "ms-appx:///MainPage.layout-1360x768.xaml";
        else if (size.Width >= 1280 && size.Height >= 1024) resourceName = "ms-appx:///MainPage.layout-1280x1024.xaml";
        else if (size.Width >= 1024 && size.Height >= 768) resourceName = "ms-appx:///MainPage.layout-1024x768.xaml";
        else if (size.Width >= 720 && size.Height >= 480) resourceName = "ms-appx:///MainPage.layout-720x480.xaml";
        else resourceName = "ms-appx:///MainPage.layout-640x480.xaml";

        this.InitializeComponent(new Uri(resourceName, UriKind.Absolute));

    }

}

}

These are the links for the code that you can use it for your scenario

https://developer.microsoft.com/en-us/windows/iot/samples/digitalsign

https://github.com/ms-iot/samples/tree/develop/DigitalSign


问:
spring file upload without commons-fileupload.jar
Literally, is it possible to make file upload without using commons-fileupload.jar in spring framework?
(if so, how can I make without it?)</p>

答: Yes, it's possible. In Servlet 3.0 environment you can use StandardServletMultipartResolver. See Spring documentation for more info: http://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/html/mvc.html#mvc-multipart-resolver-standard


问:
C++ multiple diamonds inheritance and pure virtual functions
Consider the following architecture:

```<code>class A  //abstract interface
{
    public:
    virtual void f() = 0;
};
class AA : public A  //abstract interface
{
    public:
    virtual void g() = 0;
};
class AAA : public AA  //abstract interface
{
    public:
    virtual void h() = 0;
};

class B :  public A // implementation class
{
    public:
    void f() override {};
};
class BB : public B, public AA {}; // implementation class
{
    public:
    void g() override {};
};
class BBB : public BB, public AAA {}; // implementation class
{
    public:
    void h() override {};
};
</code>```

As such, BB and BBB are virtual classes, because f is not overridden by BB, and neither f nor g are by BBB. My wish is to be able to instantiate BB and BBB (so that BB and BBB use the override of f defined by B, and BBB uses the override of g defined by BB).

The question is: which inheritance relationships should be marked as virtual to instantiate BB and BBB ?

The inheritance diagram should ideally look like this:

```<code>A
|\
| \
|  \
AA   B
| \  |
|  \ |
AAA  BB
  \  |
   \ |
     BBB
</code>```

The idea behind this design is that A, AA and AAA are interfaces describing incremental feature levels. B, BB and BB are one corresponding incremental implementation. (So that BB for instance defines everything needed by AA, and also features what's in B)

答:
if A AA AAA are really only interfaces, i mean they don't have any members, then you don't need any virtaul inheritance, implement only interfaces and call them from base classes. What you implemented in B for interface A, must be implemented also in BB, then call B:pureVirtual() in BB. Otherwise should be like this; (Then you should have a look at: 'class1' : inherits 'class2::member' via dominance)

```<code>class A
{
public:
  virtual void f() = 0;
};
class AA : virtual public A
{
public:
  virtual void g() = 0;
};
class AAA : virtual public AA
{
public:
  virtual void h() = 0;
};

class B : virtual public A
{
public:
  void f() override { }
};
class BB : public B, virtual public AA
{
public:
  void g() override { }
};
class BBB : public BB, public AAA
{
public:
  void h() override { }
};
</code>```

Edit: (Without virtual inheritance)

```<code>class A  //abstract interface
{
public:
  virtual void f() = 0;
};
class AA : public A  //abstract interface
{
public:
  virtual void g() = 0;
};
class AAA : public AA  //abstract interface
{
public:
  virtual void h() = 0;
};

class B : public A // implementation class
{
public:
  void f() override {}
};
class BB : public B, public AA // implementation class
{
public:
  void g() override {}
  void f() override { B::f(); }
};
class BBB : public BB, public AAA // implementation class
{
public:
  void h() override {}

  void g() override { BB::g(); }
  void f() override { BB::f(); }
};
</code>```

Body:
Consider the following architecture:

class A  //abstract interface
{
    public:
    virtual void f() = 0;
};
class AA : public A  //abstract interface
{
    public:
    virtual void g() = 0;
};
class AAA : public AA  //abstract interface
{
    public:
    virtual void h() = 0;
};

class B :  public A // implementation class
{
    public:
    void f() override {};
};
class BB : public B, public AA {}; // implementation class
{
    public:
    void g() override {};
};
class BBB : public BB, public AAA {}; // implementation class
{
    public:
    void h() override {};
};

As such, BB and BBB are virtual classes, because f is not overridden by BB, and neither f nor g are by BBB. My wish is to be able to instantiate BB and BBB (so that BB and BBB use the override of f defined by B, and BBB uses the override of g defined by BB).

The question is: which inheritance relationships should be marked as virtual to instantiate BB and BBB ?

The inheritance diagram should ideally look like this:

A
|\
| \
|  \
AA   B
| \  |
|  \ |
AAA  BB
  \  |
   \ |
     BBB

The idea behind this design is that A, AA and AAA are interfaces describing incremental feature levels. B, BB and BB are one corresponding incremental implementation. (So that BB for instance defines everything needed by AA, and also features what's in B)

Body:
if A AA AAA are really only interfaces, i mean they don't have any members, then you don't need any virtaul inheritance, implement only interfaces and call them from base classes. What you implemented in B for interface A, must be implemented also in BB, then call B:pureVirtual() in BB. Otherwise should be like this; (Then you should have a look at: 'class1' : inherits 'class2::member' via dominance)

class A
{
public:
  virtual void f() = 0;
};
class AA : virtual public A
{
public:
  virtual void g() = 0;
};
class AAA : virtual public AA
{
public:
  virtual void h() = 0;
};

class B : virtual public A
{
public:
  void f() override { }
};
class BB : public B, virtual public AA
{
public:
  void g() override { }
};
class BBB : public BB, public AAA
{
public:
  void h() override { }
};

Edit: (Without virtual inheritance)

class A  //abstract interface
{
public:
  virtual void f() = 0;
};
class AA : public A  //abstract interface
{
public:
  virtual void g() = 0;
};
class AAA : public AA  //abstract interface
{
public:
  virtual void h() = 0;
};

class B : public A // implementation class
{
public:
  void f() override {}
};
class BB : public B, public AA // implementation class
{
public:
  void g() override {}
  void f() override { B::f(); }
};
class BBB : public BB, public AAA // implementation class
{
public:
  void h() override {}

  void g() override { BB::g(); }
  void f() override { BB::f(); }
};


问:
MongoDB: Find all documents except those where a date range condition matches
Requirement: I want a collection of all customers who did not perform the "View" event in last 5 hours.

Data:

```<code>{
    name: "Sheldon",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 10 hours ago"
        },
        {
            event: "Some other event",
            timestamp: "timestamp equivalent to 8 hours ago"
        },
        {
            event: "View",
            timestamp: "timestamp equivalent to 2 hours ago"
        }
    ]
},
{
    name: "Leonard",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 10 hours ago"
        }
    ]
},
{
    name: "Howard",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 2 hours ago"
        }
    ]
},
{
    name: "Raj",
    events: [
        {
            event: "Some other event",
            timestamp: "timestamp equivalent to 6 hours ago"
        }
    ]
}
</code>```

I have tried out the following, but it always returns "Sheldon" (possibly because the other event ends up satisfying the criteria?).

```<code>q.where({
    $and: [
        {
            'events': {
                $not: {
                    $elemMatch: {
                        event: "View",
                        timestamp: {
                            $gte: "timestamp equivalent to 5 hours ago"
                        }
                    }
                }
            }
        }
    ]
});
</code>```

What can I do so that only documents for "Leonard" and "Raj" are returned?

答:
To get users how has not visited in last 5 hours. you can try it

```<code>db.collectionName.find({
    events: {
        $not: {
            $elemMatch: {
                event: "View",
                timestamp: {
                    $gt: ISODate("2017-03-29T05:12:37.420Z") // equivalent to 5 hours ago
                }
            }
         }
    }
}, {name: 1})
</code>```

This query returned only documents for Leonard and Raj for your given example

N.B: Like your query but I used find instead of where, no need to use $and and used $gt instead of $gte

Tested for documents.

```<code>{
    "_id" : ObjectId("58db886e4b9e731aaefa9820"),
    "name" : "Sheldon",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T00:09:18.723Z")
        },
        {
            "event" : "Some other event",
            "timestamp" : ISODate("2017-03-29T02:10:04.492Z")
        },
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T08:11:02.196Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9821"),
    "name" : "Leonard",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T00:11:23.084Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9822"),
    "name" : "Howard",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T08:11:02.196Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9823"),
    "name" : "Raj",
    "events" : [
        {
            "event" : "Some other event",
            "timestamp" : ISODate("2017-03-29T04:10:42.972Z")
        }
    ]
}
</code>```

After apply my query result:

```<code>{
    "_id" : ObjectId("58db886e4b9e731aaefa9821"),
    "name" : "Leonard"
},
{
    "_id" : ObjectId("58db886e4b9e731aaefa9823"),
    "name" : "Raj"
}
</code>```

Body:
Requirement: I want a collection of all customers who did not perform the "View" event in last 5 hours.

Data:

{
    name: "Sheldon",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 10 hours ago"
        },
        {
            event: "Some other event",
            timestamp: "timestamp equivalent to 8 hours ago"
        },
        {
            event: "View",
            timestamp: "timestamp equivalent to 2 hours ago"
        }
    ]
},
{
    name: "Leonard",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 10 hours ago"
        }
    ]
},
{
    name: "Howard",
    events: [
        {
            event: "View",
            timestamp: "timestamp equivalent to 2 hours ago"
        }
    ]
},
{
    name: "Raj",
    events: [
        {
            event: "Some other event",
            timestamp: "timestamp equivalent to 6 hours ago"
        }
    ]
}

I have tried out the following, but it always returns "Sheldon" (possibly because the other event ends up satisfying the criteria?).

q.where({
    $and: [
        {
            'events': {
                $not: {
                    $elemMatch: {
                        event: "View",
                        timestamp: {
                            $gte: "timestamp equivalent to 5 hours ago"
                        }
                    }
                }
            }
        }
    ]
});

What can I do so that only documents for "Leonard" and "Raj" are returned?

Body:
To get users how has not visited in last 5 hours. you can try it

db.collectionName.find({
    events: {
        $not: {
            $elemMatch: {
                event: "View",
                timestamp: {
                    $gt: ISODate("2017-03-29T05:12:37.420Z") // equivalent to 5 hours ago
                }
            }
         }
    }
}, {name: 1})

This query returned only documents for Leonard and Raj for your given example

N.B: Like your query but I used find instead of where, no need to use $and and used $gt instead of $gte

Tested for documents.

{
    "_id" : ObjectId("58db886e4b9e731aaefa9820"),
    "name" : "Sheldon",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T00:09:18.723Z")
        },
        {
            "event" : "Some other event",
            "timestamp" : ISODate("2017-03-29T02:10:04.492Z")
        },
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T08:11:02.196Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9821"),
    "name" : "Leonard",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T00:11:23.084Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9822"),
    "name" : "Howard",
    "events" : [
        {
            "event" : "View",
            "timestamp" : ISODate("2017-03-29T08:11:02.196Z")
        }
    ]
}
{
    "_id" : ObjectId("58db886e4b9e731aaefa9823"),
    "name" : "Raj",
    "events" : [
        {
            "event" : "Some other event",
            "timestamp" : ISODate("2017-03-29T04:10:42.972Z")
        }
    ]
}

After apply my query result:

{
    "_id" : ObjectId("58db886e4b9e731aaefa9821"),
    "name" : "Leonard"
},
{
    "_id" : ObjectId("58db886e4b9e731aaefa9823"),
    "name" : "Raj"
}


问:
Can we use truncate with where clause?
I know that we cannot use where clause with truncate..But i want to delete some records in a table by keeping other records as usual by using truncate...

Can we do that??

答:
No, TRUNCATE is all or nothing. You can do a DELETE FROM

  WHERE <conditions> but this loses the speed advantages of TRUNCATE.

This thread is a good read :)

Title: Can we use truncate with where clause?

Body:
No, TRUNCATE is all or nothing. You can do a DELETE FROM <table>
  WHERE <conditions> but this loses the speed advantages of TRUNCATE.

This thread is a good read :)


问:
Test login with protractor on a non angular page
I am trying to use protractor for e2e testing but first I need to login on a non-angular page. I try to directly use the webDriver as indicated here but it fails.

My e2e test:

```<code>describe('angularjs homepage', function() {

  it('should prompt the login page', function() {
    browser.get('/');
    expect(browser.driver.find(By.id('user_password')));
  });

});
</code>```

My logs:

```<code>Running "protractor:all" (protractor) task
Using the selenium server at http://localhost:4444/wd/hub
F

Failures:

  1) angularjs homepage should prompt the login page
   Message:
     TypeError: Object [object Object] has no method 'find'
</code>```

Do you know a solution?

答:
For a non angular page, first use this

```<code>browser.ignoreSynchronization = true;
</code>```

The above line will tell protractor that it's not an angular page, and you can perform any action on your non-angular page. Now when you are done, and want to move to an angular page use

```<code>browser.ignoreSynchronization = false;
</code>```

Body:
I am trying to use protractor for e2e testing but first I need to login on a non-angular page. I try to directly use the webDriver as indicated here but it fails.

My e2e test:

describe('angularjs homepage', function() {

  it('should prompt the login page', function() {
    browser.get('/');
    expect(browser.driver.find(By.id('user_password')));
  });

});

My logs:

Running "protractor:all" (protractor) task
Using the selenium server at http://localhost:4444/wd/hub
F

Failures:

  1) angularjs homepage should prompt the login page
   Message:
     TypeError: Object [object Object] has no method 'find'

Do you know a solution?

Body:
For a non angular page, first use this

browser.ignoreSynchronization = true;

The above line will tell protractor that it's not an angular page, and you can perform any action on your non-angular page. Now when you are done, and want to move to an angular page use

browser.ignoreSynchronization = false;


问:
How do I get an object from S3 using it's pre-signed url in boto3?
I have generated a pre-signed url for an object in one of my buckets using boto3:

```<code>s3.generate_presigned_url('get_object', Params = {'Bucket': 'https://s3.amazonaws.com/<>', 'Key': '<>.json'}, ExpiresIn = 100)
</code>```

Now, how do I get_object it in boto3? The boto3's get_object reference doesn't specify any argument for a pre-signed url.

So, how do I get that object from S3 using it's pre-signed url in boto3?

答:
If you have a pre-signed URL, you don't need boto -- you can download the object using any HTTP user agent library.

Conversely, if you have boto and the credentials, you don't need a pre-signed URL.

Pre-signed URLs are intended for allowing someone with credentials to enable someone else without credentials to access a resource, without exposing the credentials to them.

A pre-signed URL includes the access-key-id and possibly a session-token, but not the access-key-secret, and are computationally-infeasible to reverse-engineer... and in this sense, they do not expose the credentials in a way that allows the entity possessing the pre-signed URL to use the associated credentials for any other purpose.

Body:
I have generated a pre-signed url for an object in one of my buckets using boto3:

s3.generate_presigned_url('get_object', Params = {'Bucket': 'https://s3.amazonaws.com/<>', 'Key': '<>.json'}, ExpiresIn = 100)

Now, how do I get_object it in boto3? The boto3's get_object reference doesn't specify any argument for a pre-signed url.

So, how do I get that object from S3 using it's pre-signed url in boto3?


问:
Create socket connection with Bluetooth device after ACTION_ACL_CONNECTED
I can get a working connection from a Bluetooth device if my application is waiting on an 'accept' call prior to the ACTION_ACL_CONNECTED broadcast being received.  If I issue the 'accept' call in response to the broadcast being received I can't make the socket connection.

Is there a way to make this happen so I can setup the socket connection in response to the Bluetooth event?

答:
I dont think there is a way to accept in response to an  ACTION_ACL_CONNECTED, this is designed to work similar to regular TCP sockets, the listening only happens (which in bluetooth terms means registering the service UUID in the SDP record and waiting for incoming connections) when the accept() call is made.

You can try accept(timeout) if you are concerned about blocking on the accept call and cant afford to have a dedicated thread to block on the accept()

ContentLicense: CC BY-SA 2.5


问:
Play speed of embedded video in Powerpoint
I thought this would be an easy question to find an answer to but surprisingly I hit dead-ends when googling.

My issue is that I have embedded a video from my computer in Powerpoint (in Microsoft Office Professional Plus 2013) and I was hoping to run it faster than 1X speed. I cannot find any option to do so. Is this something that can be done?

If not the only option I can think of is to try to edit the actual video clip to be faster somehow (does anyone have any recommended free software?). I can then simply embed the sped-up video.

Thanks in advance!

答:
Use this link:
http://www.pptfaq.com/FAQ00712_Playing_movies_in_slow_or_fast_motion.htm

for the 'windows media player' object enable the 'developer' tab from powerpoint options - custom ribbons - tick the developer box.
Once developer tab is shown click on more options - select the 'windows media player'.


问:
SAS Retain statement - how to retain previous non missing values into new column for comparison
I am simply looking to create a new column retaining the value of a specific column within the previous record, so that I can compare the existing column against the new column. Further down the line I want to be able to output records whereby the values in both columns are different and lose the records where the values are the same

Essentially I want my dataset to look like this, where the first idr has the retained date set to null:

```<code>Idr Date1           Date2
1   20/01/2016  .
1   20/01/2016  20/01/2016
1   18/10/2016  20/01/2016
2   07/03/2016  .
2   18/05/2016  07/03/2016
2   21/10/2016  18/05/2016
3   29/01/2016  .
3   04/02/2016  29/01/2016
3   04/02/2016  04/02/2016
</code>```

I have used code along the following lines in the past whereby I have created a temporary variable referencing the data I want to retain:

```<code>date_temp=date1;
    data example2;
    set example1;
    by idr date1;
    date_temp=date1;
retain date_temp ;
    if first.idr then do;
        date_temp=date1;
    end;else do;
        date2=date_temp;
    end;
 run;
</code>```

I have searched the highs and lows of google - Any help would be greatly appreciated

答:
The trick here is to set the value of the retained variable ready for the next row after you've already output the current row, rather than relying on the default implicit output at the end of the data step:

```<code>data example2;
    set example1;
    by idr;
    retain date2;
    if first.idr then call missing(date2);
    output;
    date2 = date1;
    format date2 ddmmyy10.;
 run;
</code>```

Logic that executes after the output statement doesn't make any difference to the row that's just been output, but until the data step proceeds to the next iteration, everything is still in the PDV, including variables that are being retained across to the next row, so this is an opportunity to update them. More details on the PDV.

Another way of doing this, using the lag function:

```<code>data example3;
    set example1;
    date2 = lag(date1);
    if idr ne lag(idr) then call missing(date2);
run;
</code>```

Be careful when using lag - it returns the value from the last time that instance of the lag function was executed during your data step, not necessarily the value of that variable from the previous row, so weird things tend to happen if you do something like if condition then mylaggedvar=lag(var);

Body:
I am simply looking to create a new column retaining the value of a specific column within the previous record, so that I can compare the existing column against the new column. Further down the line I want to be able to output records whereby the values in both columns are different and lose the records where the values are the same

Essentially I want my dataset to look like this, where the first idr has the retained date set to null:

Idr Date1           Date2
1   20/01/2016  .
1   20/01/2016  20/01/2016
1   18/10/2016  20/01/2016
2   07/03/2016  .
2   18/05/2016  07/03/2016
2   21/10/2016  18/05/2016
3   29/01/2016  .
3   04/02/2016  29/01/2016
3   04/02/2016  04/02/2016

I have used code along the following lines in the past whereby I have created a temporary variable referencing the data I want to retain:

date_temp=date1;
    data example2;
    set example1;
    by idr date1;
    date_temp=date1;
retain date_temp ;
    if first.idr then do;
        date_temp=date1;
    end;else do;
        date2=date_temp;
    end;
 run;

I have searched the highs and lows of google - Any help would be greatly appreciated

Body:
The trick here is to set the value of the retained variable ready for the next row after you've already output the current row, rather than relying on the default implicit output at the end of the data step:

data example2;
    set example1;
    by idr;
    retain date2;
    if first.idr then call missing(date2);
    output;
    date2 = date1;
    format date2 ddmmyy10.;
 run;

Logic that executes after the output statement doesn't make any difference to the row that's just been output, but until the data step proceeds to the next iteration, everything is still in the PDV, including variables that are being retained across to the next row, so this is an opportunity to update them. More details on the PDV.

Another way of doing this, using the lag function:

data example3;
    set example1;
    date2 = lag(date1);
    if idr ne lag(idr) then call missing(date2);
run;

Be careful when using lag - it returns the value from the last time that instance of the lag function was executed during your data step, not necessarily the value of that variable from the previous row, so weird things tend to happen if you do something like if condition then mylaggedvar=lag(var);


问:
Calculate the json's value then show in html
I have a json array:

```<code>[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]
</code>```

My code is :

```<code>$.ajax({
    url: "120.58.243.11:8080/needCal/myJson.json",
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, value) {
            items.push("<tr>");
            items.push("<td id=''" + key + "''>" + value.value+ < /td>");
            items.push("<td id=''" + key + "''>" + total of values + < /td>");
            items.push("</tr>");
        });
    }
});
</code>```

I want to calculate the values, how to do with that?

答:
```<code>$.ajax({
    url: "120.58.243.11:8080/needCal/myJson.json",
    dataType:'json',
    success: function(data){
    var items = [];

    var totalOfValue = 0;
    $.each(data,function(key,value){
        totalOfValue = totalOfValue + parseInt(value.value);
    });

    $.each(data,function(key,value){
        items.push("<tr>");
        items.push("<td id='" +key+ "'>" + value.value+</td>");
        items.push("<td id='" +key+ "'>" + totalOfValue +</td>");
        items.push("</tr>");
    });
    }
   }
);
</code>```

Body:
I have a json array:

[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]

My code is :

$.ajax({
    url: "120.58.243.11:8080/needCal/myJson.json",
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, value) {
            items.push("
");
            items.push("" + value.value+ 	");
            items.push("" + total of values + 	");
            items.push("
");
        });
    }
});

I want to calculate the values, how to do with that?


问:
Navigate between views in Xamarin (visual studio) PCL project
I cant find a way to implement an onClick event on a button that will allow the application to navigate between the login and the second view.

How can I do that ?

Here is what i did

I created a method in my LoginViewModel.cs file that should redirect me to the second view.

```<code> class LoginViewModel
{
 private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
}
</code>```

Then I've defined a BindingContext in my Login.cs

```<code> public partial class Login : ContentPage
    {
        public Login()
        {
            InitializeComponent();
            BindingContext = new LoginViewModel();
        }
    }
</code>```

Then I define a button in my Login.xaml that has a binded command property

```<code> <StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Command="{Binding connexion}" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Command="{Binding SecondView_Click}"></Button>
    </StackLayout>
</code>```

答:
Here is what I did.

I found that there is a "clicked" property on  that prompt an intellisense dropdown with a "new event handler".

```<code><StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Clicked="connexion" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Clicked="SecondView_Click"></Button>
    </StackLayout>
</code>```

Once i did that it created a method in the code behind "Login.xaml.cs".

From there I just paste the navigation method and it worked

```<code>private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
</code>```

The fact that it is a PCL project makes it difficult to find the right information because everything you find on the internet concerns the ios/android solution and not the portable solution.

Body:
I cant find a way to implement an onClick event on a button that will allow the application to navigate between the login and the second view.

How can I do that ?

Here is what i did

I created a method in my LoginViewModel.cs file that should redirect me to the second view.

 class LoginViewModel
{
 private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
}

Then I've defined a BindingContext in my Login.cs

 public partial class Login : ContentPage
    {
        public Login()
        {
            InitializeComponent();
            BindingContext = new LoginViewModel();
        }
    }

Then I define a button in my Login.xaml that has a binded command property

 <StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Command="{Binding connexion}" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Command="{Binding SecondView_Click}"></Button>
    </StackLayout>

Body:
Here is what I did.

I found that there is a "clicked" property on  that prompt an intellisense dropdown with a "new event handler".

<StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Clicked="connexion" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Clicked="SecondView_Click"></Button>
    </StackLayout>

Once i did that it created a method in the code behind "Login.xaml.cs".

From there I just paste the navigation method and it worked

private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }

The fact that it is a PCL project makes it difficult to find the right information because everything you find on the internet concerns the ios/android solution and not the portable solution.


答:
Firstly, avoid reference arrays. They don't play well with generics. Use List instead.

It's not clear to me if you intend FirstType to be a type or a generic parameter (which would usually be given a single letter name).

If FirstType is a type

```<code>public static Pair<FirstType,FirstType> sortMinMax(List<FirstType> things) {
</code>```

If you mean a generic parameter, look at java.util.Collections.sort.

```<code>public static <T extends Comparable<? super T>> void sort(List<T> list) {
</code>```

So

```<code>public static <T extends Comparable<? super T>> Pair<T,T> sortMinMax(List<T> list) {
</code>```

Title: Generic Methods in Java: "Object does not take parameters"

Body:
I want to create a generic method inside a class which takes an array of given type objects and sorts them to return a pair object containing the minimum array item and the maximum array item.

At the moment I get 3 compiler errors:

type Object does not take parameters: public <FirstType> Pair sortMinMax(Object<FirstType>[] array)

type Object does not take parameters: Object<FirstType> minimum = array[0]

type Object does not take parameters: Object<FirstType> maximum = array[0]

Here is my Class:

public class MinMaxArray {

  // takes an array of a given object and returns a pair
  // of the min and max array elements
  public <FirstType> Pair sortMinMax(Object<FirstType>[] array) {
    Object<FirstType> minimum = array[0];
    Object<FirstType> maximum = array[0];

    // loop through all array items and perform sort
    for (int counter = 1; counter < array.length; counter++) {
      // if this element is less than current min, set as min
      // else if this element is greater than current max, set as max
      if (array[counter].compareTo(minimum) < 0) {
        minimum = array[counter];
      } else if (array[counter].comparTo(maximum) > 0) {
        maximum = array[counter];
      } // end if else new min, max
    } // end for (all array items)

    return new Pair<FirstType, FirstType>(minimum, maximum);
  } // end compare()

} // end MinMaxArray

Body:
Firstly, avoid reference arrays. They don't play well with generics. Use List instead.

It's not clear to me if you intend FirstType to be a type or a generic parameter (which would usually be given a single letter name).

If FirstType is a type

public static Pair<FirstType,FirstType> sortMinMax(List<FirstType> things) {

If you mean a generic parameter, look at java.util.Collections.sort.

public static <T extends Comparable<? super T>> void sort(List<T> list) {

So

public static <T extends Comparable<? super T>> Pair<T,T> sortMinMax(List<T> list) {


问:
javascript chess board string concatenation
Why isn't my code working Its suppose to print a chessboard but it seams like its only printing the newline characters?

I am relatively new to JavaScript. Its suppose to determine if the line is number is even or odd and depending and then add  '#' and  ' ' to the board string. If the program is at the end of a row it adds a '\n'.

```<code>var width = 8, height = 8;

let board = "";

for(let n=0; n<height; n++)
{
  if(height % 2 === 0)
  {
    for(let i=0; i<width ; i++)
    {
      if(width%2===0)
      {
        board = board + " ";
      }
      else {
        board = board + "#";
      }
      if (i =width-1)
      {
        board = board + "\n";
      }
    }
  }
  else{
    for(let i=0; i<width ; i++)
    {
      if(width%2===0)
      {
        board += "#";
      }
      else {
        board += " ";
      }
      if (i =width-1)
      {
        board = board + "\n";
      }
    }
  }
}
console.log(board);
</code>```

答:
There's two things you're doing wrong :

At one place in your code, you're doing an i = width - 1 assignment where you should be doing a i == width - 1 comparison

At a few places in your code, you're comparing a value with width or height, where should should be comparing with n or i

Fixed code :

```<code>var width = 8, height = 8;
let board = "";

for(let n=0; n<height; n++)
{
  if(n % 2 === 0)
  {
    for(let i=0; i<width ; i++)
    {
      if(i%2===0)
      {
        board += " ";
      }
      else {
        board += "#";
      }
      if (i == width-1)
      {
        board += "\n";
      }
    }
  }
  else {
    for(let i=0; i<width ; i++)
    {
      if(i%2===0)
      {
        board += "#";
      }
      else {
        board += " ";
      }
      if (i == width-1)
      {
        board += "\n";
      }
    }
  }
}
</code>```

(see also this Fiddle)

After some further improvements :

```<code>let width = 8, height = 8, board = "";

for(let i = 0; i < height; i++) {
    for(let j = 0; j < width; j++) {
        if((i % 2 === 0 && j % 2 === 0) || (i % 2 !== 0 && j % 2 !== 0)) {
            board += " ";
        } else {
            board += "#";
        }
    }
    board += "\n";
}
</code>```

(see also this Fiddle)

Body:
Why isn't my code working Its suppose to print a chessboard but it seams like its only printing the newline characters?

I am relatively new to JavaScript. Its suppose to determine if the line is number is even or odd and depending and then add  '#' and  ' ' to the board string. If the program is at the end of a row it adds a '\n'.

var width = 8, height = 8;

let board = "";

for(let n=0; n<height; n++)
{
  if(height % 2 === 0)
  {
    for(let i=0; i<width ; i++)
    {
      if(width%2===0)
      {
        board = board + " ";
      }
      else {
        board = board + "#";
      }
      if (i =width-1)
      {
        board = board + "\n";
      }
    }
  }
  else{
    for(let i=0; i<width ; i++)
    {
      if(width%2===0)
      {
        board += "#";
      }
      else {
        board += " ";
      }
      if (i =width-1)
      {
        board = board + "\n";
      }
    }
  }
}
console.log(board);

Body:
There's two things you're doing wrong :

At one place in your code, you're doing an i = width - 1 assignment where you should be doing a i == width - 1 comparison

At a few places in your code, you're comparing a value with width or height, where should should be comparing with n or i

Fixed code :

var width = 8, height = 8;
let board = "";

for(let n=0; n<height; n++)
{
  if(n % 2 === 0)
  {
    for(let i=0; i<width ; i++)
    {
      if(i%2===0)
      {
        board += " ";
      }
      else {
        board += "#";
      }
      if (i == width-1)
      {
        board += "\n";
      }
    }
  }
  else {
    for(let i=0; i<width ; i++)
    {
      if(i%2===0)
      {
        board += "#";
      }
      else {
        board += " ";
      }
      if (i == width-1)
      {
        board += "\n";
      }
    }
  }
}

(see also this Fiddle)

After some further improvements :

let width = 8, height = 8, board = "";

for(let i = 0; i < height; i++) {
    for(let j = 0; j < width; j++) {
        if((i % 2 === 0 && j % 2 === 0) || (i % 2 !== 0 && j % 2 !== 0)) {
            board += " ";
        } else {
            board += "#";
        }
    }
    board += "\n";
}

(see also this Fiddle)


问:
Mongo: Move json string to a part of the document
I have a mongo collection where documents have aprox the following structure:

```<code>item{
    data{"emailBody":
           "{\"uniqueKey\":\" this is a stringified json\"}"
    }
}
</code>```

What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.

I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".

Is there a better way to handle stringified json in mongo?

答:
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:

```<code>db.collection.find({ "item.data.emailBody": { "$type": 2 } })
  .snapshot().forEach(function(doc){
    parsedEmailBody = JSON.parse(doc.item.data.emailBody);
    printjson(parsedEmailBody);
    db.collection.updateOne(
        { "_id": doc._id },
        { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
    );
});
</code>```

For large collections, leverage the updates using the Bulk API:

```<code>var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
    ops = [];

cursor.forEach(function(doc){
    var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
    ops.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
        }
    });

    if (ops.length === 500) {
        db.collection.bulkWrite(ops);
        ops = [];
    }
});

if (ops.length > 0) { db.collection.bulkWrite(ops); }
</code>```

Body:
I have a mongo collection where documents have aprox the following structure:

item{
    data{"emailBody":
           "{\"uniqueKey\":\" this is a stringified json\"}"
    }
}

What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.

I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".

Is there a better way to handle stringified json in mongo?

Body:
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:

db.collection.find({ "item.data.emailBody": { "$type": 2 } })
  .snapshot().forEach(function(doc){
    parsedEmailBody = JSON.parse(doc.item.data.emailBody);
    printjson(parsedEmailBody);
    db.collection.updateOne(
        { "_id": doc._id },
        { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
    );
});

For large collections, leverage the updates using the Bulk API:

var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
    ops = [];

cursor.forEach(function(doc){
    var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
    ops.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
        }
    });

    if (ops.length === 500) {
        db.collection.bulkWrite(ops);
        ops = [];
    }
});

if (ops.length > 0) { db.collection.bulkWrite(ops); }


问:
.sh script doesn't return variable correctly
I have created a file called alias.sh in which I have put this code:

```<code>#!/bin/bash

OUTPUT="$(alias | awk -F'[ =]' '{print $2}')"
echo "${OUTPUT}"
</code>```

Whenever I run the command alias | awk -F'[ =]' '{print $2}' in a terminal, it correctly returns a list of set aliases in my preferred format.

However, when I execute the script like $ ./alias.sh, it simply returns an empty line.

The script works if I replace the alias | awk -F'[ =]' '{print $2}' command with the ls command. It even preserves line breaks.

Can anybody help me understand why the script does not return the expected result?

答: You use $2 in the AWK script. However, that is replaced by the shell as the second argument to the shell script, which is nothing. You need to escape the dollar-sign, as in \$2. Or not use double-quotes " around the sub-shell.

Body:
I have created a file called alias.sh in which I have put this code:

#!/bin/bash

OUTPUT="$(alias | awk -F'[ =]' '{print $2}')"
echo "${OUTPUT}"

Whenever I run the command alias | awk -F'[ =]' '{print $2}' in a terminal, it correctly returns a list of set aliases in my preferred format.

However, when I execute the script like $ ./alias.sh, it simply returns an empty line.

The script works if I replace the alias | awk -F'[ =]' '{print $2}' command with the ls command. It even preserves line breaks.

Can anybody help me understand why the script does not return the expected result?


问:
Notify TextChanged in an EditText
Is there any way to notify the EditText that the text has changed when I do an EditText.setText("blablabla");

I have a SimpleTextChangeListener attached to this EditText and I want this to trigger when I do a setText on the EditText.

Is there any way I can achieve this?

答:
You can use TextWatcher to trigger any action on EditText.setText("blablabla"); If you setText to your EditText, onTextChanged() method will be called. Then you can trigger your desired action there.

```<code>editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                  // Trigger on setText
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
</code>```

Hope this helps.

Title: Notify TextChanged in an EditText

Body:
You can use TextWatcher to trigger any action on EditText.setText("blablabla"); If you setText to your EditText, onTextChanged() method will be called. Then you can trigger your desired action there.

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                  // Trigger on setText
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

Hope this helps.


问:
WPF - Refer to app icon in code
i have added an icon to a WPF app in the project properties.

How do I refer to that icon so I can add it to a
NotifyIcon that I am creating for system tray.

In code that is??

```<code>  System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
  ni.Icon = new System.Drawing.Icon("MyIcon.ico");
</code>```

Does not work.
Malcolm

答:
```<code>System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ni.Icon = System.Drawing.Icon.ExtractAssociatedIcon(
             System.Reflection.Assembly.GetEntryAssembly().ManifestModule.Name);
ni.Visible = true;
</code>```

OwnerDisplayName: Malcolm

Title: WPF - Refer to app icon in code

Body:
i have added an icon to a WPF app in the project properties.

How do I refer to that icon so I can add it to a
NotifyIcon that I am creating for system tray.

In code that is??

  System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
  ni.Icon = new System.Drawing.Icon("MyIcon.ico");

Does not work.
Malcolm

OwnerDisplayName: Stanislav Kniazev


问:
Invisible components and events
I have Flex 4 application in which I have one component as top layer which displays something like tooltips, basically user sees "presentation" which explains usage and meaning of the tools "below", sliders, checkboxes, text fields etc.
I made this "presentation" using sequences so first tooltip is visible, then becomes invisible, second is visible etc.

I tried to disable mouseChildren, mouseEnabled and other possible parameters which would disable those tooltips from preventing user clicking on some button or checkbox.

Obviously those components which render tooltips even tough invisible, are still "clickable".

Is there any way to fix this?

Thanks in advance

答:
Yep, answered my own question, here's the secret:</p>

```<code><s:SetAction property="includeInLayout" startDelay="0" value="false"/>
<s:SetAction property="includeInLayout" startDelay="30000" value="true"/>
</code>```

Title: Invisible components and events

Body:
Yep, answered my own question, here's the secret:

<s:SetAction property="includeInLayout" startDelay="0" value="false"/>
<s:SetAction property="includeInLayout" startDelay="30000" value="true"/>


问:
How to correctly link an external library using CMake?
I'm trying to use the Chilkat C++ library to do a cryptography assignment, but I cannot seem to get the library to link properly. As of right now the header file CkRsa.h cannot be found by the compiler. I've spent a few hours searching across the internet for solutions to no avail. Here is what I have so far (this is all in a Mac OS X environment):

The lib files are installed in /users/Adam/Desktop/chilkat/libDyn and the header files are in /users/Adam/Desktop/chilkat/include
Here is my CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.6)
project(SocketEncryption)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_library(chilkat STATIC IMPORTED)
set_property(
        TARGET chilkat
        PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
add_executable(SocketEncryption ${SOURCE_FILES})

target_link_libraries(SocketEncryption chilkat)
</code>```

Here is my main.cpp

```<code>#include <iostream>
#include <CkRsa.h>
//#include <CkPrivateKey.h>
//#include <CkSocket.h>

int main() {
    CkRsa alice;
    CkRsa bob;

    // Key Generation
    bool success = alice.GenerateKey(1024);
    const char *alicePublicKey = alice.exportPublicKey();
    const char *alicePrivateKey = alice.exportPrivateKey();
    const char *aliceMessage = "Hi, Bob. How are you?";

    // Encryption Step
    std::cout << "Encryption started." << std::endl;
    CkRsa rsaEncryptor;
    rsaEncryptor.put_EncodingMode("hex");
    success = rsaEncryptor.ImportPublicKey(alicePublicKey);
    bool usePrivateKey = false;
    const char * ciphertext = rsaEncryptor.encryptStringENC(aliceMessage, success);
    std::cout << ciphertext << std::endl;

    return 0;
}
</code>```

答:
I think this is a simply problem of how you ordered your calls. CMake does parse its scripts sequential. So the include_directories() call has to be put before the add_executable() call:

```<code>include_directories("/users/Adam/Desktop/chilkat/include")
add_executable(SocketEncryption ${SOURCE_FILES})
</code>```

The better way since CMake 2.8.12 would be to let the library propagate its header file paths:

```<code>target_include_directories(chilkat PUBLIC "/users/Adam/Desktop/chilkat/include")
</code>```

Or - for readability - add it directly via target properties:

```<code>set_property(
    TARGET chilkat
    PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
</code>```

See also CMake: Creating Relocatable Packages.

References

target_include_directories()

How is CMake used?

Is Cmake set variable recursive?

Body:
I'm trying to use the Chilkat C++ library to do a cryptography assignment, but I cannot seem to get the library to link properly. As of right now the header file CkRsa.h cannot be found by the compiler. I've spent a few hours searching across the internet for solutions to no avail. Here is what I have so far (this is all in a Mac OS X environment):

The lib files are installed in /users/Adam/Desktop/chilkat/libDyn and the header files are in /users/Adam/Desktop/chilkat/include
Here is my CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(SocketEncryption)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_library(chilkat STATIC IMPORTED)
set_property(
        TARGET chilkat
        PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
add_executable(SocketEncryption ${SOURCE_FILES})

target_link_libraries(SocketEncryption chilkat)

Here is my main.cpp

#include <iostream>
#include <CkRsa.h>
//#include <CkPrivateKey.h>
//#include <CkSocket.h>

int main() {
    CkRsa alice;
    CkRsa bob;

    // Key Generation
    bool success = alice.GenerateKey(1024);
    const char *alicePublicKey = alice.exportPublicKey();
    const char *alicePrivateKey = alice.exportPrivateKey();
    const char *aliceMessage = "Hi, Bob. How are you?";

    // Encryption Step
    std::cout << "Encryption started." << std::endl;
    CkRsa rsaEncryptor;
    rsaEncryptor.put_EncodingMode("hex");
    success = rsaEncryptor.ImportPublicKey(alicePublicKey);
    bool usePrivateKey = false;
    const char * ciphertext = rsaEncryptor.encryptStringENC(aliceMessage, success);
    std::cout << ciphertext << std::endl;

    return 0;
}

Body:
I think this is a simply problem of how you ordered your calls. CMake does parse its scripts sequential. So the include_directories() call has to be put before the add_executable() call:

include_directories("/users/Adam/Desktop/chilkat/include")
add_executable(SocketEncryption ${SOURCE_FILES})

The better way since CMake 2.8.12 would be to let the library propagate its header file paths:

target_include_directories(chilkat PUBLIC "/users/Adam/Desktop/chilkat/include")

Or - for readability - add it directly via target properties:

set_property(
    TARGET chilkat
    PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)

See also CMake: Creating Relocatable Packages.

References

target_include_directories()

How is CMake used?

Is Cmake set variable recursive?


问:
VBA - Name Excel Table Range and Paste Into Sheet 2
Can you name a Range("O1:AG15") with a specific cell text.

IE A1 contains "1234" ... name Range("O1:AG15") "1234" then copy that range into Worksheet2 (Not important where).

答:
To add a Named Range (workbook scope) that refers to Range("O1:AG15") in "Sheet1" use the line below:

```<code>ThisWorkbook.Names.Add _
            Name:=Worksheets("Sheet1").Range("A1").Value, _
            RefersTo:=Worksheets("Sheet1").Range("O1:AG15")
</code>```

To copy this Range to "Sheet2" use the code line below:

```<code>Range(Worksheets("Sheet1").Range("A1").Value).Copy Destination:=Worksheets("Sheet2").Range("A1")
</code>```

Edit 1: for Debug

```<code>Dim RangeName As String

RangeName = Worksheets("Sheet1").Range("A1").value
MsgBox RangeName

ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=Worksheets("Sheet1").Range("O1:AG15")
</code>```

Body:
To add a Named Range (workbook scope) that refers to Range("O1:AG15") in "Sheet1" use the line below:

ThisWorkbook.Names.Add _
            Name:=Worksheets("Sheet1").Range("A1").Value, _
            RefersTo:=Worksheets("Sheet1").Range("O1:AG15")

To copy this Range to "Sheet2" use the code line below:

Range(Worksheets("Sheet1").Range("A1").Value).Copy Destination:=Worksheets("Sheet2").Range("A1")

Edit 1: for Debug

Dim RangeName As String

RangeName = Worksheets("Sheet1").Range("A1").value
MsgBox RangeName

ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=Worksheets("Sheet1").Range("O1:AG15")