问:
cv2.calcOpticalFlowPyrLK Adding New Points
The Problem

I am trying to add custom points for tracking in Lucas Kanade optical flow tracking method.  But I get an Assertion failed error when I call this function after inserting my custom points to the points array that was automatically calculated.

```<code>OpenCV Error: Assertion failed ((npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0) in calcOpticalFlowPyrLK, file /opt/opencv-3.1.0/opencv/modules/video/src/lkpyramid.cpp, line 1114
Traceback (most recent call last):
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/pydevd.py", line 1580, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/pydevd.py", line 964, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/work/12_Kyloren/Repository/kyloren/firmware/Python/modules/kanade.py", line 45, in <module>
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
cv2.error: /opt/opencv-3.1.0/opencv/modules/video/src/lkpyramid.cpp:1114: error: (-215) (npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0 in function calcOpticalFlowPyrLK
</code>```

The Code

I first sample points on mouse click like this:-

```<code>def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=float)
        user_points[0][0] = [x,y]

cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)
</code>```

Then I concatenate it to the main points array that is automatically created from goodFeaturesToTrack

```<code>p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)
</code>```

This is how I concatenate

```<code>if len(user_points) > 0:
    p0 = np.concatenate([p0, user_points])
    user_points = np.empty([0,1,2])
</code>```

It fails at this line

```<code>    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
</code>```

I have stepped and debugged and fixed all numpy array mismatch issues.  So the issue is with some internal mechanism.

Can anyone help?

The Full Code

I have modified this program here (the first one) and below is my fully modified code.

```<code>import numpy as np
import cv2
cap = cv2.VideoCapture("/work/12_Kyloren/Videos/WC5_Door_Front.mp4")
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 100,
                       qualityLevel = 0.3,
                       minDistance = 7,
                       blockSize = 7 )
# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))
# Take first frame and find corners in it
ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

# add points to the existing array on mouseclick
user_points = np.empty([0,1,2],dtype=float)
def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=float)
        user_points[0][0] = [x,y]

# set the mouse call back
cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)

# start the processing
while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if len(user_points) > 0:
        p0 = np.concatenate([p0, user_points])
        user_points = np.empty([0,1,2])

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    # Select good points
    good_new = p1[st==1]
    good_old = p0[st==1]
    # draw the tracks
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    img = cv2.add(frame,mask)
    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)
cv2.destroyAllWindows()
cap.release()
</code>```

Reproduce Error

Double Clicking on the preview window will cause it to crash with an assertion fail error.

答:
The issue was with the data type of the array.  I had supplied float instead of np.float32 and that was the issue!  It assumed float64 for the array and openCV rejected that.

The correct code now becomes

```<code># add points to the existing array on mouseclick
user_points = np.empty([0,1,2],dtype=np.float32)
def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=np.float32)
        user_points[0][0] = [x,y]

# set the mouse call back
cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)
</code>```

Body:
The Problem

I am trying to add custom points for tracking in Lucas Kanade optical flow tracking method.  But I get an Assertion failed error when I call this function after inserting my custom points to the points array that was automatically calculated.

OpenCV Error: Assertion failed ((npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0) in calcOpticalFlowPyrLK, file /opt/opencv-3.1.0/opencv/modules/video/src/lkpyramid.cpp, line 1114
Traceback (most recent call last):
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/pydevd.py", line 1580, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/pydevd.py", line 964, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/opt/pycharm-community-2016.2.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/work/12_Kyloren/Repository/kyloren/firmware/Python/modules/kanade.py", line 45, in <module>
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
cv2.error: /opt/opencv-3.1.0/opencv/modules/video/src/lkpyramid.cpp:1114: error: (-215) (npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0 in function calcOpticalFlowPyrLK

The Code

I first sample points on mouse click like this:-

def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=float)
        user_points[0][0] = [x,y]

cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)

Then I concatenate it to the main points array that is automatically created from goodFeaturesToTrack

p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)

This is how I concatenate

if len(user_points) > 0:
    p0 = np.concatenate([p0, user_points])
    user_points = np.empty([0,1,2])

It fails at this line

    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)

I have stepped and debugged and fixed all numpy array mismatch issues.  So the issue is with some internal mechanism.

Can anyone help?

The Full Code

I have modified this program here (the first one) and below is my fully modified code.

import numpy as np
import cv2
cap = cv2.VideoCapture("/work/12_Kyloren/Videos/WC5_Door_Front.mp4")
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 100,
                       qualityLevel = 0.3,
                       minDistance = 7,
                       blockSize = 7 )
# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))
# Take first frame and find corners in it
ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

# add points to the existing array on mouseclick
user_points = np.empty([0,1,2],dtype=float)
def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=float)
        user_points[0][0] = [x,y]

# set the mouse call back
cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)

# start the processing
while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if len(user_points) > 0:
        p0 = np.concatenate([p0, user_points])
        user_points = np.empty([0,1,2])

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    # Select good points
    good_new = p1[st==1]
    good_old = p0[st==1]
    # draw the tracks
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    img = cv2.add(frame,mask)
    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)
cv2.destroyAllWindows()
cap.release()

Reproduce Error

Double Clicking on the preview window will cause it to crash with an assertion fail error.

Body:
The issue was with the data type of the array.  I had supplied float instead of np.float32 and that was the issue!  It assumed float64 for the array and openCV rejected that.

The correct code now becomes

# add points to the existing array on mouseclick
user_points = np.empty([0,1,2],dtype=np.float32)
def sample_track_points(event, x,y, flags, param):
    global user_points
    if event == cv2.EVENT_LBUTTONDBLCLK:
        user_points = np.empty([1, 1, 2], dtype=np.float32)
        user_points[0][0] = [x,y]

# set the mouse call back
cv2.namedWindow("frame")
cv2.setMouseCallback("frame",sample_track_points)


来源: stackexchange

问:
Custom Datagrid OnKeyDown check IsEnabled Items
I have a data grid with Static Data and two of the items are disabled. The only issue is with Silverlight when using the arrow keys to navigate thru the data grid items the disabled items also get focused on.

I have created a custom data grid class and referenced it in the XAML, and then when using the OnKeyDown event I check for IsEnabled True or False. but so far it is not getting the correct values and I think it is because Where I set the IsEnabled status I am referencing the default Datagrid class?

CustomDataGrid

```<code>public class CustomGrid : DataGrid
    {
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if(IsEnabled != false)
                base.OnKeyDown(e);
        }
    }
</code>```

Xaml

```<code>  <UserControl.Resources>
        <Style x:Key="DataGridStyle1" TargetType="local:CustomGrid">
            <Setter Property="RowStyle">
                <Setter.Value>
                    <Style TargetType="sdk:DataGridRow">
                        <Setter Property="IsEnabled" Value="{Binding enabled}"/> //CheckIsEnabled Value
                    </Style>
                </Setter.Value>
            </Setter>...
</code>```

```<code><local:CustomGrid x:Name="McDataGrid" HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="400" Style="{StaticResource DataGridStyle1}"/>
</code>```

List Data

```<code> private List<Model> Data()
        {
            list.Add(new Model(1, "Test", "1", true));
            list.Add(new Model(2, "Ger", "2", true));
            list.Add(new Model(3, "dsg", "3", true));
            list.Add(new Model(4, "Hd", "4", false));
            list.Add(new Model(5, "TeHRFdgst", "5", false));
            return list;
        }

        public class Model : INotifyPropertyChanged
        {
            public bool _enabled;
            public int Id { get; set; }
            public string Name { get; set; }
            public string Prop { get; set; }
            public bool enabled
            {
                get { return _enabled; }

                set
                {
                    _enabled = value;
                    OnPropertyChanged("enabled");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;

            public Model(int id, string name, string prop, bool isenabled)
            {
                Id = id;
                Name = name;
                Prop = prop;
                enabled = isenabled;

            }

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

When I change this

答:
Try something like this:

```<code>public class CustomGrid : DataGrid
{
    private List<Model> models;
    public CustomGrid()
    {
        Loaded += (s,e) => models = ItemsSource as List<Model>;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (models == null)
            return;

        Model model = CurrentItem as Model;
        if (model == null)
            return;

        int index = models.IndexOf(model);
        switch (e.Key)
        {
            case Key.Down:
                //is the next model disabled?
                if (index < models.Count - 1 && !models[index + 1].enabled)
                    e.Handled = true;
                break;
            case Key.Up:
                if (index > 0 && !models[index - 1].enabled)
                    e.Handled = true;
                break;
        }
    }
}
</code>```

XAML:

```<code><UserControl ...>
    <UserControl.Resources>
        <Style x:Key="DataGridStyle1" TargetType="local:CustomGrid">
            <Setter Property="RowStyle">
                <Setter.Value>
                    <Style TargetType="sdk:DataGridRow">
                        <Setter Property="IsEnabled" Value="{Binding enabled}"/>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <local:CustomGrid x:Name="McDataGrid" Style="{StaticResource DataGridStyle1}" />
    </Grid>
</UserControl>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data grid with Static Data and two of the items are disabled. The only issue is with Silverlight when using the arrow keys to navigate thru the data grid items the disabled items also get focused on.

I have created a custom data grid class and referenced it in the XAML, and then when using the OnKeyDown event I check for IsEnabled True or False. but so far it is not getting the correct values and I think it is because Where I set the IsEnabled status I am referencing the default Datagrid class?

CustomDataGrid

public class CustomGrid : DataGrid
    {
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if(IsEnabled != false)
                base.OnKeyDown(e);
        }
    }

Xaml

  <UserControl.Resources>

                </Setter.Value>
            </Setter>...

<local:CustomGrid x:Name="McDataGrid" HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="400" Style="{StaticResource DataGridStyle1}"/>

List Data

 private List<Model> Data()
        {
            list.Add(new Model(1, "Test", "1", true));
            list.Add(new Model(2, "Ger", "2", true));
            list.Add(new Model(3, "dsg", "3", true));
            list.Add(new Model(4, "Hd", "4", false));
            list.Add(new Model(5, "TeHRFdgst", "5", false));
            return list;
        }

        public class Model : INotifyPropertyChanged
        {
            public bool _enabled;
            public int Id { get; set; }
            public string Name { get; set; }
            public string Prop { get; set; }
            public bool enabled
            {
                get { return _enabled; }

                set
                {
                    _enabled = value;
                    OnPropertyChanged("enabled");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;

            public Model(int id, string name, string prop, bool isenabled)
            {
                Id = id;
                Name = name;
                Prop = prop;
                enabled = isenabled;

            }

            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

When I change this

Body:
Try something like this:

public class CustomGrid : DataGrid
{
    private List<Model> models;
    public CustomGrid()
    {
        Loaded += (s,e) => models = ItemsSource as List<Model>;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (models == null)
            return;

        Model model = CurrentItem as Model;
        if (model == null)
            return;

        int index = models.IndexOf(model);
        switch (e.Key)
        {
            case Key.Down:
                //is the next model disabled?
                if (index < models.Count - 1 && !models[index + 1].enabled)
                    e.Handled = true;
                break;
            case Key.Up:
                if (index > 0 && !models[index - 1].enabled)
                    e.Handled = true;
                break;
        }
    }
}

XAML:

<UserControl ...>
    <UserControl.Resources>
        <Style x:Key="DataGridStyle1" TargetType="local:CustomGrid">
            <Setter Property="RowStyle">
                <Setter.Value>
                    <Style TargetType="sdk:DataGridRow">
                        <Setter Property="IsEnabled" Value="{Binding enabled}"/>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <local:CustomGrid x:Name="McDataGrid" Style="{StaticResource DataGridStyle1}" />
    </Grid>
</UserControl>


问:
Subtract x days from day of Month
I have a date which is coming in the form of 21,23,24,25.....

What I want is to subtract 4 days from current day of the month.

My attempt is reported below but it is giving me dates in the form of dd/mm/yyyy. I just want the day.

```<code>Calendar cal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
Date curdteMinusFourDays=cal.getTime();
String curdteMinusFourDaysStr=curdteMinusFourDays.toString();
System.out.println(curdteMinusFourDays);

tripDate.click();

List<WebElement> listofdates=CommonBrowserSetup.driver.findElements(By.tagName("td"));
for (int i=1;i<=listofdates.size();i++){
    System.out.println(listofdates.get(i).getText());
    String d1=listofdates.get(i).getText();
    if(d1.contains(curdteMinusFourDaysStr)){
        listofdates.get(i).click();
        break;
    }
}
</code>```

答:
Try below code it will give result in form of day of the month

Ex: If today's date is 30 then below code will give output as 26.

```<code>Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
</code>```

Let me know if it helps you.

Title: Subtract x days from day of Month

Body:
I have a date which is coming in the form of 21,23,24,25.....

What I want is to subtract 4 days from current day of the month.

My attempt is reported below but it is giving me dates in the form of dd/mm/yyyy. I just want the day.

Calendar cal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
Date curdteMinusFourDays=cal.getTime();
String curdteMinusFourDaysStr=curdteMinusFourDays.toString();
System.out.println(curdteMinusFourDays);

tripDate.click();

List<WebElement> listofdates=CommonBrowserSetup.driver.findElements(By.tagName("td"));
for (int i=1;i<=listofdates.size();i++){
    System.out.println(listofdates.get(i).getText());
    String d1=listofdates.get(i).getText();
    if(d1.contains(curdteMinusFourDaysStr)){
        listofdates.get(i).click();
        break;
    }
}

Body:
Try below code it will give result in form of day of the month

Ex: If today's date is 30 then below code will give output as 26.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));

Let me know if it helps you.


问:
Why does my application still run after closing main window?
If I make a JFrame like this

```<code>public static void main(String[] args) {

     new JFrame().setVisible(true);
}
</code>```

then after closing the window the appication doesn't stop (I need to kill it).

What is the proper way of showing application's main windows ?

I'd also like to know a reason of a proposed solution.

Thanks in advance.

答:
The correct way to do this (unless you're writing a very trivial single-window app, i.e. no other windows or threads etc..) is to catch the windowClosing() event, and then call the dispose(); method of the form.

If your program doesn't completely exit after this, it means you have other non-deamon threads running, and you must stop these as best you see fit depending on your program.

Calling System.exit() or setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); will force stop any other threads (and the whole program), meaning your code is less portable, and force-stopping threads is obviously dangerous (in a programming kind of way).

OwnerDisplayName: lbownik

ContentLicense: CC BY-SA 2.5

Body:
If I make a JFrame like this

public static void main(String[] args) {

     new JFrame().setVisible(true);
}

then after closing the window the appication doesn't stop (I need to kill it).

What is the proper way of showing application's main windows ?

I'd also like to know a reason of a proposed solution.

Thanks in advance.

LastEditorDisplayName: mmyers


问:
PHP - when to use private static properties in the class
I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:

Declaring class properties or methods as static makes them accessible
  without needing an instantiation of the class. A property declared as
  static cannot be accessed with an instantiated class object (though a
  static method can).

Does that mean that I can access static properties without instantiation of the class. So, for example:

```<code>class Foo{

    static $bar;

    public function __construct($bar){
        $this->bar = $bar;
    }
</code>```

So, I can access the $bar property of the class like so?

```<code>Foo::$bar
</code>```

But, if I do this, it wouldn't work?

```<code>$foo = new Foo();
$foo::$bar
</code>```

And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.

答:
When you declare a normal property, there is a different value of that property for every instance you create of that class (each object you create with new Foo). For a static property, there is one copy of that variable for the whole class.

This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.

As a simple example, you could have a counter that gave each instance of the class a unique number. You don't need code outside the class to see or change this counter, so you mark it private, but it needs to be shared amongst all instances, so you mark it static.

```<code>class Foo {
    // Static counter; shared with every instance
    private static $nextID=0;

    // Normal instance property: each instance will have its own value
    private $myID;

    public function __construct() {
        // Set the ID for this instance to the next ID
        $this->myID = self::$nextID;
        // Increment the shared counter
        self::$nextID++;
    }
}
</code>```

Body:
I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:

Declaring class properties or methods as static makes them accessible
  without needing an instantiation of the class. A property declared as
  static cannot be accessed with an instantiated class object (though a
  static method can).

Does that mean that I can access static properties without instantiation of the class. So, for example:

class Foo{

    static $bar;

    public function __construct($bar){
        $this->bar = $bar;
    }

So, I can access the $bar property of the class like so?

Foo::$bar

But, if I do this, it wouldn't work?

$foo = new Foo();
$foo::$bar

And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.

Body:
When you declare a normal property, there is a different value of that property for every instance you create of that class (each object you create with new Foo). For a static property, there is one copy of that variable for the whole class.

This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.

As a simple example, you could have a counter that gave each instance of the class a unique number. You don't need code outside the class to see or change this counter, so you mark it private, but it needs to be shared amongst all instances, so you mark it static.

class Foo {
    // Static counter; shared with every instance
    private static $nextID=0;

    // Normal instance property: each instance will have its own value
    private $myID;

    public function __construct() {
        // Set the ID for this instance to the next ID
        $this->myID = self::$nextID;
        // Increment the shared counter
        self::$nextID++;
    }
}


问:
What's a good way to consume a PowerShell Cmdlet in a NAnt build system?
We use NAnt extensively for our build system. Recently, I've written a couple PowerShell Cmdlets to perform a few database related things. At first, the intent of these Cmdlets was not to necessarily run within our build process. However, this has recently become a need and we would like to run a few of these Cmdlets from our NAnt based build process.

These Cmdlets are written in C# and we have a SnapIn for them (if that matters at all).

A few ideas:

Use the exec task to call PowerShell? (not sure how this would work though)

Write a custom NAnt task that references and uses the Cmdlet?

What might be a good way to do this?

答:
You can use the below exec task in your nant script to call your ps cmdlets.</p>

```<code><exec program="powershell" workingdir="${BuildManagementDir}" verbose="true">
    <arg value="-noprofile"/>
    <arg value="-nologo"/>
    <arg value="-noninteractive"/>
    <arg value="-command"/>
    <arg value=".\xyz.ps1"/>
</exec>
</code>```

Body:
You can use the below exec task in your nant script to call your ps cmdlets.

<exec program="powershell" workingdir="${BuildManagementDir}" verbose="true">
    <arg value="-noprofile"/>
    <arg value="-nologo"/>
    <arg value="-noninteractive"/>
    <arg value="-command"/>
    <arg value=".\xyz.ps1"/>
</exec>


问:
Getting another table's string via it's id
I have two tables, but since I can't format them here, you can check the table on this imgur img

The wildcard roles includes strings like department.* or blogger.department.*

I'm trying to create a role/permission inheritance system but i'm stuck on creating a many-to-many relationship

I've tried to use eloquent but since "wildcards" can't be/aren't a model , I can't use eloquent. So I tried to use the DB Facade but I'm not very good with SQL/DB so I've honestly got no clue on how to do this.

Here's what I need

Get the role ID (eg: admin = 1)

Get all wildcard_roles from the table role_wildcards by the Role ID

Return a collection of all the wildcard strings

Notes

It doesn't have to use eloquent, it can use the DB facade

答:
First of you create a relationship from role_wildcards to roles

```<code>public function role()
{
    return $this->belongsTo('App\roles','parent_role_id','id');
}
</code>```

then you use relationship like below

```<code>DB::table('role_wildcards')->with('role')->whereParentRoleId($this->id)->get();
</code>```

Body:
First of you create a relationship from role_wildcards to roles

public function role()
{
    return $this->belongsTo('App\roles','parent_role_id','id');
}

then you use relationship like below

DB::table('role_wildcards')->with('role')->whereParentRoleId($this->id)->get();


问:
Issue using While+if statements together in Python
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.</p>

```<code>import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*
</code>```

答:
The "break" must be sent to another position (in the exception branche). Else the code part:

```<code>if os.path.isfile("Z:\\xyz\\second.xlsx"):
    print("Next has started")
    subprocess.call([sys.executable,'Next Python.py'])
</code>```

will never be executed and thus your other file is not loaded.

Body:
Can someone please check below code, as i am using while and If statement together in python and calling one more python code, but it is executing all the code except calling the other python code.

import os
import psycopg2
import os.path
import subprocess
import sys

if os.path.isfile("Z:\\xyz\\New.xlsx"):
    while True:
        conn = psycopg2.connect(database="gp_bdl", user="adwed1", password="***", host="bdlgp12", port="6200")
        cur = conn.cursor()
        print ("Opened database successfully")
        try:
            cur.execute('''select function1();''')
            conn.commit()
            conn.close()

        except psycopg2.OperationalError:
            continue
        break;
        if os.path.isfile("Z:\\xyz\\second.xlsx"):
         print("Next has started")
         subprocess.call([sys.executable,'Next Python.py'])
    else:
         print("Nothing")
else:
   print("No Process")*

Body:
The "break" must be sent to another position (in the exception branche). Else the code part:

if os.path.isfile("Z:\\xyz\\second.xlsx"):
    print("Next has started")
    subprocess.call([sys.executable,'Next Python.py'])

will never be executed and thus your other file is not loaded.


问:
Find out if a business is currently open in T-SQL
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

```<code>CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)
</code>```

Sample data in this table includes:

```<code>INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);
</code>```

Now I want to create a function which returns if a business is currently open or closed.

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO
</code>```

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;
</code>```

答:
SQL Server's date/time functions are horrible. Here is a query that get's today's weekday's opening hours and converts them into today's opening hours (e.g. Thursday 13:00 to 2017-03-30 13:00) first. Then this is used to check whether now it's open or not.

```<code>select count(*) as isopen
from
(
  select
    cast(cast(getdate() as date) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber = datepart(dw, getdate())
) as today
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);
</code>```

You can simply adopt this to your function to get it more readable and convenient.

UPDATE: We must consider yesterday, too, to get opening times over midnight. Thanks to Serg for pointing this out. The query gets way more complicated unfortunately:

```<code>select count(*) as isopen
from
(
  select -- today's opening hours
    cast(cast(getdate() as date) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber = datepart(dw, getdate())
  union all
  select -- yesterday's opening hours
    cast(dateadd('d', -1, cast(getdate() as date)) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber % 7 + 1 = datepart(dw, getdate())
) as today_and yesterday
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);
</code>```

UPDATE 2: Here a simplified version where I convert all opening times to the last six days plus today (hope I've got the math right). I've also added the businessid that I forgot in above queries.

```<code>select count(*) as isopen
from
(
  select
    cast(dateadd('d', - (7 + datepart(dw, getdate()) - daynumber) % 7, cast(getdate() as date)) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where businessid = @businessid
) as these_last_seven_days
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);
</code>```

Body:
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)

Sample data in this table includes:

INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);

Now I want to create a function which returns if a business is currently open or closed.

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;

Body:
SQL Server's date/time functions are horrible. Here is a query that get's today's weekday's opening hours and converts them into today's opening hours (e.g. Thursday 13:00 to 2017-03-30 13:00) first. Then this is used to check whether now it's open or not.

select count(*) as isopen
from
(
  select
    cast(cast(getdate() as date) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber = datepart(dw, getdate())
) as today
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);

You can simply adopt this to your function to get it more readable and convenient.

UPDATE: We must consider yesterday, too, to get opening times over midnight. Thanks to Serg for pointing this out. The query gets way more complicated unfortunately:

select count(*) as isopen
from
(
  select -- today's opening hours
    cast(cast(getdate() as date) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber = datepart(dw, getdate())
  union all
  select -- yesterday's opening hours
    cast(dateadd('d', -1, cast(getdate() as date)) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where daynumber % 7 + 1 = datepart(dw, getdate())
) as today_and yesterday
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);

UPDATE 2: Here a simplified version where I convert all opening times to the last six days plus today (hope I've got the math right). I've also added the businessid that I forgot in above queries.

select count(*) as isopen
from
(
  select
    cast(dateadd('d', - (7 + datepart(dw, getdate()) - daynumber) % 7, cast(getdate() as date)) as datetime) + opentime as opendatetime,
    duration
  from process.openinghours
  where businessid = @businessid
) as these_last_seven_days
where getdate() between opendatetime and dateadd(mi, duration, opendatetime);


问:
How to get distinct data from two tables using SQL Select query
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

```<code>Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000
</code>```

Table_Innovation

```<code>Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno
</code>```

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

```<code>counts
 2
</code>```

output: How many users started Innovation base on email need details of users.

```<code> Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000
</code>```

答:
You can get using distinct count and exists for these queries

For count:

```<code>select count(distinct Email) from Table_innovation
</code>```

For distinct users

```<code>select * from Table_UserInformation t where exists (select 1 from Table_innovation i where i.email = t.email)
</code>```

Body:
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000

Table_Innovation

Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

counts
 2

output: How many users started Innovation base on email need details of users.

 Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000

Body:
You can get using distinct count and exists for these queries

For count:

select count(distinct Email) from Table_innovation

For distinct users

select * from Table_UserInformation t where exists (select 1 from Table_innovation i where i.email = t.email)


问:
How to convert a specific string to integer?
Hi here is the scenario that I have strings like this;

```<code>$a="08";
$b="00";
$c="0";
</code>```

actually this is time part of a datetime i want to get these as integer

答:
```<code><?php
$n="19.99";
print intval($n*100); // prints 1998
print intval(strval($n*100)); // prints 1999
?>
</code>```

Use something like this.

Body:
Hi here is the scenario that I have strings like this;

$a="08";
$b="00";
$c="0";

actually this is time part of a datetime i want to get these as integer

Body:
<?php
$n="19.99";
print intval($n*100); // prints 1998
print intval(strval($n*100)); // prints 1999
?>

Use something like this.


问:
How to declare different functions in different conditions?

Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

```<code>// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}
</code>```

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.

答:
Your thinking about it incorrectly. Just declare your functions. Declaring the function is just creating it. If you use it or not is up to you. All it's saying is don't try to conditionally create functions. Use

if statements

To call or not call the functions. Don't use them to decide whether or not to

create the function

Body:
Additionally, function declarations should never appear inside of
  block statements. For example, this code won’t behave as expected:

// Bad
if (condition) {
    function doSomething() {
    alert("Hi!");
  }
} else {
    function doSomething() {
    alert("Yo!");
  }
}

Exactly how this will work from browser to browser will vary. Most
  browsers automatically take the second declaration without evaluating
  condition; Firefox evaluates condition and uses the appropriate
  function declaration. This is a gray area in the ECMAScript
  specification and should thus be avoided. Function declarations should
  be used only outside of conditional statements. This pattern is
  explicitly forbidden in the Google JavaScript Style Guide.

I find these words in the book Maintainable JavaScript in page 42, it says that declaring function in 'if' statement is basicly not allowed. So what's the proper method to declare different functions in different conditions? This book didn't give a solution on this issue.


问:
Appending to $(this)
Within a function loop, I need to traverse further into the DOM.

```<code>$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */
</code>```

This is similar to what I'm trying to do in a function

```<code>$(this) = $('.panel_wrapper .panel');
$(this) .foo
</code>```

The following is a better example:

```<code>$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});
</code>```

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

```<code>$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});
</code>```

答:
You could use the .find() function:

```<code>$(this).find('.foo');
</code>```

Title: Appending to $(this)

Body:
Within a function loop, I need to traverse further into the DOM.

$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */

This is similar to what I'm trying to do in a function

$(this) = $('.panel_wrapper .panel');
$(this) .foo

The following is a better example:

$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});

Body:
You could use the .find() function:

$(this).find('.foo');


问:
Path to mpdf/jpgraph library in PHPExcel example on Windows
I'm trying to run the 36chartreadwritePDF.php example of PHPExcel. I have the lastest of the jpgraph and mpdf library placed within the Example folder of the PHPExcel folder (as folders mpdf and jpgraph respectively). Now To link the code to the library, this is what I have:

```<code>$rendererLibrary = 'mpdf.php';
//$rendererLibrary = 'domPDF0.6.0beta3';
$rendererLibraryPath = dirname(__FILE__) . '/mpdf/src/' . $rendererLibrary;

$rendererLibrary = 'jpgraph.php';
$rendererLibraryPath = dirname(__FILE__) . '/jpgraph/src/' . $rendererLibrary;
</code>```

I tried to echo the first $rendererLibraryPath I got C:\wamp\www\PHPExcel\Examples/mpdf/src/mpdf.php which really cannot load the library cause the there is a coombination of backslashes \ and forwardslashes /

Now if I change /jpgraph/src/ to \jpgraph\src\ and /mpdf/src/ to \mpdf\src\ I typically get a unexpected string error.

So what's the way around this to link the libraries right on windows (8.1)

答:
I solved this by adding the line:</p>

```<code>$rendererLibraryPath = str_replace('/', '\\', $rendererLibraryPath);
</code>```

Body:
I'm trying to run the 36chartreadwritePDF.php example of PHPExcel. I have the lastest of the jpgraph and mpdf library placed within the Example folder of the PHPExcel folder (as folders mpdf and jpgraph respectively). Now To link the code to the library, this is what I have:

$rendererLibrary = 'mpdf.php';
//$rendererLibrary = 'domPDF0.6.0beta3';
$rendererLibraryPath = dirname(__FILE__) . '/mpdf/src/' . $rendererLibrary;

$rendererLibrary = 'jpgraph.php';
$rendererLibraryPath = dirname(__FILE__) . '/jpgraph/src/' . $rendererLibrary;

I tried to echo the first $rendererLibraryPath I got C:\wamp\www\PHPExcel\Examples/mpdf/src/mpdf.php which really cannot load the library cause the there is a coombination of backslashes \ and forwardslashes /

Now if I change /jpgraph/src/ to \jpgraph\src\ and /mpdf/src/ to \mpdf\src\ I typically get a unexpected string error.

So what's the way around this to link the libraries right on windows (8.1)

Body:
I solved this by adding the line:

$rendererLibraryPath = str_replace('/', '\\', $rendererLibraryPath);


问:
I want to print these two words from two buttons, but it didn't work as I imagined
I want to print these two words called "yes" and "no" by two buttons.

When I clicked the first button to print "yes", the two buttons were covered by the word "yes", I don't how to work it out.

Here is my code and the screen shot:
before
after

<!DOCTYPE html>

 <meta charset="utf-8">
 <title>example</title>

 <button type="button" onclick="yes()">print yes</button>
 <button type="button" onclick="no()">print no</button>

```

答:
This because of you are using document.write()  this will override the page. So use div for this propose

Here is the example

<!DOCTYPE html>

 <meta charset="utf-8">
 <title>example</title>

 <button type="button" onclick="yes()">print yes</button>
 <button type="button" onclick="no()">print no</button>

```

ContentLicense: CC BY-SA 4.0

Body:
This because of you are using document.write()  this will override the page. So use div for this propose

Here is the example

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>example</title>
 <script type="text/javascript">
  function yes()
  {
   document.getElementById("myDiv").innerHTML="YES";
  }
  function no()
  {
   document.getElementById("myDiv").innerHTML="NO";
  }
 </script>
</head>
<body>
  <div id="myDiv">

</div>
 <button type="button" onclick="yes()">print yes</button>
 <button type="button" onclick="no()">print no</button>
</body>
</html>


问:
Rule for route and on "." or "/"
I want to configure  url manager . I need if  route match  /deti/festival.  or /deti/festival/  Yii enable Deti controller and festival action, but now for this requests yii return  404 , what's  wrong? If i use option 'suffix'=>'/'  rule  /deti/festival/  work , but other   rules  don't  work .
What i must do ? </p>

```<code>'urlManager'=>[
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules'=>[
            'messages' => 'lk/default/messages',
            'students' => 'lk/student/index',
            'ulogin/ulogin' => '/reg/ulogin/ulogin',
            'ulogin/auth' => '/reg/ulogin/auth',
            'lk/anketa/auth' => '/lk/auth/auth',
            'lk/anketa/logout' => '/lk/auth/logout',
            'deti' => '/deti/deti',
            'festival'=>'/deti/deti/view?id=562',
            '/deti/festival'=>'/deti/deti/festival',
            '/deti/eco'=>'/deti/deti/eco',
            '/deti/festival[.\/]?'=>'/deti/deti/festival',
            '/deti/eco/'=>'/deti/deti/eco',
            '/profile/exhview.php'=>'/exhibitions/default/old',
            '/profile/user.php'=>'/profile/profile/old'
        ]
    ]
</code>```

答:
for suffix, you can write url rules like below.</p>

```<code>'rules' => [
    // ...other url rules...
    [
        'pattern' => 'deti/festival',
        'route' => 'deti/deti/festival',
        'suffix' => '/',
    ],
]
</code>```

Title: Rule for route and on "." or "/"

Body:
I want to configure  url manager . I need if  route match  /deti/festival.  or /deti/festival/  Yii enable Deti controller and festival action, but now for this requests yii return  404 , what's  wrong? If i use option 'suffix'=>'/'  rule  /deti/festival/  work , but other   rules  don't  work .
What i must do ?

'urlManager'=>[
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules'=>[
            'messages' => 'lk/default/messages',
            'students' => 'lk/student/index',
            'ulogin/ulogin' => '/reg/ulogin/ulogin',
            'ulogin/auth' => '/reg/ulogin/auth',
            'lk/anketa/auth' => '/lk/auth/auth',
            'lk/anketa/logout' => '/lk/auth/logout',
            'deti' => '/deti/deti',
            'festival'=>'/deti/deti/view?id=562',
            '/deti/festival'=>'/deti/deti/festival',
            '/deti/eco'=>'/deti/deti/eco',
            '/deti/festival[.\/]?'=>'/deti/deti/festival',
            '/deti/eco/'=>'/deti/deti/eco',
            '/profile/exhview.php'=>'/exhibitions/default/old',
            '/profile/user.php'=>'/profile/profile/old'
        ]
    ]

Body:
for suffix, you can write url rules like below.

'rules' => [
    // ...other url rules...
    [
        'pattern' => 'deti/festival',
        'route' => 'deti/deti/festival',
        'suffix' => '/',
    ],
]


问:
Update a List of KeyValue pair
I have a WPF application where I need to implement this concept:

There is a combobox and a datagrid. The combobox holds a list of sellers, and the datagrid holds the rates of items they sell.

I want something like this:

```<code>client -> null

item    |   rate
--------------------
itemA   |   0.00
itemB   |   0.00
itemC   |   0.00
</code>```

When none of the client (seller) is selected, all the rates of items default to 0.00.

Now, let's say I choose a client by name of clientA, who does not sell ItemB. Then, the display should reflect this.

```<code>client -> clientA

item    |   rate
--------------------
itemA   |   5.00
itemB   |   0.00
itemC   |   8.00
</code>```

Basically, it should show 0.00 instead of null for the items a client does not sell.

This is actually the work of a Dictionary, or in case of WPF, an ObservableDictionary.

But, I am using Caliburn, and I would like to solve it by using BindableCollection.

So, I have something similar to this:

```<code>if (SelectedReferenceClient == null)
{
    Rates = new BindableCollection<KeyValuePair<string, decimal>>(itemrepository.FindWhere(c => true).Select(c => new KeyValuePair<string, decimal>(key: c.Name, value: 0)));;
} //retrieve all items and put value to zero.

    var SelectedClientRates = new List<KeyValuePair<string, decimal>>(raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate)));
    //get rates of items they sell

    foreach (var a in SelectedClientRates)
    {
        var b = Rates.FirstOrDefault(c => c.key == a.key);
        b.value = a.value;
    }//update the values in BindingCollection
</code>```

This might work, but it's noisy and it's kludgy. Is there any LINQ way to do this? As LINQ abhors side effects, my first thought was that it wasnt possible.

But, if I want to stick to BindableCollection and not use ObservableDictionary, is there any better way to do this?

答:
If creating a new BindableCollection<T> instance is an option (rather than updating the existing), you can build IEnumerable<T> query with LINQ and pass it to the BindableCollection<T> constructor overload accepting IEnumerable<T>:

```<code>var keys = SelectedReferenceClient == null ? itemrepository.FindWhere(c => true).Select(c => c.Name) : Rates.Select(rate => rate.Key);
var rates = raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate));
var combined = from key in keys
               join rate in rates on key equals rate.Key into match
               from rate in match.DefaultIfEmpty()
               select new KeyValuePair<string, decimal>(key: key, value: rate.Key != null ? rate.Value : 0);
Rates = new BindableCollection<KeyValuePair<string, decimal>>(combined);
</code>```

The LINQ part is a simple left outer join between 2 enumerables. The left enumerable contains all items and is obtained from either repository or the already populated storage, while the right enumerable contains the selected item/value pairs and is obtained from its repository with the corresponding filter.

Once the correlation is done by left outer join operator, the resulting value is determined from the presence/absence of the match - either the match value or 0. The only unusual  here is the check for match existence - normally we use something like right != null, but since here the right is a struct (value type), we use a string member of the struct for the same purpose.

Title: Update a List of KeyValue pair

Body:
I have a WPF application where I need to implement this concept:

There is a combobox and a datagrid. The combobox holds a list of sellers, and the datagrid holds the rates of items they sell.

I want something like this:

client -> null

item    |   rate
--------------------
itemA   |   0.00
itemB   |   0.00
itemC   |   0.00

When none of the client (seller) is selected, all the rates of items default to 0.00.

Now, let's say I choose a client by name of clientA, who does not sell ItemB. Then, the display should reflect this.

client -> clientA

item    |   rate
--------------------
itemA   |   5.00
itemB   |   0.00
itemC   |   8.00

Basically, it should show 0.00 instead of null for the items a client does not sell.

This is actually the work of a Dictionary, or in case of WPF, an ObservableDictionary.

But, I am using Caliburn, and I would like to solve it by using BindableCollection.

So, I have something similar to this:

if (SelectedReferenceClient == null)
{
    Rates = new BindableCollection<KeyValuePair<string, decimal>>(itemrepository.FindWhere(c => true).Select(c => new KeyValuePair<string, decimal>(key: c.Name, value: 0)));;
} //retrieve all items and put value to zero.

    var SelectedClientRates = new List<KeyValuePair<string, decimal>>(raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate)));
    //get rates of items they sell

    foreach (var a in SelectedClientRates)
    {
        var b = Rates.FirstOrDefault(c => c.key == a.key);
        b.value = a.value;
    }//update the values in BindingCollection

This might work, but it's noisy and it's kludgy. Is there any LINQ way to do this? As LINQ abhors side effects, my first thought was that it wasnt possible.

But, if I want to stick to BindableCollection and not use ObservableDictionary, is there any better way to do this?

Body:
If creating a new BindableCollection<T> instance is an option (rather than updating the existing), you can build IEnumerable<T> query with LINQ and pass it to the BindableCollection<T> constructor overload accepting IEnumerable<T>:

var keys = SelectedReferenceClient == null ? itemrepository.FindWhere(c => true).Select(c => c.Name) : Rates.Select(rate => rate.Key);
var rates = raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate));
var combined = from key in keys
               join rate in rates on key equals rate.Key into match
               from rate in match.DefaultIfEmpty()
               select new KeyValuePair<string, decimal>(key: key, value: rate.Key != null ? rate.Value : 0);
Rates = new BindableCollection<KeyValuePair<string, decimal>>(combined);

The LINQ part is a simple left outer join between 2 enumerables. The left enumerable contains all items and is obtained from either repository or the already populated storage, while the right enumerable contains the selected item/value pairs and is obtained from its repository with the corresponding filter.

Once the correlation is done by left outer join operator, the resulting value is determined from the presence/absence of the match - either the match value or 0. The only unusual  here is the check for match existence - normally we use something like right != null, but since here the right is a struct (value type), we use a string member of the struct for the same purpose.


问:
iPhone: Icon extension error in the archive validation
Using the Xcode 3.2.3 I updated my app to iOS4 and build an archive.
When I tried to validate the application I received these warnings:

"Icon specified in the Info.plist CFBundleIconFile does not have an extension: icon"

Since my app is a universal app I have 4 icons mentioned in the plist and therefore 4 errors. I will also point out that in my plist the icons appear under CFBundleIconFiles and not CFBundleIconFile.

It is a known fact that it is better not to write the extensions of the icons otherwise the automatic retina display image choosing mechanism won't kick in and take the proper iPhone4 @2x icons.

What am I missing here?

答:
To save you some reading time on Chris Redfords link:

You need the following entries in info plist:
CFBundleIconFile with the name of the 57x57 png file (e.g. icon.png)
CFBundleIconFiles Array with one row containing the name of the file without extensions (e.g icon)


问:
choppy transition with d3 area linearGradient
JSFIDDLE: https://jsfiddle.net/6xq2wrfb/

It is probably something very simple I'm missing, but the graph starts with 60 seconds worth of data, then a new value is added every second. However, once the 60 second mark is reached, the graph becomes jerky and there is a gap. In order to update the graph, the translate offset I use is simply 60 seconds from the current time:

```<code>// Slide the area left

svg.select("path").transition().attr('transform', "translate(" + x(d3.time.second.offset(now, -60)) + ")");
</code>```

But this fails once I hit the 60 second mark. For the life of me I can't figure this out. Any suggestions?

答:
I think a better version is here: https://jsfiddle.net/6xq2wrfb/1/

Basically, the following:

```<code>svg.select("path").transition().attr('transform', "translate(" + x(d3.time.second.offset(now, -60)) + ")");
</code>```

now becomes:

```<code>svg.select("path").transition().attr('transform', "translate(" + x(data[0].time) + ",0)");
</code>```

Body:
JSFIDDLE: https://jsfiddle.net/6xq2wrfb/

It is probably something very simple I'm missing, but the graph starts with 60 seconds worth of data, then a new value is added every second. However, once the 60 second mark is reached, the graph becomes jerky and there is a gap. In order to update the graph, the translate offset I use is simply 60 seconds from the current time:

// Slide the area left

svg.select("path").transition().attr('transform', "translate(" + x(d3.time.second.offset(now, -60)) + ")");

But this fails once I hit the 60 second mark. For the life of me I can't figure this out. Any suggestions?

Body:
I think a better version is here: https://jsfiddle.net/6xq2wrfb/1/

Basically, the following:

svg.select("path").transition().attr('transform', "translate(" + x(d3.time.second.offset(now, -60)) + ")");

now becomes:

svg.select("path").transition().attr('transform', "translate(" + x(data[0].time) + ",0)");


问:
.SelectMany with C#
I found this post and I need something similar

stackoverflow.com/questions/41282053/groupby-multiple-date-properties-by-month-and-year-in-linq/43112774#43112774

I need to group by month and year, but at the same time I need a property of the main element, which I can not access

```<code>var departments = stops
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = 0,
        Count = g.Count()
    });
</code>```

I would need access to "stops.Duration" but if i do this: .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

it does not group me by month-year

Can anybody help me?

Sorry for my english and thank you very much

答:
```<code>int Month = 0, Year= 0, Duration = 0;
var departments = stops
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { Month, Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = g.Sum(v => Duration),
        Count = g.Count()
    });
</code>```

For me, this is the final solution

Title: .SelectMany with C#

Body:
I found this post and I need something similar

stackoverflow.com/questions/41282053/groupby-multiple-date-properties-by-month-and-year-in-linq/43112774#43112774

I need to group by month and year, but at the same time I need a property of the main element, which I can not access

var departments = stops
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = 0,
        Count = g.Count()
    });

I would need access to "stops.Duration" but if i do this: .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

it does not group me by month-year

Can anybody help me?

Sorry for my english and thank you very much

Body:
int Month = 0, Year= 0, Duration = 0;
var departments = stops
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { Month, Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = g.Sum(v => Duration),
        Count = g.Count()
    });

For me, this is the final solution


问:
NPM does not install anything : it hangs
Whenever I want to install a module with NPM, it hangs at that stage:

```<code>npm install express
npm http GET https://registry.npmjs.org/express
</code>```

And that's it. It has that behavior for anything I input instead of express. I installed nodejs and nvm that way (Ubuntu 13.10):

```<code>sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
</code>```

I tried looking on the Internet and GitHub and I found a closed issue about npm hanging forever when trying to install a module.. but it was a really old issue. Before I ask the developers, am I missing something obvious ?

I tried compiling both nodejs and npm but the result was the same.

EDIT: npm install express -verbose -> http://pastebin.com/tGY3V6Ly
Error:

```<code>npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, cause=140072708810560:error:140770FC:SSL   routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:766:
</code>```

答: I had this problem inside a Windows git bash terminal - reinstalling the latest version of git bash fixed it</p>

Body:
Whenever I want to install a module with NPM, it hangs at that stage:

npm install express
npm http GET https://registry.npmjs.org/express

And that's it. It has that behavior for anything I input instead of express. I installed nodejs and nvm that way (Ubuntu 13.10):

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

I tried looking on the Internet and GitHub and I found a closed issue about npm hanging forever when trying to install a module.. but it was a really old issue. Before I ask the developers, am I missing something obvious ?

I tried compiling both nodejs and npm but the result was the same.

EDIT: npm install express -verbose -> http://pastebin.com/tGY3V6Ly
Error:

npm info retry will retry, error on last attempt: Error: tunneling socket could not be established, cause=140072708810560:error:140770FC:SSL   routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:766:


问:
How to get the last Unicode text element efficiently
How to get the last Unicode text element of a string without iterating the entire string? There are two ways offered by System.Globalization.StringInfo, but I suspect them to enumerate the entire string:</p>

```<code>    [TestMethod]
    [TestCategory("Verification")]
    public void GetLastTextElement_TextEndsWithSurrogatePair_GetsSurrogatePair()
    {
        // Arrange
        const string OsmanyaDigitOne = "\U000104A1";
        const string OsmanyaDigitTwo = "\U000104A2";
        const string Target = "abc" + OsmanyaDigitOne + "de" + OsmanyaDigitTwo;

        // Act
        int length = Target.Length;
        string lastSubstring = Target.Substring(length - 1);

        StringInfo stringInfo = new StringInfo(Target);
        int lengthInTextElements = stringInfo.LengthInTextElements;
        string lastTextElement = stringInfo.SubstringByTextElements(lengthInTextElements - 1);

        string lastTextElementInOneExpression = Target.Substring(StringInfo.ParseCombiningCharacters(Target).Last());

        // Assert
        Assert.AreEqual(9, length, @"Wrong length");
        Assert.AreNotEqual(OsmanyaDigitTwo, lastSubstring, @"Unexpectedly got last text element");
        Assert.AreEqual(7, lengthInTextElements, @"Wrong length in text elements");
        Assert.AreEqual(OsmanyaDigitTwo, lastTextElement, @"Wrong last text element");
        Assert.AreEqual(OsmanyaDigitTwo, lastTextElementInOneExpression, @"Wrong last text element");
    }
</code>```

答:
last Unicode text element efficiently

If you simply mean the last unicode codepoint then it is quite easy:

```<code>string unicode = Target.Length >= 2 && char.IsLowSurrogate(Target, Target.Length - 1) && char.IsHighSurrogate(Target, Target.Length - 2)
    ? Target.Substring(Target.Length - 2, 2)
    : Target.Substring(Target.Length - 1, 1).ToString();
</code>```

If you mean the last grapheme (so the last codepoint together with for example the combining marks that could follow it, so potentially multiple codepoints, like e + ◌̃) it is more complex.

Body:
How to get the last Unicode text element of a string without iterating the entire string? There are two ways offered by System.Globalization.StringInfo, but I suspect them to enumerate the entire string:

    [TestMethod]
    [TestCategory("Verification")]
    public void GetLastTextElement_TextEndsWithSurrogatePair_GetsSurrogatePair()
    {
        // Arrange
        const string OsmanyaDigitOne = "\U000104A1";
        const string OsmanyaDigitTwo = "\U000104A2";
        const string Target = "abc" + OsmanyaDigitOne + "de" + OsmanyaDigitTwo;

        // Act
        int length = Target.Length;
        string lastSubstring = Target.Substring(length - 1);

        StringInfo stringInfo = new StringInfo(Target);
        int lengthInTextElements = stringInfo.LengthInTextElements;
        string lastTextElement = stringInfo.SubstringByTextElements(lengthInTextElements - 1);

        string lastTextElementInOneExpression = Target.Substring(StringInfo.ParseCombiningCharacters(Target).Last());

        // Assert
        Assert.AreEqual(9, length, @"Wrong length");
        Assert.AreNotEqual(OsmanyaDigitTwo, lastSubstring, @"Unexpectedly got last text element");
        Assert.AreEqual(7, lengthInTextElements, @"Wrong length in text elements");
        Assert.AreEqual(OsmanyaDigitTwo, lastTextElement, @"Wrong last text element");
        Assert.AreEqual(OsmanyaDigitTwo, lastTextElementInOneExpression, @"Wrong last text element");
    }

Body:
last Unicode text element efficiently

If you simply mean the last unicode codepoint then it is quite easy:

string unicode = Target.Length >= 2 && char.IsLowSurrogate(Target, Target.Length - 1) && char.IsHighSurrogate(Target, Target.Length - 2)
    ? Target.Substring(Target.Length - 2, 2)
    : Target.Substring(Target.Length - 1, 1).ToString();

If you mean the last grapheme (so the last codepoint together with for example the combining marks that could follow it, so potentially multiple codepoints, like e + ◌̃) it is more complex.


问:
Why isn't this mobx-react observer firing a render?
Note, I am using Typescript.

In my store I have a field specified as so:

@observable public characters: {[name: string] : Types.Character} = {};

Types.Character is defined:

```<code>export class Character {
    name: string;
    gender: Gender;
    @observable status: Status;
    @observable statusmsg: string;
}
</code>```

And I have a React component marked as observer:

```<code>@observer
export default class NamePlate extends React.Component<INamePlateProps, {}> {

    render(){
        let char: Types.Character = chatStore.characters[this.props.characterName];

        let textStyle: Object = {
            color: Types.getGenderColourFromString(char.gender)
        };

        return <div className="comp-nameplate" title={char.statusmsg}>
            <img src={`images/status-small-${char.status}.png`}/>
            <span className="nameplatecharname" style={textStyle}>{char.name}</span>
        </div>;
    }

}
</code>```

I am changing the char.statusmg and char.status properties but the observer component is not re-rendering.

```<code>private receiveSTA(obj: Packets.IReceivePacketSTA){
    let char: Types.Character = this.characters[obj.character];
    char.status = Types.getStatusTypeFromString(obj.status);
    char.statusmsg = obj.statusmsg;
}
</code>```

I'd guess that the problem is to do with how the observable is nested down in an object in my store? I have no idea. I've found getting to grips with this set-up extremely difficult and hard to find information for. There's so many competing set-ups of mobx, react and mobx+react that most material is out-right wrong at worst and misleading at best.

I am using the latest versions of Typescript, react, react-dom, mobx and mobx-react.

答:
MobX does not support dynamic addition / removal of keys on objects. For dynamically keyed objects maps should be used, so:

characters = observable.map<Character>()

See https://mobx.js.org/refguide/map.html

In general any not too opionated react boilerplate works for mobx, as it is trivial to add to an existing object. So I tend to not use any boiler plate at all, or, for a quick setup, create-react-app + react-app-rewired to add decorator support

Body:
Note, I am using Typescript.

In my store I have a field specified as so:

@observable public characters: {[name: string] : Types.Character} = {};

Types.Character is defined:

export class Character {
    name: string;
    gender: Gender;
    @observable status: Status;
    @observable statusmsg: string;
}

And I have a React component marked as observer:

@observer
export default class NamePlate extends React.Component<INamePlateProps, {}> {

    render(){
        let char: Types.Character = chatStore.characters[this.props.characterName];

        let textStyle: Object = {
            color: Types.getGenderColourFromString(char.gender)
        };

        return

            <img src={`images/status-small-${char.status}.png`}/>
            {char.name}

;
    }

}

I am changing the char.statusmg and char.status properties but the observer component is not re-rendering.

private receiveSTA(obj: Packets.IReceivePacketSTA){
    let char: Types.Character = this.characters[obj.character];
    char.status = Types.getStatusTypeFromString(obj.status);
    char.statusmsg = obj.statusmsg;
}

I'd guess that the problem is to do with how the observable is nested down in an object in my store? I have no idea. I've found getting to grips with this set-up extremely difficult and hard to find information for. There's so many competing set-ups of mobx, react and mobx+react that most material is out-right wrong at worst and misleading at best.

I am using the latest versions of Typescript, react, react-dom, mobx and mobx-react.


问:
Angular2 How to pass selected value to other component
Hi I am tryng to pass value selected from one of the options.
I used ngModel to save the value but I can't figure out how to pass it to other component. Since they are connected but not nested, I couldn't use Eventemitter cause I reckon to use Eventemiiter, I should use child component's selector to nest the component in the parent component which I do not want to do.

These two components are seperated and I want to pass selected value to the other component? How can I achieve this?

Below is my code.

Component 1's template

```<code> <div>
    <select (change)="printValue()" formControlName="dogName"
     class="form-control"
     class="selectionbox"
     [(ngModel)]="selected_dog" required>

  <option *ngFor="let d of dogs" [ngValue]="d">
     {{d.dogName}}
  </option>
     </select>
</code>```

Component1's component

```<code>     selected_dog: string;
     printValue () {
     console.log (this.selected_dog)} // checked if the value is properly stored.
</code>```

And now, I want to pass 'selected_dog' value to Component2.
Component2

```<code>     value1: string; //how to pass selected_dog value to component2's value1.
</code>```

I am not sure what to use ( eventEmitter, output/ input? / ng-content?)

I appreciate your help in advance.

答:
In the service if you are facing issues with get value you could make the variable static and just access the variable without even injecting, like
AppMessageService.value1.</p>

Body:
Hi I am tryng to pass value selected from one of the options.
I used ngModel to save the value but I can't figure out how to pass it to other component. Since they are connected but not nested, I couldn't use Eventemitter cause I reckon to use Eventemiiter, I should use child component's selector to nest the component in the parent component which I do not want to do.

These two components are seperated and I want to pass selected value to the other component? How can I achieve this?

Below is my code.

Component 1's template

    <select (change)="printValue()" formControlName="dogName"
     class="form-control"
     class="selectionbox"
     [(ngModel)]="selected_dog" required>

  <option *ngFor="let d of dogs" [ngValue]="d">
     {{d.dogName}}
  </option>
     </select>

Component1's component

     selected_dog: string;
     printValue () {
     console.log (this.selected_dog)} // checked if the value is properly stored.

And now, I want to pass 'selected_dog' value to Component2.
Component2

     value1: string; //how to pass selected_dog value to component2's value1.

I am not sure what to use ( eventEmitter, output/ input? / ng-content?)

I appreciate your help in advance.


问:
Can create culture for en-EN on local dev machine
I just deployed our application to our azure staging environment and ran into an issue with the en-EN culture not being supported. After some digging I find out that there is no such culture, and I should use en-GB or en-USinstead.

But, now to my question. On my local development machine I've got no problems creating a CultureInfo with en-EN.

```<code>CultureInfo ci = new CultureInfo("en-EN");
Console.WriteLine("culture: "+ ci.ThreeLetterISOLanguageName);
</code>```

Outputs culture: eng

I also tried enumerating all cultures with CultureInfo.GetCultures(CultureTypes.AllCultures); and there's no corresponding en-EN culture in the result.

So, what's going on, why can I create a culture which shouldn't exist?

答:
If you are using Windows 10 the culture behaviour has changed: "unkown", but "maybe existing" cultures (3-letter iso) will only result in an "Unkown locale" culture with LCID 4096.
Pre-Windows 10 this would result in an exception (unless you have installed such a custom culture)

MSDN-Link

```<code>        try
        {

            // ok
            CultureInfo culture1 = new CultureInfo("foo");
            CultureInfo culture2 = new CultureInfo("xyz");
            CultureInfo culture3 = new CultureInfo("en-xy");

            // not ok - exception
            CultureInfo culture4 = new CultureInfo("foox");

        }
        catch (Exception exc)
        {

        }
</code>```

Body:
I just deployed our application to our azure staging environment and ran into an issue with the en-EN culture not being supported. After some digging I find out that there is no such culture, and I should use en-GB or en-USinstead.

But, now to my question. On my local development machine I've got no problems creating a CultureInfo with en-EN.

CultureInfo ci = new CultureInfo("en-EN");
Console.WriteLine("culture: "+ ci.ThreeLetterISOLanguageName);

Outputs culture: eng

I also tried enumerating all cultures with CultureInfo.GetCultures(CultureTypes.AllCultures); and there's no corresponding en-EN culture in the result.

So, what's going on, why can I create a culture which shouldn't exist?

Body:
If you are using Windows 10 the culture behaviour has changed: "unkown", but "maybe existing" cultures (3-letter iso) will only result in an "Unkown locale" culture with LCID 4096.
Pre-Windows 10 this would result in an exception (unless you have installed such a custom culture)

MSDN-Link

        try
        {

            // ok
            CultureInfo culture1 = new CultureInfo("foo");
            CultureInfo culture2 = new CultureInfo("xyz");
            CultureInfo culture3 = new CultureInfo("en-xy");

            // not ok - exception
            CultureInfo culture4 = new CultureInfo("foox");

        }
        catch (Exception exc)
        {

        }


答:
why?

you are using document.write().

document write is rewrite your whole document just like new page or empty body.and then print with value of the `document.write('value'

)`

If you show with same page declare with some element .and pass the data with element using innerHTML .

Demo

function yes() {
  document.getElementById("demo").innerHTML = "YES";
}

function no() {
  document.getElementById("demo").innerHTML = "NO";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

<p id="demo"></p></code>```

Title: I want to print these two words from two buttons, but it didn't work as I imagined

Body:
I want to print these two words called "yes" and "no" by two buttons.

When I clicked the first button to print "yes", the two buttons were covered by the word "yes", I don't how to work it out.

Here is my code and the screen shot:
before
after

<!DOCTYPE html>

 <meta charset="utf-8">
 <title>example</title>

 <button type="button" onclick="yes()">print yes</button>
 <button type="button" onclick="no()">print no</button>

Body:
why?

you are using document.write().

document write is rewrite your whole document just like new page or empty body.and then print with value of the `document.write('value'

)`

If you show with same page declare with some element .and pass the data with element using innerHTML .

Demo

function yes() {
  document.getElementById("demo").innerHTML = "YES";
}

function no() {
  document.getElementById("demo").innerHTML = "NO";
}

<button type="button" onclick="yes()">print yes</button>
<button type="button" onclick="no()">print no</button>

<p id="demo"></p>


问:
Problem with adding to list inside a loop in java
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

```<code>import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}
</code>```

And this is the result I got after running:

```<code>current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New
</code>```

Please help!!!!

答:
It doesn't add multiple copies, it allways add f as a new list item after first iteration you have f then f,f then f,f,f then f,f,f,f in your list. And you are allways modifing your only array f so all elements conatin the same two numbers

You should change:

```<code>for(int j=0; j<2; j++){
f[0] = i;
</code>```

to

```<code>for(int j=0; j<2; j++){
f = new int [2];
f[0] = i;
</code>```

I don't understand your condition

```<code>if(!(G.contains(f))){
</code>```

f is never in the G because you never put it there, so no possible chance it could get there

Body:
I wrote a code to check if an array is not in a list, then it should add it to another list. I used a linked list for this. But my problem is the program always add multiple copies of the current array and remove what's inside in the list before: My code is as follows:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Trial{

    public static void main(final String[] args){

        final List<int[]> G = new LinkedList<int[]>();
        final List<int[]> New = new LinkedList<int[]>();

        final int[] f = new int[2];

        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                f[0] = i;
                f[1] = j;
                // System.out.println("f is "+Arrays.toString(f));
                if(!(G.contains(f))){
                    System.out.println("current f is " + Arrays.toString(f));
                    // I print here in order to see what is f
                    New.add(f);
                    System.out.println("content of the list New");
                    // I print the list New to see its contents
                    for(int k = 0; k < New.size(); k++){
                        System.out.println(Arrays.toString(New.get(k)));
                    }
                    System.out.println("finished printing the list New");
                }
            }
        }

    }

}

And this is the result I got after running:

current f is [0, 0]
content of the list New
[0, 0]
finished printing the list New
current f is [0, 1]
content of the list New
[0, 1]
[0, 1]
finished printing the list New
current f is [1, 0]
content of the list New
[1, 0]
[1, 0]
[1, 0]
finished printing the list New
current f is [1, 1]
content of the list New
[1, 1]
[1, 1]
[1, 1]
[1, 1]
finished printing the list New

Please help!!!!

Body:
It doesn't add multiple copies, it allways add f as a new list item after first iteration you have f then f,f then f,f,f then f,f,f,f in your list. And you are allways modifing your only array f so all elements conatin the same two numbers

You should change:

for(int j=0; j<2; j++){
f[0] = i;

to

for(int j=0; j<2; j++){
f = new int [2];
f[0] = i;

I don't understand your condition

if(!(G.contains(f))){

f is never in the G because you never put it there, so no possible chance it could get there


问:
How to extract image inside bounding box which was drawn manually
I have many images which have bounding boxes all drawn in the same color and are all rectangles.
How can I extract the image inside the bounding box?
There are similar questions but none of those solutions work properly.
Can anybody help please?
The below image is an example.
I would like to use python Opencv to do this.

EDIT------------------------------------------------------------------

This code works perfectly for all the images. It's based on answer from sipho

```<code>img = cv2.imread(img_url)
hsv_min = np.array([0, 250, 100],np.uint8)
hsv_max = np.array([10, 255, 255],np.uint8)

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

frame_threshed = cv2.inRange(hsv_img, hsv_min, hsv_max)

# Perform morphology
se = np.ones((1,1), dtype='uint8')
image_close = cv2.morphologyEx(frame_threshed, cv2.MORPH_CLOSE, se)
cv2.imshow(image_close)
cv2.waitkey(0)

# detect contours on the morphed image
ret,thresh = cv2.threshold(image_close,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

areaArray = []
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    areaArray.append(area)

# Sort countours based on area
sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True)

# find the nth largest contour [n-1][1], in this case 2
largestcontour = sorteddata[0][1]

# get the bounding rectangle of the contour
x, y, w, h = cv2.boundingRect(largestcontour)

cropped_img = img[y+3:y+h-3,x+3:x+w-3]
cv2.imshow('cropped', cropped_img)
cv2.waitkey(0)
</code>```

答:
You could try the following:

Convert image to HSV

Threshold image with colors in a certain range

Detect contours in the thresholded image

Filter contours using hierachy to only extract inner contours

Extract ROIs based on the bounding rectangles of the contours

If you are still completely stumped, view this example code

Body:
I have many images which have bounding boxes all drawn in the same color and are all rectangles.
How can I extract the image inside the bounding box?
There are similar questions but none of those solutions work properly.
Can anybody help please?
The below image is an example.
I would like to use python Opencv to do this.

EDIT------------------------------------------------------------------

This code works perfectly for all the images. It's based on answer from sipho

img = cv2.imread(img_url)
hsv_min = np.array([0, 250, 100],np.uint8)
hsv_max = np.array([10, 255, 255],np.uint8)

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

frame_threshed = cv2.inRange(hsv_img, hsv_min, hsv_max)

# Perform morphology
se = np.ones((1,1), dtype='uint8')
image_close = cv2.morphologyEx(frame_threshed, cv2.MORPH_CLOSE, se)
cv2.imshow(image_close)
cv2.waitkey(0)

# detect contours on the morphed image
ret,thresh = cv2.threshold(image_close,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

areaArray = []
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    areaArray.append(area)

# Sort countours based on area
sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True)

# find the nth largest contour [n-1][1], in this case 2
largestcontour = sorteddata[0][1]

# get the bounding rectangle of the contour
x, y, w, h = cv2.boundingRect(largestcontour)

cropped_img = img[y+3:y+h-3,x+3:x+w-3]
cv2.imshow('cropped', cropped_img)
cv2.waitkey(0)