问:
DataTemplate doesn't properly bind the properties as specified
I have the following DataTemplate in DataTemplates.xaml

```<code><DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>
</code>```

I make sure that this DataTemplate is usable within the application scope via the following App.xaml definition:

```<code><Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DataTemplates.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

And this is my control ExcelReport.xaml:

```<code><UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
    <UserControl.DataContext>
        <local:ExcelReportVM/>
    </UserControl.DataContext>
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>
</code>```

My code behind: ExcelReport.xaml.cs

```<code>   public partial class ExcelReport : UserControl
    {

  public static readonly DependencyProperty RowColorConverterProperty = DependencyProperty.Register(
              "RowColorConverter",
              typeof(IValueConverter),
              typeof(ExcelReport),
              new FrameworkPropertyMetadata(new PropertyChangedCallback(OnRowColorConverterChanged))
            );

    public IValueConverter RowColorConverter
        {
            get { return (IValueConverter)GetValue(RowColorConverterProperty); }
            set { SetValue(RowColorConverterProperty, value); }
        }

   public ExcelReport()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

 private void OnLoaded(object sender, RoutedEventArgs e)
{
    Debug.Assert(DataContext.GetType()==typeof(ExcelReportVM)); //DataContext is correct
    Debug.Assert(RowColorConverter!=null); //but this is null
  }
}
</code>```

I've no idea why I can successfully bind the DataContext, but the <DataTemplate DataType="{x:Type local:ExcelReportVM}"> that I define is not used, I thought everything inside the DataTemplates.xaml is accessible to ExcelReport.xaml?

Note: There is no error in the output window, and there is no exception been thrown anywhere in the code.

答:
This is how I fix the problem, I don't set the UserControl.DataContext to ExcelReportVM at ExcelReport.xaml; instead, I set the ContentControl.Content to ExcelReportVM at MainWindow.xaml.

Updated code at ExcelReport.xaml:

```<code><UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
  <!--  <UserControl.DataContext>   this is not longer needed
        <local:ExcelReportVM/>
    </UserControl.DataContext> -->
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>
</code>```

Code at MainWindow.xaml

```<code><Syncfusion:RibbonWindow x:Class="WpfApplication1.MainWindow"
            ...
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" WindowState="Maximized"
        Syncfusion:SkinStorage.VisualStyle="Office2013"
        xmlns:Syncfusion="http://schemas.syncfusion.com/wpf">

    <Grid x:Name="ExcelReport22">
        <ContentControl>   <!-- this is where the ExcelReportVM is binded to -->
            <local:ExcelReportVM/>
        </ContentControl>

    </Grid>
</Syncfusion:RibbonWindow>
</code>```

Body:
I have the following DataTemplate in DataTemplates.xaml

<DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>

I make sure that this DataTemplate is usable within the application scope via the following App.xaml definition:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DataTemplates.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

And this is my control ExcelReport.xaml:

<UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
    <UserControl.DataContext>
        <local:ExcelReportVM/>
    </UserControl.DataContext>
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>

My code behind: ExcelReport.xaml.cs

   public partial class ExcelReport : UserControl
    {

  public static readonly DependencyProperty RowColorConverterProperty = DependencyProperty.Register(
              "RowColorConverter",
              typeof(IValueConverter),
              typeof(ExcelReport),
              new FrameworkPropertyMetadata(new PropertyChangedCallback(OnRowColorConverterChanged))
            );

    public IValueConverter RowColorConverter
        {
            get { return (IValueConverter)GetValue(RowColorConverterProperty); }
            set { SetValue(RowColorConverterProperty, value); }
        }

   public ExcelReport()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

 private void OnLoaded(object sender, RoutedEventArgs e)
{
    Debug.Assert(DataContext.GetType()==typeof(ExcelReportVM)); //DataContext is correct
    Debug.Assert(RowColorConverter!=null); //but this is null
  }
}

I've no idea why I can successfully bind the DataContext, but the <DataTemplate DataType="{x:Type local:ExcelReportVM}"> that I define is not used, I thought everything inside the DataTemplates.xaml is accessible to ExcelReport.xaml?

Note: There is no error in the output window, and there is no exception been thrown anywhere in the code.

Body:
This is how I fix the problem, I don't set the UserControl.DataContext to ExcelReportVM at ExcelReport.xaml; instead, I set the ContentControl.Content to ExcelReportVM at MainWindow.xaml.

Updated code at ExcelReport.xaml:

<UserControl x:Class="WpfApplication1.ExcelReport"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              ....
             xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="HeaderTemplate">
            <TextBlock TextAlignment="Center" Text="{Binding .}" TextWrapping="WrapWithOverflow" />
        </DataTemplate>

    </UserControl.Resources>
  <!--  <UserControl.DataContext>   this is not longer needed
        <local:ExcelReportVM/>
    </UserControl.DataContext> -->
    <syncfusion:SfDataGrid ItemsSource="{Binding Entries}" x:Name="grid" Background="White"
                           HeaderTemplate="{StaticResource HeaderTemplate}"

                           SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=UserControl}}">
    </syncfusion:SfDataGrid>
</UserControl>

Code at MainWindow.xaml

<Syncfusion:RibbonWindow x:Class="WpfApplication1.MainWindow"
            ...
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" WindowState="Maximized"
        Syncfusion:SkinStorage.VisualStyle="Office2013"
        xmlns:Syncfusion="http://schemas.syncfusion.com/wpf">

    <Grid x:Name="ExcelReport22">
        <ContentControl>   <!-- this is where the ExcelReportVM is binded to -->
            <local:ExcelReportVM/>
        </ContentControl>

    </Grid>
</Syncfusion:RibbonWindow>


来源: stackexchange

问:
Mongoose fetch records from two related collections with populate
I need to know how to perform lookup operation in the following collections.
The id of collection one is used as projectsId in collection two. I have given the contoller.js and model files below kindly tell me where I have to place the lookup to get the records from two collections

collection one:

```<code>/* 1 */
{
    "_id" : ObjectId("58dcda850a13352724d4c716"),
    "name" : "senthil",
    "designation" : "CI",
    "berief_text" : null,
    "status" : 1,
    "__v" : 0,
    "type" : 1
}

/* 2 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c719"),
    "name" : "ssss",
    "designation" : "sssss",
    "berief_text" : null,
    "status" : 2,
    "__v" : 0
}
</code>```

collection two:

```<code>/* 1 */
{
    "_id" : ObjectId("58dcda850a13352724d4c717"),
    "imageLocation" : "uploads\\project_images\\14908688692032.png",
    "projectId" : ObjectId("58dcda850a13352724d4c716"),
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("58dcda850a13352724d4c718"),
    "imageLocation" : "uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG",
    "projectId" : ObjectId("58dcda850a13352724d4c716"),
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c71a"),
    "imageLocation" : "uploads\\project_images\\14908689587042.png",
    "projectId" : ObjectId("58dcdade0a13352724d4c719"),
    "__v" : 0
}

/* 4 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c71b"),
    "imageLocation" : "uploads\\project_images\\14908689587321.png",
    "projectId" : ObjectId("58dcdade0a13352724d4c719"),
    "__v" : 0
}
</code>```

controller.js

```<code>var express = require("express"),
 router = express.Router(),
 project = require("../../models/project.js"),
 projectimage = require("../../models/projectimages.js"),
router.get("/", function(req, res) {

 project.find({}, function(err, data){
          if(err){
            res.send(err);
          }
          res.send(data);
        });

  projectimage.find({}, function(err, data){
          if(err){
            res.send(err);
          }
          res.send(data);
        });

})
</code>```

project.js

```<code>var mongoose = require("mongoose"),
 Schema = mongoose.Schema,
 objectId = mongoose.Schema.ObjectId;
    var projectSchema = new Schema({
      name    : {type: String, required : true},
      designation    : {type: String, required : true},
      status    : {type: Number, required : true},
      type    : {type: Number, required : true},
      berief_text : {type: String, required : true},
        });
    var project = mongoose.model("project", projectSchema);
    module.exports = project;
</code>```

projectimages.js

```<code>var mongoose = require("mongoose"),
 Schema = mongoose.Schema,
 objectId = mongoose.Schema.ObjectId;

var ProjectimageSchema = new mongoose.Schema({
    imageLocation: String,
    projectId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'project'
    },

});

var projectimage = mongoose.model("projectimage", ProjectimageSchema);

module.exports = projectimage;
</code>```

obtained output

Server is running at : http://localhost:3002

```<code>[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1 },
  { _id: 58dcdade0a13352724d4c719,
    name: 'ssss',
    designation: 'sssss',
    berief_text: null,
    status: 2,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71a,
    imageLocation: 'uploads\\project_images\\14908689587042.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71b,
    imageLocation: 'uploads\\project_images\\14908689587321.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1 },
  { _id: 58dcdade0a13352724d4c719,
    name: 'ssss',
    designation: 'sssss',
    berief_text: null,
    status: 2,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71a,
    imageLocation: 'uploads\\project_images\\14908689587042.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71b,
    imageLocation: 'uploads\\project_images\\14908689587321.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 } ]
</code>```

expected output

```<code>[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1.
    images:[{ _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 }]
},

]
</code>```

my for each loop

```<code> project.find({}, function(err, data){
          if(err){
            res.send(err);
          }

for each (var v in data) {
    console.log(v);
}
        });
</code>```

答:
Use population to to get referenced data. While your reference is currently be defined in your ProjectimageSchema you have to add a ref to projectsSchema too. You may going to rename the ref property projectId in your ProjectimageSchema into project to make it more clear.

Project Schema

```<code>var projectSchema = new Schema({
    name: {type: String, required : true},
    designation: {type: String, required : true},
    status: {type: Number, required : true},
    type: {type: Number, required : true},
    berief_text: {type: String, required : true},
    images: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Projectimage'
    }
});
</code>```

ProjectImages Schema

```<code>var ProjectimageSchema = new mongoose.Schema({
    imageLocation: String,
    project: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'project'
    }
});
</code>```

Once you done this you could fetch the related data + related data with populate:

```<code>//get all project with relates images
project.find()
    .populate('images')
    .exec(function (err, post) {
        if (err) return handleError(err);
    });

//get all project images with relates projects
projectimage.find()
    .populate('project')
    .exec(function (err, post) {
        if (err) return handleError(err);
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to know how to perform lookup operation in the following collections.
The id of collection one is used as projectsId in collection two. I have given the contoller.js and model files below kindly tell me where I have to place the lookup to get the records from two collections

collection one:

/* 1 */
{
    "_id" : ObjectId("58dcda850a13352724d4c716"),
    "name" : "senthil",
    "designation" : "CI",
    "berief_text" : null,
    "status" : 1,
    "__v" : 0,
    "type" : 1
}

/* 2 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c719"),
    "name" : "ssss",
    "designation" : "sssss",
    "berief_text" : null,
    "status" : 2,
    "__v" : 0
}

collection two:

/* 1 */
{
    "_id" : ObjectId("58dcda850a13352724d4c717"),
    "imageLocation" : "uploads\\project_images\\14908688692032.png",
    "projectId" : ObjectId("58dcda850a13352724d4c716"),
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("58dcda850a13352724d4c718"),
    "imageLocation" : "uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG",
    "projectId" : ObjectId("58dcda850a13352724d4c716"),
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c71a"),
    "imageLocation" : "uploads\\project_images\\14908689587042.png",
    "projectId" : ObjectId("58dcdade0a13352724d4c719"),
    "__v" : 0
}

/* 4 */
{
    "_id" : ObjectId("58dcdade0a13352724d4c71b"),
    "imageLocation" : "uploads\\project_images\\14908689587321.png",
    "projectId" : ObjectId("58dcdade0a13352724d4c719"),
    "__v" : 0
}

controller.js

var express = require("express"),
 router = express.Router(),
 project = require("../../models/project.js"),
 projectimage = require("../../models/projectimages.js"),
router.get("/", function(req, res) {

 project.find({}, function(err, data){
          if(err){
            res.send(err);
          }
          res.send(data);
        });

  projectimage.find({}, function(err, data){
          if(err){
            res.send(err);
          }
          res.send(data);
        });

})

project.js

var mongoose = require("mongoose"),
 Schema = mongoose.Schema,
 objectId = mongoose.Schema.ObjectId;
    var projectSchema = new Schema({
      name    : {type: String, required : true},
      designation    : {type: String, required : true},
      status    : {type: Number, required : true},
      type    : {type: Number, required : true},
      berief_text : {type: String, required : true},
        });
    var project = mongoose.model("project", projectSchema);
    module.exports = project;

projectimages.js

var mongoose = require("mongoose"),
 Schema = mongoose.Schema,
 objectId = mongoose.Schema.ObjectId;

var ProjectimageSchema = new mongoose.Schema({
    imageLocation: String,
    projectId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'project'
    },

});

var projectimage = mongoose.model("projectimage", ProjectimageSchema);

module.exports = projectimage;

obtained output

Server is running at : http://localhost:3002

[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1 },
  { _id: 58dcdade0a13352724d4c719,
    name: 'ssss',
    designation: 'sssss',
    berief_text: null,
    status: 2,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71a,
    imageLocation: 'uploads\\project_images\\14908689587042.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71b,
    imageLocation: 'uploads\\project_images\\14908689587321.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1 },
  { _id: 58dcdade0a13352724d4c719,
    name: 'ssss',
    designation: 'sssss',
    berief_text: null,
    status: 2,
    __v: 0 } ]
[ { _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71a,
    imageLocation: 'uploads\\project_images\\14908689587042.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 },
  { _id: 58dcdade0a13352724d4c71b,
    imageLocation: 'uploads\\project_images\\14908689587321.png',
    projectId: 58dcdade0a13352724d4c719,
    __v: 0 } ]

expected output

[ { _id: 58dcda850a13352724d4c716,
    name: 'senthil',
    designation: 'CI',
    berief_text: null,
    status: 1,
    __v: 0,
    type: 1.
    images:[{ _id: 58dcda850a13352724d4c717,
    imageLocation: 'uploads\\project_images\\14908688692032.png',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 },
  { _id: 58dcda850a13352724d4c718,
    imageLocation: 'uploads\\project_images\\1490868869210201876891658ad792131c9520170222051225.JPG',
    projectId: 58dcda850a13352724d4c716,
    __v: 0 }]
},

]

my for each loop

 project.find({}, function(err, data){
          if(err){
            res.send(err);
          }

for each (var v in data) {
    console.log(v);
}
        });

Body:
Use population to to get referenced data. While your reference is currently be defined in your ProjectimageSchema you have to add a ref to projectsSchema too. You may going to rename the ref property projectId in your ProjectimageSchema into project to make it more clear.

Project Schema

var projectSchema = new Schema({
    name: {type: String, required : true},
    designation: {type: String, required : true},
    status: {type: Number, required : true},
    type: {type: Number, required : true},
    berief_text: {type: String, required : true},
    images: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Projectimage'
    }
});

ProjectImages Schema

var ProjectimageSchema = new mongoose.Schema({
    imageLocation: String,
    project: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'project'
    }
});

Once you done this you could fetch the related data + related data with populate:

//get all project with relates images
project.find()
    .populate('images')
    .exec(function (err, post) {
        if (err) return handleError(err);
    });

//get all project images with relates projects
projectimage.find()
    .populate('project')
    .exec(function (err, post) {
        if (err) return handleError(err);
    });


问:
onAccessibilityEvent(AccessibilityEvent event)->event.getText() Identifying hint and user text
```<code> public void onAccessibilityEvent(AccessibilityEvent event) {
      case AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE:
                String text = event.getText().toString();
}
</code>```

The current code even return the hint in the event.getText(), How to know whether the text is user entered or hint.

答: we can use getBeforeText() from the event function</p>

Body:
 public void onAccessibilityEvent(AccessibilityEvent event) {
      case AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE:
                String text = event.getText().toString();
}

The current code even return the hint in the event.getText(), How to know whether the text is user entered or hint.


问:
index match value error
When I try to do an index-match lookup with 2 conditions, I always get a #Value! error even though I seem to be doing everything about in the exact same way as every excel tutorial out there.

Need it for a file with over 400'000 rows, so anything manual isn't really an option. Any advice? Thanks a million in advance!

Table 1

X1        X2          Y

Apple   01.05.2010  CHF 10

Apple   30.02.2010  CHF 15

Mango   20.01.2008  CHF 5

Mango   10.12.2011  CHF 4

…   …   …

Table 2

X1        X2          Y

Apple   01.05.2010  #VALUE!

Formula in field Y of Table 2:

```<code>=INDEX(D4:D7;MATCH(H4&I4;B4:B7&C4:C7;0))
</code>```

答: Max nothing is wrong with your Formula, you simply press F2,, and press Ctrl +Shift +DEL since it's an Array formula. </p>

Title: index match value error

Body:
When I try to do an index-match lookup with 2 conditions, I always get a #Value! error even though I seem to be doing everything about in the exact same way as every excel tutorial out there.

Need it for a file with over 400'000 rows, so anything manual isn't really an option. Any advice? Thanks a million in advance!

Table 1

X1        X2          Y

Apple   01.05.2010  CHF 10

Apple   30.02.2010  CHF 15

Mango   20.01.2008  CHF 5

Mango   10.12.2011  CHF 4

…   …   …

Table 2

X1        X2          Y

Apple   01.05.2010  #VALUE!

Formula in field Y of Table 2:

=INDEX(D4:D7;MATCH(H4&I4;B4:B7&C4:C7;0))


问:
Accessing Elements or Controls in a UWP ControlTemplate
I have a XAML UserControl that inherits from the CalendarView element. In the CalendarViewItemStyle, I have edited the ControlTemplate to hold a Grid and a TextBox.

```<code><Style x:Name="CalDayStyle"
           TargetType="CalendarViewDayItem">
        <Setter Property="Background"
                Value="Transparent" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate x:Name="cTemp">
                    <Grid x:Name="RootGrid"
                          Background="{TemplateBinding Background}">
                        <StackPanel x:Name="CalDayStack"
                                    Orientation="Vertical"
                                    VerticalAlignment="Stretch">
                            <TextBlock x:Name="tasksPres"
                                       TextAlignment="Center"
                                       HorizontalAlignment="Stretch">

                            </TextBlock>
                        </StackPanel>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

I am trying to access the TextBox but to no avail, using FindName(). What do I do.

答:
FindName cannot find names that are defined in applied templates. To find items in applied templates, use VisualTreeHelper.GetChild to get the applied template root object. Then you can call FindName on that root object, and you will be searching the XAML namescope of the template rather than the greater page.

If you want to get the TextBlock in your Style, you should be able touse the VisualTreeHelper to get it.

For examole:

```<code>public MainPage()
{
    this.InitializeComponent();
    texts = new List<TextBlock>();
}

private List<TextBlock> texts;

private void Button_Click(object sender, RoutedEventArgs e)
{
    IEnumerable<TextBlock> textBlocks = FindVisualChildren<TextBlock>(Mycontrol);
    foreach (var textBlock in textBlocks)
    {
        if (textBlock.Name == "tasksPres")
        {
            texts.Add(textBlock);
        }
    }
    foreach (var item in texts)
    {
        item.Text = "11111111111";
    }
}

private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}
</code>```

Body:
I have a XAML UserControl that inherits from the CalendarView element. In the CalendarViewItemStyle, I have edited the ControlTemplate to hold a Grid and a TextBox.

I am trying to access the TextBox but to no avail, using FindName(). What do I do.

Body:
FindName cannot find names that are defined in applied templates. To find items in applied templates, use VisualTreeHelper.GetChild to get the applied template root object. Then you can call FindName on that root object, and you will be searching the XAML namescope of the template rather than the greater page.

If you want to get the TextBlock in your Style, you should be able touse the VisualTreeHelper to get it.

For examole:

public MainPage()
{
    this.InitializeComponent();
    texts = new List<TextBlock>();
}

private List<TextBlock> texts;

private void Button_Click(object sender, RoutedEventArgs e)
{
    IEnumerable<TextBlock> textBlocks = FindVisualChildren<TextBlock>(Mycontrol);
    foreach (var textBlock in textBlocks)
    {
        if (textBlock.Name == "tasksPres")
        {
            texts.Add(textBlock);
        }
    }
    foreach (var item in texts)
    {
        item.Text = "11111111111";
    }
}

private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}


问:
C# - Is it possible (and how) to perform XSL transformations using SgmlReader
I needed to transform the contents of an HTML web page using XSLT
. Hence I used SgmlReader and wrote the snippet shown below (I
thought, in the end, it's an XmlReader too ...)

```<code>XmlReader xslr = XmlReader.Create(new StringReader(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" +
    "<xsl:output method=\"xml\" encoding=\"UTF-8\" version=\"1.0\" />" +
    "<xsl:template match=\"/\">" +
    "<XXX xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><xsl:value-of select=\"count(//br)\" /></XXX>" +
    "</xsl:template>" +
    "</xsl:stylesheet>"));

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xslr);

using (SgmlReader html = new SgmlReader())
{
    StringBuilder sb = new StringBuilder();
    using (TextWriter sw = new StringWriter(sb))
    using (XmlWriter xw = new XmlTextWriter(sw))
    {
        html.InputStream = new StringReader(Resources.html_orig);
        html.DocType = "HTML";

        try
        {
            xslt.Transform(html, xw);
            string output = sb.ToString();
            System.Console.WriteLine(output);
        }
        catch (Exception exc)
        {
            System.Console.WriteLine("{0} : {1}", exc.GetType().Name, exc.Message);
            System.Console.WriteLine(exc.StackTrace);
        }
    }
}
</code>```

Nonetheless , I get thos error message

```<code>NullReferenceException : Object reference not set to an instance of an object.
   at MS.Internal.Xml.Cache.XPathDocumentBuilder.Initialize(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at MS.Internal.Xml.Cache.XPathDocumentBuilder..ctor(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
   at System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
   at System.Xml.Xsl.Runtime.XmlQueryContext.ConstructDocument(Object dataSource, String uriRelative, Uri uriResolved)
   at System.Xml.Xsl.Runtime.XmlQueryContext..ctor(XmlQueryRuntime runtime, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules)
   at System.Xml.Xsl.Runtime.XmlQueryRuntime..ctor(XmlQueryStaticData data, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer, Boolean closeWriter)
   at System.Xml.Xsl.XmlILCommand.Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results)
   at System.Xml.Xsl.XslCompiledTransform.Transform(XmlReader input, XmlWriter results)
</code>```

I found a way to work around this by converting the HTML to XML and then applying the transform , but that's an inefficient solution because :

Intermediate XHTML output goes to a buffer , so extra memory is needed

Conversion process needs extra CPU processing
and the same hierarchy is traversed twice (in theory unnecessarily).

So (since I know StackOverflow community always provides great answers whereas other C# forums have completely disappointed me ;o) I'll be looking for feedback and suggestions so as to perform XSL transformations using HTML directly (even if SgmlReader needs to be replaced by another similar library).

答:
Even if the SgmlReader class is extending the XmlReader class it doesn't mean that it also behaves like an XmlReader.

Technically it also does not make sense that SgmlReader is a subclass of XmlReader, simply because SGML is a superset of XML and not a subset.

You didn't write about the purpose of your transformation, but in general HTML Agility Pack is a good option for manipulating HTML.

ContentLicense: CC BY-SA 4.0

Body:
I needed to transform the contents of an HTML web page using XSLT
. Hence I used SgmlReader and wrote the snippet shown below (I
thought, in the end, it's an XmlReader too ...)

XmlReader xslr = XmlReader.Create(new StringReader(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" +
    "<xsl:output method=\"xml\" encoding=\"UTF-8\" version=\"1.0\" />" +
    "<xsl:template match=\"/\">" +
    "<XXX xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><xsl:value-of select=\"count(//br)\" /></XXX>" +
    "</xsl:template>" +
    "</xsl:stylesheet>"));

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xslr);

using (SgmlReader html = new SgmlReader())
{
    StringBuilder sb = new StringBuilder();
    using (TextWriter sw = new StringWriter(sb))
    using (XmlWriter xw = new XmlTextWriter(sw))
    {
        html.InputStream = new StringReader(Resources.html_orig);
        html.DocType = "HTML";

        try
        {
            xslt.Transform(html, xw);
            string output = sb.ToString();
            System.Console.WriteLine(output);
        }
        catch (Exception exc)
        {
            System.Console.WriteLine("{0} : {1}", exc.GetType().Name, exc.Message);
            System.Console.WriteLine(exc.StackTrace);
        }
    }
}

Nonetheless , I get thos error message

NullReferenceException : Object reference not set to an instance of an object.
   at MS.Internal.Xml.Cache.XPathDocumentBuilder.Initialize(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at MS.Internal.Xml.Cache.XPathDocumentBuilder..ctor(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
   at System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
   at System.Xml.Xsl.Runtime.XmlQueryContext.ConstructDocument(Object dataSource, String uriRelative, Uri uriResolved)
   at System.Xml.Xsl.Runtime.XmlQueryContext..ctor(XmlQueryRuntime runtime, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules)
   at System.Xml.Xsl.Runtime.XmlQueryRuntime..ctor(XmlQueryStaticData data, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer, Boolean closeWriter)
   at System.Xml.Xsl.XmlILCommand.Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results)
   at System.Xml.Xsl.XslCompiledTransform.Transform(XmlReader input, XmlWriter results)

I found a way to work around this by converting the HTML to XML and then applying the transform , but that's an inefficient solution because :

Intermediate XHTML output goes to a buffer , so extra memory is needed

Conversion process needs extra CPU processing
and the same hierarchy is traversed twice (in theory unnecessarily).

So (since I know StackOverflow community always provides great answers whereas other C# forums have completely disappointed me ;o) I'll be looking for feedback and suggestions so as to perform XSL transformations using HTML directly (even if SgmlReader needs to be replaced by another similar library).

ContentLicense: CC BY-SA 2.5


问:
mPdf - How do get word break?
I have a justified text in mPDF within a column:

```<code><columns column-count="2" vAlign="justify" column-gap="9" />
Lorem ipsum ....
</code>```

Is it possible to get a word break, so you do not get such ugly lines:

答:
TL;DR: It's all described in the documentation.

Either split your words manually with Word break U+200B characters, or you can use mPDFs auto hyphenation which has a dictionary for Deutsch already distributed with the package.

```<code><?php

$mpdf = new mPDF();

$mpdf->SHYlang = 'de';
$mpdf->SHYleftmin = 3;

$mpdf->WriteHTML('auflauerte und hatte das Lebkuchenhäuschen bloß gebaut, um sie');

$mpdf->Output();
</code>```

You can also use CSS property

```<code>hyphens: auto;
</code>```

Entire hyphenation example can be found in the mPDF examples repository.

Title: mPdf - How do get word break?

Body:
I have a justified text in mPDF within a column:

<columns column-count="2" vAlign="justify" column-gap="9" />
Lorem ipsum ....

Is it possible to get a word break, so you do not get such ugly lines:

Body:
TL;DR: It's all described in the documentation.

Either split your words manually with Word break U+200B characters, or you can use mPDFs auto hyphenation which has a dictionary for Deutsch already distributed with the package.

<?php

$mpdf = new mPDF();

$mpdf->SHYlang = 'de';
$mpdf->SHYleftmin = 3;

$mpdf->WriteHTML('auflauerte und hatte das Lebkuchenhäuschen bloß gebaut, um sie');

$mpdf->Output();

You can also use CSS property

hyphens: auto;

Entire hyphenation example can be found in the mPDF examples repository.


问:
Extend current API's in Magento to get items in JSON format
I am a beginner to Magento. I am trying to extend the current API classes in Magento to fulfill my requirements and retrieve data in JSON format. I need:

I need to get all stores in a website

I need to get all Categories and Subcategories in a specific store

I need to get all products in a specific Category.

All data retrieved should be in JSON format.

Any blog/Forum topic? Any kind of help?

Thanks in advance.

答:
never been is such situation , but an idea came to mind is to invoke a SOAP service or XML-RPC , then convert whatever data needed to JSON.

Magento offers SOAP or XML-RPC web service to be automatically generated with specific roles for users, very useful.


问:
Counter not working when use if check
When I click on my button I am trying to check the label-category has been created

($('#label-' + category_name).length === 0) {

For some reason if i use  ($('#label-' + category_name).length === 0) { it is stopping the counter.

Question: How can I make sure that can get the counter to work when have this if ($('#label-' + category_name).length === 0) {

I use codeigniter frame work also if that helps

Example how should perform here

```<code><script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    e.preventDefault();

    var category_name = $(this).attr('data-name');
    var category_id = $(this).attr('data-id');

    if ($('#label-' + category_name).length === 0) {

        switch(counter) {
            case 0:
                element = 'label-default';
                break;
            case 1:
                element = 'label-primary';
                break;
            case 2:
                element = 'label-success';
                break;
            case 3:
                element = 'label-info';
                break;
            case 4:
                element = 'label-warning';
                break;
        }

        counter = (counter + 1) % 5;

        html = '';
        html += '<li id="label-'+category_name+'">';
        html += '<span class="label ' + element + '">';
        html += category_name;
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);

    }

    $('.categories-panel').html("");
});
</script>
</code>```

Full code

```<code><?php if ($categories) {?>
    <div class="panel panel-default">
        <div class="panel-body">
            <?php
            foreach (array_chunk($categories, 4) as $category) {
            ?>
                <div class="row">
                    <?php
                    foreach ($category as $category) {
                    ?>
                        <div class="col-sm-4">
                            <div class="media">
                                <div class="media-left">
                                    <a href="#"></a>
                                </div>
                                <div class="media-body">
                                    <h4 class="media-heading" style="cursor: pointer;">
                                        <span
                                            class="category_title"
                                            id="category_title"
                                            data-name="<?php echo $category['name'];?>"
                                            data-id="<?php echo $category['category_id'];?>"
                                        >
                                            <?php echo $category['name'];?>
                                        </span>
                                    </h4>
                                    <?php
                                    echo $category['description'];
                                    ?>
                                </div>
                            </div>
                        </div>
                    <?php
                    }
                    ?>
                </div>
            <?php
            }
            ?>
        </div>
    </div>
<?php
}
?>

<script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    e.preventDefault();

    var category_name = $(this).attr('data-name');
    var category_id = $(this).attr('data-id');

    if ($('#label-' + category_name).length === 0) {

        switch(counter) {
            case 0:
                element = 'label-default';
                break;
            case 1:
                element = 'label-primary';
                break;
            case 2:
                element = 'label-success';
                break;
            case 3:
                element = 'label-info';
                break;
            case 4:
                element = 'label-warning';
                break;
        }

        counter = (counter + 1) % 5;

        html = '';
        html += '<li id="label-'+category_name+'">';
        html += '<span class="label ' + element + '">';
        html += category_name;
        html += '</span>';
        html += '</li>';

        $('.categories ul').append(html);

    }

    $('.categories-panel').html("");
});
</script>
</code>```

ask.php

```<code><div class="container">
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        </div>
    </div>

    <?php
    echo form_open(
        'questions/ask/submit',
        array(
            'id' => 'post-form'
        )
    );
    ?>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="text"
                    name="ask_title"
                    id="ask_title"
                    placeholder="Question Title"
                    class="form-control"
                />
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <textarea
                    name="ask_message"
                    id="ask_message"
                    class="form-control"
                    rows="15"
                    placeholder="Your message..."
                ></textarea>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="categories">
                <ul class="list-inline"></ul>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="text"
                    name="category_name"
                    id="category_name"
                    class="form-control"
                    placeholder="Choose category"
                />
                <div class="categories-panel"></div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="form-group">
                <input
                    type="submit"
                    name="submit_button"
                    id="submit_button"
                    class="btn btn-default"
                />
            </div>
        </div>
    </div>

    <?php echo form_close();?>
</div>

<script type="text/javascript">
    $( document ).ready(function() {
        $("#category_name").on('keyup', function(e){
            $.ajax({
                url: '<?php echo base_url('questions/ask/getcategories');?>',
                type: "post",
                data: {
                    category_name: $('#category_name').val()
                },
                dataType: 'json',
                success: function(json){
                    $('.categories-panel').html(json);
                }
            });
        });
    });
</script>
</code>```

答:
WORKING NOW What I have done now is moved this script below over to the main ask.php view in my codeigniter

And I have added

```<code>e.stopPropagation();
e.preventDefault();

if ($('span[id="' + category_name + '"]').length > 0) {
    return false;
}
</code>```

Script

```<code><script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    var category_name = $(this).attr('data-name');

    e.stopPropagation();
    e.preventDefault();

    if ($('span[id="' + category_name + '"]').length > 0) {
        return false;
    }

    switch(counter) {
        case 0:
            element = 'label-default';
        break;
        case 1:
            element = 'label-primary';
        break;
        case 2:
            element = 'label-success';
        break;
        case 3:
            element = 'label-info';
        break;
        case 4:
            element = 'label-warning';
        break;
    }

    counter = (counter + 1) % 5;

    html = '';
    html += '<li>';
    html += '<span id="' + category_name + '" class="label ' + element + '">' + category_name + '</span>';
    html += '</li>';

    $('.categories ul').append(html);

    //$('.categories-panel').html("");
});
</script>
</code>```

Title: Counter not working when use if check

Body:
When I click on my button I am trying to check the label-category has been created

($('#label-' + category_name).length === 0) {

For some reason if i use  ($('#label-' + category_name).length === 0) { it is stopping the counter.

Question: How can I make sure that can get the counter to work when have this if ($('#label-' + category_name).length === 0) {

I use codeigniter frame work also if that helps

Example how should perform here

Full code

<?php if ($categories) {?>

            <?php
            foreach (array_chunk($categories, 4) as $category) {
            ?>

                    <?php
                    foreach ($category as $category) {
                    ?>

                                        <span
                                            class="category_title"
                                            id="category_title"
                                            data-name="<?php echo $category['name'];?>"
                                            data-id="<?php echo $category['category_id'];?>"
                                        >
                                            <?php echo $category['name'];?>

                                    <?php
                                    echo $category['description'];
                                    ?>

                    <?php
                    }
                    ?>

            <?php
            }
            ?>

<?php
}
?>

ask.php

    <?php
    echo form_open(
        'questions/ask/submit',
        array(
            'id' => 'post-form'
        )
    );
    ?>

                <input
                    type="text"
                    name="ask_title"
                    id="ask_title"
                    placeholder="Question Title"
                    class="form-control"
                />

                <textarea
                    name="ask_message"
                    id="ask_message"
                    class="form-control"
                    rows="15"
                    placeholder="Your message..."
                ></textarea>

                <input
                    type="text"
                    name="category_name"
                    id="category_name"
                    class="form-control"
                    placeholder="Choose category"
                />

                <input
                    type="submit"
                    name="submit_button"
                    id="submit_button"
                    class="btn btn-default"
                />

    <?php echo form_close();?>

Body:
WORKING NOW What I have done now is moved this script below over to the main ask.php view in my codeigniter

And I have added

e.stopPropagation();
e.preventDefault();

if ($('span[id="' + category_name + '"]').length > 0) {
    return false;
}

Script

<script type="text/javascript">
var counter = 0;

$(document).on('click', '.category_title', function(e){

    var category_name = $(this).attr('data-name');

    e.stopPropagation();
    e.preventDefault();

    if ($('span[id="' + category_name + '"]').length > 0) {
        return false;
    }

    switch(counter) {
        case 0:
            element = 'label-default';
        break;
        case 1:
            element = 'label-primary';
        break;
        case 2:
            element = 'label-success';
        break;
        case 3:
            element = 'label-info';
        break;
        case 4:
            element = 'label-warning';
        break;
    }

    counter = (counter + 1) % 5;

    html = '';
    html += '<li>';
    html += '<span id="' + category_name + '" class="label ' + element + '">' + category_name + '</span>';
    html += '</li>';

    $('.categories ul').append(html);

    //$('.categories-panel').html("");
});
</script>


问:
Timeout is displaying Text in command prompt
I know I posted a comment recently, but I need more help, (this is probably some thing really obvious).

Anyway, my problem is when I use

```<code>timeout 2
</code>```

It shows the text, that I do not want the user to see.

```<code>Waiting for NUMBER seconds, press a key to continue ...
</code>```

How do I make it so this text can not be seen?

Thanks for any help!

答:
```<code>timeout /t 2 >nul
</code>```

Not sure just timeout 2 would work - and make sure there's a space after the 2

...Ah, yes the /T is optional...make an uncommon amount of sense.

Body:
I know I posted a comment recently, but I need more help, (this is probably some thing really obvious).

Anyway, my problem is when I use

timeout 2

It shows the text, that I do not want the user to see.

Waiting for NUMBER seconds, press a key to continue ...

How do I make it so this text can not be seen?

Thanks for any help!

Body:
timeout /t 2 >nul

Not sure just timeout 2 would work - and make sure there's a space after the 2

...Ah, yes the /T is optional...make an uncommon amount of sense.


问:
Bloomberg API Corporate actions export in C#
Currently at my workplace we export Bloomberg Dividends manually. I would like to automate the process to make it a little easier for our team. Idea is, from the corporate actions I need to grab dividends, splits, M & A, and listings for a specific date. So far I've seen conflicting answers as to whether this is possible or not. If it is, how would I request such data?</p>

答:
I don't believe that exists. To my knowledge you can only extract via API fields such as BDP BDH BDS BTH and eventually BEQS.

Create a portfolio via BBU, then exctracting in CACT as xls is quite easy.


问:
RabbitMQ Management Plugin vs. AMQP
I wish to programmatically  manage exchanges, queues, bindings, and view resource usage of my rabbitmq server. I can do all these by making REST API calls made available by rabbitmq management plugin. However, is it possible to achieve all that using AMQP protocol instead of using the management plugin? In other words, will an AMQP client allow me to do everything that the management plugin does?

If there is no alternative, is there any performance concern if I enable and use the management plugin?

答:
In theory someone could implement a way that all the info is delivered via an AMQP queue. But it would have to be so that no consumer should ACK any of the messages because then they would be gone from the queue and the publisher would have to figure this out and publish the same thing again. In other words, it shouldn't be done.
Also it would be semantically (?) wrong, since AMQP by it's nature is designed with flowing/changing/dynamic data in mind, and all this data about resources, queues etc is static (and in some cases meta) info.

No performance concerns (in this context of course).

Additionally you can also use the command line tool if it's more comfortable

Title: RabbitMQ Management Plugin vs. AMQP


问:
cakephp - Followers relationship
Im trying to create a User Connections relationship:

Following (people im following).

Followers (people who follows me).

My question:

It is a self-relationship? How do I define this?

Thanks in advance.

答:
What you are looking for is a HABTM relationship. Although you will be referring twice to the same model (User) instead to two separate ones form the join-table.

```<code>-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `users` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `username` VARCHAR(45) NULL ,
  `password` VARCHAR(100) NULL ,
  `email` VARCHAR(100) NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `followers_users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `followers_users` (
  `user_id` INT NOT NULL ,
  `follower_id` INT NOT NULL ,
  PRIMARY KEY (`user_id`, `follower_id`) ,
  INDEX `fk_followers_users_users1` (`follower_id` ASC) ,
  CONSTRAINT `fk_followers_users_users`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_followers_users_users1`
    FOREIGN KEY (`follower_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code>```

You can create a FollowersController that extends UsersController and then further define the relationship in the follower model. So you would actually have a model to refer back to.

I hope this helps.

Title: cakephp - Followers relationship

Body:
What you are looking for is a HABTM relationship. Although you will be referring twice to the same model (User) instead to two separate ones form the join-table.

-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `users` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `username` VARCHAR(45) NULL ,
  `password` VARCHAR(100) NULL ,
  `email` VARCHAR(100) NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `followers_users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `followers_users` (
  `user_id` INT NOT NULL ,
  `follower_id` INT NOT NULL ,
  PRIMARY KEY (`user_id`, `follower_id`) ,
  INDEX `fk_followers_users_users1` (`follower_id` ASC) ,
  CONSTRAINT `fk_followers_users_users`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_followers_users_users1`
    FOREIGN KEY (`follower_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

You can create a FollowersController that extends UsersController and then further define the relationship in the follower model. So you would actually have a model to refer back to.

I hope this helps.


问:
determining the bounding box around the contours
I am trying to determine the bounding box around a specific contour level in the contourf plot:

Plot the contourf plot of the data

Plot the contour with level 0.075 on the same plot.

Extract the contour data from the contour level

Calculate the centroid for each contour data

Do loop for each element of centroid x y and calculate distance to other
centroid x y. Merge Contour data with distances less than threshold of 5,
and place it in areas.

Replot data and create boxes surrounding area x y data for each area on the
same plot.

Here is the code which generates the contourf plot and tries to create bounding box:

```<code>axes(handles.axes1);
cla(handles.axes1);

contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap(handles.axes1,'jet');
colorbar(handles.axes1);
axis equal
caxis([cMin cMax]);
hold on

[Cm,hm] = contour(xC(1,:),yC(:,1),zDiff,[0.075 0.075],'k');
axis equal

Sm = contourdata(Cm);

hwb = waitbar(0.1, 'Processing')

[p,q] = size(Sm);

for i = 1:q

    pts = centroid(Sm(1,i).xdata,Sm(1,i).ydata);
    format long
    centCt(i,1) = pts(1);
    centCt(i,2) = pts(2);
end

[centCxs,indxs] = sort(centCt(:,1));
centCys = centCt(indxs,2);

Se = Sm;

for i = 1:q

Se(1,i).flag = 0;

end

ct = 1;

for j = 1:q
datax = [];
datay = [];
 ct2 = 1;
    for i = 1:q

        rcentd  = sqrt((centCxs(i,1) - centCxs(j,1)).^2 + (centCys(i,1) - centCys(j,1)).^2);

        if(rcentd < 5)
            if(Se(1,i).flag == 0)
              datax = [datax;Se(1,i).xdata];
              datay = [datay;Se(1,i).ydata];

              Se(1,i).flag = 1;

              ct2 = ct2 + 1;

            end

        end
    end

if(ct2 > 5)

     area(ct).xdat = datax;
     area(ct).ydat = datay;
     ct = ct + 1;
end

end

close(hwb);

cla(handles.axes1);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap(handles.axes1,'jet');
colorbar(handles.axes1);
axis equal
caxis([cMin cMax]);
hold on

hold(handles.axes1,'on');

for i = 1:length(area)
    [rectx,recty] = minboundrect(area(i).xdat,area(i).ydat);
    plot(rectx,recty,'-k');
end
</code>```

Initial Contour Picture:

Results I am getting:

Desired Result:

答:
the only thing you need to change is the last part where you're computing the bounding boxes:

```<code>for i = 1:length(area)
    minMaxX = [min(area(i).xdat),max(area(i).xdat)];
    minMaxY = [min(area(i).ydat),max(area(i).ydat)];
    rect = [minMaxX(1),minMaxY(1),diff(minMaxX),diff(minMaxY)];
    plot(area(i).xdat,area(i).ydat,'.')
    rectangle('Position',rect,'EdgeColor','k')
end
</code>```

if you will run the whole modified script (which requires contourdata):

```<code>[xC,yC] = meshgrid(-5:0.1:5);
zDiff = abs(peaks(xC,yC));
subplot(121);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap('jet');
colorbar();
axis equal
hold on

[Cm,hm] = contour(xC(1,:),yC(:,1),zDiff,3 + [0 0],'k');
axis equal

Sm = contourdata(Cm);
[p,q] = size(Sm);
for i = 1:q
    pts = centroid(Sm(1,i).xdata,Sm(1,i).ydata);
    format long
    centCt(i,1) = pts(1);
    centCt(i,2) = pts(2);
end
area = struct([]);
[centCxs,indxs] = sort(centCt(:,1));
centCys = centCt(indxs,2);
Se = Sm;
for i = 1:q
    Se(1,i).flag = 0;
end
ct = 1;
for j = 1:q
    datax = [];
    datay = [];
    ct2 = 1;
    for i = 1:q
        rcentd  = sqrt((centCxs(i,1) - centCxs(j,1)).^2 + (centCys(i,1) - centCys(j,1)).^2);
        if(rcentd < 1.5)
            if(Se(1,i).flag == 0)
                datax = [datax;Se(1,i).xdata];
                datay = [datay;Se(1,i).ydata];

                Se(1,i).flag = 1;
                ct2 = ct2 + 1;
            end
        end
    end

    if(ct2 > 1)
        area(ct).xdat = datax;
        area(ct).ydat = datay;
        ct = ct + 1;
    end
end

%
subplot(122);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap('jet');
colorbar();
axis equal
hold on

for i = 1:length(area)
    minMaxX = [min(area(i).xdat),max(area(i).xdat)];
    minMaxY = [min(area(i).ydat),max(area(i).ydat)];
    rect = [minMaxX(1),minMaxY(1),diff(minMaxX),diff(minMaxY)];
    rectangle('Position',rect,'EdgeColor','k')
end
</code>```

you will get:

Body:
I am trying to determine the bounding box around a specific contour level in the contourf plot:

Plot the contourf plot of the data

Plot the contour with level 0.075 on the same plot.

Extract the contour data from the contour level

Calculate the centroid for each contour data

Do loop for each element of centroid x y and calculate distance to other
centroid x y. Merge Contour data with distances less than threshold of 5,
and place it in areas.

Replot data and create boxes surrounding area x y data for each area on the
same plot.

Here is the code which generates the contourf plot and tries to create bounding box:

axes(handles.axes1);
cla(handles.axes1);

contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap(handles.axes1,'jet');
colorbar(handles.axes1);
axis equal
caxis([cMin cMax]);
hold on

[Cm,hm] = contour(xC(1,:),yC(:,1),zDiff,[0.075 0.075],'k');
axis equal

Sm = contourdata(Cm);

hwb = waitbar(0.1, 'Processing')

[p,q] = size(Sm);

for i = 1:q

    pts = centroid(Sm(1,i).xdata,Sm(1,i).ydata);
    format long
    centCt(i,1) = pts(1);
    centCt(i,2) = pts(2);
end

[centCxs,indxs] = sort(centCt(:,1));
centCys = centCt(indxs,2);

Se = Sm;

for i = 1:q

Se(1,i).flag = 0;

end

ct = 1;

for j = 1:q
datax = [];
datay = [];
 ct2 = 1;
    for i = 1:q

        rcentd  = sqrt((centCxs(i,1) - centCxs(j,1)).^2 + (centCys(i,1) - centCys(j,1)).^2);

        if(rcentd < 5)
            if(Se(1,i).flag == 0)
              datax = [datax;Se(1,i).xdata];
              datay = [datay;Se(1,i).ydata];

              Se(1,i).flag = 1;

              ct2 = ct2 + 1;

            end

        end
    end

if(ct2 > 5)

     area(ct).xdat = datax;
     area(ct).ydat = datay;
     ct = ct + 1;
end

end

close(hwb);

cla(handles.axes1);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap(handles.axes1,'jet');
colorbar(handles.axes1);
axis equal
caxis([cMin cMax]);
hold on

hold(handles.axes1,'on');

for i = 1:length(area)
    [rectx,recty] = minboundrect(area(i).xdat,area(i).ydat);
    plot(rectx,recty,'-k');
end

Initial Contour Picture:

Results I am getting:

Desired Result:

Body:
the only thing you need to change is the last part where you're computing the bounding boxes:

for i = 1:length(area)
    minMaxX = [min(area(i).xdat),max(area(i).xdat)];
    minMaxY = [min(area(i).ydat),max(area(i).ydat)];
    rect = [minMaxX(1),minMaxY(1),diff(minMaxX),diff(minMaxY)];
    plot(area(i).xdat,area(i).ydat,'.')
    rectangle('Position',rect,'EdgeColor','k')
end

if you will run the whole modified script (which requires contourdata):

[xC,yC] = meshgrid(-5:0.1:5);
zDiff = abs(peaks(xC,yC));
subplot(121);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap('jet');
colorbar();
axis equal
hold on

[Cm,hm] = contour(xC(1,:),yC(:,1),zDiff,3 + [0 0],'k');
axis equal

Sm = contourdata(Cm);
[p,q] = size(Sm);
for i = 1:q
    pts = centroid(Sm(1,i).xdata,Sm(1,i).ydata);
    format long
    centCt(i,1) = pts(1);
    centCt(i,2) = pts(2);
end
area = struct([]);
[centCxs,indxs] = sort(centCt(:,1));
centCys = centCt(indxs,2);
Se = Sm;
for i = 1:q
    Se(1,i).flag = 0;
end
ct = 1;
for j = 1:q
    datax = [];
    datay = [];
    ct2 = 1;
    for i = 1:q
        rcentd  = sqrt((centCxs(i,1) - centCxs(j,1)).^2 + (centCys(i,1) - centCys(j,1)).^2);
        if(rcentd < 1.5)
            if(Se(1,i).flag == 0)
                datax = [datax;Se(1,i).xdata];
                datay = [datay;Se(1,i).ydata];

                Se(1,i).flag = 1;
                ct2 = ct2 + 1;
            end
        end
    end

    if(ct2 > 1)
        area(ct).xdat = datax;
        area(ct).ydat = datay;
        ct = ct + 1;
    end
end

%
subplot(122);
contourf(xC(1,:),yC(:,1),zDiff, 200,'LineColor','none');
colormap('jet');
colorbar();
axis equal
hold on

for i = 1:length(area)
    minMaxX = [min(area(i).xdat),max(area(i).xdat)];
    minMaxY = [min(area(i).ydat),max(area(i).ydat)];
    rect = [minMaxX(1),minMaxY(1),diff(minMaxX),diff(minMaxY)];
    rectangle('Position',rect,'EdgeColor','k')
end

you will get:


问:
Python: Assistance with json and reading from a file
Say i have a notepad file (.txt) with the following content:

```<code>"Hello I am really bad at programming"
</code>```

Using json, how would I get the sentence from the file to the python program which I can then use as a variable?

So far I have this code:

```<code>newfile = open((compfilename)+'.txt', 'r')

saveddata = json.load(newfile)

orgsentence = saveddata[0]
</code>```

I always get this error:

```<code>   return codecs.ascii_decode(input, self.errors)[0]
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0:           ordinal not in range(128)
</code>```

Thanks in advance for any help!

答:
```<code>import json

with open('file.txt') as f:
    data = json.load(f)
</code>```

Body:
Say i have a notepad file (.txt) with the following content:

"Hello I am really bad at programming"

Using json, how would I get the sentence from the file to the python program which I can then use as a variable?

So far I have this code:

newfile = open((compfilename)+'.txt', 'r')

saveddata = json.load(newfile)

orgsentence = saveddata[0]

I always get this error:

   return codecs.ascii_decode(input, self.errors)[0]
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0:           ordinal not in range(128)

Thanks in advance for any help!


问:
Swift collectionViewCells are not showing
I have got this Swift code
`

```<code>let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}
</code>```

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

答:
Try it.
You add in the class</p>

```<code>UICollectionViewDataSource and UICollectionVIewDelegate.
</code>```

Body:
I have got this Swift code
`

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

Body:
Try it.
You add in the class

UICollectionViewDataSource and UICollectionVIewDelegate.


问:
what does "driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities); " mean in appium
I am new to appium and want to find out what certain line of basic code mean. can anyone tel me what the below code line indicate?
It will be nice if you mention what this url indicate: "http://172.16.1.34:80"
specially "80" and if it can be changed which other possible port number can be put.

driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities);

答:
```<code>driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities);
</code>```

The above line indicates that android driver targeting at at ip address http://172.16.1.34:80 which appium to run scripts.

Capabilities : The capabilities are the configuration for test scrip at which environment you want to run script.

Body:
driver = new AndroidDriver(new URL("http://172.16.1.34:80"), capabilities);

The above line indicates that android driver targeting at at ip address http://172.16.1.34:80 which appium to run scripts.

Capabilities : The capabilities are the configuration for test scrip at which environment you want to run script.


问:
swift - Function that fetches and appends Firebase values returns an empty string
I'm trying to create a function that grabs the category children's keys of a given user UID in Firebase, appends them to an array and then finally joins them together into one long string. Everything works well until the observeSingleEvent function completes and the return value is empty. Here's my code:

```<code>let referenceDatabase = FIRDatabase.database().reference()

func fetchBuddyInfo(category: String, buddyId: String) -> String {

    var buddyInterestsArray = [String]()
    var buddyInterests = String()

    referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in

        for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {

            buddyInterestsArray.append(categoryItems.key)
         }

         buddyInterests = buddyInterestsArray.joined(separator: ",")
    })
    return buddyInterests
}
</code>```

I think it has something to do with the nested scope of the observeSingleEvent function since buddyInterests seems to lose its value after running the function, but I can't figure out how to pull the value out.

答:
Problem

observeSingleEvent(of:with:) is an asynchronous operation, which means that it can return later after executing the function. That's why in your case you get always an empty String as return value

Solution

So in your case you can create a completion handler like this:

```<code>func fetchBuddyInfo(category: String, buddyId: String, completion: @escaping (String) -> ()) {

  var buddyInterestsArray = [String]()
  var buddyInterests = String()

  referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in

    for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {

      buddyInterestsArray.append(categoryItems.key)
    }

    buddyInterests = buddyInterestsArray.joined(separator: ",")

    completion(buddyInterests)
  })
}
</code>```

And call your function like this:

```<code>fetchBuddyInfo(category: categoryString, buddyId: buddyId) { (buddyInfoString) in
  // do whatever you want with your buddyInfoString
}
</code>```

Body:
I'm trying to create a function that grabs the category children's keys of a given user UID in Firebase, appends them to an array and then finally joins them together into one long string. Everything works well until the observeSingleEvent function completes and the return value is empty. Here's my code:

let referenceDatabase = FIRDatabase.database().reference()

func fetchBuddyInfo(category: String, buddyId: String) -> String {

    var buddyInterestsArray = [String]()
    var buddyInterests = String()

    referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in

        for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {

            buddyInterestsArray.append(categoryItems.key)
         }

         buddyInterests = buddyInterestsArray.joined(separator: ",")
    })
    return buddyInterests
}

I think it has something to do with the nested scope of the observeSingleEvent function since buddyInterests seems to lose its value after running the function, but I can't figure out how to pull the value out.

Body:
Problem

observeSingleEvent(of:with:) is an asynchronous operation, which means that it can return later after executing the function. That's why in your case you get always an empty String as return value

Solution

So in your case you can create a completion handler like this:

func fetchBuddyInfo(category: String, buddyId: String, completion: @escaping (String) -> ()) {

  var buddyInterestsArray = [String]()
  var buddyInterests = String()

  referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in

    for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {

      buddyInterestsArray.append(categoryItems.key)
    }

    buddyInterests = buddyInterestsArray.joined(separator: ",")

    completion(buddyInterests)
  })
}

And call your function like this:

fetchBuddyInfo(category: categoryString, buddyId: buddyId) { (buddyInfoString) in
  // do whatever you want with your buddyInfoString
}


问:
How to add item to listbox?
I am creating a simple GUI program to manage priorities. I am having troubles with adding items to the listbox. I tried to create an instance of Priority class by passing two attributes to the constructor and then use g.listBox.insert(END, item), but it seems it doesn't work like that. I am getting an error:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Exception in Tkinter callback Traceback (most recent call last):

  File "/usr/lib/python3.5/tkinter/init.py", line 1553, in call
      return self.func(*args)   File "/home/cali/PycharmProjects/priorities/priorities.py", line 52, in
  addItem
      item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c')) AttributeError: 'GuiPart' object has no attribute 'textBox'

Process finished with exit code 0

Here is what I have done:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        Button(self.root,
               text = "Add",
               command = self.addItem).grid(row = 2, column = 0, sticky = W + E)

        Button(self.root,
               text="Remove",
               command = self.removeItem).grid(row = 2, column = 1, sticky = W + E)

        Button(self.root,
               text="Edit",
               command = self.editItem).grid(row = 2, column = 2, sticky = W + E)

        listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)

        textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)

    def addItem(self):
        item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c'))

        g.listBox.insert(END, item)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()
</code>```

I'm using Python 3.5.

答:
So if I understood your aim, you are trying to describe a priority by allowing the user to type, within the text zone widget, its information which consists in its subject and  order; after that, the user can click on the "Add" button to insert the priority information into your list box.

There are lot of things to consider around your code. If I go to fix and comment them one by one, I believe my answer will be long while I feel lazy today.

I think my program below is easy to understand (ask a clarification otherwise). I did not find specifications inherent to how the propriety information is typed in the text zone. So my program below works under the assumption the user types the priority subject on the first line of the text area, and then uses a new line to type the priority order.  The click on "Add" button will lead to the insertion of these 2 data on the same line of the text box widget as shown below:

Here is an MCVE:

```<code>import tkinter as tk

class ProioritiesManager(tk.Frame):

   def __init__(self, master):
       tk.Frame.__init__(self, master)
       self.master = master
       self.master.resizable(width = False, height = False)
       self.master.title("Priorities")
       self.create_buttons()
       self.create_listbox()
       self.create_priorities_description_zone()

   def create_buttons(self):
       add_item = tk.Button(self.master, text='Add', command=self.add_item)
       add_item.grid(row=2, column=0, sticky=tk.W+tk.E)
       remove_item = tk.Button(self.master, text='Remove', command=self.remove_item)
       remove_item.grid(row=2, column=1, sticky=tk.W+tk.E)
       edit_item = tk.Button(self.master, text='Edit', command=self.edit_item)
       edit_item.grid(row=2, column=2, sticky=tk.W+tk.E)

   def create_listbox(self):
       self.item_alternatives = tk.Listbox(self.master, width=30)
       self.item_alternatives.grid(row=1, sticky=tk.W+tk.E, columnspan=3)

   def create_priorities_description_zone(self):
       self.priority_text_zone = tk.Text(self.master, height=10, width=30)
       self.priority_text_zone.grid(row=3, columnspan=3, sticky=tk.W+tk.E+tk.N+tk.S)

   def get_priority_subject(self):
       return self.priority_text_zone.get('1.0', '1.0 lineend')

   def get_priority_order(self):
       return self.priority_text_zone.get('2.0', '2.0 lineend')

   def add_item(self):
       self.item_alternatives.insert(tk.END, self.get_priority_subject()+'  '+ self.get_priority_order())

   def remove_item(self):
       pass

   def edit_item(self):
       pass

if __name__ == "__main__":
    root = tk.Tk()
    ProioritiesManager(root)
    root.mainloop()
</code>```

If you want to give a good UX to your GUI then it would be nice if you add a button to allow the user to clear the content of the text area so that he can type in a new priority:

For this purpose, you can add a rest button to create_buttons() function by adding these 2 lines of code:

```<code>clear_text_area = tk.Button(self.master, text='Reset', command=self.reset_priority_text_zone)
clear_text_area.grid(row=4, column=2)
</code>```

The callback reset_priority_text_zone() is defined this way:

```<code>def reset_priority_text_zone(self):
       self.priority_text_zone.delete('1.0', tk.END)
</code>```

Title: How to add item to listbox?

Body:
I am creating a simple GUI program to manage priorities. I am having troubles with adding items to the listbox. I tried to create an instance of Priority class by passing two attributes to the constructor and then use g.listBox.insert(END, item), but it seems it doesn't work like that. I am getting an error:

/usr/bin/python3.5 /home/cali/PycharmProjects/priorities/priorities.py
  Exception in Tkinter callback Traceback (most recent call last):

  File "/usr/lib/python3.5/tkinter/init.py", line 1553, in call
      return self.func(*args)   File "/home/cali/PycharmProjects/priorities/priorities.py", line 52, in
  addItem
      item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c')) AttributeError: 'GuiPart' object has no attribute 'textBox'

Process finished with exit code 0

Here is what I have done:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:

    def __init__(self, subject, priority):
        self.subject = subject
        self.priority = priority

    def subject(self):
        return self.subject

    def priority(self):
        return self.priority

class GuiPart:

    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def createWidgets(self):

        Button(self.root,
               text = "Add",
               command = self.addItem).grid(row = 2, column = 0, sticky = W + E)

        Button(self.root,
               text="Remove",
               command = self.removeItem).grid(row = 2, column = 1, sticky = W + E)

        Button(self.root,
               text="Edit",
               command = self.editItem).grid(row = 2, column = 2, sticky = W + E)

        listBox = Listbox(width = 30).grid(row = 1, sticky = W + E, columnspan = 3)

        textBox = Text(height=10, width=30).grid(row = 3, columnspan = 3, sticky = W + E + N + S)

    def addItem(self):
        item = Priority(subject = g.textBox.get("1.0", 'end-1c'), priority = g.textBox.get("1.0", 'end-1c'))

        g.listBox.insert(END, item)

    def removeItem(self):
       pass

    def editItem(self):
        pass

class Client:
    pass

if __name__ == "__main__":
    g = GuiPart()
    g.createWidgets()
    g.root.mainloop()

I'm using Python 3.5.

Body:
So if I understood your aim, you are trying to describe a priority by allowing the user to type, within the text zone widget, its information which consists in its subject and  order; after that, the user can click on the "Add" button to insert the priority information into your list box.

There are lot of things to consider around your code. If I go to fix and comment them one by one, I believe my answer will be long while I feel lazy today.

I think my program below is easy to understand (ask a clarification otherwise). I did not find specifications inherent to how the propriety information is typed in the text zone. So my program below works under the assumption the user types the priority subject on the first line of the text area, and then uses a new line to type the priority order.  The click on "Add" button will lead to the insertion of these 2 data on the same line of the text box widget as shown below:

Here is an MCVE:

import tkinter as tk

class ProioritiesManager(tk.Frame):

   def __init__(self, master):
       tk.Frame.__init__(self, master)
       self.master = master
       self.master.resizable(width = False, height = False)
       self.master.title("Priorities")
       self.create_buttons()
       self.create_listbox()
       self.create_priorities_description_zone()

   def create_buttons(self):
       add_item = tk.Button(self.master, text='Add', command=self.add_item)
       add_item.grid(row=2, column=0, sticky=tk.W+tk.E)
       remove_item = tk.Button(self.master, text='Remove', command=self.remove_item)
       remove_item.grid(row=2, column=1, sticky=tk.W+tk.E)
       edit_item = tk.Button(self.master, text='Edit', command=self.edit_item)
       edit_item.grid(row=2, column=2, sticky=tk.W+tk.E)

   def create_listbox(self):
       self.item_alternatives = tk.Listbox(self.master, width=30)
       self.item_alternatives.grid(row=1, sticky=tk.W+tk.E, columnspan=3)

   def create_priorities_description_zone(self):
       self.priority_text_zone = tk.Text(self.master, height=10, width=30)
       self.priority_text_zone.grid(row=3, columnspan=3, sticky=tk.W+tk.E+tk.N+tk.S)

   def get_priority_subject(self):
       return self.priority_text_zone.get('1.0', '1.0 lineend')

   def get_priority_order(self):
       return self.priority_text_zone.get('2.0', '2.0 lineend')

   def add_item(self):
       self.item_alternatives.insert(tk.END, self.get_priority_subject()+'  '+ self.get_priority_order())

   def remove_item(self):
       pass

   def edit_item(self):
       pass

if __name__ == "__main__":
    root = tk.Tk()
    ProioritiesManager(root)
    root.mainloop()

If you want to give a good UX to your GUI then it would be nice if you add a button to allow the user to clear the content of the text area so that he can type in a new priority:

For this purpose, you can add a rest button to create_buttons() function by adding these 2 lines of code:

clear_text_area = tk.Button(self.master, text='Reset', command=self.reset_priority_text_zone)
clear_text_area.grid(row=4, column=2)

The callback reset_priority_text_zone() is defined this way:

def reset_priority_text_zone(self):
       self.priority_text_zone.delete('1.0', tk.END)


问:
Reusing Activity and buttons for Quiz Application in Android
I am making a small quiz application as part of a bigger application. I have about 18 questions and I don't want to make a new activity for each question. How do I change the button implementation everytime a button is clicked. Say for Question 1 I give answer A, the question and buttons should change for Question 2.

Thanks,

答:
set an int on Shared Preference for the question no to be asked

```<code>SharedPreferences preferences = getSharedPreferences("QUIZ", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("question_no",1);
editor.apply();
</code>```

Then on button click

```<code>button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int q_no = preferences.getInt("question_no",1);
        switch (q_no){
            case 1:
                textView.setText("Question 1:");
                break;
            case 2:
                textView.setText("Question 2:");
                break;
            case 3:
                textView.setText("Question 3:");
                break;
            ...
            default:
                /*End all question*/
        }

        editor.putInt("question_no",q_no+1);
        editor.apply();
    }
});
</code>```

Body:
set an int on Shared Preference for the question no to be asked

SharedPreferences preferences = getSharedPreferences("QUIZ", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("question_no",1);
editor.apply();

Then on button click

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int q_no = preferences.getInt("question_no",1);
        switch (q_no){
            case 1:
                textView.setText("Question 1:");
                break;
            case 2:
                textView.setText("Question 2:");
                break;
            case 3:
                textView.setText("Question 3:");
                break;
            ...
            default:
                /*End all question*/
        }

        editor.putInt("question_no",q_no+1);
        editor.apply();
    }
});


问:
ExoPlayer set commands cant find UNKNOWN_TIME
i'm trying to set the commands of exoPlayer but i don't know how to set the

```<code>getDuration();
getCurrentPosition();
</code>```

I found this but what i have to set on UNKNOWN_TIME cause its telling me cannot resolve symbol UNKNOWN_TIME

```<code>@Override
public int getCurrentPosition() {
    return exoPlayer.getDuration() == ExoPlayer.UNKNOWN_TIME ? 0
            : (int) exoPlayer.getCurrentPosition();
}

@Override
public int getDuration() {
    return exoPlayer.getDuration() == ExoPlayer.UNKNOWN_TIME ? 0
            : (int) exoPlayer.getDuration();
}
</code>```

答: For ExoPlayer 2.0 You should use C.TIME_UNSET constant (from com.google.android.exoplayer2 package) instead of ExoPlayer.UNKNOWN_TIME (see this description for getDuration() method for ExoPlayer 2.0.

Body:
i'm trying to set the commands of exoPlayer but i don't know how to set the

getDuration();
getCurrentPosition();

I found this but what i have to set on UNKNOWN_TIME cause its telling me cannot resolve symbol UNKNOWN_TIME

@Override
public int getCurrentPosition() {
    return exoPlayer.getDuration() == ExoPlayer.UNKNOWN_TIME ? 0
            : (int) exoPlayer.getCurrentPosition();
}

@Override
public int getDuration() {
    return exoPlayer.getDuration() == ExoPlayer.UNKNOWN_TIME ? 0
            : (int) exoPlayer.getDuration();
}


问:
Using CoreBluetooth to connect to Windows10 with iOS devices
Question1.
IOBluetooth can support connection  both ways via LE or classic. However it only supports macOs. CoreBluetooth supports only up to LE along with IOS.

As far as I know, in order for me to connect my bluetooth connection within IOs device, I must use CoreBluetooth frameworks. Am I correct?

Question2.
CoreBluetooth frameworks can connect Windows10 labtop with bluetooth connection?

答:
Your question is a bit vague. I assume you just want to have a way to exchange some data between an iOS app and your Windows 10 desktop.

Yes, you are correct. Usage of Bluetooth Classic in any of your iOS apps requires Apple MFI Membership and only makes sense if you have your own product. If you are not a member of the MFI program then you are left with CoreBluetooth (BLE). Please note, that BLE is significantly slower than Bluetooth Classic so it only makes sense for applications that require transmission of small data packets (expect around 4kB/s max).

Yes, as long as your Windows 10 device supports BLE. If you want to use any of the SIG adopted Profiles such as HID over Gatt you should be able to connect without any additional software. Otherwise you need to implement your own profile. If you want to know more about your options, I suggest you have a look at the CoreBluetooth documentation and/or get a copy of Getting Started with Bluetooth Low Energy which is a comprehensive read on the topic.


问:
Ambiguous type variable error msg
I don't think it is a bug, but I am a bit puzzled as to why that doesn't work. A bonus question is why does it mention variable e? There is no variable e.

```
    Prelude> :m +Control.Exception
    Prelude Control.Exception> handle (\_-> return "err") undefined

    <interactive>:1:0:
        Ambiguous type variable `e' in the constraint:
          `Exception e'
            arising from a use of `handle' at <interactive>:1:0-35
        Probable fix: add a type signature that fixes these type variable(s)
    Prelude Control.Exception>
```

Apparently it works fine in ghci 6.8, I am using 6.10.1.

Edit: I have minimized the code. I expect that to have the same result in both 6.8 and 6.10

```<code>class C a

foo :: C a => (a -> Int)-> Int
foo _ = 1

arg :: C a => a -> Int
arg _ = 2

bar :: Int
bar = foo arg
</code>```

trying to compile it:

```
[1 of 1] Compiling Main             ( /tmp/foo.hs, interpreted )

/tmp/foo.hs:12:10:
    Ambiguous type variable `a' in the constraint:
      `C a' arising from a use of `arg' at /tmp/foo.hs:12:10-12
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
Prelude Control.Exception>
```

答:
This problem shows up only in GHC 6.10; it can't be duplicated in GHC 6.8 because the type of handle is different:

```<code>: nr@homedog 620 ; ghci
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
Prelude> :m +Control.Exception
Prelude Control.Exception>  handle (\_ -> return "err") undefined
"err"
Prelude Control.Exception>
</code>```

OK maybe I can get this right at last.  I think the problem is not the monomorphism restriction, but rather you've hit an instance of the Read/Show problem: you're offering to handle some type of exception, in the new version of `handle, there is more than one type of exception, and the type of that exception does not appear in your result.  So the compiler has no way of knowing which type of exception you're trying to handle. One way to work this is to pick one.  Here's some code that works:

```<code>Prelude Control.Exception> let alwaysError :: SomeException -> IO String; alwaysError = \_ -> return "err"
Prelude Control.Exception> handle alwaysError undefined
"err"
</code>```

Incidentally, the example use of handle in the GHC library documentation does not compile under 6.10.  I have filed a bug report.

OwnerDisplayName: luntain

Title: Ambiguous type variable error msg

Body:
I don't think it is a bug, but I am a bit puzzled as to why that doesn't work. A bonus question is why does it mention variable e? There is no variable e.

    Prelude> :m +Control.Exception
    Prelude Control.Exception> handle (\_-> return "err") undefined

    <interactive>:1:0:
        Ambiguous type variable `e' in the constraint:
          `Exception e'
            arising from a use of `handle' at <interactive>:1:0-35
        Probable fix: add a type signature that fixes these type variable(s)
    Prelude Control.Exception>

Apparently it works fine in ghci 6.8, I am using 6.10.1.

Edit: I have minimized the code. I expect that to have the same result in both 6.8 and 6.10

class C a

foo :: C a => (a -> Int)-> Int
foo _ = 1

arg :: C a => a -> Int
arg _ = 2

bar :: Int
bar = foo arg

trying to compile it:

[1 of 1] Compiling Main             ( /tmp/foo.hs, interpreted )

/tmp/foo.hs:12:10:
    Ambiguous type variable `a' in the constraint:
      `C a' arising from a use of `arg' at /tmp/foo.hs:12:10-12
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
Prelude Control.Exception>

LastEditorDisplayName: luntain

Body:
This problem shows up only in GHC 6.10; it can't be duplicated in GHC 6.8 because the type of handle is different:

: nr@homedog 620 ; ghci
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
Prelude> :m +Control.Exception
Prelude Control.Exception>  handle (\_ -> return "err") undefined
"err"
Prelude Control.Exception>

OK maybe I can get this right at last.  I think the problem is not the monomorphism restriction, but rather you've hit an instance of the Read/Show problem: you're offering to handle some type of exception, in the new version of `handle, there is more than one type of exception, and the type of that exception does not appear in your result.  So the compiler has no way of knowing which type of exception you're trying to handle. One way to work this is to pick one.  Here's some code that works:

Prelude Control.Exception> let alwaysError :: SomeException -> IO String; alwaysError = \_ -> return "err"
Prelude Control.Exception> handle alwaysError undefined
"err"

Incidentally, the example use of handle in the GHC library documentation does not compile under 6.10.  I have filed a bug report.

OwnerDisplayName: Norman Ramsey

LastEditorDisplayName: Norman Ramsey