问:
Exploit a backup program using C
I'm doing an assignment of a security course that asks me to find 4 vulnerabilities of a backup program (setuid) and use each of them to gain root access (on a virtual linux machine with old version of gcc etc.).
There should be one of buffer overflow and one of format string.

Could anyone help me to point out where the 4 vulnerabilities are?
I think the buffer overflow can happened in copyFile().

The following is the code for backup.c: (which can be invoked in "backup backup foo" or "backup restore foo")

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define CMD_BACKUP 0
#define CMD_RESTORE 1

#define BACKUP_DIRECTORY "/usr/share/backup"
#define FORBIDDEN_DIRECTORY "/etc"

static
int copyFile(char* src, char* dst)
{
  char buffer[3072]; /* 3K ought to be enough for anyone*/
  unsigned int i, len;
  FILE *source, *dest;
  int c;

  source = fopen(src, "r");
  if (source == NULL) {
    fprintf(stderr, "Failed to open source file\n");
    return -1;
  }

  i = 0;
  c = fgetc(source);
  while (c != EOF) {
    buffer[i]  = (unsigned char) c;
    c = fgetc(source);
    i++;
  }

  len = i;
  fclose(source);

  dest = fopen(dst, "w");
  if (dest == NULL) {
    fprintf(stderr, "Failed to open destination file\n");
    return -1;
  }

  for(i = 0; i < len; i++)
    fputc(buffer[i], dest);

  fclose(dest);

  return 0;
}

static
int restorePermissions(char* target)
{
  pid_t pid;
  int status;
  char *user, *userid, *ptr;
  FILE *file;
  char buffer[64];
  mode_t mode;

  // execute "chown" to assign file ownership to user
  pid = fork();

  // error
  if (pid < 0) {
    fprintf(stderr, "Fork failed\n");
    return -1;
  }

  // parent
  if (pid > 0) {
    waitpid(pid, &status, 0);
    if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
      return -1;
  }
  else {

    // child
    // retrieve username
    user = getenv("USER");
    // retrieve corresponding userid
    file = fopen("/etc/passwd", "r");
    if (file == NULL) {
      fprintf(stderr, "Failed to open password file\n");
      return -1;
    }
    userid = NULL;
    while (!feof(file)) {
      if (fgets(buffer, sizeof(buffer), file) != NULL) {
    ptr = strtok(buffer, ":");
    if (strcmp(ptr, user) == 0) {
      strtok(NULL, ":"); // password
      userid = strtok(NULL, ":"); // userid
      ptr = strtok(NULL, ":"); // group
      *ptr = '\0';
      break;
    }
      }
    }

    if (userid != NULL)
      execlp("/bin/chown", "/bin/chown", userid, target, NULL);

    // reached only in case of error
    return -1;
  }

  mode = S_IRUSR | S_IWUSR | S_IEXEC;
  chmod(target, mode);

  return 0;
}

static
void usage(char* parameter)
{
  char newline = '\n';
  char output[96];
  char buffer[96];

  snprintf(buffer, sizeof(buffer),
        "Usage: %.60s backup|restore pathname%c", parameter, newline);

  sprintf(output, buffer);
  printf(output);
}

int main(int argc, char* argv[])
{
  int cmd;
  char *path, *ptr;
  char *forbidden = FORBIDDEN_DIRECTORY;
  char *src, *dst, *buffer;
  struct stat buf;

  if (argc != 3) {
    usage(argv[0]);
    return 1;
  }

  if (strcmp("backup", argv[1]) == 0) {
    cmd = CMD_BACKUP;
  }
  else if (strcmp("restore", argv[1]) == 0) {
    cmd = CMD_RESTORE;
  } else {
    usage(argv[0]);
    return 1;
  }

  path = argv[2];

  // prevent access to forbidden directory
  ptr = realpath(path, NULL);
  if (ptr != NULL && strstr(ptr, forbidden) == ptr) {
    fprintf(stderr, "Not allowed to access target/source %s\n", path);
    return 1;
  }

  // set up paths for copy operation
  buffer = malloc(strlen(BACKUP_DIRECTORY) + 1 + strlen(path) + 1);
  if (buffer == NULL) {
    fprintf(stderr, "Failed to allocate memory\n");
    return 1;
  }

  if (cmd == CMD_BACKUP) {
    src = path;

    dst = buffer;
    strcpy(dst, BACKUP_DIRECTORY);
    strcat(dst, "/");
    strcat(dst, path);
  }
  else {
    src = buffer;
    strcpy(src, BACKUP_DIRECTORY);
    strcat(src, "/");
    strcat(src, path);

    dst = path;

    // don't overwrite existing file if we don't own it
    if (stat(dst, &buf) == 0 && buf.st_uid != getuid()) {
      fprintf(stderr, "Not your file: %s\n", dst);
      return 1;
    }
  }

  // perform actual backup/restore operation
  if (copyFile(src, dst) < 0)
    return 1;

  // grant user access to restored file
  if (cmd == CMD_RESTORE) {
    if (restorePermissions(path) < 0)
      return 1;
  }

  return 0;
}
</code>```

And something useful:

```<code>  // one way to invoke backup
  //system("/usr/local/bin/backup backup foo");

  // another way
  args[0] = TARGET; args[1] = "backup";
  args[2] = "foo"; args[3] = NULL;

  env[0] = NULL;
  if (execve(TARGET, args, env) < 0)
    fprintf(stderr, "execve failed.\n");
  exit(0);
</code>```

答:
You can't exploit buffer-overflows on Linux anymore, since SE-Linux prevents malicious or accidental unintended code execution by aborting the program in question, and by Wand-addresss randomization.

You need to switch off those programms first, but that requires root access in the first place.

Title: Exploit a backup program using C

Body:
I'm doing an assignment of a security course that asks me to find 4 vulnerabilities of a backup program (setuid) and use each of them to gain root access (on a virtual linux machine with old version of gcc etc.).
There should be one of buffer overflow and one of format string.

Could anyone help me to point out where the 4 vulnerabilities are?
I think the buffer overflow can happened in copyFile().

The following is the code for backup.c: (which can be invoked in "backup backup foo" or "backup restore foo")

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#define CMD_BACKUP 0
#define CMD_RESTORE 1

#define BACKUP_DIRECTORY "/usr/share/backup"
#define FORBIDDEN_DIRECTORY "/etc"

static
int copyFile(char* src, char* dst)
{
  char buffer[3072]; /* 3K ought to be enough for anyone*/
  unsigned int i, len;
  FILE *source, *dest;
  int c;

  source = fopen(src, "r");
  if (source == NULL) {
    fprintf(stderr, "Failed to open source file\n");
    return -1;
  }

  i = 0;
  c = fgetc(source);
  while (c != EOF) {
    buffer[i]  = (unsigned char) c;
    c = fgetc(source);
    i++;
  }

  len = i;
  fclose(source);

  dest = fopen(dst, "w");
  if (dest == NULL) {
    fprintf(stderr, "Failed to open destination file\n");
    return -1;
  }

  for(i = 0; i < len; i++)
    fputc(buffer[i], dest);

  fclose(dest);

  return 0;
}

static
int restorePermissions(char* target)
{
  pid_t pid;
  int status;
  char *user, *userid, *ptr;
  FILE *file;
  char buffer[64];
  mode_t mode;

  // execute "chown" to assign file ownership to user
  pid = fork();

  // error
  if (pid < 0) {
    fprintf(stderr, "Fork failed\n");
    return -1;
  }

  // parent
  if (pid > 0) {
    waitpid(pid, &status, 0);
    if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
      return -1;
  }
  else {

    // child
    // retrieve username
    user = getenv("USER");
    // retrieve corresponding userid
    file = fopen("/etc/passwd", "r");
    if (file == NULL) {
      fprintf(stderr, "Failed to open password file\n");
      return -1;
    }
    userid = NULL;
    while (!feof(file)) {
      if (fgets(buffer, sizeof(buffer), file) != NULL) {
    ptr = strtok(buffer, ":");
    if (strcmp(ptr, user) == 0) {
      strtok(NULL, ":"); // password
      userid = strtok(NULL, ":"); // userid
      ptr = strtok(NULL, ":"); // group
      *ptr = '\0';
      break;
    }
      }
    }

    if (userid != NULL)
      execlp("/bin/chown", "/bin/chown", userid, target, NULL);

    // reached only in case of error
    return -1;
  }

  mode = S_IRUSR | S_IWUSR | S_IEXEC;
  chmod(target, mode);

  return 0;
}

static
void usage(char* parameter)
{
  char newline = '\n';
  char output[96];
  char buffer[96];

  snprintf(buffer, sizeof(buffer),
        "Usage: %.60s backup|restore pathname%c", parameter, newline);

  sprintf(output, buffer);
  printf(output);
}

int main(int argc, char* argv[])
{
  int cmd;
  char *path, *ptr;
  char *forbidden = FORBIDDEN_DIRECTORY;
  char *src, *dst, *buffer;
  struct stat buf;

  if (argc != 3) {
    usage(argv[0]);
    return 1;
  }

  if (strcmp("backup", argv[1]) == 0) {
    cmd = CMD_BACKUP;
  }
  else if (strcmp("restore", argv[1]) == 0) {
    cmd = CMD_RESTORE;
  } else {
    usage(argv[0]);
    return 1;
  }

  path = argv[2];

  // prevent access to forbidden directory
  ptr = realpath(path, NULL);
  if (ptr != NULL && strstr(ptr, forbidden) == ptr) {
    fprintf(stderr, "Not allowed to access target/source %s\n", path);
    return 1;
  }

  // set up paths for copy operation
  buffer = malloc(strlen(BACKUP_DIRECTORY) + 1 + strlen(path) + 1);
  if (buffer == NULL) {
    fprintf(stderr, "Failed to allocate memory\n");
    return 1;
  }

  if (cmd == CMD_BACKUP) {
    src = path;

    dst = buffer;
    strcpy(dst, BACKUP_DIRECTORY);
    strcat(dst, "/");
    strcat(dst, path);
  }
  else {
    src = buffer;
    strcpy(src, BACKUP_DIRECTORY);
    strcat(src, "/");
    strcat(src, path);

    dst = path;

    // don't overwrite existing file if we don't own it
    if (stat(dst, &buf) == 0 && buf.st_uid != getuid()) {
      fprintf(stderr, "Not your file: %s\n", dst);
      return 1;
    }
  }

  // perform actual backup/restore operation
  if (copyFile(src, dst) < 0)
    return 1;

  // grant user access to restored file
  if (cmd == CMD_RESTORE) {
    if (restorePermissions(path) < 0)
      return 1;
  }

  return 0;
}

And something useful:

  // one way to invoke backup
  //system("/usr/local/bin/backup backup foo");

  // another way
  args[0] = TARGET; args[1] = "backup";
  args[2] = "foo"; args[3] = NULL;

  env[0] = NULL;
  if (execve(TARGET, args, env) < 0)
    fprintf(stderr, "execve failed.\n");
  exit(0);


来源: stackexchange

问:
How to make screenshot by Selenide every time when @Then falls?
I use Selenide + Cucumber + IntellijIDEA and I want to get screenshot every time when @Then - inside only assertEquals - falls with java.lang.AssertionError.

How can I configure it? Now it makes screenshots every time when @When falls, but if it's @Then I can only see actual and expected values.

答:
Check official documentation to understand how to manipulate with screenshot taking logic.

Selenide takes screenshots automatically on every test failure. And its a really good in-built feature, so I only see benefit if it gets screenshot even if you are on Given/When step cause it may help you to analyse why your test failed

ContentLicense: CC BY-SA 3.0


问:
How to run flyway:migrate on a cloned database
We have a production database and we maintain it by using flyway.  Recently we cloned our production database to create a UAT database.  The UAT database has the same schema and data as that in production.  Now we try to run "mvn flyway:migrate" on the UAT database to test new flyway script.  However, we got

```<code>+---------+-----------------------+---------------------+---------+
| Version | Description           | Installed on        | State   |
+---------+-----------------------+---------------------+---------+
| 0.0.1   | script.1              |                     | <Baseln |
| 0.0.2   | script.2              |                     | <Baseln |
| 0.0.3   | script.3              |                     | <Baseln |
| 0.1.1   | script.4              |                     | <Baseln |
| 0.1.2   | script.5              |                     | <Baseln |
| 0.2.0   | script.6              |                     | <Baseln |
| 0.5.1   | script.7              |                     | <Baseln |
| 0.5.2   | script.8              |                     | <Baseln |
| 0.6.0   | script.9              |                     | <Baseln |
| 0.7.0   | script.10             |                     | <Baseln |
| 0.8.0   | script.11             |                     | <Baseln |
| 0.9.0   | script.12             |                     | <Baseln |
| 0.10.0  | script.13             |                     | <Baseln |
| 0.11.1  | script.14             |                     | <Baseln |
| 0.12.0  | script.15             |                     | <Baseln |
| 0.13.0  | script.16             |                     | <Baseln |
| 0.14.0  | script.17             |                     | <Baseln |
| 0.15.0  | script.18             |                     | <Baseln |
| 0.16.0  | script.19             |                     | <Baseln |
| 0.16.1  | script.20             |                     | <Baseln |
| 0.17.0  | script.21             |                     | <Baseln |
| 0.17.1  | script.22             |                     | <Baseln |
| 0.18.0  | script.23             |                     | <Baseln |
| 1       | << Flyway Baseline >> | 2016-11-07 08:11:33 | Baselin |
| 1.16.0  | script.19             | 2017-02-15 10:03:18 | Future  |
| 1.16.1  | script.20             | 2017-02-15 10:03:18 | Future  |
+---------+-----------------------+---------------------+---------+
</code>```

The script.23 is a new script.  We expect the state is pending.
However, the state of all scripts became Baseln.  I searched the relating topics for a day but could not find scenarios closed to my case.  Is there any configuration on flyway (maven) I can use to run migrate command on a cloned database?  Please help.  (My database is SQL Server 2014, flyway version 4.0 ,maven version is 3.5, JDK version 1.7)

Thanks a lot.
Chi-Fu

答:
I think that all versions lower than the baseline are not executed - they are supposed to belong to the baseline.

If script.23 is a new migration it should have a version greater than the last version, typically 1.18.0 (According to standard flyway config, V1_18_0__script.23.sql rather than V0_18_0__script.23.sql).

After having renamed this file, do a repair before trying to migrate again.

Body:
We have a production database and we maintain it by using flyway.  Recently we cloned our production database to create a UAT database.  The UAT database has the same schema and data as that in production.  Now we try to run "mvn flyway:migrate" on the UAT database to test new flyway script.  However, we got

+---------+-----------------------+---------------------+---------+
| Version | Description           | Installed on        | State   |
+---------+-----------------------+---------------------+---------+
| 0.0.1   | script.1              |                     | <Baseln |
| 0.0.2   | script.2              |                     | <Baseln |
| 0.0.3   | script.3              |                     | <Baseln |
| 0.1.1   | script.4              |                     | <Baseln |
| 0.1.2   | script.5              |                     | <Baseln |
| 0.2.0   | script.6              |                     | <Baseln |
| 0.5.1   | script.7              |                     | <Baseln |
| 0.5.2   | script.8              |                     | <Baseln |
| 0.6.0   | script.9              |                     | <Baseln |
| 0.7.0   | script.10             |                     | <Baseln |
| 0.8.0   | script.11             |                     | <Baseln |
| 0.9.0   | script.12             |                     | <Baseln |
| 0.10.0  | script.13             |                     | <Baseln |
| 0.11.1  | script.14             |                     | <Baseln |
| 0.12.0  | script.15             |                     | <Baseln |
| 0.13.0  | script.16             |                     | <Baseln |
| 0.14.0  | script.17             |                     | <Baseln |
| 0.15.0  | script.18             |                     | <Baseln |
| 0.16.0  | script.19             |                     | <Baseln |
| 0.16.1  | script.20             |                     | <Baseln |
| 0.17.0  | script.21             |                     | <Baseln |
| 0.17.1  | script.22             |                     | <Baseln |
| 0.18.0  | script.23             |                     | <Baseln |
| 1       | << Flyway Baseline >> | 2016-11-07 08:11:33 | Baselin |
| 1.16.0  | script.19             | 2017-02-15 10:03:18 | Future  |
| 1.16.1  | script.20             | 2017-02-15 10:03:18 | Future  |
+---------+-----------------------+---------------------+---------+

The script.23 is a new script.  We expect the state is pending.
However, the state of all scripts became Baseln.  I searched the relating topics for a day but could not find scenarios closed to my case.  Is there any configuration on flyway (maven) I can use to run migrate command on a cloned database?  Please help.  (My database is SQL Server 2014, flyway version 4.0 ,maven version is 3.5, JDK version 1.7)

Thanks a lot.
Chi-Fu


问:
ExpressJS - Call an outer function in router.get and render its data
I need to call functions in order to render mysql queries data to my views instead of having the query functions inside the router.get

How can I call a function() inside router.get so I can render its query output through EJS or any other templating engine?

index.js

```<code>function fdb(mypar) {
    obj = {}
    con.query(mypar, (err, rows) => {
        if (err) throw err
        obj = rows[0]
        console.log(obj)
        //rows data fetching OK using stored procedure get_all_1 when route '/' is called
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1')
    console.log(obj) // {}

    to_render = { print: obj }
    console.log(to_render) // { print: {} }

    res.render('index', to_render);
    //it obviously cannot render anything
    //GET / 500
});
</code>```

index.ejs

```<code><% print.forEach(function (qdata) { %>
    <tr>
        <td>
            <%= qdata.name %>
        </td>
        <td>
            <%= qdata.location %>
        </td>
    </tr>
<% }) %>
</code>```

I understannd somehow that obj gets out of scope when I try to call it through fdb() function inside the router.get but can't figure out how to manipulate that scope.

答:
Do this . You can use callback function  for this .</p>

```<code>function fdb(mypar, callback) {
    con.query(mypar, (err, rows) => {
         callback(err,rows);

    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1',function(err,obj){

    if (err) throw err;
    obj = rows[0]
    console.log(obj);
    to_render = { print: obj }
    console.log(to_render) // { print: {} }
    res.render('index', to_render);
  });
});
</code>```

Body:
I need to call functions in order to render mysql queries data to my views instead of having the query functions inside the router.get

How can I call a function() inside router.get so I can render its query output through EJS or any other templating engine?

index.js

function fdb(mypar) {
    obj = {}
    con.query(mypar, (err, rows) => {
        if (err) throw err
        obj = rows[0]
        console.log(obj)
        //rows data fetching OK using stored procedure get_all_1 when route '/' is called
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1')
    console.log(obj) // {}

    to_render = { print: obj }
    console.log(to_render) // { print: {} }

    res.render('index', to_render);
    //it obviously cannot render anything
    //GET / 500
});

index.ejs

<% print.forEach(function (qdata) { %>

            <%= qdata.name %>

            <%= qdata.location %>

<% }) %>

I understannd somehow that obj gets out of scope when I try to call it through fdb() function inside the router.get but can't figure out how to manipulate that scope.

Body:
Do this . You can use callback function  for this .

function fdb(mypar, callback) {
    con.query(mypar, (err, rows) => {
         callback(err,rows);

    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1',function(err,obj){

    if (err) throw err;
    obj = rows[0]
    console.log(obj);
    to_render = { print: obj }
    console.log(to_render) // { print: {} }
    res.render('index', to_render);
  });
});


问:
wpf bind event or command to function on item data context
I have some WPF code that looks like this

C#

```<code>namespace ItemEventTest
{
public partial class MainWindow : Window
 {
    public MainWindow()
    {
        DataContext = this;

        MyItems = new ObservableCollection<MyItem>();
        MyItems.Add(new MyItem { Name = "Otto" });
        MyItems.Add(new MyItem { Name = "Dag" });
        MyItems.Add(new MyItem { Name = "Karin" });

        InitializeComponent();
    }

    public ObservableCollection<MyItem> MyItems { get; set; }
}

public class MyItem :INotifyPropertyChanged
{
    private string m_name;

    public string Name
    {
        get { return m_name; }
        set
        {
            m_name = value;
            OnPropertyChanged();
        }
    }

    public void WhenMouseMove()
    {
        //Do stuff
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
 }
}
</code>```

Xaml

```<code><Window x:Class="ItemEventTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ItemEventTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding MyItems}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="local:MyItem">
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
</code>```

What I now want to do is when the mouse moves over an item is to call WhenMouseMove on the object that is the source of that item.

I would like to have the function called directly on the object and not by first going through MainWindow or some view model connected to MainWindow. It feels like it should be possible because the data is bound that way but I haven't managed to find a description of how to do it.

答:
If you are seeking solution in MVVM pattern

Edit: Add a reference to System.Windows.Interactivity dll (which is system defined if Blend or VS2015 installed)

then add following namespace xmlns:i="schemas.microsoft.com/expression/2010/interactivity"

// xaml file

```<code><Grid>
        <ListBox ItemsSource="{Binding MyItems}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="local:MyItem">
                    <TextBlock Text="{Binding Name}">
                          <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseEnter">
                    <i:InvokeCommandAction Command="{Binding MouseHoveredItemChangedCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</code>```

// viewmodel (MyItem class)

```<code>  public void WhenMouseMove()
        {
            //Do stuff
            Console.WriteLine(Name);
        }

        private RelayCommand _MouseHoveredItemChangedCommand;
        public RelayCommand MouseHoveredItemChangedCommand
        {
            get
            {
                if (_MouseHoveredItemChangedCommand == null)
                {
                    _MouseHoveredItemChangedCommand = new RelayCommand(WhenMouseMove);
                }
                return _MouseHoveredItemChangedCommand;
            }
        }
</code>```

// RelayCommand class

```<code> public class RelayCommand : ICommand
        {
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
            private Action methodToExecute;
            private Func<bool> canExecuteEvaluator;
            public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
            {
                this.methodToExecute = methodToExecute;
                this.canExecuteEvaluator = canExecuteEvaluator;
            }
            public RelayCommand(Action methodToExecute)
                : this(methodToExecute, null)
            {
            }
            public bool CanExecute(object parameter)
            {
                if (this.canExecuteEvaluator == null)
                {
                    return true;
                }
                else
                {
                    bool result = this.canExecuteEvaluator.Invoke();
                    return result;
                }
            }
            public void Execute(object parameter)
            {
                this.methodToExecute.Invoke();
            }
        }
</code>```

Body:
I have some WPF code that looks like this

C#

namespace ItemEventTest
{
public partial class MainWindow : Window
 {
    public MainWindow()
    {
        DataContext = this;

        MyItems = new ObservableCollection<MyItem>();
        MyItems.Add(new MyItem { Name = "Otto" });
        MyItems.Add(new MyItem { Name = "Dag" });
        MyItems.Add(new MyItem { Name = "Karin" });

        InitializeComponent();
    }

    public ObservableCollection<MyItem> MyItems { get; set; }
}

public class MyItem :INotifyPropertyChanged
{
    private string m_name;

    public string Name
    {
        get { return m_name; }
        set
        {
            m_name = value;
            OnPropertyChanged();
        }
    }

    public void WhenMouseMove()
    {
        //Do stuff
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
 }
}

Xaml

<Window x:Class="ItemEventTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ItemEventTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding MyItems}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="local:MyItem">
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

What I now want to do is when the mouse moves over an item is to call WhenMouseMove on the object that is the source of that item.

I would like to have the function called directly on the object and not by first going through MainWindow or some view model connected to MainWindow. It feels like it should be possible because the data is bound that way but I haven't managed to find a description of how to do it.

Body:
If you are seeking solution in MVVM pattern

Edit: Add a reference to System.Windows.Interactivity dll (which is system defined if Blend or VS2015 installed)

then add following namespace xmlns:i="schemas.microsoft.com/expression/2010/interactivity"

// xaml file

<Grid>
        <ListBox ItemsSource="{Binding MyItems}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="local:MyItem">
                    <TextBlock Text="{Binding Name}">
                          <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseEnter">
                    <i:InvokeCommandAction Command="{Binding MouseHoveredItemChangedCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

// viewmodel (MyItem class)

  public void WhenMouseMove()
        {
            //Do stuff
            Console.WriteLine(Name);
        }

        private RelayCommand _MouseHoveredItemChangedCommand;
        public RelayCommand MouseHoveredItemChangedCommand
        {
            get
            {
                if (_MouseHoveredItemChangedCommand == null)
                {
                    _MouseHoveredItemChangedCommand = new RelayCommand(WhenMouseMove);
                }
                return _MouseHoveredItemChangedCommand;
            }
        }

// RelayCommand class

 public class RelayCommand : ICommand
        {
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
            private Action methodToExecute;
            private Func<bool> canExecuteEvaluator;
            public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
            {
                this.methodToExecute = methodToExecute;
                this.canExecuteEvaluator = canExecuteEvaluator;
            }
            public RelayCommand(Action methodToExecute)
                : this(methodToExecute, null)
            {
            }
            public bool CanExecute(object parameter)
            {
                if (this.canExecuteEvaluator == null)
                {
                    return true;
                }
                else
                {
                    bool result = this.canExecuteEvaluator.Invoke();
                    return result;
                }
            }
            public void Execute(object parameter)
            {
                this.methodToExecute.Invoke();
            }
        }


问:
Why am I not able to return a fragment?
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

```<code>import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答: Remove the First line of import android.app.fragment. Add android.support.v4.app.Fragment </p>

Title: Why am I not able to return a fragment?

Body:
I'm getting an error on the line containing return MyFragment.get(position); inside the MyViewPageAdapter class.

Upon hovering over the error, the error is telling me:

Incompatible types.
Required: android.support.v4.app.Fragment
Found:android.app.Fragment

How can I fix this?

Here's MainActivity.java:

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TabLayout MyTabs;
    ViewPager MyPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyTabs = (TabLayout)findViewById(R.id.MyTabs);
        MyPage = (ViewPager) findViewById(R.id.MyPage);

        MyTabs.setupWithViewPager(MyPage);
        setUpViewPager(MyPage);

    }

    public void setUpViewPager(ViewPager viewpage) {
        MyViewPageAdapter Adapter = new MyViewPageAdapter(getSupportFragmentManager());
        Adapter.AddFragmentPage(new Page_1(), "Page 1");
        Adapter.AddFragmentPage(new Page_2(), "Page 2");
        Adapter.AddFragmentPage(new Page_3(), "Page 3");

        viewpage.setAdapter(Adapter);
    }

    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> MyFragment = new ArrayList<>();
        private List<String> MyPageTitle = new ArrayList<>();

        public MyViewPageAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        public void AddFragmentPage(Fragment Frag, String Title) {
            MyFragment.add(Frag);
            MyPageTitle.add(Title);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return MyFragment.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return MyPageTitle.get(position);
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


问:
Order by not working in SQL analytical functions
```<code>create table Employee
(
 Ename varchar (255),
 empno  integer primary key,
 deptno integer ,
 salary integer
 );
</code>```

`

```<code>insert into Employee values ('Gauhar khan',1000,10,5000);
insert into Employee values ('Gauri sharma',1001,10,6000);
insert into Employee values ('Gauresh verma',1002,10,7000);
insert into Employee values ('Raja ashokan',1003,20,8000);
insert into Employee values ('Divya Nair',1004,20,19000);
insert into Employee values ('Ashwin Thakare',1005,20,10000);
insert into Employee values ('Uttam Thapa',1006,30,7800);
insert into Employee values ('Krutagnya Thakker',1007,30,11000);
insert into Employee values ('Kritika manocha',1008,30,12000);
</code>```

`

```<code>select * from Employee;
</code>```

`

```<code>SELECT empno,
       deptno,
       salary,
       SUM(salary) OVER(PARTITION BY deptno ORDER BY salary) AS dept_running_total
FROM Employee;
</code>```

It returns the error :

```<code>Error: near line 1: near "(": syntax error
</code>```

I have tried using only partition by clause as well still returned the same error. Please guide me in resolving the error. I tried running this over various online sql editors.

答:
This works fine in SQL Server 2014. I can only assume this is not actually the query you are running

SqlFiddle

Body:
create table Employee
(
 Ename varchar (255),
 empno  integer primary key,
 deptno integer ,
 salary integer
 );

`

insert into Employee values ('Gauhar khan',1000,10,5000);
insert into Employee values ('Gauri sharma',1001,10,6000);
insert into Employee values ('Gauresh verma',1002,10,7000);
insert into Employee values ('Raja ashokan',1003,20,8000);
insert into Employee values ('Divya Nair',1004,20,19000);
insert into Employee values ('Ashwin Thakare',1005,20,10000);
insert into Employee values ('Uttam Thapa',1006,30,7800);
insert into Employee values ('Krutagnya Thakker',1007,30,11000);
insert into Employee values ('Kritika manocha',1008,30,12000);

`

select * from Employee;

`

SELECT empno,
       deptno,
       salary,
       SUM(salary) OVER(PARTITION BY deptno ORDER BY salary) AS dept_running_total
FROM Employee;

It returns the error :

Error: near line 1: near "(": syntax error

I have tried using only partition by clause as well still returned the same error. Please guide me in resolving the error. I tried running this over various online sql editors.


问:
Linq: How to OrderBy the SUM of one table and the COUNT of another
As per a previous question, I've got the following LINQ expression.

```<code>Events.Where(Function(e) e.EventDate >= Date.Today) _
            .OrderByDescending(Function(e) (((e.EventVotes.Sum(Function(s) s.Vote)) * 2) + (e.Comments.Count))) _
            .Skip(0) _
            .Take(5)
</code>```

Which converts to the following SQL

```<code>-- Region Parameters
DECLARE @p0 DateTime2 = '2011-01-17 00:00:00.0000000'
DECLARE @p1 Int = 2
DECLARE @p2 Int = 0
DECLARE @p3 Int = 5
-- EndRegion
SELECT [t3].[ID], [t3].[UserID], [t3].[RegionID], [t3].[LocationID], [t3].[Title], [t3].[Description], [t3].[EventDate], [t3].[URL], [t3].[Phone], [t3].[TicketPriceLow], [t3].[TicketPriceHigh], [t3].[DatePosted], [t3].[isHighlighted]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY (((
        SELECT SUM([t1].[Vote])
        FROM [dbo].[EventVotes] AS [t1]
        WHERE [t1].[EventID] = [t0].[ID]
        )) * @p1) + ((
        SELECT COUNT(*)
        FROM [dbo].[Comments] AS [t2]
        WHERE [t2].[EventID] = [t0].[ID]
        )) DESC) AS [ROW_NUMBER], [t0].[ID], [t0].[UserID], [t0].[RegionID], [t0].[LocationID], [t0].[Title], [t0].[Description], [t0].[EventDate], [t0].[URL], [t0].[Phone], [t0].[TicketPriceLow], [t0].[TicketPriceHigh], [t0].[DatePosted], [t0].[isHighlighted]
    FROM [dbo].[Events] AS [t0]
    WHERE [t0].[EventDate] >= @p0
    ) AS [t3]
WHERE [t3].[ROW_NUMBER] BETWEEN @p2 + 1 AND @p2 + @p3
ORDER BY [t3].[ROW_NUMBER]
</code>```

My problem now is when it comes to ordering when some events don't have any votes or comments.

Here is what the EventVotes table looks like (in it's entirety)

```<code>| UserID | EventID | Vote |
| 1      | 51      | 1    |
| 1      | 52      | 1    |
| 2      | 52      | 1    |
| 1      | 53      | 1    |
| 2      | 53      | -1   |
| 3      | 53      | -1   |
</code>```

The Comments table is completely empty, so since we're just doing a Count on it, we can assume that everything comes back Null.

Now when I run the query above, the result order is as follows

52

  51

  53

  1

  2

  3

When it "should" be

52

  51

  1

  2

  3

  53

because event number 53 has a vote count of "-1" while event numbers 1, 2, and 3 have a vote count of "0"

Can anyone help figure out how to enhance the Linq expression to account for events that haven't been voted on?

Here's a screenshot

EDIT:

Ok, so I've simplified the query in LinqPad to this, and the result is that I only get three results.

```<code>Events.OrderByDescending(Function(e) (((e.EventVotes.Sum(Function(s) s.Vote)) * 2) + (e.Comments.Count)))
</code>```

What this is telling me is that the orderby is only grabbing those three results (51, 52, 53), then it appends the rest of the results AFTER the order clause.  I need to figure out a way to include the rest of the "null" results in the Lambda expression.

答:
Here's a C# solution.  I tried to translate it into VB, but my VB skills (and desire to learn it, honestly) are nil, and I gave up.  I'll try to highlight the critical points to help with the translation.

Here's the full statement:

```<code>context.Events.OrderByDescending(e => (((e.EventVotes.Sum(s => (int?)s.Vote) ?? 0) * 2) + e.Comments.Count))
</code>```

What's critical is that s.Vote is first cast to a nullable integer so that the result of Sum() will be a nullable integer.  A nullable result allows you to explicitly check for null and use zero for the rest of calculation if the result was indeed null.

For VB translation purposes, ?? is a C# null-coalesce operator where (for example) myNullableIntVar ?? 0 evaluates to the value of myNullableIntVar, or if it is null, then 0.

Here's the SQL generated by the above statement, FWIW:

```<code>exec sp_executesql N'SELECT [t0].[EventID], [t0].[Name]
FROM [dbo].[Events] AS [t0]
ORDER BY ((COALESCE((
    SELECT SUM([t2].[value])
    FROM (
        SELECT [t1].[Vote] AS [value], [t1].[EventID]
        FROM [dbo].[EventVotes] AS [t1]
        ) AS [t2]
    WHERE [t2].[EventID] = [t0].[EventID]
    ),@p0)) * @p1) + ((
    SELECT COUNT(*)
    FROM [dbo].[Comments] AS [t3]
    WHERE [t3].[EventID] = [t0].[EventID]
    )) DESC',N'@p0 int,@p1 int',@p0=0,@p1=2
</code>```

Edit by rockinthesixstring

I've added the VB.NET version below - This works exactly as expected.  I tried to do a DirectCast(s.Vote, Integer?) but it threw an error saying that Integer cannot be converted to Integer?, So I had to take this approach.

```<code>Events.OrderByDescending(Function(e) (((If(e.EventVotes.Sum(Function(s) s.Vote),
                                           e.EventVotes.Sum(Function(s) s.Vote),
                                           0)) * 2) + e.Comments.Count))
</code>```

Which resulted in this SQL Query

```<code>-- Region Parameters
DECLARE @p0 Int = 0
DECLARE @p1 Int = 2
-- EndRegion
SELECT [t0].[ID], [t0].[UserID], [t0].[RegionID], [t0].[LocationID], [t0].[Title], [t0].[Description], [t0].[EventDate], [t0].[URL], [t0].[Phone], [t0].[TicketPriceLow], [t0].[TicketPriceHigh], [t0].[DatePosted], [t0].[isHighlighted]
FROM [dbo].[Events] AS [t0]
ORDER BY ((
    (CASE
        WHEN (CONVERT(Bit,(
            SELECT SUM([t1].[Vote])
            FROM [dbo].[EventVotes] AS [t1]
            WHERE [t1].[EventID] = [t0].[ID]
            ))) = 1 THEN (
            SELECT SUM([t2].[Vote])
            FROM [dbo].[EventVotes] AS [t2]
            WHERE [t2].[EventID] = [t0].[ID]
            )
        ELSE @p0
     END)) * @p1) + ((
    SELECT COUNT(*)
    FROM [dbo].[Comments] AS [t3]
    WHERE [t3].[EventID] = [t0].[ID]
    )) DESC
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As per a previous question, I've got the following LINQ expression.

Events.Where(Function(e) e.EventDate >= Date.Today) _
            .OrderByDescending(Function(e) (((e.EventVotes.Sum(Function(s) s.Vote)) * 2) + (e.Comments.Count))) _
            .Skip(0) _
            .Take(5)

Which converts to the following SQL

-- Region Parameters
DECLARE @p0 DateTime2 = '2011-01-17 00:00:00.0000000'
DECLARE @p1 Int = 2
DECLARE @p2 Int = 0
DECLARE @p3 Int = 5
-- EndRegion
SELECT [t3].[ID], [t3].[UserID], [t3].[RegionID], [t3].[LocationID], [t3].[Title], [t3].[Description], [t3].[EventDate], [t3].[URL], [t3].[Phone], [t3].[TicketPriceLow], [t3].[TicketPriceHigh], [t3].[DatePosted], [t3].[isHighlighted]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY (((
        SELECT SUM([t1].[Vote])
        FROM [dbo].[EventVotes] AS [t1]
        WHERE [t1].[EventID] = [t0].[ID]
        )) * @p1) + ((
        SELECT COUNT(*)
        FROM [dbo].[Comments] AS [t2]
        WHERE [t2].[EventID] = [t0].[ID]
        )) DESC) AS [ROW_NUMBER], [t0].[ID], [t0].[UserID], [t0].[RegionID], [t0].[LocationID], [t0].[Title], [t0].[Description], [t0].[EventDate], [t0].[URL], [t0].[Phone], [t0].[TicketPriceLow], [t0].[TicketPriceHigh], [t0].[DatePosted], [t0].[isHighlighted]
    FROM [dbo].[Events] AS [t0]
    WHERE [t0].[EventDate] >= @p0
    ) AS [t3]
WHERE [t3].[ROW_NUMBER] BETWEEN @p2 + 1 AND @p2 + @p3
ORDER BY [t3].[ROW_NUMBER]

My problem now is when it comes to ordering when some events don't have any votes or comments.

Here is what the EventVotes table looks like (in it's entirety)

| UserID | EventID | Vote |
| 1      | 51      | 1    |
| 1      | 52      | 1    |
| 2      | 52      | 1    |
| 1      | 53      | 1    |
| 2      | 53      | -1   |
| 3      | 53      | -1   |

The Comments table is completely empty, so since we're just doing a Count on it, we can assume that everything comes back Null.

Now when I run the query above, the result order is as follows

52

  51

  53

  1

  2

  3

When it "should" be

52

  51

  1

  2

  3

  53

because event number 53 has a vote count of "-1" while event numbers 1, 2, and 3 have a vote count of "0"

Can anyone help figure out how to enhance the Linq expression to account for events that haven't been voted on?

Here's a screenshot

EDIT:

Ok, so I've simplified the query in LinqPad to this, and the result is that I only get three results.

Events.OrderByDescending(Function(e) (((e.EventVotes.Sum(Function(s) s.Vote)) * 2) + (e.Comments.Count)))

What this is telling me is that the orderby is only grabbing those three results (51, 52, 53), then it appends the rest of the results AFTER the order clause.  I need to figure out a way to include the rest of the "null" results in the Lambda expression.

Body:
Here's a C# solution.  I tried to translate it into VB, but my VB skills (and desire to learn it, honestly) are nil, and I gave up.  I'll try to highlight the critical points to help with the translation.

Here's the full statement:

context.Events.OrderByDescending(e => (((e.EventVotes.Sum(s => (int?)s.Vote) ?? 0) * 2) + e.Comments.Count))

What's critical is that s.Vote is first cast to a nullable integer so that the result of Sum() will be a nullable integer.  A nullable result allows you to explicitly check for null and use zero for the rest of calculation if the result was indeed null.

For VB translation purposes, ?? is a C# null-coalesce operator where (for example) myNullableIntVar ?? 0 evaluates to the value of myNullableIntVar, or if it is null, then 0.

Here's the SQL generated by the above statement, FWIW:

exec sp_executesql N'SELECT [t0].[EventID], [t0].[Name]
FROM [dbo].[Events] AS [t0]
ORDER BY ((COALESCE((
    SELECT SUM([t2].[value])
    FROM (
        SELECT [t1].[Vote] AS [value], [t1].[EventID]
        FROM [dbo].[EventVotes] AS [t1]
        ) AS [t2]
    WHERE [t2].[EventID] = [t0].[EventID]
    ),@p0)) * @p1) + ((
    SELECT COUNT(*)
    FROM [dbo].[Comments] AS [t3]
    WHERE [t3].[EventID] = [t0].[EventID]
    )) DESC',N'@p0 int,@p1 int',@p0=0,@p1=2

Edit by rockinthesixstring

I've added the VB.NET version below - This works exactly as expected.  I tried to do a DirectCast(s.Vote, Integer?) but it threw an error saying that Integer cannot be converted to Integer?, So I had to take this approach.

Events.OrderByDescending(Function(e) (((If(e.EventVotes.Sum(Function(s) s.Vote),
                                           e.EventVotes.Sum(Function(s) s.Vote),
                                           0)) * 2) + e.Comments.Count))

Which resulted in this SQL Query

-- Region Parameters
DECLARE @p0 Int = 0
DECLARE @p1 Int = 2
-- EndRegion
SELECT [t0].[ID], [t0].[UserID], [t0].[RegionID], [t0].[LocationID], [t0].[Title], [t0].[Description], [t0].[EventDate], [t0].[URL], [t0].[Phone], [t0].[TicketPriceLow], [t0].[TicketPriceHigh], [t0].[DatePosted], [t0].[isHighlighted]
FROM [dbo].[Events] AS [t0]
ORDER BY ((
    (CASE
        WHEN (CONVERT(Bit,(
            SELECT SUM([t1].[Vote])
            FROM [dbo].[EventVotes] AS [t1]
            WHERE [t1].[EventID] = [t0].[ID]
            ))) = 1 THEN (
            SELECT SUM([t2].[Vote])
            FROM [dbo].[EventVotes] AS [t2]
            WHERE [t2].[EventID] = [t0].[ID]
            )
        ELSE @p0
     END)) * @p1) + ((
    SELECT COUNT(*)
    FROM [dbo].[Comments] AS [t3]
    WHERE [t3].[EventID] = [t0].[ID]
    )) DESC


问:
Sonata admin User
I want to set up my own Permission in Sonata Admin Bundle but I read the documentation and I am confused. I can add the standard permission to roles but What I want to do is create my own permission "PUSH" that means if a user can create PUSH notification.

I am following the instructions given in Official Documentation but I am not able to do it. For sure that I am misunderstanding something because I think that is something really normal to do.

More in detail. We have these permissions and I want to add another permission here.

```<code>Permission  Description
LIST    view the list of objects
VIEW    view the detail of one object
CREATE  create a new object
EDIT    update an existing object
DELETE  delete an existing object
EXPORT  (for the native Sonata export links)
ALL grants LIST, VIEW, CREATE, EDIT, DELETE and EXPORT
</code>```

My configuration is:

```<code>security:
    handler: sonata.admin.security.handler.acl

    information:
        PUSH:     [LIST, PUSH]
        GUEST:    [VIEW, LIST]
        STAFF:    [EDIT, LIST, CREATE, PUSH]
        EDITOR:   [OPERATOR, EXPORT]
        ADMIN:    [MASTER]

    admin_permissions: [VIEW, CREATE, LIST, DELETE, UNDELETE, PUSH, EXPORT, OPERATOR, MASTER]
</code>```

But when I execute this command to setup the new command is not working

```<code>php app/console sonata:admin:setup-acl
</code>```

I get this error:

```<code>[InvalidArgumentException]
  The code "PUSH" is not supported
</code>```

Any Ideas? Maybe is not possible to do what I want.

答:
I don't find how to solve it what I want but I did a work around.

The Idea is that I create a new Role (PUSH_ROLE) and then I assigned this Role to the users that I want. Then in the twig template I check if is_granted('ROLE_PUSH') is True.

How to create a New role:

```<code>sonata_admin:
    security:
        handler: sonata.admin.security.handler.acl

        role_admin: ROLE_ADMIN
        role_super_admin: ROLE_SUPER_ADMIN
</code>```

Title: Sonata admin User

Body:
I want to set up my own Permission in Sonata Admin Bundle but I read the documentation and I am confused. I can add the standard permission to roles but What I want to do is create my own permission "PUSH" that means if a user can create PUSH notification.

I am following the instructions given in Official Documentation but I am not able to do it. For sure that I am misunderstanding something because I think that is something really normal to do.

More in detail. We have these permissions and I want to add another permission here.

Permission  Description
LIST    view the list of objects
VIEW    view the detail of one object
CREATE  create a new object
EDIT    update an existing object
DELETE  delete an existing object
EXPORT  (for the native Sonata export links)
ALL grants LIST, VIEW, CREATE, EDIT, DELETE and EXPORT

My configuration is:

security:
    handler: sonata.admin.security.handler.acl

    information:
        PUSH:     [LIST, PUSH]
        GUEST:    [VIEW, LIST]
        STAFF:    [EDIT, LIST, CREATE, PUSH]
        EDITOR:   [OPERATOR, EXPORT]
        ADMIN:    [MASTER]

    admin_permissions: [VIEW, CREATE, LIST, DELETE, UNDELETE, PUSH, EXPORT, OPERATOR, MASTER]

But when I execute this command to setup the new command is not working

php app/console sonata:admin:setup-acl

I get this error:

[InvalidArgumentException]
  The code "PUSH" is not supported

Any Ideas? Maybe is not possible to do what I want.

Body:
I don't find how to solve it what I want but I did a work around.

The Idea is that I create a new Role (PUSH_ROLE) and then I assigned this Role to the users that I want. Then in the twig template I check if is_granted('ROLE_PUSH') is True.

How to create a New role:

sonata_admin:
    security:
        handler: sonata.admin.security.handler.acl

        role_admin: ROLE_ADMIN
        role_super_admin: ROLE_SUPER_ADMIN


问:
Retrieving JSON elements in Swift 3
I have following JSON file

```<code>{
    "events": [
               {
               "date": "01/11/2017",
               "name": [
                        "Tulsi Vivah",
                        "Pradosh Vrat"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               },
               {
               "date": "03/11/2017",
               "name": [
                        "Guru Nanak Jayanti"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               }
               ]
}
</code>```

I want to parse this and put the elements in the objectArray in the code below:

```<code>struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
        var sectionImages : [String]!
    }
    var objectArray = [Objects]()
</code>```

I have written following code for reading the file:

```<code>if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data as Data, options: [])
</code>```

My question is how do I typecast "json" to read the individual elements to fill the above objectArray.

Thanks!

答:
To retrieve data from JSON file

(Swift 3)

```<code>if let path = NSBundle.mainBundle().pathForResource("myJson", ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
    {
        if let jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String: Any]
        {
            if let eventsInfo = jsonResult["events"] as? [Any]
            {
                // Here you will get your data in Array format.
                // for e.g
                //   print(eventsInfo[0]["date"])
                // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
            }
        }
     }
}
</code>```

(Swift 4)

```<code>if let path = Bundle.main.path(forResource: "myJson", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let eventsInfo = jsonResult["events"] as? [Any] {
                    // Here you will get your data in Array format.
                    // for e.g
                    //   print(eventsInfo[0]["date"])
                    // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
          }
      } catch {
           // handle error
      }
}
</code>```

Title: Retrieving JSON elements in Swift 3

Body:
I have following JSON file

{
    "events": [
               {
               "date": "01/11/2017",
               "name": [
                        "Tulsi Vivah",
                        "Pradosh Vrat"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               },
               {
               "date": "03/11/2017",
               "name": [
                        "Guru Nanak Jayanti"
                        ],
               "photo": [
                         "photo_chaturthi",
                         "photo_ekadashi"
                         ]
               }
               ]
}

I want to parse this and put the elements in the objectArray in the code below:

struct Objects {

        var sectionName : String!
        var sectionObjects : [String]!
        var sectionImages : [String]!
    }
    var objectArray = [Objects]()

I have written following code for reading the file:

if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data as Data, options: [])

My question is how do I typecast "json" to read the individual elements to fill the above objectArray.

Thanks!

Body:
To retrieve data from JSON file

(Swift 3)

if let path = NSBundle.mainBundle().pathForResource("myJson", ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
    {
        if let jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String: Any]
        {
            if let eventsInfo = jsonResult["events"] as? [Any]
            {
                // Here you will get your data in Array format.
                // for e.g
                //   print(eventsInfo[0]["date"])
                // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
            }
        }
     }
}

(Swift 4)

if let path = Bundle.main.path(forResource: "myJson", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let eventsInfo = jsonResult["events"] as? [Any] {
                    // Here you will get your data in Array format.
                    // for e.g
                    //   print(eventsInfo[0]["date"])
                    // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
          }
      } catch {
           // handle error
      }
}


问:
pass data from Collectionview to UIcollectionResuableview
I have a collectionView to which the data (String) is passed from another VC upon load. Now when I want to pass this data (String) to the UICollectionReusabelView. I am performing the following steps

CollectionViewVC:

```<code>class PhotoDetailVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, PDHeaderViewDelegate {

// Following variables are the ones to which the data is passed to.
var image : String!
var user: User!
var post: Posts!

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    print(post.imageURL)

    collectionView.delegate = self
    collectionView.dataSource = self

    setupCells()
    increaseView()
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "mainImage", for: indexPath) as! PDHeader

    // I am setting the ReusableView properties through this section. Instead I just want to pass them to the header and then do stuff over there.

    header.post = self.post
    header.lol = post.postauthor
    header.label.text = post.caption
    header.label.sizeToFit()
    header.delegate = self
    let ref = URL(string: post.imageURL)
    Nuke.loadImage(with: ref!, into: header.mainPic)
    imageInHeaderForAuthor(author: post.postauthor, view: header.profilePic)

    return header
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

    let size = CGSize(width: collectionView.frame.width, height: collectionView.frame.height - 15)
    return size
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = (collectionView.bounds.size.width/3) - 1
    let size = CGSize(width: width, height: width)
    return size

}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func collectionView(_ collectionView: UICollectionView, layout
    collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func imageInHeaderForAuthor(author: String, view: UIImageView){
    FBDataservice.ds.REF_USERS.child(author).observeSingleEvent(of: .value, with: { (snapshot) in
        if let allData = snapshot.value as? Dictionary<String, Any> {
            if let cred = allData["credentials"] as? Dictionary<String, Any> {
                let postuser = User(userid: author, userData: cred)
                if postuser.userPic != nil {
                    let req = URL(string: postuser.userPic)
                    Nuke.loadImage(with: req!, into: view)
                }
            }
        }
    })
}

}
</code>```

ReusableView:

```<code>class PDHeader: UICollectionReusableView, FloatyDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var mainPic: UIImageView!
@IBOutlet weak var profilePic: UIImageView!

var image : String!
var post: Posts!
var lol: String!
var floaty = Floaty()
var isOwner : Bool!
var delegate: PDHeaderViewDelegate!

override func awakeFromNib() {
    super.awakeFromNib()

    //This returns nil every time.
    print(post.postauthor)

    layoutFAB()
    profilePic.makeCircle()
    label.addDropShadow(opacity: 3, radius: 8)

}

func setDelegate(delegate: PDHeaderViewDelegate) {
    self.delegate = delegate
}

func layoutFAB() {
    floaty.openAnimationType = .pop
    floaty.buttonImage = UIImage(named: "options")
    floaty.addItem("Report", icon: UIImage(named: "trash")) { item in
        self.delegate.fabReportClicked()
    }
    if isOwner{
        floaty.addItem("Edit Profile", icon: UIImage(named: "edit")) { item in
            self.delegate.fabEditClicked()
        }
        floaty.addItem("Delete", icon: UIImage(named: "trash")) { item in
            self.delegate.fabDeleteButton()
        }
    }

    floaty.fabDelegate = self
    floaty.buttonColor = UIColor.white
    floaty.hasShadow = true
    floaty.size = 45
    addSubview(floaty)
}

}
</code>```

I have commented the code with the issues.
TL;DR - The collections doesn't pass data to header and as a result I have to set them from viewForSupplementaryElementOfKind.

what is the actual issue here? Is the header being load before the data is passed to it? If not, how can I fix this?

答:
If I have understood you can try with this option:

```<code>class PDHeader: UICollectionReusableView, FloatyDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var mainPic: UIImageView!
    @IBOutlet weak var profilePic: UIImageView!

    var image : String!
    var lol: String!
    var floaty = Floaty()
    var isOwner : Bool!
    var delegate: PDHeaderViewDelegate!

    var post: Posts!{
        didSet {
           lol = post.postauthor
           label.text = post.caption
           // etc ...
        }
</code>```

Then:

```<code>func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "mainImage", for: indexPath) as! PDHeader

    header.post = self.post
    header.delegate = self

    return header
}
</code>```

Body:
I have a collectionView to which the data (String) is passed from another VC upon load. Now when I want to pass this data (String) to the UICollectionReusabelView. I am performing the following steps

CollectionViewVC:

class PhotoDetailVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, PDHeaderViewDelegate {

// Following variables are the ones to which the data is passed to.
var image : String!
var user: User!
var post: Posts!

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    print(post.imageURL)

    collectionView.delegate = self
    collectionView.dataSource = self

    setupCells()
    increaseView()
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "mainImage", for: indexPath) as! PDHeader

    // I am setting the ReusableView properties through this section. Instead I just want to pass them to the header and then do stuff over there.

    header.post = self.post
    header.lol = post.postauthor
    header.label.text = post.caption
    header.label.sizeToFit()
    header.delegate = self
    let ref = URL(string: post.imageURL)
    Nuke.loadImage(with: ref!, into: header.mainPic)
    imageInHeaderForAuthor(author: post.postauthor, view: header.profilePic)

    return header
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

    let size = CGSize(width: collectionView.frame.width, height: collectionView.frame.height - 15)
    return size
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = (collectionView.bounds.size.width/3) - 1
    let size = CGSize(width: width, height: width)
    return size

}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func collectionView(_ collectionView: UICollectionView, layout
    collectionViewLayout: UICollectionViewLayout,
                    minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func imageInHeaderForAuthor(author: String, view: UIImageView){
    FBDataservice.ds.REF_USERS.child(author).observeSingleEvent(of: .value, with: { (snapshot) in
        if let allData = snapshot.value as? Dictionary<String, Any> {
            if let cred = allData["credentials"] as? Dictionary<String, Any> {
                let postuser = User(userid: author, userData: cred)
                if postuser.userPic != nil {
                    let req = URL(string: postuser.userPic)
                    Nuke.loadImage(with: req!, into: view)
                }
            }
        }
    })
}

}

ReusableView:

class PDHeader: UICollectionReusableView, FloatyDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var mainPic: UIImageView!
@IBOutlet weak var profilePic: UIImageView!

var image : String!
var post: Posts!
var lol: String!
var floaty = Floaty()
var isOwner : Bool!
var delegate: PDHeaderViewDelegate!

override func awakeFromNib() {
    super.awakeFromNib()

    //This returns nil every time.
    print(post.postauthor)

    layoutFAB()
    profilePic.makeCircle()
    label.addDropShadow(opacity: 3, radius: 8)

}

func setDelegate(delegate: PDHeaderViewDelegate) {
    self.delegate = delegate
}

func layoutFAB() {
    floaty.openAnimationType = .pop
    floaty.buttonImage = UIImage(named: "options")
    floaty.addItem("Report", icon: UIImage(named: "trash")) { item in
        self.delegate.fabReportClicked()
    }
    if isOwner{
        floaty.addItem("Edit Profile", icon: UIImage(named: "edit")) { item in
            self.delegate.fabEditClicked()
        }
        floaty.addItem("Delete", icon: UIImage(named: "trash")) { item in
            self.delegate.fabDeleteButton()
        }
    }

    floaty.fabDelegate = self
    floaty.buttonColor = UIColor.white
    floaty.hasShadow = true
    floaty.size = 45
    addSubview(floaty)
}

}

I have commented the code with the issues.
TL;DR - The collections doesn't pass data to header and as a result I have to set them from viewForSupplementaryElementOfKind.

what is the actual issue here? Is the header being load before the data is passed to it? If not, how can I fix this?

Body:
If I have understood you can try with this option:

class PDHeader: UICollectionReusableView, FloatyDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var mainPic: UIImageView!
    @IBOutlet weak var profilePic: UIImageView!

    var image : String!
    var lol: String!
    var floaty = Floaty()
    var isOwner : Bool!
    var delegate: PDHeaderViewDelegate!

    var post: Posts!{
        didSet {
           lol = post.postauthor
           label.text = post.caption
           // etc ...
        }

Then:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "mainImage", for: indexPath) as! PDHeader

    header.post = self.post
    header.delegate = self

    return header
}


问:
Angular 4+ best practice HTTP service
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

```<code>export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}
</code>```

TaskService

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}
</code>```

TaskComponent

```<code>export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}
</code>```

template

```<code><input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

答:
Well there are two things why it's not working:

1.) the interface isn't transpired into JS. If you look at the JavaScript code that’s generated you won’t see interfaces used at all. (JavaScript simply doesn’t support them) Meaning your task property remains undefined after transpiling your code.

2/) Since your property isn't a valid object, it wasn't bound to your element, so even if your http request gets back with a valid response , it will not update the content.

Now the solution is rather easy, either assign an empty object to the task property ... or create a task class which will implement your interface and contain  properties with some default values ( null or "" values depending on the property type. ). Then instantiate it while while initializing your component.

(below may not be syntactically correct, but you get the message )

```<code>interface iTask{
  title: string
}

class Task implements iTask{
  title: ""
}

export class TaskComponent implements OnInit {
    task: Task;
    constructor(){
       this.task = new Task();
    }
}
</code>```

Title: Angular 4+ best practice HTTP service

Body:
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}

TaskService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}

TaskComponent

export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}

template

<input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

Body:
Well there are two things why it's not working:

1.) the interface isn't transpired into JS. If you look at the JavaScript code that’s generated you won’t see interfaces used at all. (JavaScript simply doesn’t support them) Meaning your task property remains undefined after transpiling your code.

2/) Since your property isn't a valid object, it wasn't bound to your element, so even if your http request gets back with a valid response , it will not update the content.

Now the solution is rather easy, either assign an empty object to the task property ... or create a task class which will implement your interface and contain  properties with some default values ( null or "" values depending on the property type. ). Then instantiate it while while initializing your component.

(below may not be syntactically correct, but you get the message )

interface iTask{
  title: string
}

class Task implements iTask{
  title: ""
}

export class TaskComponent implements OnInit {
    task: Task;
    constructor(){
       this.task = new Task();
    }
}


问:
Define and Execute Dynamic Methods
```<code>private ComplexAdvertismentsQuery QueryForm1(string searchQuery)
private ComplexAdvertismentsQuery QueryForm2(string searchQuery)
private ComplexAdvertismentsQuery QueryForm3(string searchQuery)
private ComplexAdvertismentsQuery QueryForm4(string searchQuery)
...
</code>```

then i check

```<code>query = QueryForm1(searchQuery);
if (query != null)
{
}

query = QueryForm2(searchQuery);
if (query != null)
{
}
</code>```

can i make this dynamic?

i look here http://msdn.microsoft.com/en-us/library/exczf7b9.aspx and try with Type but this is not class it is jut method.

答:
You can do that with an array of strong-typed delegates and iterate on it to execute all your methods.

```<code>var listOfQueries = new List<Func<string, ComplexAdvertismentsQuery>> {
  QueryForm1, QueryForm2, QueryForm3, QueryForm4
};

foreach (var queryForm in listOfQueries) {
  var query = queryForm(searchQuery);

  if (query != null) {
    // do something
  }
}
</code>```

If needed, you can populate the list by used reflection and get the corresponding delegate for each one, and pay the cost for reflection only once.

The drawback of this method is that all your methods must have the same prototype (ComplexAdvertismentsQuery method(string) here).

Title: Define and Execute Dynamic Methods

Body:
private ComplexAdvertismentsQuery QueryForm1(string searchQuery)
private ComplexAdvertismentsQuery QueryForm2(string searchQuery)
private ComplexAdvertismentsQuery QueryForm3(string searchQuery)
private ComplexAdvertismentsQuery QueryForm4(string searchQuery)
...

then i check

query = QueryForm1(searchQuery);
if (query != null)
{
}

query = QueryForm2(searchQuery);
if (query != null)
{
}

can i make this dynamic?

i look here http://msdn.microsoft.com/en-us/library/exczf7b9.aspx and try with Type but this is not class it is jut method.

Body:
You can do that with an array of strong-typed delegates and iterate on it to execute all your methods.

var listOfQueries = new List<Func<string, ComplexAdvertismentsQuery>> {
  QueryForm1, QueryForm2, QueryForm3, QueryForm4
};

foreach (var queryForm in listOfQueries) {
  var query = queryForm(searchQuery);

  if (query != null) {
    // do something
  }
}

If needed, you can populate the list by used reflection and get the corresponding delegate for each one, and pay the cost for reflection only once.

The drawback of this method is that all your methods must have the same prototype (ComplexAdvertismentsQuery method(string) here).


问:
Dynamic center div bootstrap
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

```

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

答:
Try using a flexbox for .container. When using justify-content: center it will center it inside the "row".

.container {
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>

</div></code>```

Title: Dynamic center div bootstrap

Body:
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

Body:
Try using a flexbox for .container. When using justify-content: center it will center it inside the "row".

.container {
  display: flex;
  justify-content: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>

</div>


问:
How can I select an element which appears in popup window using Selenium?
I  have selected the popup window using cssSelector
ex:

```<code>WebElement a = TestApp.getInstance().getDriver().findElement(By.cssSelector("#PopupWindow0")) ;
</code>```

now I want to select an element which is inside this popup.

答:
After you retrieved WebElement 'a' you can call .findElement on it, for example:

```<code>a.findElement(By.id("example"));
</code>```

This will search for all elements inside the pop-up window

Body:
I  have selected the popup window using cssSelector
ex:

WebElement a = TestApp.getInstance().getDriver().findElement(By.cssSelector("#PopupWindow0")) ;

now I want to select an element which is inside this popup.

Body:
After you retrieved WebElement 'a' you can call .findElement on it, for example:

a.findElement(By.id("example"));

This will search for all elements inside the pop-up window


问:
Translate 3D MAX file or DAE file with Autodesk Forge
My developer tried to upload and translate AutoDesk-Forge files from 3D MAX and other with DAE format. However, only the main file can be translated. All the rest of images, labels... are not in.
We still try and not sure anyone did the same thing.
Thank you. </p>

答: I just got a simplest dataset. One face is attached with a texture material image. I made an zip and sent to Forge services. It looks it can be translated. Could you check my test data anything different to yours?


问:
Attribute Routing doesn't work
I'm creating a rest api in visual studio express 2013.

I have 2 controllers: one for orders and one for clients.

I've already created the following:

/api/clients GET information about all clients

/api/clients/1 GET information about client with id = 1

/api/orders/10 GET information about order with id = 10

Now, I want to create this:

/api/clients/1/orders - GET information about all orders of client with id 1

I've read about attribute routing, but I can't make it work.

OrdersController.cs

```<code>[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
    public Order Get(string id)
    {
        // ...
    }

    [Route("clients/{id}/orders")]
    public List<Order> GetByClient(string id)
    {
        // ...
    }
}
</code>```

WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS
        config.EnableCors();

        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

RouteConfig.cs

```<code>public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

Like this, all of the other requests work properly, but when I try to access /api/clients/1/orders, I get the error HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

But as soon as I uncomment config.MapHttpAttributeRoutes();, I'm no longer able to access any of the requests - they all return this:

```<code><Error>
    <Message>An error has occurred.</Message>
<ExceptionMessage>
    The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
    at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>
</code>```

What am I doing wrong here?

答:
Uncomment your config.MapHttpAttributeRoutes() line, then in your Global.asax file, replace this:

```<code>WebApiConfig.Register(GlobalConfiguration.Configuration);
</code>```

with this:

```<code>GlobalConfiguration.Configure(WebApiConfig.Register);
</code>```

You can read about it here:

Attribute Routing in ASP.NET Web API 2

Title: Attribute Routing doesn't work

Body:
I'm creating a rest api in visual studio express 2013.

I have 2 controllers: one for orders and one for clients.

I've already created the following:

/api/clients GET information about all clients

/api/clients/1 GET information about client with id = 1

/api/orders/10 GET information about order with id = 10

Now, I want to create this:

/api/clients/1/orders - GET information about all orders of client with id 1

I've read about attribute routing, but I can't make it work.

OrdersController.cs

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
    public Order Get(string id)
    {
        // ...
    }

    [Route("clients/{id}/orders")]
    public List<Order> GetByClient(string id)
    {
        // ...
    }
}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS
        config.EnableCors();

        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Like this, all of the other requests work properly, but when I try to access /api/clients/1/orders, I get the error HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

But as soon as I uncomment config.MapHttpAttributeRoutes();, I'm no longer able to access any of the requests - they all return this:

<Error>
    <Message>An error has occurred.</Message>
<ExceptionMessage>
    The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
    at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>

What am I doing wrong here?

Body:
Uncomment your config.MapHttpAttributeRoutes() line, then in your Global.asax file, replace this:

WebApiConfig.Register(GlobalConfiguration.Configuration);

with this:

GlobalConfiguration.Configure(WebApiConfig.Register);

You can read about it here:

Attribute Routing in ASP.NET Web API 2


问:
Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )
I'm trying to debug this problem but not sure where exactly i need to replace SWT jar file for Eclipse.

Current System Config:

```<code>Eclipse Helios 3.6 - 32 Bit
JDK 1.6
JVM - 32 Bit
Windows 7 - 64 Bit
</code>```

Error Message:

```<code>java.lang.UnsatisfiedLinkError: Cannot load 64-bit SWT libraries on 32-bit JVM
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:194)
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:174)
    at org.eclipse.swt.internal.C.<clinit>(C.java:21)
    at org.eclipse.swt.widgets.Display.<clinit>(Display.java:138)
    at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:687)
    at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:161)
    at de.vogella.rcp.intro.first.Application.start(Application.java:18)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)
An error has occurred. See the log file
</code>```

Workaround:

Link1: Understood the cause of the problem and i tried to replace 64-bit SWT to 32 Bit but i'm not sure whether i'm doing it right ?

downloaded 32-bit file swt-3.6.1-win32-win32-x86.zip
 Extracted the zip file
 Have files as shown below

copied swt.jar file
 navigated to C:\Program Files\eclipse\plugins
 removed 64-bit Swt file ( i.e org.eclipse.swt.win32.win32.x86_64.source_3.6.2.v3659c )
 placed copied swt.jar file and relaunched

Still throws SAME ERROR

also tried renaming the swt.jar file to org.eclipse.swt.win32.win32.x86_64.source_3.6.2.v3659c

Still same ERROR

Link2: Suggested the alternative solution but couldn't resolve the problem.

Still same ERROR

I really don't want to uninstall 32-JVM and 32-Bit Eclipse and install corresponding 64 Bit versions.

Not an OPTION

Workaround After the paulsm4 and Paul Webster response & i'm confused

When i tried executing this to check JVM, JRE version in Eclipse

```<code>package javaVersion;

public class JavaVersion
{

    public static void main( String[] args )
    {
        System.out.println( "JRE Version :" + System.getProperty( "java.runtime.version" ) );
        System.out.println( "JVM Bit size: " + System.getProperty( "sun.arch.data.model" ) );

    }

}
</code>```

Output:

```<code>1.6.0_31-b05
JVM Bit size: 32
</code>```

However when i tried on command line for JAVA - VERSION

So my understanding system has 64bit JVM where as Eclispe is reading 32 Bit JVM. So how can i divert system to read 32 Bit JVM ?

答:
I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.
Perfect Answer, Thanks Nikil.</p>

Body:
I'm trying to debug this problem but not sure where exactly i need to replace SWT jar file for Eclipse.

Current System Config:

Eclipse Helios 3.6 - 32 Bit
JDK 1.6
JVM - 32 Bit
Windows 7 - 64 Bit

Error Message:

java.lang.UnsatisfiedLinkError: Cannot load 64-bit SWT libraries on 32-bit JVM
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:194)
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:174)
    at org.eclipse.swt.internal.C.<clinit>(C.java:21)
    at org.eclipse.swt.widgets.Display.<clinit>(Display.java:138)
    at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:687)
    at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:161)
    at de.vogella.rcp.intro.first.Application.start(Application.java:18)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1384)
An error has occurred. See the log file

Workaround:

Link1: Understood the cause of the problem and i tried to replace 64-bit SWT to 32 Bit but i'm not sure whether i'm doing it right ?

downloaded 32-bit file swt-3.6.1-win32-win32-x86.zip
 Extracted the zip file
 Have files as shown below

copied swt.jar file
 navigated to C:\Program Files\eclipse\plugins
 removed 64-bit Swt file ( i.e org.eclipse.swt.win32.win32.x86_64.source_3.6.2.v3659c )
 placed copied swt.jar file and relaunched

Still throws SAME ERROR

also tried renaming the swt.jar file to org.eclipse.swt.win32.win32.x86_64.source_3.6.2.v3659c

Still same ERROR

Link2: Suggested the alternative solution but couldn't resolve the problem.

Still same ERROR

I really don't want to uninstall 32-JVM and 32-Bit Eclipse and install corresponding 64 Bit versions.

Not an OPTION

Workaround After the paulsm4 and Paul Webster response & i'm confused

When i tried executing this to check JVM, JRE version in Eclipse

package javaVersion;

public class JavaVersion
{

    public static void main( String[] args )
    {
        System.out.println( "JRE Version :" + System.getProperty( "java.runtime.version" ) );
        System.out.println( "JVM Bit size: " + System.getProperty( "sun.arch.data.model" ) );

    }

}

Output:

1.6.0_31-b05
JVM Bit size: 32

However when i tried on command line for JAVA - VERSION

So my understanding system has 64bit JVM where as Eclispe is reading 32 Bit JVM. So how can i divert system to read 32 Bit JVM ?