问:
Value Converter Without Binding On Image Source - conversion
I bind string property from view model class on image source in view. String property can have value 1 for man and 2 for woman. I use also converter on binding which returns uri for image source.

In view I have this:

```<code>    <Image Style="{StaticResource InfoIcon}"
           Source="{Binding ., Mode=OneWay,UpdateSourceTrigger=PropertyChanged,
                Converter={StaticResource sexImgConverter},
                ConverterParameter=Oponent.Info.Sex}"/>
</code>```

Converter method is here:

```<code>    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        const string woman = "/images/icons/chat/woman.png";
        const string man = "/images/icons/chat/man.png";

        string result = string.Empty;

        string result = int.Parse(value.ToString()) == 1 ? man : woman;

        return new Uri(result);
    }
</code>```

Problem is I bind property sex (in view Oponent.Info.Sex) which is type string and parse to integer.

But if I add debuger break point on line :

```<code>string resul = int.Parse(value.ToString()) == 1 ? man : woman;
</code>```

I see that value is type of my view model class.

I try use this convert method no another bind, here is it:

```<code><TextBlock Style="{StaticResource InfoText}">
     <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1} rokov">
            <Binding Path="Oponent.Info.Sex" Converter="{StaticResource sexConverter}"/>
            <Binding Path= "Oponent.Info.Age"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
</code>```

I use the same conveter add debuger break point on line:

```<code>string resul = int.Parse(value.ToString()) == 1 ? man : woman;
</code>```

I see the value is type of string.

What have I done wrong?

答:
It looks like you're confusing how the different parts of the Binding relate to the Convert method parameters. Here's the method signature for IValueConverter.Convert:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
</code>```

The value parameter comes from the Binding's value, which is what normally gets assigned directly to the target property. In your case your Binding is using {Binding .} (equivalent to just {Binding}) which uses the current DataContext as the source, and specifies no path so results in the DataContext object as your value (in this case your View Model class).

The ConverterParameter set in the Binding shows up as the parameter parameter in the Convert method. This is not a bound value and needs to be some type of fixed value: a string, x:Static object reference, StaticResource, etc. The way you've declared your Binding it is most likely being parsed as a string: "Oponent.Info.Sex", which you should see at the breakpoint as the parameter in the Convert method.

The Binding you're using in the MultiBinding is using the parameters in the correct places. Try this instead for your Source binding (your Mode and UpdateSourceTrigger settings are unneeded):

```<code>Source="{Binding Path=Oponent.Info.Sex, Converter={StaticResource sexImgConverter}}"
</code>```

Body:
I bind string property from view model class on image source in view. String property can have value 1 for man and 2 for woman. I use also converter on binding which returns uri for image source.

In view I have this:

    <Image Style="{StaticResource InfoIcon}"
           Source="{Binding ., Mode=OneWay,UpdateSourceTrigger=PropertyChanged,
                Converter={StaticResource sexImgConverter},
                ConverterParameter=Oponent.Info.Sex}"/>

Converter method is here:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        const string woman = "/images/icons/chat/woman.png";
        const string man = "/images/icons/chat/man.png";

        string result = string.Empty;

        string result = int.Parse(value.ToString()) == 1 ? man : woman;

        return new Uri(result);
    }

Problem is I bind property sex (in view Oponent.Info.Sex) which is type string and parse to integer.

But if I add debuger break point on line :

string resul = int.Parse(value.ToString()) == 1 ? man : woman;

I see that value is type of my view model class.

I try use this convert method no another bind, here is it:

<TextBlock Style="{StaticResource InfoText}">
     <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1} rokov">
            <Binding Path="Oponent.Info.Sex" Converter="{StaticResource sexConverter}"/>
            <Binding Path= "Oponent.Info.Age"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

I use the same conveter add debuger break point on line:

string resul = int.Parse(value.ToString()) == 1 ? man : woman;

I see the value is type of string.

What have I done wrong?

Body:
It looks like you're confusing how the different parts of the Binding relate to the Convert method parameters. Here's the method signature for IValueConverter.Convert:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

The value parameter comes from the Binding's value, which is what normally gets assigned directly to the target property. In your case your Binding is using {Binding .} (equivalent to just {Binding}) which uses the current DataContext as the source, and specifies no path so results in the DataContext object as your value (in this case your View Model class).

The ConverterParameter set in the Binding shows up as the parameter parameter in the Convert method. This is not a bound value and needs to be some type of fixed value: a string, x:Static object reference, StaticResource, etc. The way you've declared your Binding it is most likely being parsed as a string: "Oponent.Info.Sex", which you should see at the breakpoint as the parameter in the Convert method.

The Binding you're using in the MultiBinding is using the parameters in the correct places. Try this instead for your Source binding (your Mode and UpdateSourceTrigger settings are unneeded):

Source="{Binding Path=Oponent.Info.Sex, Converter={StaticResource sexImgConverter}}"


来源: stackexchange

问:
Javafx tableviews don't display after adding rowfactory
I am trying to set up a netbeans/javafx program that displays a list of Pet objects, and gives every row an onclick listener.

I have the following in fxml:

MyTables.fxml

```<code><VBox alignment="CENTER" layoutX="11.0" layoutY="12.0" prefWidth="345.0">
    <children>
        <TableView id="Table1" fx:id="Table1" styleClass="mytable"/>
        <TableView id="Table2" fx:id="Table2" styleClass="mytable"/>
        <TableView id="Table3" fx:id="Table3" styleClass="mytable"/>
        <TableView id="Table4" fx:id="Table4" styleClass="mytable"/>
    </children>
</VBox>
</code>```

I'm using netbeans, so I set up a topComponent for the view which loads the FXML, which in turn loads a controller class.

In my controller class I have the following code to add content to the table.  The intention is for each table to have 3 rows that correspond to the ID, Name, and Owner of the contained Pet object.

MyTablesController.java

```<code>public class MyTablesController implements Initializable {

    @FXML
    private TableView<Pet> Table1;
    @FXML
    private TableView<Pet> Table2;
    @FXML
    private TableView<Pet> Table3;
    @FXML
    private TableView<Pet> Table4;

    private TableView<Pet>[] allTables;

    public MyTablesController() {
        allTables = new TableView[4];
        allTables[0] = Table1;
        allTables[1] = Table2;
        allTables[2] = Table3;
        allTables[3] = Table4;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        for(TableView<Pet> table : allTables) {
            table.getColumns().add(createCol("ID", Pet::idProperty, 100));
            table.getColumns().add(createCol("Name", Pet::nameProperty, 140));
            table.getColumns().add(createCol("Owner", Pet::ownerProperty, 100));
            table.getItems().addAll(
                    new Pet("1234", "spot", "joe"),
                    new Pet("5432", "snowball", "bill"),
                    new Pet("7612", "snoopy", "frank")
            );
        }

        setupTableRowDragEvents();
    }

    private TableColumn<Pet, String> createCol(String title,
            Function<Pet, ObservableValue<String>> mapper, double size) {

        TableColumn<Pet, String> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> mapper.apply(cellData.getValue()));
        col.setPrefWidth(size);
        return col ;
    }

    private void setupTableRowDragEvents() {
        for (TableView<Pet> table : allTables) {
            table.setRowFactory(tv -> {
                TableRow<Pet> row = new TableRow<>();
                row.setOnMouseClicked(event -> {
                    System.out.println("I CLICKED ON " + row.getItem().getName()");
                });
                return row;
            });
        }
    }
}
</code>```

Finally, here is the Pet object:

Pet.java

```<code>public final class Pet {

    public final StringProperty id = new SimpleStringProperty(this, "id");
    public final StringProperty name = new SimpleStringProperty(this, "name");
    public final StringProperty owner = new SimpleStringProperty(this, "owner");

    public Pet() {}

    public Pet(String id, String name, String owner) {
        this.id.set(id);
        this.name.set(name);
        this.owner.set(owner);
    }

    public String getId() {
        return id.get();
    }

    public void setId(String id) {
        this.id.set(id);
    }

    public StringProperty idProperty() {
        return id;
    }

    public String getName() {
        return name.get();
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public StringProperty nameProperty() {
        return name;
    }

    public String getOwner() {
        return owner.get();
    }

    public void setOwner(String owner) {
        this.owner.set(owner);
    }

    public StringProperty ownerProperty() {
        return owner;
    }
}
</code>```

Here's my problem.

If I leave MyTablesController.initialize empty, the 4 graphs display just fine.  It's only when I add the rest of the code (the setCols calls and the setupTableRowDragEvents() call)...

The graphs don't display if either or both of the those things in initialize() exist.  I get no error message or strange behavior other than the window being totally empty and the graphs not showing up.

I'm basing my code off of sort tableview with drag and drop (rows) .  I can't figure out where I'm screwing up when compared to this.  Is that answer just wrong and nobody bothered to check it?

What am I doing wrong here?

答:
At the time you populate the array, the table view references are all null, so you fill your array with null references. Then when you iterate through the array, you will get a null pointer exception the first time you call table.getColumns(). Move the code from the controller constructor to the beginning of initialize():

```<code>public class MyTablesController implements Initializable {

    @FXML
    private TableView<Pet> Table1;
    @FXML
    private TableView<Pet> Table2;
    @FXML
    private TableView<Pet> Table3;
    @FXML
    private TableView<Pet> Table4;

    private TableView<Pet>[] allTables;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        allTables = new TableView[4];
        allTables[0] = Table1;
        allTables[1] = Table2;
        allTables[2] = Table3;
        allTables[3] = Table4;

        for(TableView<Pet> table : allTables) {
            table.getColumns().add(createCol("ID", Pet::idProperty, 100));
            table.getColumns().add(createCol("Name", Pet::nameProperty, 140));
            table.getColumns().add(createCol("Owner", Pet::ownerProperty, 100));
            table.getItems().addAll(
                    new Pet("1234", "spot", "joe"),
                    new Pet("5432", "snowball", "bill"),
                    new Pet("7612", "snoopy", "frank")
            );
        }

        setupTableRowDragEvents();
    }

    // ...

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set up a netbeans/javafx program that displays a list of Pet objects, and gives every row an onclick listener.

I have the following in fxml:

MyTables.fxml

<VBox alignment="CENTER" layoutX="11.0" layoutY="12.0" prefWidth="345.0">
    <children>
        <TableView id="Table1" fx:id="Table1" styleClass="mytable"/>
        <TableView id="Table2" fx:id="Table2" styleClass="mytable"/>
        <TableView id="Table3" fx:id="Table3" styleClass="mytable"/>
        <TableView id="Table4" fx:id="Table4" styleClass="mytable"/>
    </children>
</VBox>

I'm using netbeans, so I set up a topComponent for the view which loads the FXML, which in turn loads a controller class.

In my controller class I have the following code to add content to the table.  The intention is for each table to have 3 rows that correspond to the ID, Name, and Owner of the contained Pet object.

MyTablesController.java

public class MyTablesController implements Initializable {

    @FXML
    private TableView<Pet> Table1;
    @FXML
    private TableView<Pet> Table2;
    @FXML
    private TableView<Pet> Table3;
    @FXML
    private TableView<Pet> Table4;

    private TableView<Pet>[] allTables;

    public MyTablesController() {
        allTables = new TableView[4];
        allTables[0] = Table1;
        allTables[1] = Table2;
        allTables[2] = Table3;
        allTables[3] = Table4;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        for(TableView<Pet> table : allTables) {
            table.getColumns().add(createCol("ID", Pet::idProperty, 100));
            table.getColumns().add(createCol("Name", Pet::nameProperty, 140));
            table.getColumns().add(createCol("Owner", Pet::ownerProperty, 100));
            table.getItems().addAll(
                    new Pet("1234", "spot", "joe"),
                    new Pet("5432", "snowball", "bill"),
                    new Pet("7612", "snoopy", "frank")
            );
        }

        setupTableRowDragEvents();
    }

    private TableColumn<Pet, String> createCol(String title,
            Function<Pet, ObservableValue<String>> mapper, double size) {

        TableColumn<Pet, String> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> mapper.apply(cellData.getValue()));
        col.setPrefWidth(size);
        return col ;
    }

    private void setupTableRowDragEvents() {
        for (TableView<Pet> table : allTables) {
            table.setRowFactory(tv -> {
                TableRow<Pet> row = new TableRow<>();
                row.setOnMouseClicked(event -> {
                    System.out.println("I CLICKED ON " + row.getItem().getName()");
                });
                return row;
            });
        }
    }
}

Finally, here is the Pet object:

Pet.java

public final class Pet {

    public final StringProperty id = new SimpleStringProperty(this, "id");
    public final StringProperty name = new SimpleStringProperty(this, "name");
    public final StringProperty owner = new SimpleStringProperty(this, "owner");

    public Pet() {}

    public Pet(String id, String name, String owner) {
        this.id.set(id);
        this.name.set(name);
        this.owner.set(owner);
    }

    public String getId() {
        return id.get();
    }

    public void setId(String id) {
        this.id.set(id);
    }

    public StringProperty idProperty() {
        return id;
    }

    public String getName() {
        return name.get();
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public StringProperty nameProperty() {
        return name;
    }

    public String getOwner() {
        return owner.get();
    }

    public void setOwner(String owner) {
        this.owner.set(owner);
    }

    public StringProperty ownerProperty() {
        return owner;
    }
}

Here's my problem.

If I leave MyTablesController.initialize empty, the 4 graphs display just fine.  It's only when I add the rest of the code (the setCols calls and the setupTableRowDragEvents() call)...

The graphs don't display if either or both of the those things in initialize() exist.  I get no error message or strange behavior other than the window being totally empty and the graphs not showing up.

I'm basing my code off of sort tableview with drag and drop (rows) .  I can't figure out where I'm screwing up when compared to this.  Is that answer just wrong and nobody bothered to check it?

What am I doing wrong here?

Body:
At the time you populate the array, the table view references are all null, so you fill your array with null references. Then when you iterate through the array, you will get a null pointer exception the first time you call table.getColumns(). Move the code from the controller constructor to the beginning of initialize():

public class MyTablesController implements Initializable {

    @FXML
    private TableView<Pet> Table1;
    @FXML
    private TableView<Pet> Table2;
    @FXML
    private TableView<Pet> Table3;
    @FXML
    private TableView<Pet> Table4;

    private TableView<Pet>[] allTables;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        allTables = new TableView[4];
        allTables[0] = Table1;
        allTables[1] = Table2;
        allTables[2] = Table3;
        allTables[3] = Table4;

        for(TableView<Pet> table : allTables) {
            table.getColumns().add(createCol("ID", Pet::idProperty, 100));
            table.getColumns().add(createCol("Name", Pet::nameProperty, 140));
            table.getColumns().add(createCol("Owner", Pet::ownerProperty, 100));
            table.getItems().addAll(
                    new Pet("1234", "spot", "joe"),
                    new Pet("5432", "snowball", "bill"),
                    new Pet("7612", "snoopy", "frank")
            );
        }

        setupTableRowDragEvents();
    }

    // ...

}


答:
Smells like logarithm..

```<code>import math

def xp_to_level(xp):
    return math.ceil(math.log(xp/368599, 1.101141)) + 61
</code>```

Usage:

```<code>>>> xp_to_level(123456)
50
</code>```

Title: How can I determine level based on experience?

Body:
How can I simply calculate the level based on an input experience?
I'm making a "pet chance generator" for a game called runescape. The program asks for your current experience and approximates the level based on the experience value input by the user. Below is the only method I could think of to do this but as you can see there is a wall of text basically copy pasted 40 times. Please help!

I currently have:

def calculate_level(xp):
if xp < 368599:
    level = 62
elif xp < 368599 * 1.101141**2:
    level = 63
elif xp < 368599 * 1.101141**3:
    level = 64
elif xp < 368599 * 1.101141**4:
    level = 65
elif xp < 368599 * 1.101141**5:
    level = 66
elif xp < 368599 * 1.101141**6:
    level = 67
elif xp < 368599 * 1.101141**7:
    level = 68
elif xp < 368599 * 1.101141**8:
    level = 69
elif xp < 368599 * 1.101141**9:
    level = 70
elif xp < 368599 * 1.101141**10:
    level = 71
elif xp < 368599 * 1.101141**11:
    level = 72
elif xp < 368599 * 1.101141**12:
    level = 73
elif xp < 368599 * 1.101141**13:
    level = 74
elif xp < 368599 * 1.101141**14:
    level = 75
elif xp < 368599 * 1.101141**15:
    level = 76
elif xp < 368599 * 1.101141**16:
    level = 77
elif xp < 368599 * 1.101141**17:
    level = 78
elif xp < 368599 * 1.101141**18:
    level = 79
elif xp < 368599 * 1.101141**19:
    level = 80
elif xp < 368599 * 1.101141**20:
    level = 81
elif xp < 368599 * 1.101141**21:
    level = 82
elif xp < 368599 * 1.101141**22:
    level = 83
elif xp < 368599 * 1.101141**23:
    level = 84
elif xp < 368599 * 1.101141**24:
    level = 85
elif xp < 368599 * 1.101141**25:
    level = 86
elif xp < 368599 * 1.101141**26:
    level = 87
elif xp < 368599 * 1.101141**27:
    level = 88
elif xp < 368599 * 1.101141**28:
    level = 89
elif xp < 368599 * 1.101141**29:
    level = 90
elif xp < 368599 * 1.101141**30:
    level = 91
elif xp < 368599 * 1.101141**31:
    level = 92
elif xp < 368599 * 1.101141**32:
    level = 93
elif xp < 368599 * 1.101141**33:
    level = 94
elif xp < 368599 * 1.101141**34:
    level = 95
elif xp < 368599 * 1.101141**35:
    level = 96
elif xp < 368599 * 1.101141**36:
    level = 97
elif xp < 368599 * 1.101141**37:
    level = 98
else:
    level = 99
return level

Body:
Smells like logarithm..

import math

def xp_to_level(xp):
    return math.ceil(math.log(xp/368599, 1.101141)) + 61

Usage:

>>> xp_to_level(123456)
50


问:
Wordpress /category/subcategory 404 error
I am new at WordPress and I would like to create a url structure for a recipe site.

/category ( eg: /recipe will list all recipes ).

/category/subcategory ( eg: recipe/chicken list of chicken recipes )

/category/subcategory/postname ( eg: recipe/chicken/Chicken-Breasts-with-Tomatoes

The problem:

When I access /category/subcategory ( /recipe/chicken ) i got 404 not found, but if i access /subcategory ( eg: /chicken ) it works.

I had marked the category "recipe" as the parent of chicken.

Tks a lot,
enog

答: I solved it by putting 'en' (short for English) as base for category. This kept the beauty of URL as well as do the job for me that I wanted. It also impacted SEO as search engine thinks of 'en' as 'English'.</p>


问:
C# & WPF - Problem with taskbar popup notifier window
I managed to create a task-bar pop-up window like the one in messenger.
The problem that when it moves down instead of disappear behind the task-bar it just goes behind it.

How can I make it disappear behind the task-bar? don't forget in windows 7 that task-bar is transparent!

Here is my code:

```<code>public partial class WindowNotifier : Window
{
    double xPos = 0;
    double yPos = 0;
    Timer closeTimer;

    public WindowNotifier()
    {
        InitializeComponent();
        closeTimer = new Timer();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        SetValues();
        closeTimer.Tick+=new EventHandler(closeTimer_Tick);
        closeTimer.Start();
    }

    private void SetValues()
    {

        xPos = System.Windows.SystemParameters.WorkArea.Width;
        yPos = System.Windows.SystemParameters.WorkArea.Height;

        this.Left = xPos - this.Width;
        this.Top = yPos - this.Height;

    }

    private void closeTimer_Tick(object sender, EventArgs e)
    {
        closeTimer.Interval = 50;
        double curYPos = this.Top;
        if (curYPos < yPos)
        {
            this.Top = curYPos + 8;

            this.Opacity = this.Opacity - 0.050;
        }
        else
        {
            this.Close();
        }
    }
}
</code>```

EDIT:
I changed the timer part so now I decrease the height of the control and relocate it.
Now the problem is that it blinks. How can I solve it?

Here is the code:

```<code>    closeTimer.Interval = 50;
    double curYPos = this.Top;
    int decAmount = 8;

    if(this.Height - decAmount > 0)
    {
        this.Height = this.Height - decAmount;
        this.Top = this.Top + decAmount;

        this.Opacity = this.Opacity - 0.010;
    }
    else
    {
        this.Height = 0;
        this.Close();
        closeTimer.Stop();
    }
</code>```

答:
Couldn't you, instead of moving it, decrease the height and move it down at the same time by the same amount?

Try SuspendLayout() and ResumeLayout() to prevent flickering. I am not quite sure this will solve the flickering but when there are many child controls it might save  the day.

You can also try to variate the interval at which you are resizing or move the code to the Redraw/Paint event.

Instead of resizing you could also try a Clipping Region.

ContentLicense: CC BY-SA 2.5

Body:
I managed to create a task-bar pop-up window like the one in messenger.
The problem that when it moves down instead of disappear behind the task-bar it just goes behind it.

How can I make it disappear behind the task-bar? don't forget in windows 7 that task-bar is transparent!

Here is my code:

public partial class WindowNotifier : Window
{
    double xPos = 0;
    double yPos = 0;
    Timer closeTimer;

    public WindowNotifier()
    {
        InitializeComponent();
        closeTimer = new Timer();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        SetValues();
        closeTimer.Tick+=new EventHandler(closeTimer_Tick);
        closeTimer.Start();
    }

    private void SetValues()
    {

        xPos = System.Windows.SystemParameters.WorkArea.Width;
        yPos = System.Windows.SystemParameters.WorkArea.Height;

        this.Left = xPos - this.Width;
        this.Top = yPos - this.Height;

    }

    private void closeTimer_Tick(object sender, EventArgs e)
    {
        closeTimer.Interval = 50;
        double curYPos = this.Top;
        if (curYPos < yPos)
        {
            this.Top = curYPos + 8;

            this.Opacity = this.Opacity - 0.050;
        }
        else
        {
            this.Close();
        }
    }
}

EDIT:
I changed the timer part so now I decrease the height of the control and relocate it.
Now the problem is that it blinks. How can I solve it?

Here is the code:

    closeTimer.Interval = 50;
    double curYPos = this.Top;
    int decAmount = 8;

    if(this.Height - decAmount > 0)
    {
        this.Height = this.Height - decAmount;
        this.Top = this.Top + decAmount;

        this.Opacity = this.Opacity - 0.010;
    }
    else
    {
        this.Height = 0;
        this.Close();
        closeTimer.Stop();
    }


问:
disable auto-lock even when iOS app is not running?
I know I can disable an iOS device's auto lock when my app is up and running, like so:

```<code>UIApplication.shared.isIdleTimerDisabled = true
</code>```

My question is: is there a way from the app to disable the auto lock of the device (so, set it to never), even when the app is not running?

答: No; having an API for that would allow third-party apps to disable a security feature of the device. You can file an enhancement request if you’ve got a use case in mind, but it may not get far.</p>

Body:
I know I can disable an iOS device's auto lock when my app is up and running, like so:

UIApplication.shared.isIdleTimerDisabled = true

My question is: is there a way from the app to disable the auto lock of the device (so, set it to never), even when the app is not running?


问:
Why single confidence interval when plotting drm model with multiple curves?
I'm doing nonlinear regression in R using drm function from drc package. The drm function takes a curveid argument, which makes drm to fit multiple curves and store the results in single model object. Next, I plot the curves and confidence intervals. I have a problem, however, when the model object contains multiple curves, the curves appear fine, but confidence interval is often plotted only for the first curve (though by the alpha level of it, it seems as if it is done several times).

Starting from the examples provided by drm, I found I get the desired behaviour, all confidence intervals appear, when I change the name of a variable fed into curveid argument—odd enough, only "CURVE" works, nothing else, even "curve" does not work (reproducible example given below). This made me think that maybe there is a bug in plot.drc (S3 method for class 'drc') so that "CURVE" is hardcoded in there. I eyeballed at the source code, but can't tell if it is true since I'm a beginner R user with little programming experience.

Most likely there is no bug and I am just missing something important.

```<code>library(drc)

# create some data
df <- data.frame(
  x=rep(c(0.003, 0.01, 0.03, 1, 3, 10, 100),2),
  y=c(3,3,3,1.5,-2,-3,-3.2, 3.5,3.5,3.2,1,-2.5,-2.8,-2.8),
  CURVE=rep(1:2, each=7)
)

# working as it should
mod1 <- drm(y~x, curveid=CURVE, data=df)
plot(mod1, type="confidence", main="working as it should")

# not working
names(df)[3] <- "curve"
mod2 <- drm(y~x, curveid=curve, data=df)
plot(mod2, type="confidence", main="not working")

# working again
names(df)[3] <- "CURVE"
mod3 <- drm(y~x, curveid=CURVE, data=df)
plot(mod3, type="confidence", main="working again")
</code>```

Resulting three plots as an image

答:
Vallo,

I can confirm the behavior you describe. Only the column name 'CURVE' works. All other names I tired do not work.

I think i have tracked this behavior to the behavior (bug?) of the ciFct subfunction in the plot.drc function.

```<code>   ciFct <- function(level, ...)
    {
        newdata <- data.frame(DOSE=dosePts, CURVE=rep(level, length(dosePts)))
        predictMat <- predict(object,
                              newdata=newdata,
                              interval = "confidence",
                              level=confidence.level)

        x <- c(dosePts, rev(dosePts))
        y <- c(predictMat[,"Lower"], rev(predictMat[,"Upper"]))
        polygon(x,y, border=NA, ...)
    }
</code>```

This is the function that calls predict() and generates the confidence bands. Note that it uses the hard-coded value 'CURVE' to build newdata on line 3. This only works properly if you used 'CURVE' in your original dataframe -- Otherwise it fails to work properly.

To fix this, you can of course always choose the column name 'CURVE'. Otherwise you will need to replace the plot.drc function with a patched version of the code above. The code can be fixed by changing the ciFit function to the following (note, only one line has been added):

```<code>  ciFct <- function(level, ...)
  {
    newdata <- data.frame(DOSE=dosePts, CURVE=rep(level, length(dosePts)))
    names(newdata)[2] <- object$curveVarNam # this is a new line to fix the bug
    predictMat <- predict(object,
                          newdata=newdata,
                          interval = "confidence",
                          level=confidence.level)

    x <- c(dosePts, rev(dosePts))
    y <- c(predictMat[,"Lower"], rev(predictMat[,"Upper"]))
    polygon(x,y, border=NA, ...)
  }
</code>```

Body:
I'm doing nonlinear regression in R using drm function from drc package. The drm function takes a curveid argument, which makes drm to fit multiple curves and store the results in single model object. Next, I plot the curves and confidence intervals. I have a problem, however, when the model object contains multiple curves, the curves appear fine, but confidence interval is often plotted only for the first curve (though by the alpha level of it, it seems as if it is done several times).

Starting from the examples provided by drm, I found I get the desired behaviour, all confidence intervals appear, when I change the name of a variable fed into curveid argument—odd enough, only "CURVE" works, nothing else, even "curve" does not work (reproducible example given below). This made me think that maybe there is a bug in plot.drc (S3 method for class 'drc') so that "CURVE" is hardcoded in there. I eyeballed at the source code, but can't tell if it is true since I'm a beginner R user with little programming experience.

Most likely there is no bug and I am just missing something important.

library(drc)

# create some data
df <- data.frame(
  x=rep(c(0.003, 0.01, 0.03, 1, 3, 10, 100),2),
  y=c(3,3,3,1.5,-2,-3,-3.2, 3.5,3.5,3.2,1,-2.5,-2.8,-2.8),
  CURVE=rep(1:2, each=7)
)

# working as it should
mod1 <- drm(y~x, curveid=CURVE, data=df)
plot(mod1, type="confidence", main="working as it should")

# not working
names(df)[3] <- "curve"
mod2 <- drm(y~x, curveid=curve, data=df)
plot(mod2, type="confidence", main="not working")

# working again
names(df)[3] <- "CURVE"
mod3 <- drm(y~x, curveid=CURVE, data=df)
plot(mod3, type="confidence", main="working again")

Resulting three plots as an image

Body:
Vallo,

I can confirm the behavior you describe. Only the column name 'CURVE' works. All other names I tired do not work.

I think i have tracked this behavior to the behavior (bug?) of the ciFct subfunction in the plot.drc function.

   ciFct <- function(level, ...)
    {
        newdata <- data.frame(DOSE=dosePts, CURVE=rep(level, length(dosePts)))
        predictMat <- predict(object,
                              newdata=newdata,
                              interval = "confidence",
                              level=confidence.level)

        x <- c(dosePts, rev(dosePts))
        y <- c(predictMat[,"Lower"], rev(predictMat[,"Upper"]))
        polygon(x,y, border=NA, ...)
    }

This is the function that calls predict() and generates the confidence bands. Note that it uses the hard-coded value 'CURVE' to build newdata on line 3. This only works properly if you used 'CURVE' in your original dataframe -- Otherwise it fails to work properly.

To fix this, you can of course always choose the column name 'CURVE'. Otherwise you will need to replace the plot.drc function with a patched version of the code above. The code can be fixed by changing the ciFit function to the following (note, only one line has been added):

  ciFct <- function(level, ...)
  {
    newdata <- data.frame(DOSE=dosePts, CURVE=rep(level, length(dosePts)))
    names(newdata)[2] <- object$curveVarNam # this is a new line to fix the bug
    predictMat <- predict(object,
                          newdata=newdata,
                          interval = "confidence",
                          level=confidence.level)

    x <- c(dosePts, rev(dosePts))
    y <- c(predictMat[,"Lower"], rev(predictMat[,"Upper"]))
    polygon(x,y, border=NA, ...)
  }


问:
find the min of the second index, then find the max of the third index of a list Python
I have a nested list like this:

```<code>a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]
</code>```

I want to transpose it and find the min of the second index, followed by the max of the third index, such that the resulting list I get is [4,2,8].

I have the following: min(a, key=lambda x: x[1]) which helps me find the min of the second index, which is 2 but Python would pick [7, 2, 6]. I'd like Python to conditionally look for the max of the third index and then return the list.

Logic:

Find the min of the 2nd index from each nested list

Then find the max of the 3rd index from each nested list

Return the actual nested list from a that satisfies both 1,2

答:
You could do something like this :

```<code>a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]

min_no=min([i[1] for i in a])
max_no=max([i[2] for i in a])
for item in a:
    if min_no and max_no in item:
        print(item)
</code>```

output:

```<code>[4, 2, 8]
</code>```

Body:
I have a nested list like this:

a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]

I want to transpose it and find the min of the second index, followed by the max of the third index, such that the resulting list I get is [4,2,8].

I have the following: min(a, key=lambda x: x[1]) which helps me find the min of the second index, which is 2 but Python would pick [7, 2, 6]. I'd like Python to conditionally look for the max of the third index and then return the list.

Logic:

Find the min of the 2nd index from each nested list

Then find the max of the 3rd index from each nested list

Return the actual nested list from a that satisfies both 1,2

Body:
You could do something like this :

a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]

min_no=min([i[1] for i in a])
max_no=max([i[2] for i in a])
for item in a:
    if min_no and max_no in item:
        print(item)

output:

[4, 2, 8]


问:
Array is giving an undefined in jquery
I want to get the id of each button and keep it in array. but the array looks undefined. why

Jquery CODE :

```<code>var arr = new Array();

$(".button").each(function () {
     arr.push($(this).attr('id'));
})

console.log(arr);//undefined

 }
</code>```

HTML CODE :

```<code>    <div id="1" class="button" data-bind="dxButton: { }"></div>
    <div id="2" class="button" data-bind="dxButton: { }"></div>
    <div id="3" class="button" data-bind="dxButton: { }"></div>
    <div id="4" class="button" data-bind="dxButton: { }"></div>
</code>```

答:
```<code> $(function(){
         var arr = new Array();
         $(".button").each(function () {
               arr.push($(this).attr('id'));
        });
        console.log(arr); //Array(4) 0:"1" 1:"2" 2:"3" 3:"4" length:4
      });

<body>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div id="1" class="button" data-bind="dxButton: { }"></div>
      <div id="2" class="button" data-bind="dxButton: { }"></div>
      <div id="3" class="button" data-bind="dxButton: { }"></div>
      <div id="4" class="button" data-bind="dxButton: { }"></div>
    </div>
  </div>
</div>
</body>
</code>```

The result is:
Array(4)
0:"1"
1:"2"
2:"3"
3:"4"
length:4

Title: Array is giving an undefined in jquery

Body:
I want to get the id of each button and keep it in array. but the array looks undefined. why

Jquery CODE :

var arr = new Array();

$(".button").each(function () {
     arr.push($(this).attr('id'));
})

console.log(arr);//undefined

 }

HTML CODE :

Body:
 $(function(){
         var arr = new Array();
         $(".button").each(function () {
               arr.push($(this).attr('id'));
        });
        console.log(arr); //Array(4) 0:"1" 1:"2" 2:"3" 3:"4" length:4
      });

<body>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div id="1" class="button" data-bind="dxButton: { }"></div>
      <div id="2" class="button" data-bind="dxButton: { }"></div>
      <div id="3" class="button" data-bind="dxButton: { }"></div>
      <div id="4" class="button" data-bind="dxButton: { }"></div>
    </div>
  </div>
</div>
</body>

The result is:
Array(4)
0:"1"
1:"2"
2:"3"
3:"4"
length:4


问:
How to run suspend method via reflection?
There is an coroutine block that can runs suspend functions.

But I call the function by invoke via reflection. This is java style invocation, apparently a simple call will not work.
Are there ways to run reflected method asynchronously? How to await this method?

```<code>import kotlin.coroutines.experimental.*

class TestClass(val InString: String) {
    suspend fun printString() {
        println(InString)
    }
}

fun launch(context: CoroutineContext, block: suspend () -> Unit) =
        block.startCoroutine(StandaloneCoroutine(context))

private class StandaloneCoroutine(override val context: CoroutineContext): Continuation<Unit> {
    override fun resume(value: Unit) {}

    override fun resumeWithException(exception: Throwable) {
        val currentThread = Thread.currentThread()
        currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception)
    }
}

fun main(args: Array<String>) {
    launch(EmptyCoroutineContext) {
        val a = TestClass("TestString");

        for (method in a.javaClass.methods) {
            if (method.name == "printString")
                method.invoke(a)  // Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments

        }
    }
}
</code>```

答:
Update

Since Kotlin 1.3 reflection natively supports calling suspending functions via KFunction.callSuspend and KFunction.callSuspendBy, so the above workaround is no longer needed.

Original Answer

Every suspend method in Kotlin is represented on JVM via CPS transformation that is explained in the coroutines design document. Java reflection is not aware about it and Kotlin reflection does not currently provide convenient means to perform invocation of suspending function either.

You'll have to do invocation with CPS transformation yourself via helper function. I'd suggest to implement the following helper for this purpose:

```<code>import java.lang.reflect.Method
import kotlin.coroutines.experimental.intrinsics.*

suspend fun Method.invokeSuspend(obj: Any, vararg args: Any?): Any? =
    suspendCoroutineOrReturn { cont ->
        invoke(obj, *args, cont)
    }
</code>```

Now if you replace invoke with invokeSuspend in your code, then it is going to work just like expected.

Body:
There is an coroutine block that can runs suspend functions.

But I call the function by invoke via reflection. This is java style invocation, apparently a simple call will not work.
Are there ways to run reflected method asynchronously? How to await this method?

import kotlin.coroutines.experimental.*

class TestClass(val InString: String) {
    suspend fun printString() {
        println(InString)
    }
}

fun launch(context: CoroutineContext, block: suspend () -> Unit) =
        block.startCoroutine(StandaloneCoroutine(context))

private class StandaloneCoroutine(override val context: CoroutineContext): Continuation<Unit> {
    override fun resume(value: Unit) {}

    override fun resumeWithException(exception: Throwable) {
        val currentThread = Thread.currentThread()
        currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception)
    }
}

fun main(args: Array<String>) {
    launch(EmptyCoroutineContext) {
        val a = TestClass("TestString");

        for (method in a.javaClass.methods) {
            if (method.name == "printString")
                method.invoke(a)  // Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments

        }
    }
}

Body:
Update

Since Kotlin 1.3 reflection natively supports calling suspending functions via KFunction.callSuspend and KFunction.callSuspendBy, so the above workaround is no longer needed.

Original Answer

Every suspend method in Kotlin is represented on JVM via CPS transformation that is explained in the coroutines design document. Java reflection is not aware about it and Kotlin reflection does not currently provide convenient means to perform invocation of suspending function either.

You'll have to do invocation with CPS transformation yourself via helper function. I'd suggest to implement the following helper for this purpose:

import java.lang.reflect.Method
import kotlin.coroutines.experimental.intrinsics.*

suspend fun Method.invokeSuspend(obj: Any, vararg args: Any?): Any? =
    suspendCoroutineOrReturn { cont ->
        invoke(obj, *args, cont)
    }

Now if you replace invoke with invokeSuspend in your code, then it is going to work just like expected.

ContentLicense: CC BY-SA 4.0


问:
How can I combine stdlib logging with py.test
I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.

The problem with this is that the logging module ends up trying to log messages to the 'stdout'-object provided by py.test after this object has been discarded by py.test. That is, I get:

```<code>Traceback (most recent call last):
  File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
    h.flush()
  File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
    self.stream.flush()
ValueError: I/O operation on closed file
</code>```

If I turn off capturing with -s, I don't have any problems, but of course that makes the test output unreadable with irrelevant logging.

Can anyone tell me the proper way to integrate stdlib logging with py.test?

(I tried looking at this, where it looks like it should just work without issues, so it didn't help me much)

答:
Logging/capturing interactions are to better work with the upcoming 2.0.1 release, which you can install already as a development snapshot by:

```<code>pip install -i http://pypi.testrun.org pytest
</code>```

You should get at least "2.0.1.dev9" when you type "py.test --version" afterwards. And the problem/error your posted should now be gone.

A bit of background: the logging package insists on "owning" the streams it uses, and by default it grabs sys.stderr and insists to close it at process exit, registered via the atexit module. py.test substitutes sys.stdout with a temporary file in order to snapshot output (including output at file-descriptor level in order to also catch subprocess output). So py.test evolved to be very careful to always use the same temporary file as to not have logging's atexit-code complain.

Not that you can also install the [pytest-capturelog][1] plugin which will help some more with dealing with logging output.

[1] http://pypi.python.org/pypi/pytest-capturelog/0.7

Body:
I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.

The problem with this is that the logging module ends up trying to log messages to the 'stdout'-object provided by py.test after this object has been discarded by py.test. That is, I get:

Traceback (most recent call last):
  File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
    h.flush()
  File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
    self.stream.flush()
ValueError: I/O operation on closed file

If I turn off capturing with -s, I don't have any problems, but of course that makes the test output unreadable with irrelevant logging.

Can anyone tell me the proper way to integrate stdlib logging with py.test?

(I tried looking at this, where it looks like it should just work without issues, so it didn't help me much)

Body:
Logging/capturing interactions are to better work with the upcoming 2.0.1 release, which you can install already as a development snapshot by:

pip install -i http://pypi.testrun.org pytest

You should get at least "2.0.1.dev9" when you type "py.test --version" afterwards. And the problem/error your posted should now be gone.

A bit of background: the logging package insists on "owning" the streams it uses, and by default it grabs sys.stderr and insists to close it at process exit, registered via the atexit module. py.test substitutes sys.stdout with a temporary file in order to snapshot output (including output at file-descriptor level in order to also catch subprocess output). So py.test evolved to be very careful to always use the same temporary file as to not have logging's atexit-code complain.

Not that you can also install the [pytest-capturelog][1] plugin which will help some more with dealing with logging output.

[1] http://pypi.python.org/pypi/pytest-capturelog/0.7


问:
apiRTC with multi page Ionic 3 app not working when navigated away from page and coming back to call page
Issue replication steps:

Click on “Click Me” button to navigate to call page.

After apiRTC initialized you should get you call ID

Click on back button to navigate to root page.

Click again on “Click Me” button to navigate to call page After
apiRTC initialized you should get you call ID but this time it will
not work.

Code

答: I recommend You to initialize apirtc and all its components in a provider and call the initializer in app.componen.ts when the app starts and platform is ready, so that you will be able to access to the same client whenever you are navigating between views. </p>


问:
Split array into chunks - is there faster method?
I'm looking for the quickest method to split an array into chunks of fixed size (last one can be smaller, of course). I've looked throughout the site and didn't find any performance-wise comparisons, so I wrote them, and here are the results:

Time in microseconds, mean/error/stddev

For int[] - 30.02 | 0.1002 | 0.0937

For IEnumerable<int> - 76.67 | 0.2146 | 0.1902

Update: Version below (in @Markus' answer) is 139.5 | 0.6702 | 0.5597

Most popular here on SO and frequently recommended method to use LINQ's  GroupBy with index/chunkSize is a no go - 267 microseconds is way too greater than either of aforementioned implementations.

Is there any faster way to split arrays?

P.S.
This is the code for Array and IEnumerable<T>:

```<code>    /// <summary>
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">Array to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this T[] source, int chunkMaxSize)
    {
        var pos = 0;
        var sourceLength = source.Length;
        do
        {
            var len = Math.Min(pos + chunkMaxSize, sourceLength) - pos;
            if (len == 0)
            {
                yield break;;
            }
            var arr = new T[len];
            Array.Copy(source, pos, arr, 0, len);
            pos += len;
            yield return arr;
        } while (pos < sourceLength);
    }

    /// <summary>
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"><see cref="IEnumerable{T}"/> to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this IEnumerable<T> source, int chunkMaxSize)
    {
        var arr = new T[chunkMaxSize];
        var pos = 0;
        foreach (var item in source)
        {
            arr[pos++] = item;
            if (pos == chunkMaxSize)
            {
                yield return arr;
                arr = new T[chunkMaxSize];
                pos = 0;
            }
        }
        if (pos > 0)
        {
            Array.Resize(ref arr, pos);
            yield return arr;
        }
    }
</code>```

P.P.S Complete solution with BenchmarkDotNet tests is on GitHub.

答:
Not really sure how this stacks up (ArraySegment), but give it a try. I've avoided using iterators but not really sure if that is really a gain here.

```<code>public static IEnumerable<T[]> AsChunks<T>(
    this T[] source, int chunkMaxSize)
{
    var chunks = source.Length / chunkMaxSize;
    var leftOver = source.Length % chunkMaxSize;
    var result = new List<T[]>(chunks + 1);
    var offset = 0;

    for (var i = 0; i < chunks; i++)
    {
        result.Add(new ArraySegment<T>(source,
                                       offset,
                                       chunkMaxSize).ToArray());
        offset += chunkMaxSize;
    }

    if (leftOver > 0)
    {
        result.Add(new ArraySegment<T>(source,
                                       offset,
                                       leftOver).ToArray());
    }

    return result;
}
</code>```

Body:
I'm looking for the quickest method to split an array into chunks of fixed size (last one can be smaller, of course). I've looked throughout the site and didn't find any performance-wise comparisons, so I wrote them, and here are the results:

Time in microseconds, mean/error/stddev

For int[] - 30.02 | 0.1002 | 0.0937

For IEnumerable<int> - 76.67 | 0.2146 | 0.1902

Update: Version below (in @Markus' answer) is 139.5 | 0.6702 | 0.5597

Most popular here on SO and frequently recommended method to use LINQ's  GroupBy with index/chunkSize is a no go - 267 microseconds is way too greater than either of aforementioned implementations.

Is there any faster way to split arrays?

P.S.
This is the code for Array and IEnumerable<T>:

    ///
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="source">Array to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this T[] source, int chunkMaxSize)
    {
        var pos = 0;
        var sourceLength = source.Length;
        do
        {
            var len = Math.Min(pos + chunkMaxSize, sourceLength) - pos;
            if (len == 0)
            {
                yield break;;
            }
            var arr = new T[len];
            Array.Copy(source, pos, arr, 0, len);
            pos += len;
            yield return arr;
        } while (pos < sourceLength);
    }

    ///
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="source"><see cref="IEnumerable{T}"/> to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this IEnumerable<T> source, int chunkMaxSize)
    {
        var arr = new T[chunkMaxSize];
        var pos = 0;
        foreach (var item in source)
        {
            arr[pos++] = item;
            if (pos == chunkMaxSize)
            {
                yield return arr;
                arr = new T[chunkMaxSize];
                pos = 0;
            }
        }
        if (pos > 0)
        {
            Array.Resize(ref arr, pos);
            yield return arr;
        }
    }

P.P.S Complete solution with BenchmarkDotNet tests is on GitHub.

Body:
Not really sure how this stacks up (ArraySegment), but give it a try. I've avoided using iterators but not really sure if that is really a gain here.

public static IEnumerable<T[]> AsChunks<T>(
    this T[] source, int chunkMaxSize)
{
    var chunks = source.Length / chunkMaxSize;
    var leftOver = source.Length % chunkMaxSize;
    var result = new List<T[]>(chunks + 1);
    var offset = 0;

    for (var i = 0; i < chunks; i++)
    {
        result.Add(new ArraySegment<T>(source,
                                       offset,
                                       chunkMaxSize).ToArray());
        offset += chunkMaxSize;
    }

    if (leftOver > 0)
    {
        result.Add(new ArraySegment<T>(source,
                                       offset,
                                       leftOver).ToArray());
    }

    return result;
}


答:
thanks everyone, it worked like this.</p>

```<code>var arr = [];
$(".button").each(function () {
  arr.push($(this).attr('id'));
        })
console.log(arr);
</code>```

Title: Array is giving an undefined in jquery

Body:
thanks everyone, it worked like this.

var arr = [];
$(".button").each(function () {
  arr.push($(this).attr('id'));
        })
console.log(arr);


问:
ReactiveUI: Return value from a custom dialog
I have a window that uses a ReactiveUI Interaction to open a second window as a modal dialog, then return data from a ListBox in the second window.

The problem is that when .ShowDialog() completes, the ViewModel's SelectedItem always evaluates to null. I've confirmed that the binding is working correctly, and the selected item is getting updated in the dialog window's ViewModel properly. It's only when I return to the Interaction that the property resets to its default value (null).

I've put together a minimal example of the issue here:

https://github.com/replicaJunction/ReactiveDialogTest

The main logic under test is in MainWindowViewModel.cs.

Edit: Here's a snippet from the code with the basic idea:

```<code>GetNumberFromDialog = new Interaction<Unit, int>();
GetNumberFromDialog.RegisterHandler(interaction =>
{
    var vm = new DialogWindowViewModel();

    // Get a reference to the view for this VM
    var view = Locator.Current.GetService<IViewFor<DialogWindowViewModel>>();

    // Set its VM to our current reference
    view.ViewModel = vm;

    var window = view as Window;
    var dialogResult = window.ShowDialog();

    // At this point, vm.SelectedNumber is expected be the number the user selected -
    // but instead, it always evaluates to 0.

    if (true == dialogResult)
        interaction.SetOutput(vm.SelectedNumber);
    else
        interaction.SetOutput(-1);
});

OpenDialog = ReactiveCommand.Create(() =>
{
    GetNumberFromDialog.Handle(Unit.Default)
        .Where(retVal => -1 != retVal) // If the dialog did not return true, don't update
        .Subscribe(retVal =>
        {
            this.MyNumber = retVal;
        });
});
</code>```

Steps to reproduce the issue:

Run the project. Note the label with the -5000 - this is the number to update.

Click the "Open Dialog" button. A dialog window opens.

Select a number in the ListBox. Note that the label under "Current Selection" updates - this is bound to the same value as the ListBox.SelectedItem.

Click OK. The dialog closes.

Expected behavior: the label in the main window beneath "my number is" should update to the value you selected in the ListBox.

Actual behavior: the label updates to 0 (default value for int).

Why is my ViewModel resetting itself when the dialog closes?

答:
Looking at your sample on GitHub helps to reveal the issue.  Your DialogWindow looks like this:

```<code>public partial class DialogWindow : Window, IViewFor<DialogWindowViewModel>
{
    public DialogWindow()
    {
        InitializeComponent();
        this.ViewModel = new DialogWindowViewModel();
        this.DataContext = this.ViewModel;

        this.ViewModel
            .WhenAnyValue(x => x.DialogResult)
            .Where(x => null != x)
            .Subscribe(val =>
            {
                this.DialogResult = val;
                this.Close();
            });
    }

    public DialogWindowViewModel ViewModel { get; set; }
    object IViewFor.ViewModel
    {
        get => ViewModel;
        set => ViewModel = (DialogWindowViewModel)value;
    }
}
</code>```

In your MainWindowViewModel, you set the DialogWindow.ViewModel property to a new instance of your DialogWindowViewModel.  The issue ocurrs at this point.  Your problem is that setting the DialogWindow.ViewModel property does not set the view's DataContext or re-create the WhenAnyValue observable.  This means the view is still binding to the SelectedNumber property on the old instance of the DialogWindowViewModel (the one created in the DialogWindow constructor).  To fix your sample code above, you can simply avoid setting the ViewModel property, and use the ViewModel that's already set on the dialog:

```<code>GetNumberFromDialog.RegisterHandler(interaction =>
{
    // Get a reference to the view for this VM
    var view = Locator.Current.GetService<IViewFor<DialogWindowViewModel>>();

    var window = view as Window;
    var dialogResult = window.ShowDialog();

    // use the ViewModel here that's already set on the DialogWindow
    if (true == dialogResult)
        interaction.SetOutput(view.ViewModel.SelectedNumber);
    else
        interaction.SetOutput(-1);
});
</code>```

Body:
I have a window that uses a ReactiveUI Interaction to open a second window as a modal dialog, then return data from a ListBox in the second window.

The problem is that when .ShowDialog() completes, the ViewModel's SelectedItem always evaluates to null. I've confirmed that the binding is working correctly, and the selected item is getting updated in the dialog window's ViewModel properly. It's only when I return to the Interaction that the property resets to its default value (null).

I've put together a minimal example of the issue here:

https://github.com/replicaJunction/ReactiveDialogTest

The main logic under test is in MainWindowViewModel.cs.

Edit: Here's a snippet from the code with the basic idea:

GetNumberFromDialog = new Interaction<Unit, int>();
GetNumberFromDialog.RegisterHandler(interaction =>
{
    var vm = new DialogWindowViewModel();

    // Get a reference to the view for this VM
    var view = Locator.Current.GetService<IViewFor<DialogWindowViewModel>>();

    // Set its VM to our current reference
    view.ViewModel = vm;

    var window = view as Window;
    var dialogResult = window.ShowDialog();

    // At this point, vm.SelectedNumber is expected be the number the user selected -
    // but instead, it always evaluates to 0.

    if (true == dialogResult)
        interaction.SetOutput(vm.SelectedNumber);
    else
        interaction.SetOutput(-1);
});

OpenDialog = ReactiveCommand.Create(() =>
{
    GetNumberFromDialog.Handle(Unit.Default)
        .Where(retVal => -1 != retVal) // If the dialog did not return true, don't update
        .Subscribe(retVal =>
        {
            this.MyNumber = retVal;
        });
});

Steps to reproduce the issue:

Run the project. Note the label with the -5000 - this is the number to update.

Click the "Open Dialog" button. A dialog window opens.

Select a number in the ListBox. Note that the label under "Current Selection" updates - this is bound to the same value as the ListBox.SelectedItem.

Click OK. The dialog closes.

Expected behavior: the label in the main window beneath "my number is" should update to the value you selected in the ListBox.

Actual behavior: the label updates to 0 (default value for int).

Why is my ViewModel resetting itself when the dialog closes?

Body:
Looking at your sample on GitHub helps to reveal the issue.  Your DialogWindow looks like this:

public partial class DialogWindow : Window, IViewFor<DialogWindowViewModel>
{
    public DialogWindow()
    {
        InitializeComponent();
        this.ViewModel = new DialogWindowViewModel();
        this.DataContext = this.ViewModel;

        this.ViewModel
            .WhenAnyValue(x => x.DialogResult)
            .Where(x => null != x)
            .Subscribe(val =>
            {
                this.DialogResult = val;
                this.Close();
            });
    }

    public DialogWindowViewModel ViewModel { get; set; }
    object IViewFor.ViewModel
    {
        get => ViewModel;
        set => ViewModel = (DialogWindowViewModel)value;
    }
}

In your MainWindowViewModel, you set the DialogWindow.ViewModel property to a new instance of your DialogWindowViewModel.  The issue ocurrs at this point.  Your problem is that setting the DialogWindow.ViewModel property does not set the view's DataContext or re-create the WhenAnyValue observable.  This means the view is still binding to the SelectedNumber property on the old instance of the DialogWindowViewModel (the one created in the DialogWindow constructor).  To fix your sample code above, you can simply avoid setting the ViewModel property, and use the ViewModel that's already set on the dialog:

GetNumberFromDialog.RegisterHandler(interaction =>
{
    // Get a reference to the view for this VM
    var view = Locator.Current.GetService<IViewFor<DialogWindowViewModel>>();

    var window = view as Window;
    var dialogResult = window.ShowDialog();

    // use the ViewModel here that's already set on the DialogWindow
    if (true == dialogResult)
        interaction.SetOutput(view.ViewModel.SelectedNumber);
    else
        interaction.SetOutput(-1);
});


问:
FAILED Not logged in. Use 'cf login' to log in
I have two Jenkins jobs calling a third job in parallel.

The third job contains :

login to cloud foundry which is a diff job.

doing something.

Logout from cloud foundry which is a diff job as well.

When running the two jobs in parallel and one of them finish first, the second one fails with the below error:

```<code>FAILED
Not logged in. Use 'cf login' to log in.
</code>```

Could someone help me to solve this?

Many things :)

答:
The cf CLI caches your refresh token and other information locally in $CF_HOME/.cf/config.json. When you call the third job in parallel, one process could be updating (or deleting from) that file while the other process tries to read from it, causing unexpected results as you're seeing.

You could set environment variable CF_HOME to something unique, e.g. to a random unique folder you create in /tmp, or to a folder with the invoking job's number if available, to ensure the processes do not collide:

CF_HOME=$(mktemp -d /tmp/cfhome.XXXXXXXXX)
cf auth ...
cf ...
cf logout
rm -rf $CF_HOME

Body:
I have two Jenkins jobs calling a third job in parallel.

The third job contains :

login to cloud foundry which is a diff job.

doing something.

Logout from cloud foundry which is a diff job as well.

When running the two jobs in parallel and one of them finish first, the second one fails with the below error:

FAILED
Not logged in. Use 'cf login' to log in.

Could someone help me to solve this?

Many things :)


问:
Ajax call failing to get the return message from web api service
I am making a simple ajax call to the web api service that serves an authentication routine.
My problem is the ajax call can make a request to the service but errors out once the service returns a boolean value.

WHAT I WANT:

All i want to do is check if the returned boolean is true or false. If true i want to redirect the user to another page.
Could somebody please help me out on this?

JQUERY CODE:

```<code><script type="text/javascript">
$(document).ready(function () {
    $('#submitButton').click(function () {
        var name = $(userNameTextBox).val);
        var pass = $(passwordTextBox).val();
        if (name.length == 0 || pass.length == 0) {
            alert("Please enter your credentials");
        }
        else {
             $.ajax({
                url: "http://localhost:50503/api/Authentication/Authenticate",
                data: { userName: name, passWord: pass },
                cache: false,
                type: 'GET',
                dataType: 'json',
                success: function (msg) {

                    alert(msg);
                },
                error: function (msg) {
                    alert("Error Message: "+msg);
                }
            });

        }//end of else
    });
});
</script>
</code>```

Here is my webapi service

```<code>public class AuthenticationController : ApiController
{
    [HttpGet]
    [Route("api/Authentication/Authenticate")]
    public bool Authenticate(string userName,string passWord)
    {
        if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
</code>```

答:
Try to use (worked for me, check responseJSON.Message of first parameter object):</p>

```<code>$.post(url, jsonData).
done(function (data) {}).
fail(function (xhr, status, err) {
   alert("Error " + err + ". " + xhr.responseJSON.Message);
});
</code>```

Body:
I am making a simple ajax call to the web api service that serves an authentication routine.
My problem is the ajax call can make a request to the service but errors out once the service returns a boolean value.

WHAT I WANT:

All i want to do is check if the returned boolean is true or false. If true i want to redirect the user to another page.
Could somebody please help me out on this?

JQUERY CODE:

Here is my webapi service

public class AuthenticationController : ApiController
{
    [HttpGet]
    [Route("api/Authentication/Authenticate")]
    public bool Authenticate(string userName,string passWord)
    {
        if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Body:
Try to use (worked for me, check responseJSON.Message of first parameter object):

$.post(url, jsonData).
done(function (data) {}).
fail(function (xhr, status, err) {
   alert("Error " + err + ". " + xhr.responseJSON.Message);
});


问:
Custom Initialize AppInsights through asp.net code
I am trying to turn on/off the appinsights in my asp.net code proramatically based on the flag returned from DB. When i research, I found the below settings in app_start. But not sure if the samething can be achieved in anywhere of the code dynamically

Disable application insights in debug

Please let me know your suggestions.

Thank you!

答:
Yes, it is possible.  many people do similar to not necessarily "disable" AI, but to send telemetry to different resources based on environment (dev/test/staging/prod/etc)

https://blogs.msdn.microsoft.com/devops/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions/

you can disable telemetry the way the link you linked did, or you could send telemetry to different resources (or no resource at all)


问:
React Redux <No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access>
I'm using React + Redux  + RoR in app. I have to do social login. For client-side I use davezuko/react-redux-starter-kit, and it's located on localhost:3000. My server - localhost:5000. All request from client to server have no problem (PUT,GET,POST). When I try login using twitter (it's work on server, localhost:5000/auth/twitter - create new user in DB with params from twitter) I have an error :

```<code>Failed to load https://api.twitter.com/oauth/authenticate?oauth_token=xxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
</code>```

on client-side I call this like:

```<code>export const requestTest = async () => {
return axios.get('http://localhost:5000/auth/twitter', {}).then(function (response) {
        console.log('cors')
    console.log(response)
    return response.data
})
</code>```

};

How can I fix it?

答:
If your React dev server origin is differs from Rails application server origin (even just by port number), Rails thinks that request is cross-origin.

When Rails receives such request it denies it unless CORS policy is set up.

The easiest way to do so is (probably) to use rack-cors gem:

1)
Add

```<code>gem 'rack-cors', require: 'rack/cors'
</code>```

to your Gemfile.

2) bundle install

3) add

```<code># see gem page for more examples
config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins /\Ahttp:\/\/localhost:\d+\z/
    resource '*', headers: :any, methods: :any
  end
end
</code>```

in class Application < Rails::Application inside your config/application.rb.

4) restart rails.

Body:
I'm using React + Redux  + RoR in app. I have to do social login. For client-side I use davezuko/react-redux-starter-kit, and it's located on localhost:3000. My server - localhost:5000. All request from client to server have no problem (PUT,GET,POST). When I try login using twitter (it's work on server, localhost:5000/auth/twitter - create new user in DB with params from twitter) I have an error :

Failed to load https://api.twitter.com/oauth/authenticate?oauth_token=xxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

on client-side I call this like:

export const requestTest = async () => {
return axios.get('http://localhost:5000/auth/twitter', {}).then(function (response) {
        console.log('cors')
    console.log(response)
    return response.data
})

};

How can I fix it?

Body:
If your React dev server origin is differs from Rails application server origin (even just by port number), Rails thinks that request is cross-origin.

When Rails receives such request it denies it unless CORS policy is set up.

The easiest way to do so is (probably) to use rack-cors gem:

1)
Add

gem 'rack-cors', require: 'rack/cors'

to your Gemfile.

2) bundle install

3) add

# see gem page for more examples
config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins /\Ahttp:\/\/localhost:\d+\z/
    resource '*', headers: :any, methods: :any
  end
end

in class Application < Rails::Application inside your config/application.rb.

4) restart rails.


问:
node stream not finish but emit end
I am reading this and wrote my codes based on examples.

My codes:

const through = require('through2');
const bluebird = require('bluebird');

```<code>function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    stream.resume();
    stream.on("end", resolve);
    stream.on("error", reject);
  });
};

module.exports = {
  up: function up() {
    console.log('startstream');
    // Doc is sequelize Model
    const stream = Doc.createReadStream({
      include: [
        {
          repository: AssociatedRepo,
          as: 'on',
          required: false,
        },
      ],
    });

    stream.pipe(through({ objectMode: true }, (doc, enc, cb) => {
      console.log('docid', doc.id);
      return doc.destroy()
        .then(() => cb());
    }));
    return streamToPromise(stream).then((data) => {
      console.log('xxxxxxxxxx', data);
      return null;
    });
  },
};
</code>```

I tried to use the above program to read and delete about 400 records. but from log, I found that the stream promise (streamToPromise(stream)) being resolved but still several records remaining. From log, I got:

```<code>xxxxxxxxxx undefined
docid 89934915596
</code>```

How to fix this? Thanks

答:
You'll need to wait for the end of the destination stream of the pipe, currently you are only waiting for the input stream. Use

```<code>const res = stream.pipe(through({objectMode: true}, …));
return streamToPromise(res);
</code>```

Title: node stream not finish but emit end

Body:
I am reading this and wrote my codes based on examples.

My codes:

const through = require('through2');
const bluebird = require('bluebird');

function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    stream.resume();
    stream.on("end", resolve);
    stream.on("error", reject);
  });
};

module.exports = {
  up: function up() {
    console.log('startstream');
    // Doc is sequelize Model
    const stream = Doc.createReadStream({
      include: [
        {
          repository: AssociatedRepo,
          as: 'on',
          required: false,
        },
      ],
    });

    stream.pipe(through({ objectMode: true }, (doc, enc, cb) => {
      console.log('docid', doc.id);
      return doc.destroy()
        .then(() => cb());
    }));
    return streamToPromise(stream).then((data) => {
      console.log('xxxxxxxxxx', data);
      return null;
    });
  },
};

I tried to use the above program to read and delete about 400 records. but from log, I found that the stream promise (streamToPromise(stream)) being resolved but still several records remaining. From log, I got:

xxxxxxxxxx undefined
docid 89934915596

How to fix this? Thanks

Body:
You'll need to wait for the end of the destination stream of the pipe, currently you are only waiting for the input stream. Use

const res = stream.pipe(through({objectMode: true}, …));
return streamToPromise(res);


问:
Agnostic way to match and wrap all strings in body (Without having to know the html structure)
I have a file strings.json which contains

```<code>{
  "fname": "First Name",
  "lname": "Last Name",
  "email": "Email"
}
</code>```

I have another file index.html which contains

```<code>  First name <input type="text" name="fname">
  Last name
  Email
</code>```

If the html file contains a string that exists in the json file, I'd like to wrap it with a span and data-attribute, using Javascript or JQuery, for example:

```<code> <span data-string="fname">First name</span><input type="text" name="fname">
 <span data-string="lname">Last name</span>
 <span data-string="email">Email</span>
</code>```

I don't want solutions like this question, my question is a lot similar but the key difference is that I want an agnostic code, that will work without knowing the structure of the html,and I don't want regex that is specific for one structure either.

You just give it string in body, it wraps all the results in a span like shown above and that's it. I haven't found an agnostic way yet. Another example is this question, not agnostic either, you have to know the html structure for it to work.

Markjs didn't work for 2 reasons:

I want to use it to select strings, it's highlighting them and I don't know how to turn highlight off

More importantly :

```<code>var myString = $("body").mark("Hi");
console.log(myString);
// returns

translate.html:17 r.fn.init(1)0: bodyaLink: ""accessKey: ""assignedSlot: nullattributes: NamedNodeMap {length: 0}background: ""baseURI: "file:///home/elie/Desktop/csc/translate.html"bgColor: ""childElementCount: 7childNodes: (14) [text, h1, br, text, mark, text, script, text, script, text, script, text, script, text]children: (7) [h1, br, mark, script, script, script, script]classList: [value: ""]className: ""clientHeight: 88clientLeft: 0clientTop: 0clientWidth: 1264contentEditable: "inherit"dataset: DOMStringMap {}dir: ""draggable: falsefirstChild: textfirstElementChild: h1hidden: falseid: ""innerHTML: "↵   <h1><mark data-markjs="true">Hi</mark>,</h1><br>↵   T<mark data-markjs="true">hi</mark>s is the text that will be translated↵↵↵<script src="jquery-3.2.1.min.js"></script>↵<script src="jquery.mark.min.js"></script>↵<script src="jquery.localize.min.js"></script>↵↵<script type="text/javascript">↵var myString = $("body").mark("Hi");↵console.log(myString);↵</script>↵↵"innerText: "Hi,↵↵↵This is the text that will be translated"isConnected: trueisContentEditable: falselang: ""lastChild: textlastElementChild: scriptlink: ""localName: "body"namespaceURI: "http://www.w3.org/1999/xhtml"nextElementSibling: nullnextSibling: nullnodeName: "BODY"nodeType: 1nodeValue: nullnonce: ""offsetHeight: 88offsetLeft: 0offsetParent: nulloffsetTop: 0offsetWidth: 1264onabort: nullonauxclick: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonbeforeunload: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nullongotpointercapture: nullonhashchange: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonlanguagechange: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonlostpointercapture: nullonmessage: nullonmessageerror: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonoffline: nullononline: nullonpagehide: nullonpageshow: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonpointercancel: nullonpointerdown: nullonpointerenter: nullonpointerleave: nullonpointermove: nullonpointerout: nullonpointerover: nullonpointerup: nullonpopstate: nullonprogress: nullonratechange: nullonrejectionhandled: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonstalled: nullonstorage: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonunhandledrejection: nullonunload: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<body>↵ <h1><mark data-markjs="true">Hi</mark>,</h1><br>↵   T<mark data-markjs="true">hi</mark>s is the text that will be translated↵↵↵<script src="jquery-3.2.1.min.js"></script>↵<script src="jquery.mark.min.js"></script>↵<script src="jquery.localize.min.js"></script>↵↵<script type="text/javascript">↵var myString = $("body").mark("Hi");↵console.log(myString);↵</script>↵↵</body>"outerText: "Hi,↵↵↵This is the text that will be translated"ownerDocument: documentparentElement: htmlparentNode: htmlprefix: nullpreviousElementSibling: headpreviousSibling: textscrollHeight: 88scrollLeft: 0scrollTop: 0scrollWidth: 1264shadowRoot: nullslot: ""spellcheck: truestyle: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}tabIndex: -1tagName: "BODY"text: ""textContent: "↵  Hi,↵    This is the text that will be translated↵↵↵↵↵↵↵↵var myString = $("body").mark("Hi");↵console.log(myString);↵↵↵"title: ""translate: truevLink: ""__proto__: HTMLBodyElementlength: 1prevObject: [document]__proto__: Object(0)
</code>```

I want console.log to return Hi

答:
Dave Gilem's replacer is a good start, but you need to recursively traverse through the DOM and apply it only to text nodes. This solution relies on jQuery. While DOM traversing using jQuery.each() is much slower, it's by far the easiest way to create a new HTML node in place of a matching string.

```<code>/**
  * replace text with <span> according to the wrapList
  * @param {Object} $elem jQuery DOM Object of a text node
  */
function replaceText($elem) {
    var pattern,
        textcontent  = $elem.text(),
        wrapList = {
            "fname": "First name",
            "lname": "Last name",
            "email": "Email"
            };

    for (const key in wrapList) {
        if (wrapList.hasOwnProperty(key)) {
            pattern = new RegExp(wrapList[key], 'g');
            // as we do a DOM manipulation, we only want to do it if necessary
            if (pattern.test(textcontent)) {
                // replace the text node with new text. $& in JS equals $0 in other languages
                textcontent = textcontent.replace(pattern,'<span data-string="'+key+'">$&</span>');
            }
        }
    }
    // a change has been made
    if (textcontent != $elem.text()) {
        $elem.replaceWith(textcontent);
    }
}

/**
  * loop through DOM nodes recursively and call replaceText() on text nodes
  * @param {Object} $elem jQuery DOM Object
  */
function replaceRecursive($elem) {
    // get the nodeType of the object's DOM node
    var nt = $elem.get(0).nodeType;
    if (nt === 3) {
        // type 3 is a text node: replace the text
        replaceText($elem);
    } else if(nt === 1) {
        // type 1 is a DOM element: loop through the child objects recursively
        $elem.contents().each(function () {
            replaceRecursive($(this));
        });
    }
}

// start with the <body> tag
replaceRecursive($('body'));
</code>```

jsfiddle

EDIT: There was a bug: Using replaceWith() in the for loop always updated the content. If there were multiple occurrences of search terms in the node, it only replaced the last one.

Body:
I have a file strings.json which contains

{
  "fname": "First Name",
  "lname": "Last Name",
  "email": "Email"
}

I have another file index.html which contains

  First name <input type="text" name="fname">
  Last name
  Email

If the html file contains a string that exists in the json file, I'd like to wrap it with a span and data-attribute, using Javascript or JQuery, for example:

 First name<input type="text" name="fname">
 Last name
 Email

I don't want solutions like this question, my question is a lot similar but the key difference is that I want an agnostic code, that will work without knowing the structure of the html,and I don't want regex that is specific for one structure either.

You just give it string in body, it wraps all the results in a span like shown above and that's it. I haven't found an agnostic way yet. Another example is this question, not agnostic either, you have to know the html structure for it to work.

Markjs didn't work for 2 reasons:

I want to use it to select strings, it's highlighting them and I don't know how to turn highlight off

More importantly :

var myString = $("body").mark("Hi");
console.log(myString);
// returns

translate.html:17 r.fn.init(1)0: bodyaLink: ""accessKey: ""assignedSlot: nullattributes: NamedNodeMap {length: 0}background: ""baseURI: "file:///home/elie/Desktop/csc/translate.html"bgColor: ""childElementCount: 7childNodes: (14) [text, h1, br, text, mark, text, script, text, script, text, script, text, script, text]children: (7) [h1, br, mark, script, script, script, script]classList: [value: ""]className: ""clientHeight: 88clientLeft: 0clientTop: 0clientWidth: 1264contentEditable: "inherit"dataset: DOMStringMap {}dir: ""draggable: falsefirstChild: textfirstElementChild: h1hidden: falseid: ""innerHTML: "↵
Hi,

↵   This is the text that will be translated↵↵↵↵↵↵↵↵↵"innerText: "Hi,↵↵↵This is the text that will be translated"isConnected: trueisContentEditable: falselang: ""lastChild: textlastElementChild: scriptlink: ""localName: "body"namespaceURI: "http://www.w3.org/1999/xhtml"nextElementSibling: nullnextSibling: nullnodeName: "BODY"nodeType: 1nodeValue: nullnonce: ""offsetHeight: 88offsetLeft: 0offsetParent: nulloffsetTop: 0offsetWidth: 1264onabort: nullonauxclick: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonbeforeunload: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nullongotpointercapture: nullonhashchange: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonlanguagechange: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonlostpointercapture: nullonmessage: nullonmessageerror: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonoffline: nullononline: nullonpagehide: nullonpageshow: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonpointercancel: nullonpointerdown: nullonpointerenter: nullonpointerleave: nullonpointermove: nullonpointerout: nullonpointerover: nullonpointerup: nullonpopstate: nullonprogress: nullonratechange: nullonrejectionhandled: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonstalled: nullonstorage: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonunhandledrejection: nullonunload: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "↵
Hi,

↵   This is the text that will be translated↵↵↵↵↵↵↵↵↵"outerText: "Hi,↵↵↵This is the text that will be translated"ownerDocument: documentparentElement: htmlparentNode: htmlprefix: nullpreviousElementSibling: headpreviousSibling: textscrollHeight: 88scrollLeft: 0scrollTop: 0scrollWidth: 1264shadowRoot: nullslot: ""spellcheck: truestyle: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}tabIndex: -1tagName: "BODY"text: ""textContent: "↵  Hi,↵    This is the text that will be translated↵↵↵↵↵↵↵↵var myString = $("body").mark("Hi");↵console.log(myString);↵↵↵"title: ""translate: truevLink: ""__proto__: HTMLBodyElementlength: 1prevObject: [document]__proto__: Object(0)

I want console.log to return Hi

Body:
Dave Gilem's replacer is a good start, but you need to recursively traverse through the DOM and apply it only to text nodes. This solution relies on jQuery. While DOM traversing using jQuery.each() is much slower, it's by far the easiest way to create a new HTML node in place of a matching string.

/**
  * replace text with <span> according to the wrapList
  * @param {Object} $elem jQuery DOM Object of a text node
  */
function replaceText($elem) {
    var pattern,
        textcontent  = $elem.text(),
        wrapList = {
            "fname": "First name",
            "lname": "Last name",
            "email": "Email"
            };

    for (const key in wrapList) {
        if (wrapList.hasOwnProperty(key)) {
            pattern = new RegExp(wrapList[key], 'g');
            // as we do a DOM manipulation, we only want to do it if necessary
            if (pattern.test(textcontent)) {
                // replace the text node with new text. $& in JS equals $0 in other languages
                textcontent = textcontent.replace(pattern,'<span data-string="'+key+'">$&</span>');
            }
        }
    }
    // a change has been made
    if (textcontent != $elem.text()) {
        $elem.replaceWith(textcontent);
    }
}

/**
  * loop through DOM nodes recursively and call replaceText() on text nodes
  * @param {Object} $elem jQuery DOM Object
  */
function replaceRecursive($elem) {
    // get the nodeType of the object's DOM node
    var nt = $elem.get(0).nodeType;
    if (nt === 3) {
        // type 3 is a text node: replace the text
        replaceText($elem);
    } else if(nt === 1) {
        // type 1 is a DOM element: loop through the child objects recursively
        $elem.contents().each(function () {
            replaceRecursive($(this));
        });
    }
}

// start with the <body> tag
replaceRecursive($('body'));

jsfiddle

EDIT: There was a bug: Using replaceWith() in the for loop always updated the content. If there were multiple occurrences of search terms in the node, it only replaced the last one.


问:
C++ - class issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

```<code>#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}
</code>```

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

答:
The error is because strncpy is declared in the cstring header file.

A pointer is used because you are working with C strings, which are char arrays. Arrays in C are used through pointers. And strncpy takes two pointers to char(char arrays) to do the copy process.

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.


问:
Gaps and Island - Microsoft Access
I am trying to group my data by: State, Product, Edition, LG_SG, Area, and Area Factor. I then want to attach the minimum start date and the maximum end date to the record. I have a Gaps and Island issue though. If you look at the data, the .8428 shows up in two blocks that are not in chronological order. How do I solve this problem in Access?

Here is my current data.

```<code>state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   11/1/2010   PPO 6   SG  1   0.86
IL  11/1/2010   12/1/2010   PPO 6   SG  1   0.86
IL  12/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    2/1/2011    PPO 6   SG  1   0.8428
IL  2/1/2011    3/1/2011    PPO 6   SG  1   0.8428
IL  3/1/2011    4/1/2011    PPO 6   SG  1   0.8428
IL  4/1/2011    5/1/2011    PPO 6   SG  1   0.8428
IL  5/1/2011    6/1/2011    PPO 6   SG  1   0.8428
IL  6/1/2011    7/1/2011    PPO 6   SG  1   0.8428
IL  7/1/2011    8/1/2011    PPO 6   SG  1   0.8428
IL  8/1/2011    9/1/2011    PPO 6   SG  1   0.8428
IL  9/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   11/1/2011   PPO 6   SG  1   0.825944
IL  11/1/2011   12/1/2011   PPO 6   SG  1   0.825944
IL  12/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    2/1/2012    PPO 6   SG  1   0.8428
IL  2/1/2012    3/1/2012    PPO 6   SG  1   0.8428
IL  3/1/2012    4/1/2012    PPO 6   SG  1   0.8428
IL  4/1/2012    5/1/2012    PPO 6   SG  1   0.8428
</code>```

I would like it to look like this.

```<code>state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    5/1/2012    PPO 6   SG  1   0.8428
</code>```

Thank you all for your help.

答:
Consider using the autonumber id field (assuming one exists) to create a distinct groups, grp, and then aggregate in outer query:

```<code>SELECT r.state, Min(r.start_date) as min_start_date, Max(r.end_date) as
       max_end_date, r.product, r.edition, r.lg_sg, Max(r.area) as max_area,
       r.area_factor
FROM
  (SELECT *,
            (SELECT max(id) FROM GapsIslandsTable sub
             WHERE sub.area_factor = g.area_factor
               AND Year(sub.start_date) = Year(g.start_date)) as grp
   FROM GapsIslandsTable g) r

GROUP BY r.state, r.product, r.edition, r.lg_sg, r.area_factor, r.grp

-- state    min_start_date  max_end_date    product edition lg_sg   max_area   area_factor
-- IL            10/1/2011      1/1/2012        PPO       6    SG          1      0.825944
-- IL             1/1/2011     10/1/2011        PPO       6    SG          1        0.8428
-- IL             1/1/2012      5/1/2012        PPO       6    SG          1        0.8428
-- IL            10/1/2010      1/1/2011        PPO       6    SG          1          0.86
</code>```

Title: Gaps and Island - Microsoft Access

Body:
I am trying to group my data by: State, Product, Edition, LG_SG, Area, and Area Factor. I then want to attach the minimum start date and the maximum end date to the record. I have a Gaps and Island issue though. If you look at the data, the .8428 shows up in two blocks that are not in chronological order. How do I solve this problem in Access?

Here is my current data.

state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   11/1/2010   PPO 6   SG  1   0.86
IL  11/1/2010   12/1/2010   PPO 6   SG  1   0.86
IL  12/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    2/1/2011    PPO 6   SG  1   0.8428
IL  2/1/2011    3/1/2011    PPO 6   SG  1   0.8428
IL  3/1/2011    4/1/2011    PPO 6   SG  1   0.8428
IL  4/1/2011    5/1/2011    PPO 6   SG  1   0.8428
IL  5/1/2011    6/1/2011    PPO 6   SG  1   0.8428
IL  6/1/2011    7/1/2011    PPO 6   SG  1   0.8428
IL  7/1/2011    8/1/2011    PPO 6   SG  1   0.8428
IL  8/1/2011    9/1/2011    PPO 6   SG  1   0.8428
IL  9/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   11/1/2011   PPO 6   SG  1   0.825944
IL  11/1/2011   12/1/2011   PPO 6   SG  1   0.825944
IL  12/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    2/1/2012    PPO 6   SG  1   0.8428
IL  2/1/2012    3/1/2012    PPO 6   SG  1   0.8428
IL  3/1/2012    4/1/2012    PPO 6   SG  1   0.8428
IL  4/1/2012    5/1/2012    PPO 6   SG  1   0.8428

I would like it to look like this.

state   start_date  end_date    product edition lg_sg   area    area_factor
IL  10/1/2010   1/1/2011    PPO 6   SG  1   0.86
IL  1/1/2011    10/1/2011   PPO 6   SG  1   0.8428
IL  10/1/2011   1/1/2012    PPO 6   SG  1   0.825944
IL  1/1/2012    5/1/2012    PPO 6   SG  1   0.8428

Thank you all for your help.

Body:
Consider using the autonumber id field (assuming one exists) to create a distinct groups, grp, and then aggregate in outer query:

SELECT r.state, Min(r.start_date) as min_start_date, Max(r.end_date) as
       max_end_date, r.product, r.edition, r.lg_sg, Max(r.area) as max_area,
       r.area_factor
FROM
  (SELECT *,
            (SELECT max(id) FROM GapsIslandsTable sub
             WHERE sub.area_factor = g.area_factor
               AND Year(sub.start_date) = Year(g.start_date)) as grp
   FROM GapsIslandsTable g) r

GROUP BY r.state, r.product, r.edition, r.lg_sg, r.area_factor, r.grp

-- state    min_start_date  max_end_date    product edition lg_sg   max_area   area_factor
-- IL            10/1/2011      1/1/2012        PPO       6    SG          1      0.825944
-- IL             1/1/2011     10/1/2011        PPO       6    SG          1        0.8428
-- IL             1/1/2012      5/1/2012        PPO       6    SG          1        0.8428
-- IL            10/1/2010      1/1/2011        PPO       6    SG          1          0.86