问:
Adding Menus to two panes of a splitPane
I want to  have a layout like this:

The grey areas will be two different menus.

I managed to make the split panes, but I can't seem to add the menus, here's my code:

```<code>package View;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;

public class TaskView extends JFrame{
    JMenuBar menuBar;
    JMenu addTask, refresh;

    private int screenHeight,screenWidth;

    public TaskView()  {

        setTitle("TASKS");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        Toolkit myScreen = Toolkit.getDefaultToolkit();
        Dimension screenSize = myScreen.getScreenSize();
        screenHeight = screenSize.height;
        screenWidth = screenSize.width;
        setSize(screenWidth/2,screenHeight/2);
        System.out.println(screenWidth/2);
        setLocation(screenWidth/4,screenHeight/4);
        placeComponents(this.getContentPane());

    }

    private void placeComponents(Container contentPane) {

        JPanel jsp1 = new JPanel();
        JPanel jsp2 = new JPanel();
        JLabel j1 = new JLabel("Area 1");
        JLabel j2 = new JLabel("Area 2");

        menuBar = new JMenuBar();
        addTask = new JMenu("Add Task");
        refresh = new JMenu("Refresh");
        menuBar.add(addTask);
        menuBar.add(refresh);

        jsp1.add(menuBar);
        jsp1.add(j1);
        jsp2.add(j2);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                true, jsp1, jsp2);

       splitPane.setUI(new BasicSplitPaneUI());

        splitPane.setOneTouchExpandable(false);
        contentPane.add(splitPane);
        splitPane.setEnabled(false);
        setVisible(true);
        splitPane.setDividerLocation(300);
    }

}
</code>```

Every time I try to add a menu it makes a mess in the left panel and it dosn't look at all like a menu, how can i add the menus without it looking like shit?

答:
try this</p>

```<code>public class TaskView extends JFrame {

    public TaskView() throws HeadlessException {
        createGUI();
    }

    private void createGUI() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(600, 400));

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
        splitPane.setResizeWeight(0.5);
        add(splitPane, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
    }

    private JPanel createPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
        JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
        JMenuItem menuItem3 = new JMenuItem("MenuItem 3");

        JMenu menu = new JMenu("Main");
        menu.add(menuItem1);
        menu.addSeparator();
        menu.add(menuItem2);
        menu.add(menuItem3);

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        menuBar.add(new JMenu("View"));

        panel.add(menuBar, BorderLayout.PAGE_START);

        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
    }
}
</code>```

Body:
I want to  have a layout like this:

The grey areas will be two different menus.

I managed to make the split panes, but I can't seem to add the menus, here's my code:

package View;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;

public class TaskView extends JFrame{
    JMenuBar menuBar;
    JMenu addTask, refresh;

    private int screenHeight,screenWidth;

    public TaskView()  {

        setTitle("TASKS");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        Toolkit myScreen = Toolkit.getDefaultToolkit();
        Dimension screenSize = myScreen.getScreenSize();
        screenHeight = screenSize.height;
        screenWidth = screenSize.width;
        setSize(screenWidth/2,screenHeight/2);
        System.out.println(screenWidth/2);
        setLocation(screenWidth/4,screenHeight/4);
        placeComponents(this.getContentPane());

    }

    private void placeComponents(Container contentPane) {

        JPanel jsp1 = new JPanel();
        JPanel jsp2 = new JPanel();
        JLabel j1 = new JLabel("Area 1");
        JLabel j2 = new JLabel("Area 2");

        menuBar = new JMenuBar();
        addTask = new JMenu("Add Task");
        refresh = new JMenu("Refresh");
        menuBar.add(addTask);
        menuBar.add(refresh);

        jsp1.add(menuBar);
        jsp1.add(j1);
        jsp2.add(j2);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                true, jsp1, jsp2);

       splitPane.setUI(new BasicSplitPaneUI());

        splitPane.setOneTouchExpandable(false);
        contentPane.add(splitPane);
        splitPane.setEnabled(false);
        setVisible(true);
        splitPane.setDividerLocation(300);
    }

}

Every time I try to add a menu it makes a mess in the left panel and it dosn't look at all like a menu, how can i add the menus without it looking like shit?

Body:
try this

public class TaskView extends JFrame {

    public TaskView() throws HeadlessException {
        createGUI();
    }

    private void createGUI() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setPreferredSize(new Dimension(600, 400));

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
        splitPane.setResizeWeight(0.5);
        add(splitPane, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
    }

    private JPanel createPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
        JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
        JMenuItem menuItem3 = new JMenuItem("MenuItem 3");

        JMenu menu = new JMenu("Main");
        menu.add(menuItem1);
        menu.addSeparator();
        menu.add(menuItem2);
        menu.add(menuItem3);

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);
        menuBar.add(new JMenu("View"));

        panel.add(menuBar, BorderLayout.PAGE_START);

        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
    }
}


来源: stackexchange

问:
System call open C can't print file content if the file is not opened as sudo
So I create a new file:

```<code> fd = open("tester.txt", O_CREAT | O_RDWR);
</code>```

then using the system call write I add some info to it. But when I try to read the info from the file, it can't be made. Using the terminal I found out, that the only way to open the file is to use sudo and the content is successfully written. However, my program can't be root. So, how do I open the file, write some content to it and without closing the C program output the file.

答:
You are missing to specify the file mode as third argument to the creating open call; try the following:

```<code>fd = open("tester.txt", O_CREAT | O_RDWR, 0644);
</code>```

Then, the file should be created with mode -rw-r--r--, so your own user can open it for reading and writing. Otherwise, it might end up with some random permission, i.e. ---------, and only root can open this for reading (without chmodding it, at least).

ContentLicense: CC BY-SA 3.0

Body:
So I create a new file:

 fd = open("tester.txt", O_CREAT | O_RDWR);

then using the system call write I add some info to it. But when I try to read the info from the file, it can't be made. Using the terminal I found out, that the only way to open the file is to use sudo and the content is successfully written. However, my program can't be root. So, how do I open the file, write some content to it and without closing the C program output the file.

Body:
You are missing to specify the file mode as third argument to the creating open call; try the following:

fd = open("tester.txt", O_CREAT | O_RDWR, 0644);

Then, the file should be created with mode -rw-r--r--, so your own user can open it for reading and writing. Otherwise, it might end up with some random permission, i.e. ---------, and only root can open this for reading (without chmodding it, at least).


问:
How to prevent page refresh in angular 4
I want to prevent page refresh by everywhere.

I tried the code below

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service';

@Component({
  selector: 'app-review-prescription',
  templateUrl: './review-prescription.component.html',
  styleUrls: ['../../assets/css/prescriptionView.css'],
  providers:[
    CommonServices
  ]
})
export class ReviewPrescriptionComponent implements OnInit {
    constructor(
        private commonServices:CommonServices,
        private router:Router
        ){}
    ngOnInit(){
      window.onbeforeunload = function(event) {
        return 'By refreshing this page you may lost all data.';
      }
  }

}
</code>```

Tried this on ngOnChanges(), ngOnInit(), ngOnDestroy() even outside the component class(sorry illogical) but nothing works?

I need solution in Angular or JavaScript not in jQuery.

Thanks.

答:
For this, you should create a Guard.

in your routing configuration file:

```<code>const routes: Routes = [
    {
        path: '',
        redirectTo: '/homePage',
        pathMatch: 'full'
    },
    {
        path: 'accueil',
        component: AccueilComponent,
        canDeactivate: [GuardName]
    }]
</code>```

By doing this you're calling your guard on the selected component

More informations Here

In your guard:

```<code>@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return true/false;
  }
}
</code>```

Body:
I want to prevent page refresh by everywhere.

I tried the code below

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service';

@Component({
  selector: 'app-review-prescription',
  templateUrl: './review-prescription.component.html',
  styleUrls: ['../../assets/css/prescriptionView.css'],
  providers:[
    CommonServices
  ]
})
export class ReviewPrescriptionComponent implements OnInit {
    constructor(
        private commonServices:CommonServices,
        private router:Router
        ){}
    ngOnInit(){
      window.onbeforeunload = function(event) {
        return 'By refreshing this page you may lost all data.';
      }
  }

}

Tried this on ngOnChanges(), ngOnInit(), ngOnDestroy() even outside the component class(sorry illogical) but nothing works?

I need solution in Angular or JavaScript not in jQuery.

Thanks.

Body:
For this, you should create a Guard.

in your routing configuration file:

const routes: Routes = [
    {
        path: '',
        redirectTo: '/homePage',
        pathMatch: 'full'
    },
    {
        path: 'accueil',
        component: AccueilComponent,
        canDeactivate: [GuardName]
    }]

By doing this you're calling your guard on the selected component

More informations Here

In your guard:

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return true/false;
  }
}


问:
How to run celery on windows?
How to run celery worker on Windows without creating Windows Service? Is there any analogy to $ celery -A your_application worker?

答:
Celery 4.0+ does not officially support window already. But it still works on window for some development/test purpose.

Use eventlet instead as below:

```<code>pip install eventlet
celery -A <module> worker -l info -P eventlet
</code>```

It works for me on window 10 + celery 4.1 + python 3.

This solution solved the following exception:

```<code>[2017-11-16 21:19:46,938: ERROR/MainProcess] Task handler raised error: ValueError('need more than 0 values to unpack',)
Traceback (most recent call last):
  File "c:\users\wchen8\work\venv\weinsta\lib\site-packages\billiard\pool.py", line 358, in workloop
    result = (True, prepare_result(fun(*args, **kwargs)))
  File "c:\users\wchen8\work\venv\weinsta\lib\site-packages\celery\app\trace.py", line 525, in _fast_trace_task
    tasks, accept, hostname = _loc
ValueError: need more than 0 values to unpack
</code>```

===== update 2018-11 =====

Eventlet has an issue on subprocess.CalledProcessError:

https://github.com/celery/celery/issues/4063

https://github.com/eventlet/eventlet/issues/357

https://github.com/eventlet/eventlet/issues/413

So try gevent instead.

```<code>pip install gevent
celery -A <module> worker -l info -P gevent
</code>```

This works for me on window 10 + celery 4.2 + python 3.6

Title: How to run celery on windows?

Body:
Celery 4.0+ does not officially support window already. But it still works on window for some development/test purpose.

Use eventlet instead as below:

pip install eventlet
celery -A <module> worker -l info -P eventlet

It works for me on window 10 + celery 4.1 + python 3.

This solution solved the following exception:

[2017-11-16 21:19:46,938: ERROR/MainProcess] Task handler raised error: ValueError('need more than 0 values to unpack',)
Traceback (most recent call last):
  File "c:\users\wchen8\work\venv\weinsta\lib\site-packages\billiard\pool.py", line 358, in workloop
    result = (True, prepare_result(fun(*args, **kwargs)))
  File "c:\users\wchen8\work\venv\weinsta\lib\site-packages\celery\app\trace.py", line 525, in _fast_trace_task
    tasks, accept, hostname = _loc
ValueError: need more than 0 values to unpack

===== update 2018-11 =====

Eventlet has an issue on subprocess.CalledProcessError:

https://github.com/celery/celery/issues/4063

https://github.com/eventlet/eventlet/issues/357

https://github.com/eventlet/eventlet/issues/413

So try gevent instead.

pip install gevent
celery -A <module> worker -l info -P gevent

This works for me on window 10 + celery 4.2 + python 3.6

ContentLicense: CC BY-SA 4.0


问:
Decreasing the size of google maps sdk for ios
i dowloaded google maps sdk (1.8.1) for ios,I'm using it in my app.But what i noticed is that size of the framework is about 55MB.Is there any way to decrease the size of framework.
A file named "A" in directory structure "GoogleMaps.framework/Versions/A" is about 54MB.Is google maps depended on this file.please suggest some help.</p>

答:
```<code>cd GoogleMaps.framework/Versions/Current
ls -lh GoogleMaps # 113 MB
</code>```

If you don't support phones higher than the iPhone 5:

```<code>lipo -remove arm_v7 GoogleMaps -o GoogleMaps
</code>```

If your development machine is a 64 bit machine:

```<code>lipo -remove i386 GoogleMaps -o GoogleMaps
</code>```

And then:

```<code>ls -lh GoogleMaps # 75MB
</code>```

Body:
cd GoogleMaps.framework/Versions/Current
ls -lh GoogleMaps # 113 MB

If you don't support phones higher than the iPhone 5:

lipo -remove arm_v7 GoogleMaps -o GoogleMaps

If your development machine is a 64 bit machine:

lipo -remove i386 GoogleMaps -o GoogleMaps

And then:

ls -lh GoogleMaps # 75MB


问:
What is the purpose of python 2.7's download package "Windows x86 MSI program database"?
Upgrading from python 2.5/2.6 to python 2.7 on WinXP, I've found new download package forms for python at http://www.python.org/download/releases/2.7.1/.

So I'm wondering what is the purpose of python 2.7's download package "Windows x86 MSI program database"? Searching on web didn't bring me clarifications on this.

Actually it contains lots for .pdb library files, which on my PC are associated to Palm PDB files. This should be false, as Palm OS is dead.

答: It is the Python windows executable with debugging extensions. Having it as part of standard release was costly in terms of size and It was made available because in Windows due to differences in Windows versions and Visual studio versions and updates, building one by the user may not represent the DLL that distributed with Python.   More details are available here http://bugs.python.org/issue1303434</p>

ContentLicense: CC BY-SA 2.5


问:
Find corresponding row or get next row in SQL
I have a table:

```<code>id value1 value2
1  1      6
2  8      10
3  14     20
</code>```

Then I have a number, let's say x=7.

My query should find out id for which x falls between value1 and value2. If x does not fall in any range, use next id. In my case x=7 I'd get id=2.

My guess it could be done somehow using windowing functions in PostgreSQL, but maybe there is a simpler solution?

答:
```<code>select *
from t
where 7 <= v2
order by v1
limit 1
</code>```

Body:
I have a table:

id value1 value2
1  1      6
2  8      10
3  14     20

Then I have a number, let's say x=7.

My query should find out id for which x falls between value1 and value2. If x does not fall in any range, use next id. In my case x=7 I'd get id=2.

My guess it could be done somehow using windowing functions in PostgreSQL, but maybe there is a simpler solution?


问:
Vaadin framework get locale from browser
I am setting the locale for the purpose of translation.
It works when the locale stays the same during a session.
However, if I change the locale in the middle of a session and reload the page, it stays in the old locale.

Do you know of a way to get the up-to-date language settings from the browser?

My Code:

```<code>@SpringUI
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = MainUI.class)
public class MainUI extends UI
{

    @Override
    protected void init(VaadinRequest request)
    {
        log.debug("MainUI init! locale: {}", getLocale());//or getSession().getLocale()
        messageByLocaleService.setLocale(getLocale());
        ...
</code>```

I found a solution myself, but I am not 100% sure this is the correct solution.

答:
I found that Page.getCurrent().getWebBrowser() sometimes throws a null exception. I also need a request object for the purpose of evaluating cookies.

I can get a request object by VaadinService.getCurrentRequest().
So I can get the locale from there and have a single-point-of-failure, making my code more reliable.

So, my current answer is:

```<code>Locale locale = VaadinService.getCurrentRequest().getLocale();
</code>```

Body:
I am setting the locale for the purpose of translation.
It works when the locale stays the same during a session.
However, if I change the locale in the middle of a session and reload the page, it stays in the old locale.

Do you know of a way to get the up-to-date language settings from the browser?

My Code:

@SpringUI
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = MainUI.class)
public class MainUI extends UI
{

    @Override
    protected void init(VaadinRequest request)
    {
        log.debug("MainUI init! locale: {}", getLocale());//or getSession().getLocale()
        messageByLocaleService.setLocale(getLocale());
        ...

I found a solution myself, but I am not 100% sure this is the correct solution.

Body:
I found that Page.getCurrent().getWebBrowser() sometimes throws a null exception. I also need a request object for the purpose of evaluating cookies.

I can get a request object by VaadinService.getCurrentRequest().
So I can get the locale from there and have a single-point-of-failure, making my code more reliable.

So, my current answer is:

Locale locale = VaadinService.getCurrentRequest().getLocale();


问:
Search bar + select tag rails
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

```<code><%= form_tag meals_path, method: 'get', id: 'products_search' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>
  </p>
<% end %>
</code>```

meals_controller.rb

```<code>@meals_search = @meals.search(params[:search], params[:search_category])
</code>```

model/meal.rb

```<code>def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end
</code>```

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?

答:
Try to change

```<code>where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
</code>```

to

```<code>where('name LIKE ? AND category = ?', "%#{search}%", search_category)
</code>```

and

```<code>where('category = ?',  "%#{search_category}%")
</code>```

to

```<code>where('category = ?',  search_category)
</code>```

The %...% syntax only works with LIKE, not with =.

Title: Search bar + select tag rails

Body:
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

<%= form_tag meals_path, method: 'get', id: 'products_search' do %>

    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>

<% end %>

meals_controller.rb

@meals_search = @meals.search(params[:search], params[:search_category])

model/meal.rb

def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?

Body:
Try to change

where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")

to

where('name LIKE ? AND category = ?', "%#{search}%", search_category)

and

where('category = ?',  "%#{search_category}%")

to

where('category = ?',  search_category)

The %...% syntax only works with LIKE, not with =.


问:
Invalid value encountered in greater - numpy array logic
The question "Why do I get an invalid value ..." has been discussed a few times already. Here is another variant which I don't quite understand yet - this is why I am opening this thread:

(1) in

```<code>y = np.nan
(~np.isnan(y)) & (y > 5.)
</code>```

I get the correct result and no error is thrown.

(2) However, in

```<code>y = np.array([np.isnan, 6.])
(~np.isnan(y)) & (y > 5.)
</code>```

the "Invalid value encountered in greater" warning is shown.

This means that the short-circuiting (Python reference) in the boolean and expression does not work if this expression is used with numpy arrays.

Digging a bit on stackoverflow (e.g. ref ) and elsewhere it seems that under the hood the array expression is written as

```<code>np.logical_and.reduce([~np.isnan(y), y>5.])
</code>```

This means that both expressions are first evaluated for all elements before they are combined (indeed, this produces the same warning). Could someone please confirm that this is what is happening? And does anyone have asolution for this problem other than looping over all array elements?

The context I am using this expression in is to set additional values in an array to nan if they exceed a threshold, i.e. the actual code has something like

```<code>y[(~np.isnan(y)) & (y > 5.)] = np.nan
</code>```

答:
This can do it, with some boolean indexing to avoid the nan and a where statement

```<code>y[np.isfinite(y)] = np.where(y[np.isfinite(y)] > 5, np.nan, y[np.isfinite(y)])
</code>```

Body:
The question "Why do I get an invalid value ..." has been discussed a few times already. Here is another variant which I don't quite understand yet - this is why I am opening this thread:

(1) in

y = np.nan
(~np.isnan(y)) & (y > 5.)

I get the correct result and no error is thrown.

(2) However, in

y = np.array([np.isnan, 6.])
(~np.isnan(y)) & (y > 5.)

the "Invalid value encountered in greater" warning is shown.

This means that the short-circuiting (Python reference) in the boolean and expression does not work if this expression is used with numpy arrays.

Digging a bit on stackoverflow (e.g. ref ) and elsewhere it seems that under the hood the array expression is written as

np.logical_and.reduce([~np.isnan(y), y>5.])

This means that both expressions are first evaluated for all elements before they are combined (indeed, this produces the same warning). Could someone please confirm that this is what is happening? And does anyone have asolution for this problem other than looping over all array elements?

The context I am using this expression in is to set additional values in an array to nan if they exceed a threshold, i.e. the actual code has something like

y[(~np.isnan(y)) & (y > 5.)] = np.nan

Body:
This can do it, with some boolean indexing to avoid the nan and a where statement

y[np.isfinite(y)] = np.where(y[np.isfinite(y)] > 5, np.nan, y[np.isfinite(y)])


问:
MS project Interop: Get task after change
I am working with MS project(2007) interop in a C# VSTO addin. I want to check the new task finish date whenever user changes the task.

I am using Application.ProjectBeforeTaskChange to monitor task changes. but it only gives task before the change and the value that is directly changing. I want task after change.

For example if i change task duration, this event only tells me that duration is changing(and the new duration). At the same time Task.Finish is also changing(which i am interested at) but the event does not give me the new Task.Finish.

Is there any way to get the task after task changing finished?(I dont want to calculate finish time)

答: It's not very elegant, but you could consider adding the task to a queue and performing your processing in a separate thread once a suitable short delay has elapsed. That way you'll be able to reload the task and pick up the modified value.</p>


问:
How to execute delete raw query in codeigniter
I have sql query for delete multiple record from database </p>

```<code>$sql="delete from users where id IN(4,5,6..)";
</code>```

<p>How to run this query in codeigniter </p>

答:
You can also execute query like this

```<code>$delete = "id IN('4','5','6')";
$this->db->where($delete);
$this->db->delete("user");
</code>```

In this you can also execure your core query.

Body:
I have sql query for delete multiple record from database

$sql="delete from users where id IN(4,5,6..)";

How to run this query in codeigniter

Body:
You can also execute query like this

$delete = "id IN('4','5','6')";
$this->db->where($delete);
$this->db->delete("user");

In this you can also execure your core query.


问:
iOS membership renewal few days late
What happens if I renew my iOS membership few days late? I know that Apple will deny "my ability to distribute applications on the App Store and your access to the iPhone Developer Program Portal." and that all my existing certificates and provisioning profiles will be revoked and invalidated. BUT, what will happen if I renew few days after that? I did not get any emails from Apple about renewal and I just found out that today is the last day to renew. Since I am from Croatia I can not pay with my credit card online, I have to send a fax. I don't think that Apple will send me a renewal code immediately and I just want to know what will happen when I renew it? Will I still have my existing apps? Will I lose anything? Thank you.</p>

答: To answer my own question. I renewed my iOS membership one day later than the due date. All my apps were "unavailable for purchase". Customers contacted me with questions why is my app in appstore if it says that it is unavailable for purchase. Everything went to normal the day that my membership was renewed. All my apps were still there and they became available for purchase again. So, it looks that it is not so much of a problem if someone is late a few days with iOS membership renewal.</p>

Title: iOS membership renewal few days late


问:
Launch share intent on Onesignal notification action button click
I am able to successfully send notifications in onesignal. All of the features are working fine. But today when I tried to implement action buttons to the notifications, its not working. I tried to add an action button with id "ActionOne", on click of this action button below notification, it should start a share intent to share the text which i want. But each time I do that the app crashes. However when I tried to add a simple toast to another action button with id "ActionTwo", it worked. Please help me out of this. Here is the code -

```<code>public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    @Override
    public void notificationOpened(OSNotificationOpenResult result) {
        OSNotificationAction.ActionType actionType = result.action.type;
        JSONObject data = result.notification.payload.additionalData;
        String open;

    if (data != null) {
        open = data.optString("open", null);

        if (open != null && open.equals("activitytwo")) {
            Log.i("OneSignalExample", "customkey set with value: " + open);
            Intent intent = new Intent(MyApplication.getContext(), Activitytwo.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        } else {
            Intent intent = new Intent(MyApplication.getContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        }

    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken){
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

        if (result.action.actionID.equals("ActionOne")) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBodyText = "hello";
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
            MyApplication.getContext().startActivity(Intent.createChooser(sharingIntent, "Share via"));

        }else if (result.action.actionID.equals("ActionTwo")) {
            Toast.makeText(MyApplication.getContext(), "ActionTwo Button was pressed", Toast.LENGTH_LONG).show();
        }
      }
   }
}
</code>```

Here is the logcat when notification is received -

```<code>11-16 18:57:47.266 26067-26067/com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.myapplication, PID: 26067
                                                             java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2851)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                              Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1372)
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1359)
                                                                 at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
                                                                 at com.myapplication.MyNotificationOpenedHandler.notificationOpened(MyNotificationOpenedHandler.java:52)
                                                                 at com.onesignal.OneSignal$15.run(OneSignal.java:1486)
                                                                 at com.onesignal.OSUtils.runOnMainUIThread(OSUtils.java:204)
                                                                 at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1483)
                                                                 at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:1432)
                                                                 at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1519)
                                                                 at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:116)
                                                                 at com.onesignal.NotificationOpenedProcessor.processFromContext(NotificationOpenedProcessor.java:51)
                                                                 at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:38)
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2844)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
Either

cache the Context object via constructor in your adapter, or

get it from your view.

Or as a last resort,

add - FLAG_ACTIVITY_NEW_TASK flag to your intent:

```<code>myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.

Body:
I am able to successfully send notifications in onesignal. All of the features are working fine. But today when I tried to implement action buttons to the notifications, its not working. I tried to add an action button with id "ActionOne", on click of this action button below notification, it should start a share intent to share the text which i want. But each time I do that the app crashes. However when I tried to add a simple toast to another action button with id "ActionTwo", it worked. Please help me out of this. Here is the code -

public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    @Override
    public void notificationOpened(OSNotificationOpenResult result) {
        OSNotificationAction.ActionType actionType = result.action.type;
        JSONObject data = result.notification.payload.additionalData;
        String open;

    if (data != null) {
        open = data.optString("open", null);

        if (open != null && open.equals("activitytwo")) {
            Log.i("OneSignalExample", "customkey set with value: " + open);
            Intent intent = new Intent(MyApplication.getContext(), Activitytwo.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        } else {
            Intent intent = new Intent(MyApplication.getContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        }

    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken){
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

        if (result.action.actionID.equals("ActionOne")) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBodyText = "hello";
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
            MyApplication.getContext().startActivity(Intent.createChooser(sharingIntent, "Share via"));

        }else if (result.action.actionID.equals("ActionTwo")) {
            Toast.makeText(MyApplication.getContext(), "ActionTwo Button was pressed", Toast.LENGTH_LONG).show();
        }
      }
   }
}

Here is the logcat when notification is received -

11-16 18:57:47.266 26067-26067/com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.myapplication, PID: 26067
                                                             java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2851)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                              Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1372)
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1359)
                                                                 at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
                                                                 at com.myapplication.MyNotificationOpenedHandler.notificationOpened(MyNotificationOpenedHandler.java:52)
                                                                 at com.onesignal.OneSignal$15.run(OneSignal.java:1486)
                                                                 at com.onesignal.OSUtils.runOnMainUIThread(OSUtils.java:204)
                                                                 at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1483)
                                                                 at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:1432)
                                                                 at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1519)
                                                                 at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:116)
                                                                 at com.onesignal.NotificationOpenedProcessor.processFromContext(NotificationOpenedProcessor.java:51)
                                                                 at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:38)
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2844)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
Either

cache the Context object via constructor in your adapter, or

get it from your view.

Or as a last resort,

add - FLAG_ACTIVITY_NEW_TASK flag to your intent:

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.


问:
Parse from TableVC to textView in other viewController swift
I am new in programming, and have problem. I am using parse for my array in  tableview. When the row is selected i want to segue on another view controller to textView. The tableview works good but i can't get text to textView.

tableVC:

```<code>import UIKit
import Parse
class ThirdTableVC: UITableViewController {
@IBOutlet weak var refresherQuotes: UIRefreshControl!
@IBOutlet var quoteTable: UITableView!

var selectedQuote: PFObject?
var quoteItems = [PFObject]()

override func viewDidLoad() {
    super.viewDidLoad()

}
@IBAction func updateQuotesResults(_ sender: UIRefreshControl) {
    fetchQuotesData()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    loadQuoteTexts(selectedQuote: selectedQuote)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return quoteItems.count
}

func fetchQuotesData() {
    let quotesQuery = PFQuery(className: "TotalTest")
    quotesQuery.whereKey("Subcategory", equalTo: selectedQuote ?? nil)
    quotesQuery.findObjectsInBackground { (objects, error) in
        if let realCategoryObjects = objects {
            self.quoteItems = realCategoryObjects
            self.tableView.reloadData()
            self.refresherQuotes.endRefreshing()
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let quoteCell = tableView.dequeueReusableCell(withIdentifier: "quoteCell", for: indexPath)

    let quoteItem = quoteItems[indexPath.row]
    let quoteUserTitle = quoteItem.object(forKey: "TextQuote") as? String

    quoteCell.textLabel?.text = quoteUserTitle

    return quoteCell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showQuoteDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let quoteobject = quoteItems[indexPath.row] as? NSDate
            let quoteController = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            quoteController.detailItem = quoteobject
            quoteController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            quoteController.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Row tapped: \(indexPath.row)")

    let selectedQuotes: PFObject = quoteItems[indexPath.row]
    let  FourthVC = self.storyboard?.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
    FourthVC.fourthTextView.text = quoteItems[indexPath.row] as? String
    self.navigationController?.pushViewController(FourthVC, animated: true)

}

func loadQuoteTexts(selectedQuote: PFObject!) {

    let quoteQuery = PFQuery(className: "TotalQuote")
    quoteQuery.whereKey("QuoteSubs", equalTo: selectedQuote ?? nil)
    quoteQuery.includeKey("QuoteSubs")

    quoteQuery.findObjectsInBackground { (result: [PFObject]?, error) in
        if let searchQuoteResults = result {

            self.quoteItems = searchQuoteResults
            self.quoteTable.reloadData()
        }
    }
}
}
</code>```

How can I change this?
viewController with textView:

```<code> import UIKit
 import Parse

 class FourthViewController: UIViewController {

var getQuote: PFObject?

@IBOutlet weak var fourthTextView: UITextView!
@IBOutlet weak var fourthLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    fourthLabel.text! = getQuote as! String
    fourthTextView.text! = getQuote as! String
}
}
</code>```

Please help me to passing texts

答:
The problem is that you are changing from a view to another with pushViewController, by doing that your prepareForSegue won't be executed.

On your didSelectRow you need to call performSegue(withIdentifier:sender:).

You can lookup this question for more information on how to do it.

Body:
I am new in programming, and have problem. I am using parse for my array in  tableview. When the row is selected i want to segue on another view controller to textView. The tableview works good but i can't get text to textView.

tableVC:

import UIKit
import Parse
class ThirdTableVC: UITableViewController {
@IBOutlet weak var refresherQuotes: UIRefreshControl!
@IBOutlet var quoteTable: UITableView!

var selectedQuote: PFObject?
var quoteItems = [PFObject]()

override func viewDidLoad() {
    super.viewDidLoad()

}
@IBAction func updateQuotesResults(_ sender: UIRefreshControl) {
    fetchQuotesData()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    loadQuoteTexts(selectedQuote: selectedQuote)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return quoteItems.count
}

func fetchQuotesData() {
    let quotesQuery = PFQuery(className: "TotalTest")
    quotesQuery.whereKey("Subcategory", equalTo: selectedQuote ?? nil)
    quotesQuery.findObjectsInBackground { (objects, error) in
        if let realCategoryObjects = objects {
            self.quoteItems = realCategoryObjects
            self.tableView.reloadData()
            self.refresherQuotes.endRefreshing()
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let quoteCell = tableView.dequeueReusableCell(withIdentifier: "quoteCell", for: indexPath)

    let quoteItem = quoteItems[indexPath.row]
    let quoteUserTitle = quoteItem.object(forKey: "TextQuote") as? String

    quoteCell.textLabel?.text = quoteUserTitle

    return quoteCell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showQuoteDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let quoteobject = quoteItems[indexPath.row] as? NSDate
            let quoteController = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            quoteController.detailItem = quoteobject
            quoteController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            quoteController.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Row tapped: \(indexPath.row)")

    let selectedQuotes: PFObject = quoteItems[indexPath.row]
    let  FourthVC = self.storyboard?.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
    FourthVC.fourthTextView.text = quoteItems[indexPath.row] as? String
    self.navigationController?.pushViewController(FourthVC, animated: true)

}

func loadQuoteTexts(selectedQuote: PFObject!) {

    let quoteQuery = PFQuery(className: "TotalQuote")
    quoteQuery.whereKey("QuoteSubs", equalTo: selectedQuote ?? nil)
    quoteQuery.includeKey("QuoteSubs")

    quoteQuery.findObjectsInBackground { (result: [PFObject]?, error) in
        if let searchQuoteResults = result {

            self.quoteItems = searchQuoteResults
            self.quoteTable.reloadData()
        }
    }
}
}

How can I change this?
viewController with textView:

 import UIKit
 import Parse

 class FourthViewController: UIViewController {

var getQuote: PFObject?

@IBOutlet weak var fourthTextView: UITextView!
@IBOutlet weak var fourthLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    fourthLabel.text! = getQuote as! String
    fourthTextView.text! = getQuote as! String
}
}

Please help me to passing texts


问:
Warning: Multiple EventSystem in scene
In Unity I have two Canvas. In every Canvas has own EventSytems.But when I RUN this it gives me yellow message

Multiple EventSystems in scene... this is not supported

..and I tried inactive one of the canvas by script.After Warning not appeared But then buttons not working. How can I solve this problem ?

答:
Only one Canvas is supported in a scene. This error shows you that having two doesn't work.

There is no reason to have more than one canvas at that.

EDIT: Technically using more than one canvas with only one of them having an EventSystem is possible, however it is not reccomended seeing as it can lead to problems down the line.

Title: Warning: Multiple EventSystem in scene


问:
What part does hardware compression play in network apps
For a long time I've assumed that when I send data down the wire, it'll be compressed for me, as NICs have supported hardware compression for decades.  Recent testing however has shown this to be a naive view, so have started implementing software compression in my apps and services.

My question therefor is, to what extent can we as software dev's rely on hardware network compression, or have I fundamentally misunderstood what it's there for.

答:
There are TCP/IP header compressions (not the payload).  Cisco also has Layer 2 payload compressions http://www.cisco.com/en/US/tech/tk713/tk802/technologies_q_and_a_item09186a008019be75.shtml that's very low in the network stack.

For network apps, you're at layer 7, and these compressions should be transparent to you.  Depending on the nature of your payload, you may have a much superior throughput than what's done in layer 2 (e.g. H.264), or marginal improvement (e.g. text file transmission).  Since lower layer is transparent, I'd suggest don't bet on it.  You might be transmitting over something that does not compress at all (e.g. IP over ATM) and thus there's nothing for you to rely on "hardware compression".


问:
Why does Typescript accept a number value as a type?
I had a bug in my Angular 4 project where I had declared a variable:

```<code>debounce: 300;
</code>```

instead of

```<code>debounce = 300;
</code>```

So of course this.debounce was undefined before the fix.

Shouldn't Typescript give me an error in this case?

答:
That line is correct because unintentionally you have used literal-types (for more information):

This example helps you to understand how literal-types is used for restricting variables to a finite set of possible values:

```<code>let zeroOrOne: 0 | 1;

zeroOrOne = 0;
// OK

zeroOrOne = 1;
// OK

zeroOrOne = 2;
// Error: Type '2' is not assignable to type '0 | 1'
</code>```

Body:
I had a bug in my Angular 4 project where I had declared a variable:

debounce: 300;

instead of

debounce = 300;

So of course this.debounce was undefined before the fix.

Shouldn't Typescript give me an error in this case?

Body:
That line is correct because unintentionally you have used literal-types (for more information):

This example helps you to understand how literal-types is used for restricting variables to a finite set of possible values:

let zeroOrOne: 0 | 1;

zeroOrOne = 0;
// OK

zeroOrOne = 1;
// OK

zeroOrOne = 2;
// Error: Type '2' is not assignable to type '0 | 1'


问:
How can I add multiple conditions to regex?
I have tried many times but could not find the solution.

One of the rules is if string ends with digit then it must contain one more digit in string anywhere

These are the rules I have - as you can see in the console my test does not work as expected

```<code>/* password length 6-80, */
/* if ends with digit then must contain two digit, */
/* 1 upper case character, 1 lowercase character, 1 digit and 1 special character. */
/* If password starts with uppercase character then 2 uppercase character are required. */
</code>```

var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])((?=\b[A-Z]).*[A-Z].*[A-Z].*|(?!\b[A-Z]))((?=.*\d$).*\d.*\d.*|(?!.*\d$)){6,80}/g;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));```

答:
That requirements look weird. Please have a read to Microsoft Password Guidance.

Must contain one digit + must contain one digit which is not last character when last is a digit = must contain one digit before last character. In other words: replace (?=.*\d) with (?=.*\d.).

Almost same for uppercase, true requirement is having an uppercase which is not first character.

var re = /^(?=.*\d.)(?=.*[a-z])(?=.+[A-Z])(?=.*[-_*&^%$#@!~]).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("false?",re.test('Aa@sasa1'));
console.log("true?",re.test('Aa@sa1sA1'));```
</div>
</div>
</p>

<p>We also can add some contrast to prevent unneeded backtracking. As quantifiers, either greedy or lazy, can lead backtracking, better option is to work around character classes.</p>

<p>Considering first lookahead we need to match a digit anywhere before the last character. <code>(?=.*\d.)</code> then becomes <code>(?=\D*\d.)</code>, matching non digits first preventing backtracking.</p>

<p>Following that principle, the whole regex becomes:</p>

```^(?=\D*\d.)(?=[^a-z]*[a-z])(?=.[^A-Z]*[A-Z])(?=[^-_*&^%$#@!~]*[-_*&^%$#@!~]).{6,80}$
```

<p>That way, when user enters a particularly long string, failing will occur fast (have a look to The elements of Regex Style).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var re = /^(?=\D*\d.)(?=[^a-z]*[a-z])(?=.[^A-Z]*[A-Z])(?=[^-_*&^%$#@!~]*[-_*&^%$#@!~]).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("false?",re.test('Aa@sasa1'));
console.log("true?",re.test('Aa@sa1sA1'));</code>```

Body:
I have tried many times but could not find the solution.

One of the rules is if string ends with digit then it must contain one more digit in string anywhere

These are the rules I have - as you can see in the console my test does not work as expected

/* password length 6-80, */
/* if ends with digit then must contain two digit, */
/* 1 upper case character, 1 lowercase character, 1 digit and 1 special character. */
/* If password starts with uppercase character then 2 uppercase character are required. */

var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_*&^%$#@!~])((?=\b[A-Z]).*[A-Z].*[A-Z].*|(?!\b[A-Z]))((?=.*\d$).*\d.*\d.*|(?!.*\d$)){6,80}/g;

console.log("false?",re.test('Aa@sasA1'));
console.log("true?",re.test('Aa@sa1sA1'));

Body:
That requirements look weird. Please have a read to Microsoft Password Guidance.

Must contain one digit + must contain one digit which is not last character when last is a digit = must contain one digit before last character. In other words: replace (?=.*\d) with (?=.*\d.).

Almost same for uppercase, true requirement is having an uppercase which is not first character.

var re = /^(?=.*\d.)(?=.*[a-z])(?=.+[A-Z])(?=.*[-_*&^%$#@!~]).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("false?",re.test('Aa@sasa1'));
console.log("true?",re.test('Aa@sa1sA1'));

We also can add some contrast to prevent unneeded backtracking. As quantifiers, either greedy or lazy, can lead backtracking, better option is to work around character classes.

Considering first lookahead we need to match a digit anywhere before the last character. (?=.*\d.) then becomes (?=\D*\d.), matching non digits first preventing backtracking.

Following that principle, the whole regex becomes:

^(?=\D*\d.)(?=[^a-z]*[a-z])(?=.[^A-Z]*[A-Z])(?=[^-_*&^%$#@!~]*[-_*&^%$#@!~]).{6,80}$

That way, when user enters a particularly long string, failing will occur fast (have a look to The elements of Regex Style).

var re = /^(?=\D*\d.)(?=[^a-z]*[a-z])(?=.[^A-Z]*[A-Z])(?=[^-_*&^%$#@!~]*[-_*&^%$#@!~]).{6,80}$/;

console.log("false?",re.test('Aa@sasA1'));
console.log("false?",re.test('Aa@sasa1'));
console.log("true?",re.test('Aa@sa1sA1'));


问:
Using if(!empty) with multiple variables not in an array
I am trying to polish some code with the if(!empty) function in PHP but I don't know how to apply this to multiple variables when they are not an array (as I had to do previously) so if I have:

```<code>$vFoo       = $item[1];
$vSomeValue = $item[2];
$vAnother   = $item[3];
</code>```

Then I want to print the result only if there is a value. This works for one variable so you have:

```<code> if (!empty($vFoo)) {
     $result .= "<li>$vFoo</li>";
 }
</code>```

I tried something along the lines of

```<code>if(!empty($vFoo,$vSomeValue,$vAnother) {
    $result .= "<li>$vFoo</li>"
    $result .= "<li>$vSomeValue</li>"
    $result .= "<li>$vAnother</li>"
}
</code>```

But of course, it doesn't work.

答:
Just for the record: array_reduce works as well.</p>

```<code>if (!array_reduce($item, function($prev_result,$next) {
    return $prev_result || empty($next); // $prev_result will be initial null=false
})) {
    // do your stuff
}
</code>```

Body:
I am trying to polish some code with the if(!empty) function in PHP but I don't know how to apply this to multiple variables when they are not an array (as I had to do previously) so if I have:

$vFoo       = $item[1];
$vSomeValue = $item[2];
$vAnother   = $item[3];

Then I want to print the result only if there is a value. This works for one variable so you have:

 if (!empty($vFoo)) {
     $result .= "
$vFoo
";
 }

I tried something along the lines of

if(!empty($vFoo,$vSomeValue,$vAnother) {
    $result .= "
$vFoo
"
    $result .= "
$vSomeValue
"
    $result .= "
$vAnother
"
}

But of course, it doesn't work.

Body:
Just for the record: array_reduce works as well.

if (!array_reduce($item, function($prev_result,$next) {
    return $prev_result || empty($next); // $prev_result will be initial null=false
})) {
    // do your stuff
}


问:
How to Disable Alt + F4 closing form?
What is the best way to disable Alt + F4 in a c# win form to prevent the user from closing the form?

I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.

答:
This is a hack to disable Alt + F4.

```<code>private void test_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4)
    {
        e.Cancel = true;
    }
}
</code>```

OwnerDisplayName: Aros

Title: How to Disable Alt + F4 closing form?

LastEditorDisplayName: CodingTheWheel

Body:
This is a hack to disable Alt + F4.

private void test_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4)
    {
        e.Cancel = true;
    }
}


问:
Reader is empty
I have a data reader that gets empty results but I don't get why?

My connection state is open, i tested my query in my DB, it returns values but there my reader.read() just get skipped

```<code>OdbcDataReader Reader;
string mond = "select fir_mdnt from safir JOIN safirbpv ON firbpv_fir = fir_fir where firbpv_ibnr = '" + _cb_Compte.SelectedItem + "' group by fir_mdnt;";
OdbcCommand mondant = new OdbcCommand(mond, InfoConnexion);

InfoConnexion.Open();
Reader = mondant.ExecuteReader();
while (Reader.Read())
{
    MessageBox.Show(Reader.ToString());
}
InfoConnexion.Close();
</code>```

答:
Please, brush up the routine and put a break point on using (OdbcDataReader reader = mondant.ExecuteReader()) {

The code cleared

```<code>//DONE: make SQL readable
//DONE: make SQL parametrized (ODBC doesn't support named parameters, but ?)
string sql =
    @"select fir_mdnt
        from safir join
             safirbpv on firbpv_fir = fir_fir
       where firbpv_ibnr = ?
    group by fir_mdnt";

//DONE: wrap IDisposable into using
//DONE: do not share the connection but create a new one
using (OdbcConnection con = new OdbcConnection(connectionStringHere)) {
  con.Open();

  //DONE: wrap IDisposable into using
  using(OdbcCommand mondant = new OdbcCommand(sql, con)) {
    //TODO: check the actual parameter type and value
    //TODO: you may want to add Trim: _cb_Compte.SelectedItem.ToString().Trim()
    mondant.Parameters.Add(new OdbcParameter("", OdbcType.Text)
      {Value = _cb_Compte.SelectedItem});

    //DONE: wrap IDisposable into using
    //TODO: put a break point here
    using (OdbcDataReader reader = mondant.ExecuteReader()) {
      while (reader.Read()) {
        MessageBox.Show(Convert.ToString(reader[0]));
      }
    }
  }
}
</code>```

Then you have to debug

Run the code.

Stop on the break point.

Check sql, parameter (its value).

Check reader.HasRows value.

Execute the query at any kind of RDMBS editor: do you have any records returned?

Title: Reader is empty

Body:
I have a data reader that gets empty results but I don't get why?

My connection state is open, i tested my query in my DB, it returns values but there my reader.read() just get skipped

OdbcDataReader Reader;
string mond = "select fir_mdnt from safir JOIN safirbpv ON firbpv_fir = fir_fir where firbpv_ibnr = '" + _cb_Compte.SelectedItem + "' group by fir_mdnt;";
OdbcCommand mondant = new OdbcCommand(mond, InfoConnexion);

InfoConnexion.Open();
Reader = mondant.ExecuteReader();
while (Reader.Read())
{
    MessageBox.Show(Reader.ToString());
}
InfoConnexion.Close();

Body:
Please, brush up the routine and put a break point on using (OdbcDataReader reader = mondant.ExecuteReader()) {

The code cleared

//DONE: make SQL readable
//DONE: make SQL parametrized (ODBC doesn't support named parameters, but ?)
string sql =
    @"select fir_mdnt
        from safir join
             safirbpv on firbpv_fir = fir_fir
       where firbpv_ibnr = ?
    group by fir_mdnt";

//DONE: wrap IDisposable into using
//DONE: do not share the connection but create a new one
using (OdbcConnection con = new OdbcConnection(connectionStringHere)) {
  con.Open();

  //DONE: wrap IDisposable into using
  using(OdbcCommand mondant = new OdbcCommand(sql, con)) {
    //TODO: check the actual parameter type and value
    //TODO: you may want to add Trim: _cb_Compte.SelectedItem.ToString().Trim()
    mondant.Parameters.Add(new OdbcParameter("", OdbcType.Text)
      {Value = _cb_Compte.SelectedItem});

    //DONE: wrap IDisposable into using
    //TODO: put a break point here
    using (OdbcDataReader reader = mondant.ExecuteReader()) {
      while (reader.Read()) {
        MessageBox.Show(Convert.ToString(reader[0]));
      }
    }
  }
}

Then you have to debug

Run the code.

Stop on the break point.

Check sql, parameter (its value).

Check reader.HasRows value.

Execute the query at any kind of RDMBS editor: do you have any records returned?


问:
String compare strange bug
I have strange bug in my code. I have variable type and when I load that from class Settings ( implements persistable ) it has value "CPU 21" (type="CPU 21"), but when I try
 if(type=="CPU 21") the condition is false. How is that possible ? </p>

答:
It's not a bug at all. It's the way that == works.

For reference types (such as string), "==" will always compare the references directly. If you have two references which refer to separate objects with equal content, then "==" will evaluate to false. Use equals for value equality.

Note that it's easy to fool yourself by using String literals, which are interned:

```<code>String x = "CPU 21";
String y = "CPU 21";
boolean b = (x == y);
</code>```

Now b is true because the values of x and y - the references are actually the same. They're referreing to the same String object. Compare that with this:

```<code>String x = new String("CPU 21");
String y = new String("CPU 21");
boolean b1 = (x == y);
boolean b2 = x.equals(y);
</code>```

Now b1 is false because x and y refer to distinct String objects, but b2 is true because String.equals(String) compares the contents of the strings in question (i.e. the character sequences represented by the strings).

Title: String compare strange bug

Body:
It's not a bug at all. It's the way that == works.

For reference types (such as string), "==" will always compare the references directly. If you have two references which refer to separate objects with equal content, then "==" will evaluate to false. Use equals for value equality.

Note that it's easy to fool yourself by using String literals, which are interned:

String x = "CPU 21";
String y = "CPU 21";
boolean b = (x == y);

Now b is true because the values of x and y - the references are actually the same. They're referreing to the same String object. Compare that with this:

String x = new String("CPU 21");
String y = new String("CPU 21");
boolean b1 = (x == y);
boolean b2 = x.equals(y);

Now b1 is false because x and y refer to distinct String objects, but b2 is true because String.equals(String) compares the contents of the strings in question (i.e. the character sequences represented by the strings).


问:
iOS BLE Scanning with (user) killed App
I am trying to find out if I can have a terminated iOS App register for Bluetooth Low Energy (BLE) events. I already got the app working in background mode while being suspended.

I also read in the official documentation about state restauration and preservation for killed Apps. As far as I can see the documentation always seems to refer to apps killed by the system due to memory shortage.

My question is whether or not there is a similar possibility for apps that were terminated by the user. I would like to (re)-create my app whenever a BLE peripheral is close.

答:
In ios possible to BLE scan and other works after kill app by user.
Tested in iOS 10(its working fine).
Not tested in iOS 11(not sure for app is run after kill app by user in iOS 11).</p>

Title: iOS BLE Scanning with (user) killed App


问:
How to create an optimizer in Tensorflow
I want to write a new optimization algorithm for my network on Tensorflow. I hope to implement the Levenberg Marquardt optimization algorithm, which now is excluded from TF API. I found poor documentation on how to write a custom optimizer, so i ask if someone can give my any advice. Thanks.</p>

答:
Before running the Tensorflow Session, one should initiate an Optimizer as seen below:

```<code># Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
</code>```

tf.train.GradientDescentOptimizer is an object of the class GradientDescentOptimizer and as the name says, it implements the gradient descent algorithm.

The method minimize() is being called with a “cost” as parameter and consists of the two methods  compute_gradients() and then apply_gradients().

For most (custom) optimizer implementations, the method apply_gradients() needs to be adapted.

This method relies on the (new) Optimizer (class), which we will create, to implement the following methods:  _create_slots(), _prepare(), _apply_dense(), and _apply_sparse().

_create_slots() and  _prepare() create and initialise additional
variables, such as momentum.

_apply_dense(), and _apply_sparse() implement the actual Ops, which update the variables.

Ops are generally written in C++ . Without having to change the C++ header yourself, you can still return a python wrapper of some Ops through these methods.
This is done as follows:

```<code>def _create_slots(self, var_list):
   # Create slots for allocation and later management of additional
   # variables associated with the variables to train.
   # for example: the first and second moments.
   '''
   for v in var_list:
      self._zeros_slot(v, "m", self._name)
      self._zeros_slot(v, "v", self._name)
   '''
def _apply_dense(self, grad, var):
   #define your favourite variable update
    # for example:
   '''
   # Here we apply gradient descents by substracting the variables
   # with the gradient times the learning_rate (defined in __init__)
   var_update = state_ops.assign_sub(var, self.learning_rate * grad)
   '''
   #The trick is now to pass the Ops in the control_flow_ops and
   # eventually groups any particular computation of the slots your
   # wish to keep track of:
   # for example:
   '''
    m_t = ...m... #do something with m and grad
    v_t = ...v... # do something with v and grad
    '''
  return control_flow_ops.group(*[var_update, m_t, v_t])
</code>```

For a more detailed explanation with example, see this blog post
https://www.bigdatarepublic.nl/custom-optimizer-in-tensorflow/

Body:
Before running the Tensorflow Session, one should initiate an Optimizer as seen below:

# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

tf.train.GradientDescentOptimizer is an object of the class GradientDescentOptimizer and as the name says, it implements the gradient descent algorithm.

The method minimize() is being called with a “cost” as parameter and consists of the two methods  compute_gradients() and then apply_gradients().

For most (custom) optimizer implementations, the method apply_gradients() needs to be adapted.

This method relies on the (new) Optimizer (class), which we will create, to implement the following methods:  _create_slots(), _prepare(), _apply_dense(), and _apply_sparse().

_create_slots() and  _prepare() create and initialise additional
variables, such as momentum.

_apply_dense(), and _apply_sparse() implement the actual Ops, which update the variables.

Ops are generally written in C++ . Without having to change the C++ header yourself, you can still return a python wrapper of some Ops through these methods.
This is done as follows:

def _create_slots(self, var_list):
   # Create slots for allocation and later management of additional
   # variables associated with the variables to train.
   # for example: the first and second moments.
   '''
   for v in var_list:
      self._zeros_slot(v, "m", self._name)
      self._zeros_slot(v, "v", self._name)
   '''
def _apply_dense(self, grad, var):
   #define your favourite variable update
    # for example:
   '''
   # Here we apply gradient descents by substracting the variables
   # with the gradient times the learning_rate (defined in __init__)
   var_update = state_ops.assign_sub(var, self.learning_rate * grad)
   '''
   #The trick is now to pass the Ops in the control_flow_ops and
   # eventually groups any particular computation of the slots your
   # wish to keep track of:
   # for example:
   '''
    m_t = ...m... #do something with m and grad
    v_t = ...v... # do something with v and grad
    '''
  return control_flow_ops.group(*[var_update, m_t, v_t])

For a more detailed explanation with example, see this blog post
https://www.bigdatarepublic.nl/custom-optimizer-in-tensorflow/


问:
Get currency ISO 4217 code based on locale
Say, if I parse HTTP Accept-Language header with Locale::acceptFromHttp is there an easy and reliable way to get user's preferred currency based on this locale identifier? Like "USD" for "en-US".

I wish there was a way to do this with PHP intl extension but so far was unable to find my answer in the manual. I saw Zend Framework can do this with Zend_Currency but it's just too bloated for my particular software.

Any other libs or ways of achieving this? Since there must be a lot of locale identifiers a simple switch is a bit of overkill.

答:
A bit late but you can get it with \NumberFormatter:

```<code><?php

$currencyPerLocale = array_reduce(
    \ResourceBundle::getLocales(''),
    function (array $currencies, string $locale) {
        $currencies[$locale] = \NumberFormatter::create(
            $locale,
            \NumberFormatter::CURRENCY
        )->getTextAttribute(\NumberFormatter::CURRENCY_CODE);

        return $currencies;
    },
    []
);
</code>```

Body:
A bit late but you can get it with \NumberFormatter:

<?php

$currencyPerLocale = array_reduce(
    \ResourceBundle::getLocales(''),
    function (array $currencies, string $locale) {
        $currencies[$locale] = \NumberFormatter::create(
            $locale,
            \NumberFormatter::CURRENCY
        )->getTextAttribute(\NumberFormatter::CURRENCY_CODE);

        return $currencies;
    },
    []
);


问:
select row where the slot is the biggest
i need to select one row where slot_left is the biggest. i tried

```<code>for ( $i=1;$i<3;$i++) {
    $sql5 = "SELECT * from user u where (
        select max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$name'
    )";
    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        // echo the id which the slot_left is the biggest
        echo $i['slot_left'];
    }
}
</code>```

but still cannot. please help!

答:
SQL can be. You select all rows from DB.

$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";

$name variable used in query not set

Variable $i is not array. Array is $row

echo $row['slot_left'];

Body:
i need to select one row where slot_left is the biggest. i tried

for ( $i=1;$i<3;$i++) {
    $sql5 = "SELECT * from user u where (
        select max(slot_left) from company c,user u
        where c.id=u.company_id and c.id='$name'
    )";
    $result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
    while($row=mysqli_fetch_array($result5)) {
        // echo the id which the slot_left is the biggest
        echo $i['slot_left'];
    }
}

but still cannot. please help!


问:
ASP.NET MVC NonAction meaning
Can anybody please tell me why should I use the NonAction attribute? I mean say I have a form with several submit values: Update, Delete or Insert. Since all the submit buttons have the same form in common I'm switching the submit value inside the controller and act accordingly.

Like this:

```<code>public ActionResult asd(string submitButton){
     switch(submitButton){
         case "Insert":
             return Insert();
         // bla bla bla
     }
}

[NonAction]
public ActionResult Insert(){
    // some code inside here
    return View();
}
</code>```

Once again, why should I use NonAction instead of something like this:

```<code>public void Insert(){
    // some code inside here
}
</code>```

答:
I just used [NonAction] in our web api, to decorate a bunch of Controller Methods (endpoints) because we had a last minute decision that we will postpone the delivery of the specific endpoints.

So it is useful, if you want to avoid exposing an API endpoint, but still want to keep the implementation for later.

So I used this attribute and it saved me a lot of time.

I will just remove it in the next release and this will simply be there!

Title: ASP.NET MVC NonAction meaning

Body:
Can anybody please tell me why should I use the NonAction attribute? I mean say I have a form with several submit values: Update, Delete or Insert. Since all the submit buttons have the same form in common I'm switching the submit value inside the controller and act accordingly.

Like this:

public ActionResult asd(string submitButton){
     switch(submitButton){
         case "Insert":
             return Insert();
         // bla bla bla
     }
}

[NonAction]
public ActionResult Insert(){
    // some code inside here
    return View();
}

Once again, why should I use NonAction instead of something like this:

public void Insert(){
    // some code inside here
}


问:
Sonarlint not syncing with SonarQube
Using Sonarlint 3.2 in Eclipse with SonarQube 5.6.6.

I have successfully bound my project(s) in Eclipse to SonarQube. However, Sonarlint is reporting no issues, while issues are reported in SonarQube. I have been unsuccesfull in resolving the error.

Below is the log file (a little bit edited for readability...) of Sonarlint console. What surprises me are the "No language available" and "No analyzers installed" messages.

Sonarlint stand alone gives expected results. The connected mode to SonarQube gives 0 issues.

```<code>Trigger: EDITOR_OPEN
SonarLint analysis of file xxx.java...
Connected mode (using configuration of 'xxx' in server 'xxx')
Starting analysis with configuration:
[
  moduleKey: xxx
  baseDir: xxx
  workDir: C:\Werkomgeving\.metadata\.plugins\org.eclipse.core.resources\.projects\LWBBusinessRules\org.sonarlint.eclipse.core
  extraProperties: {sonar.java.source=1.6, sonar.java.target=1.6, sonar.libraries=yyyyy, sonar.binaries=C:xxx, sonar.java.binaries=C:xxx, sonar.java.test.binaries=C:xxx}
  inputFiles: [
    xxx.java
  ]
]

No language available
No analyzers installed
Start analysis
Quality profiles:
Index files
Setting filesystem encoding: UTF-8
1 files indexed
Found 0 issue(s)
Done in 23 ms
</code>```

答:
SonarLint 3.2 is incompatible with the server 5.6.6 version. We had to revert to version 2.5.1 of SonarLint. After we did that, we see issues from SonarLint itself and from the server.

Upgrading the server was not possible in our situation.

Title: Sonarlint not syncing with SonarQube

Body:
Using Sonarlint 3.2 in Eclipse with SonarQube 5.6.6.

I have successfully bound my project(s) in Eclipse to SonarQube. However, Sonarlint is reporting no issues, while issues are reported in SonarQube. I have been unsuccesfull in resolving the error.

Below is the log file (a little bit edited for readability...) of Sonarlint console. What surprises me are the "No language available" and "No analyzers installed" messages.

Sonarlint stand alone gives expected results. The connected mode to SonarQube gives 0 issues.

Trigger: EDITOR_OPEN
SonarLint analysis of file xxx.java...
Connected mode (using configuration of 'xxx' in server 'xxx')
Starting analysis with configuration:
[
  moduleKey: xxx
  baseDir: xxx
  workDir: C:\Werkomgeving\.metadata\.plugins\org.eclipse.core.resources\.projects\LWBBusinessRules\org.sonarlint.eclipse.core
  extraProperties: {sonar.java.source=1.6, sonar.java.target=1.6, sonar.libraries=yyyyy, sonar.binaries=C:xxx, sonar.java.binaries=C:xxx, sonar.java.test.binaries=C:xxx}
  inputFiles: [
    xxx.java
  ]
]

No language available
No analyzers installed
Start analysis
Quality profiles:
Index files
Setting filesystem encoding: UTF-8
1 files indexed
Found 0 issue(s)
Done in 23 ms


问:
REST to return content after POST on Java service
New users are created with the POST method, and after this the database will attach it an unique ID, which is necessary to create a token.

The only way to create a token, is after the process of user creation. I query it from the database and now it should have ID on it, but I can't figure how to do that.

Is there any way to retrieve the entity from database right after creating it?

If looked at this similar question, but couldn't find an answer: Is it ok by REST to return content after POST?

```<code>@POST
    @Consumes({MediaType.APPLICATION_JSON})
    public Response create(@QueryParam("email") String email, @QueryParam("username") String userName, @QueryParam("password") String password) {
        if (TextUtil.isEmpty(userName) || TextUtil.isEmpty(password) || TextUtil.isEmpty(email)) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } else {
            User newUser = new User();
            newUser.setEmail(email);
            newUser.setUsername(userName);
            newUser.setPass(password);
            super.create(newUser); //ths line create user in database
            String id = newUser.getUid() + ""; //the newUser has no id yet so it is null but I want this id from database
            return Response.status(Response.Status.OK).entity("id: " + id).build();
        }
    }
</code>```

Create super.method

```<code>public void create(T entity) {
        getEntityManager().persist(entity);
    }
</code>```

I generate REST api using this tutorial
https://netbeans.org/kb/docs/websvc/rest.html

答:
```<code>getEntityManager().persist(entity);
</code>```

Set the id of the entity by calling entity.setId(...).

Body:
New users are created with the POST method, and after this the database will attach it an unique ID, which is necessary to create a token.

The only way to create a token, is after the process of user creation. I query it from the database and now it should have ID on it, but I can't figure how to do that.

Is there any way to retrieve the entity from database right after creating it?

If looked at this similar question, but couldn't find an answer: Is it ok by REST to return content after POST?

@POST
    @Consumes({MediaType.APPLICATION_JSON})
    public Response create(@QueryParam("email") String email, @QueryParam("username") String userName, @QueryParam("password") String password) {
        if (TextUtil.isEmpty(userName) || TextUtil.isEmpty(password) || TextUtil.isEmpty(email)) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } else {
            User newUser = new User();
            newUser.setEmail(email);
            newUser.setUsername(userName);
            newUser.setPass(password);
            super.create(newUser); //ths line create user in database
            String id = newUser.getUid() + ""; //the newUser has no id yet so it is null but I want this id from database
            return Response.status(Response.Status.OK).entity("id: " + id).build();
        }
    }

Create super.method

public void create(T entity) {
        getEntityManager().persist(entity);
    }

I generate REST api using this tutorial
https://netbeans.org/kb/docs/websvc/rest.html

Body:
getEntityManager().persist(entity);

Set the id of the entity by calling entity.setId(...).


问:
Kentico 10 Link to existing page feature
Is there any way to force Kentico 10 to adopt a certain template when I link to another page with a template of a type I do not want?

An example would be I have a folder of CTA's. I want one of these CTA's to link to a page that uses the template "genericTemplate" but I would like the linked page I just created to be of template type "nonGenericTemplate".

The reason for this is that "genericTemplate" does not have the fields I am looking for and I would prefer to not force people to input field data in two places ("genericTemplate" and "nonGenericTemplate")

答:
I maybe misunderstanding what you mean by CTA; to me it's a link that a user can click on.

I don't believe that Kentico puts the field on the Page Template object, but on the Page Type object. The Page Type reflects what can be stored against a page, the Page Template reflects how the page looks.

When you create pages in Kentico you can assign a default Page Template to a Page Type in the administration interface; it's in the New document settings category of the Page Type interface called Default page template

If it's Page Type you meant, you can change the administration interface itself to only display fields when certain criteria are met. You could write a macro too, if the logic is quite complex. You can do this against a field itself or if you've got linked classes you can do it against the whole group. That way, you'd only need one Page Type to cover all eventualities.

John


问:
Generating random transition probability matrix python
I was wondering whether there is an easy way to generate a square matrix filled with random numbers in python, given some conditions:

the rows have to sum up to 1.

the values on the diagonal should be significantly higher than the
other values.

This is a stochastic matrix, and generating one is possible, however the tricky part is the condition about the diagonal.
e.g. for a 4x4 matrix the output should look something like this:

```<code>[[0.90, 0.03, 0.03, 0.04],
[0.01, 0.98, 0.005, 0.005],
[0.04, 0.01, 0.92, 0.03],
[0.00, 0.02, 0.03, 0.95]]
</code>```

Are there good ways to generate such matrix for a variable size?

答:
Here is a quick-and-dirty solution

```<code>import random

k = 4

result = [[random.uniform(0, 0.1 / k) for i in range(k)] for j in range(k)]
for j, r in enumerate(result):
    r[j] += 1 - sum(r)
</code>```

You may want to consider using a different random distribution and also have a look at numpy.

Body:
I was wondering whether there is an easy way to generate a square matrix filled with random numbers in python, given some conditions:

the rows have to sum up to 1.

the values on the diagonal should be significantly higher than the
other values.

This is a stochastic matrix, and generating one is possible, however the tricky part is the condition about the diagonal.
e.g. for a 4x4 matrix the output should look something like this:

[[0.90, 0.03, 0.03, 0.04],
[0.01, 0.98, 0.005, 0.005],
[0.04, 0.01, 0.92, 0.03],
[0.00, 0.02, 0.03, 0.95]]

Are there good ways to generate such matrix for a variable size?

Body:
Here is a quick-and-dirty solution

import random

k = 4

result = [[random.uniform(0, 0.1 / k) for i in range(k)] for j in range(k)]
for j, r in enumerate(result):
    r[j] += 1 - sum(r)

You may want to consider using a different random distribution and also have a look at numpy.


问:
Using Export-CLixml with boolean values
I'm trying to export a Boolean value to CliXML using this code:

```<code>[bool]$test = $true | Export-Clixml -Path C:\test.clxml
</code>```

Returns the error : Cannot convert value "System.Management.Automation.PSCustomObject" to Type "System.Boolean".

I can export strings to CliXML however:

```<code>[string]$test = 'true' | Export-Clixml -Path C:\test.clxml
</code>```

What is wrong with the boolean example?

答:
Export-CliXml does not return any objects.  It takes your input and turns it into a file.

When you assign a pipeline to a variable, you get the results of the last item in the chain (in this case, no return is $Null or an empty value)

Working example:

```<code>$Test = $True
$Test | Export-CliXml -Path 'C:\test.xml'

$Test = 'true'
$Test | Export-CliXml -Path 'C:\test.xml'
</code>```

Additionally, it is unnecessary and bad style to manually define variable types like you're doing.  The interpreter is intelligent enough to know the types of direct assignments like that.  It's better to do it on the other side if you're trying to type-cast.

e.g.

```<code>$Test = [String]$True
</code>```

In your specific use-case, it appears that Export-CliXml is returning a [PSCustomObject] but with your variable assignment as [Bool], it's failing to type-cast it.

Title: Using Export-CLixml with boolean values

Body:
I'm trying to export a Boolean value to CliXML using this code:

[bool]$test = $true | Export-Clixml -Path C:\test.clxml

Returns the error : Cannot convert value "System.Management.Automation.PSCustomObject" to Type "System.Boolean".

I can export strings to CliXML however:

[string]$test = 'true' | Export-Clixml -Path C:\test.clxml

What is wrong with the boolean example?

Body:
Export-CliXml does not return any objects.  It takes your input and turns it into a file.

When you assign a pipeline to a variable, you get the results of the last item in the chain (in this case, no return is $Null or an empty value)

Working example:

$Test = $True
$Test | Export-CliXml -Path 'C:\test.xml'

$Test = 'true'
$Test | Export-CliXml -Path 'C:\test.xml'

Additionally, it is unnecessary and bad style to manually define variable types like you're doing.  The interpreter is intelligent enough to know the types of direct assignments like that.  It's better to do it on the other side if you're trying to type-cast.

e.g.

$Test = [String]$True

In your specific use-case, it appears that Export-CliXml is returning a [PSCustomObject] but with your variable assignment as [Bool], it's failing to type-cast it.


问:
How can I get data from json file using vue js 2?
I am trying to get data from json file, it has just json data.

```<code>[{"id":81,"body":"There are some reason to fix the issues","created_at":"2017-11-16 11:56:47","updated_at":"2017-11-16 11:56:47"}]
</code>```

I added vue-resource and properly use it as per vue syntax.

```<code>import vueResource from 'vue-resource'
Vue.use(vueResource)
</code>```

In my userlist component i am trying following script

```<code> export default {

    data:function(){
      return {
        list:[],
        car:{
          id:'',
          body:''
        }
      };
    },

    created: function(){
      this.fetchCarList();
    },

    methods:{
      fetchCarList: function(){
        this.$http.get('http://localhost:8080/api.js').then(function(response){
          this.list = response.data
        });
      }

    }
}
</code>```

And this is component HTML loop

```<code><ul id="example-1">
    <li v-for="item in list">
        {{ item.body }}
    </li>
</ul>
</code>```

I have checked http://localhost:8080/api.js which is properly returning the data. Also when I am adding the json data in fetchCarList method then loop works fine but with get() call it does not working.

How can I solve the issue?

答:
You have a scoping issue: this within the callback does not refer to your Vue instance. That is because you are not using ES6 arrow function, i.e.:

```<code>this.$http.get('http://localhost:8080/api.js').then(response => {
    this.list = response.data
});
</code>```

...which means the outer this is not passed in. You will have to proxy that yourself, i.e. var self = this on the outside, and then use self.list = response.data:

```<code>var self = this;
this.$http.get('http://localhost:8080/api.js').then(response => {
    self.list = response.data
});
</code>```

Body:
I am trying to get data from json file, it has just json data.

[{"id":81,"body":"There are some reason to fix the issues","created_at":"2017-11-16 11:56:47","updated_at":"2017-11-16 11:56:47"}]

I added vue-resource and properly use it as per vue syntax.

import vueResource from 'vue-resource'
Vue.use(vueResource)

In my userlist component i am trying following script

 export default {

    data:function(){
      return {
        list:[],
        car:{
          id:'',
          body:''
        }
      };
    },

    created: function(){
      this.fetchCarList();
    },

    methods:{
      fetchCarList: function(){
        this.$http.get('http://localhost:8080/api.js').then(function(response){
          this.list = response.data
        });
      }

    }
}

And this is component HTML loop

        {{ item.body }}

I have checked http://localhost:8080/api.js which is properly returning the data. Also when I am adding the json data in fetchCarList method then loop works fine but with get() call it does not working.

How can I solve the issue?

Body:
You have a scoping issue: this within the callback does not refer to your Vue instance. That is because you are not using ES6 arrow function, i.e.:

this.$http.get('http://localhost:8080/api.js').then(response => {
    this.list = response.data
});

...which means the outer this is not passed in. You will have to proxy that yourself, i.e. var self = this on the outside, and then use self.list = response.data:

var self = this;
this.$http.get('http://localhost:8080/api.js').then(response => {
    self.list = response.data
});


问:
Drag item outside the scrollable container
So the "item" is draggable, but it disappears when I try to move it outside the scrollable container. I have tried with z-index but it does not seem to work. Any idea what could be wrong?

A working pen: https://codepen.io/anon/pen/ZaXVaE

```<code>body {
  background-color: lightyellow;
}

.container {
  height: 500px;
  width: 300px;
  margin: 0 auto;
  overflow-y: scroll;
  background: #ccc;
}

.item {
  border: 1px solid blue;
  width: 100px;
  margin: 0 auto;
  z-index: 9999;
}

<div class="container">
  <div class="item">
    Move me
  </div>
</div>

$(".item").draggable({revert: true});
</code>```

答: It's because .container has overflow: scrooll. This won't be visible with overflow like this

Body:
So the "item" is draggable, but it disappears when I try to move it outside the scrollable container. I have tried with z-index but it does not seem to work. Any idea what could be wrong?

A working pen: https://codepen.io/anon/pen/ZaXVaE

body {
  background-color: lightyellow;
}

.container {
  height: 500px;
  width: 300px;
  margin: 0 auto;
  overflow-y: scroll;
  background: #ccc;
}

.item {
  border: 1px solid blue;
  width: 100px;
  margin: 0 auto;
  z-index: 9999;
}

    Move me

$(".item").draggable({revert: true});


问:
Node types not working in typescript
I have included a Typescript definition file so that I can program my very basic node express server in Typescript. I have installed the types using:

npm install @types/node --save-dev

Sadly, my IDE (VS Code) still doesn't recognise the Node typings:

server.ts

```<code>import * as express from "express";

const app = express();

app.get('/', (req, res) => {
  res.send('Hello Typescript!')
});

const server = app.listen(3000, () => {
  console.log("listening on port 3000")
})
</code>```

errors

app.get Property 'get' does not exist on type 'Function'

app.listen Property 'listen' does not exist on type 'Function'

答:
You will also need types for Express:

npm install @types/express --save-dev

Title: Node types not working in typescript

Body:
I have included a Typescript definition file so that I can program my very basic node express server in Typescript. I have installed the types using:

npm install @types/node --save-dev

Sadly, my IDE (VS Code) still doesn't recognise the Node typings:

server.ts

import * as express from "express";

const app = express();

app.get('/', (req, res) => {
  res.send('Hello Typescript!')
});

const server = app.listen(3000, () => {
  console.log("listening on port 3000")
})

errors

app.get Property 'get' does not exist on type 'Function'

app.listen Property 'listen' does not exist on type 'Function'