问:
How to use automatically move respondents in Qualtrics with global timer for Block with multiple page break?

.header-cont {
   width:100%;
   position:fixed;
   top:0px;
   z-index:1000;
 }
 .header {
   height:auto;
   background:#FFFFFF;
   width:100%;
   top: 0px;
 margin:0px auto;
   position:fixed;
  z-index:1000;
 }
 .timer{
   width: 500px;
   margin: auto;
   text-align: center;
   vertical-align: middle;
   line-height: 50px;
   font-size: 28px;
 }```
</div>
</div>
</p>

<p>in my Survey I have multiple questions separated with page break in the block, I want to use the same timer for the entire questions, even though the questions will displays at different pages. I have sample code that can count but nothing happened after the timer is over. the result is not auto submitted. after the timers is up I want to redirect the users to answer some bio questions. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Qualtrics.SurveyEngine.addOnload(function()
{

var header = document.createElement("div");
 header.className = "header"
 header.id = "header_1";

var timer = document.createElement("div");
 timer.className = "timer";
 timer.id = "timer_1";
 timer.innerHTML = "Time Remaining: <span id='time'>02:00</span>";

header.appendChild(timer);
document.body.insertBefore(header, document.body.firstChild);

function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  var myTimer = setInterval(function() {
   minutes = parseInt(timer / 60, 10)
   seconds = parseInt(timer % 60, 10);
   minutes = minutes < 10 ? "0" + minutes : minutes;
   seconds = seconds < 10 ? "0" + seconds : seconds;
   var text = ('innerText' in display)? 'innerText' : 'textContent';
   display[text] = minutes + ":" + seconds;
   if (--timer < 0) {
    clearInterval(myTimer);
    timeOver();
   }
  }, 1000);
 }
 var timerSeconds = 120,
 display = document.querySelector('#time');
 startTimer(timerSeconds, display);
 var timeOver = function() {
  document.getElementById("timer_1").innerHTML = "Time is up.";
  x = 1;
  var bgColor = setInterval(change, 1000);
 }

});</code>```

答:
You can pass the time remaining from one page to the next using an embedded data variable, and you can use the embedded data variable in question display logic so that once time is up, you don't display the remaining questions. You can advance to the next page by clicking the next button.

In your survey flow initialize the embedded data variable timeRemaining before the question block:

```<code>timeRemaining = 120
</code>```

Then in your code timerSeconds gets set to timeRemaining:

```<code>var timerSeconds = parseInt("${e://Field/timeRemaining}");
</code>```

In your startTimer function, update timeRemaining:

```<code>Qualtrics.SurveyEngine.setEmbeddedData('timeRemaining', timer);
</code>```

Then at the end of your timeOver function go to the next page:

```<code>$('NextButton').click();
</code>```

Your display logic on all questions except the first:

```<code>if timeRemaining > 0
</code>```

Copy your script to the first question on each page in the block.

Body:
.header-cont {
   width:100%;
   position:fixed;
   top:0px;
   z-index:1000;
 }
 .header {
   height:auto;
   background:#FFFFFF;
   width:100%;
   top: 0px;
 margin:0px auto;
   position:fixed;
  z-index:1000;
 }
 .timer{
   width: 500px;
   margin: auto;
   text-align: center;
   vertical-align: middle;
   line-height: 50px;
   font-size: 28px;
 }

in my Survey I have multiple questions separated with page break in the block, I want to use the same timer for the entire questions, even though the questions will displays at different pages. I have sample code that can count but nothing happened after the timer is over. the result is not auto submitted. after the timers is up I want to redirect the users to answer some bio questions.

Qualtrics.SurveyEngine.addOnload(function()
{

var header = document.createElement("div");
 header.className = "header"
 header.id = "header_1";

var timer = document.createElement("div");
 timer.className = "timer";
 timer.id = "timer_1";
 timer.innerHTML = "Time Remaining: 02:00";

header.appendChild(timer);
document.body.insertBefore(header, document.body.firstChild);

function startTimer(duration, display) {
  var timer = duration, minutes, seconds;
  var myTimer = setInterval(function() {
   minutes = parseInt(timer / 60, 10)
   seconds = parseInt(timer % 60, 10);
   minutes = minutes < 10 ? "0" + minutes : minutes;
   seconds = seconds < 10 ? "0" + seconds : seconds;
   var text = ('innerText' in display)? 'innerText' : 'textContent';
   display[text] = minutes + ":" + seconds;
   if (--timer < 0) {
    clearInterval(myTimer);
    timeOver();
   }
  }, 1000);
 }
 var timerSeconds = 120,
 display = document.querySelector('#time');
 startTimer(timerSeconds, display);
 var timeOver = function() {
  document.getElementById("timer_1").innerHTML = "Time is up.";
  x = 1;
  var bgColor = setInterval(change, 1000);
 }

});

Body:
You can pass the time remaining from one page to the next using an embedded data variable, and you can use the embedded data variable in question display logic so that once time is up, you don't display the remaining questions. You can advance to the next page by clicking the next button.

In your survey flow initialize the embedded data variable timeRemaining before the question block:

timeRemaining = 120

Then in your code timerSeconds gets set to timeRemaining:

var timerSeconds = parseInt("${e://Field/timeRemaining}");

In your startTimer function, update timeRemaining:

Qualtrics.SurveyEngine.setEmbeddedData('timeRemaining', timer);

Then at the end of your timeOver function go to the next page:

$('NextButton').click();

Your display logic on all questions except the first:

if timeRemaining > 0

Copy your script to the first question on each page in the block.


来源: stackexchange

问:
How to use same form code for add,update

test.kv

:kivy 1.10.0

```<code><CRUD>:
    title: self.mode + " State"
    size_hint: None, None
    size: 350, 350
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                text: root.label_rec_id
            Label:
                id: userid
                text: root.col_data[0]  # root.userid
            Label:
                text: "First Name"
            TextInput:
                id: fname
                text: root.col_data[1]  # root.fname
            Label:
                text: "Last Name"
            TextInput:
                id: lname
                text: root.col_data[2]  # root.lname
        Button:
            size_hint: 1, 0.4
            text: "Save Changes"
            on_release:
                root.package_changes(fname.text, lname.text)
                app.root.update_changes(root)
                root.dismiss()
        Button:
            size_hint: 1, 0.4
            text: "Cancel Changes"
            on_release: root.dismiss()
</code>```

when click on any row then edit form open.Can i use same form for add user.

At this time i click on add user then user.py file run and open a new form.how to use same form for both add update.

答:
Yes, you can use the same form to add city. In the example, I added a button, a method add_record, some variable e.g. mode of type StringProperty, and INSERT SQL command. Please refer to the example for details.

Example

main.py

```<code>import kivy

kivy.require('1.10.0')  # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.lang import Builder

from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window

Window.size = (500, 500)

MAX_TABLE_COLS = 3

con = lite.connect('company.db')
# con.text_factory = str
cur = con.cursor()

class CRUD(Popup):
    """CRUD - Create, Read, Update, Delete"""
    label_id_text = ObjectProperty(None)
    label_id_data = ObjectProperty(None)

    mode = StringProperty("")
    label_rec_id = StringProperty("UserID")
    start_point = NumericProperty(0)
    col_data = ListProperty(["", "", ""])

    def __init__(self, obj, **kwargs):
        super(CRUD, self).__init__(**kwargs)
        self.mode = obj.mode
        if obj.mode == "Add":
            self.label_id_text.opacity = 0  # invisible
            self.label_id_data.opacity = 0  # invisible
        else:
            self.label_id_text.opacity = 1  # visible
            self.label_id_data.opacity = 1  # visible
            self.start_point = obj.start_point
            self.col_data[0] = obj.rv_data[obj.start_point]["text"]
            self.col_data[1] = obj.rv_data[obj.start_point + 1]["text"]
            self.col_data[2] = obj.rv_data[obj.start_point + 2]["text"]

    def package_changes(self, fname, lname):
        self.col_data[1] = fname
        self.col_data[2] = lname

class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleGridLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)
    mode = StringProperty("")

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
        self.rv_data = rv.data

    def on_press(self):
        self.mode = "Update"
        self.start_point = 0
        end_point = MAX_TABLE_COLS
        rows = len(self.rv_data) // MAX_TABLE_COLS
        for row in range(rows):
            if self.index in list(range(end_point)):
                break
            self.start_point += MAX_TABLE_COLS
            end_point += MAX_TABLE_COLS

        popup = CRUD(self)
        popup.open()

class RV(BoxLayout):
    rv_data = ListProperty([])
    start_point = NumericProperty(0)
    mode = StringProperty("")

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_users()

    def get_users(self):
        '''This result retrieve from database'''
        self.rv_data = []

        cur.execute("SELECT * FROM Users ORDER BY UserID ASC")
        rows = cur.fetchall()

        # create data_items
        for row in rows:
            for col in row:
                self.rv_data.append(col)

    def add_record(self):
        self.mode = "Add"
        popup = CRUD(self)
        popup.open()

    def update_changes(self, obj):
        if obj.mode == "Add":
            # insert record into Database Table
            cur.execute("INSERT INTO Users VALUES(NULL, ?, ?)",
                        (obj.col_data[1], obj.col_data[2]))
        else:
            # update Database Table
            cur.execute("UPDATE Users SET FirstName=?, LastName=? WHERE UserID=?",
                        (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()
        self.get_users()

class ListUser(App):
    title = "Users"

    def build(self):
        self.root = Builder.load_file('main.kv')
        return RV()

if __name__ == '__main__':
    ListUser().run()
</code>```

main.kv

```<code>#:kivy 1.10.0

<CRUD>:
    label_id_text: label_id_text
    label_id_data: label_id_data

    title: self.mode + " State"
    size_hint: None, None
    size: 350, 350
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                id: label_id_text
                text: "ID"
            Label:
                id: label_id_data
                text: root.col_data[0]  # root.userid
            Label:
                text: "First Name"
            TextInput:
                id: fname
                text: root.col_data[1]  # root.fname
            Label:
                text: "Last Name"
            TextInput:
                id: lname
                text: root.col_data[2]  # root.lname
        Button:
            size_hint: 1, 0.4
            text: "Confirm " + root.mode
            on_release:
                root.package_changes(fname.text, lname.text)
                app.root.update_changes(root)
                root.dismiss()
        Button:
            size_hint: 1, 0.4
            text: "Cancel " + root.mode
            on_release: root.dismiss()

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    BoxLayout:
        orientation: "vertical"

        Button:
            size_hint: 1, 0.1
            text: "Add Record"
            on_press: root.add_record()

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                text: "ID"
            Label:
                text: "First Name"
            Label:
                text: "Last Name"

        BoxLayout:
            RecycleView:
                viewclass: 'SelectableButton'
                data: [{'text': str(x)} for x in root.rv_data]
                SelectableRecycleGridLayout:
                    cols: 3
                    default_size: None, dp(26)
                    default_size_hint: 1, None
                    size_hint_y: None
                    height: self.minimum_height
                    orientation: 'vertical'
                    multiselect: True
                    touch_multiselect: True
</code>```

Output

ContentLicense: CC BY-SA 3.0

Body:
test.kv

:kivy 1.10.0

<CRUD>:
    title: self.mode + " State"
    size_hint: None, None
    size: 350, 350
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                text: root.label_rec_id
            Label:
                id: userid
                text: root.col_data[0]  # root.userid
            Label:
                text: "First Name"
            TextInput:
                id: fname
                text: root.col_data[1]  # root.fname
            Label:
                text: "Last Name"
            TextInput:
                id: lname
                text: root.col_data[2]  # root.lname
        Button:
            size_hint: 1, 0.4
            text: "Save Changes"
            on_release:
                root.package_changes(fname.text, lname.text)
                app.root.update_changes(root)
                root.dismiss()
        Button:
            size_hint: 1, 0.4
            text: "Cancel Changes"
            on_release: root.dismiss()

when click on any row then edit form open.Can i use same form for add user.

At this time i click on add user then user.py file run and open a new form.how to use same form for both add update.

Body:
Yes, you can use the same form to add city. In the example, I added a button, a method add_record, some variable e.g. mode of type StringProperty, and INSERT SQL command. Please refer to the example for details.

Example

main.py

import kivy

kivy.require('1.10.0')  # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.lang import Builder

from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window

Window.size = (500, 500)

MAX_TABLE_COLS = 3

con = lite.connect('company.db')
# con.text_factory = str
cur = con.cursor()

class CRUD(Popup):
    """CRUD - Create, Read, Update, Delete"""
    label_id_text = ObjectProperty(None)
    label_id_data = ObjectProperty(None)

    mode = StringProperty("")
    label_rec_id = StringProperty("UserID")
    start_point = NumericProperty(0)
    col_data = ListProperty(["", "", ""])

    def __init__(self, obj, **kwargs):
        super(CRUD, self).__init__(**kwargs)
        self.mode = obj.mode
        if obj.mode == "Add":
            self.label_id_text.opacity = 0  # invisible
            self.label_id_data.opacity = 0  # invisible
        else:
            self.label_id_text.opacity = 1  # visible
            self.label_id_data.opacity = 1  # visible
            self.start_point = obj.start_point
            self.col_data[0] = obj.rv_data[obj.start_point]["text"]
            self.col_data[1] = obj.rv_data[obj.start_point + 1]["text"]
            self.col_data[2] = obj.rv_data[obj.start_point + 2]["text"]

    def package_changes(self, fname, lname):
        self.col_data[1] = fname
        self.col_data[2] = lname

class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleGridLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Button '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    rv_data = ObjectProperty(None)
    start_point = NumericProperty(0)
    mode = StringProperty("")

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
        self.rv_data = rv.data

    def on_press(self):
        self.mode = "Update"
        self.start_point = 0
        end_point = MAX_TABLE_COLS
        rows = len(self.rv_data) // MAX_TABLE_COLS
        for row in range(rows):
            if self.index in list(range(end_point)):
                break
            self.start_point += MAX_TABLE_COLS
            end_point += MAX_TABLE_COLS

        popup = CRUD(self)
        popup.open()

class RV(BoxLayout):
    rv_data = ListProperty([])
    start_point = NumericProperty(0)
    mode = StringProperty("")

    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.get_users()

    def get_users(self):
        '''This result retrieve from database'''
        self.rv_data = []

        cur.execute("SELECT * FROM Users ORDER BY UserID ASC")
        rows = cur.fetchall()

        # create data_items
        for row in rows:
            for col in row:
                self.rv_data.append(col)

    def add_record(self):
        self.mode = "Add"
        popup = CRUD(self)
        popup.open()

    def update_changes(self, obj):
        if obj.mode == "Add":
            # insert record into Database Table
            cur.execute("INSERT INTO Users VALUES(NULL, ?, ?)",
                        (obj.col_data[1], obj.col_data[2]))
        else:
            # update Database Table
            cur.execute("UPDATE Users SET FirstName=?, LastName=? WHERE UserID=?",
                        (obj.col_data[1], obj.col_data[2], obj.col_data[0]))
        con.commit()
        self.get_users()

class ListUser(App):
    title = "Users"

    def build(self):
        self.root = Builder.load_file('main.kv')
        return RV()

if __name__ == '__main__':
    ListUser().run()

main.kv

#:kivy 1.10.0

<CRUD>:
    label_id_text: label_id_text
    label_id_data: label_id_data

    title: self.mode + " State"
    size_hint: None, None
    size: 350, 350
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        GridLayout:
            cols: 2
            Label:
                id: label_id_text
                text: "ID"
            Label:
                id: label_id_data
                text: root.col_data[0]  # root.userid
            Label:
                text: "First Name"
            TextInput:
                id: fname
                text: root.col_data[1]  # root.fname
            Label:
                text: "Last Name"
            TextInput:
                id: lname
                text: root.col_data[2]  # root.lname
        Button:
            size_hint: 1, 0.4
            text: "Confirm " + root.mode
            on_release:
                root.package_changes(fname.text, lname.text)
                app.root.update_changes(root)
                root.dismiss()
        Button:
            size_hint: 1, 0.4
            text: "Cancel " + root.mode
            on_release: root.dismiss()

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size

<RV>:
    BoxLayout:
        orientation: "vertical"

        Button:
            size_hint: 1, 0.1
            text: "Add Record"
            on_press: root.add_record()

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

            Label:
                text: "ID"
            Label:
                text: "First Name"
            Label:
                text: "Last Name"

        BoxLayout:
            RecycleView:
                viewclass: 'SelectableButton'
                data: [{'text': str(x)} for x in root.rv_data]
                SelectableRecycleGridLayout:
                    cols: 3
                    default_size: None, dp(26)
                    default_size_hint: 1, None
                    size_hint_y: None
                    height: self.minimum_height
                    orientation: 'vertical'
                    multiselect: True
                    touch_multiselect: True

Output


问:
How can I extract a parameter named "action" from the url without having to manually parse the querystring in MVC?
I have a site entry controller that is used via a url generated by a single sign on manager.  The SSO manager appends an identifying hash as an action parameter to the url of the system it is attempting to sign on to.

So the url being generated by the SSO manager looks like:

```<code>http://mysite/Entry/SingleSignOn?action=123456789ABCDEFG
</code>```

I think I just need to set up a better route, but I haven't been able to get it to work yet.  When I try to get the action from the url via standard MVC binding, it is giving me the name of the action, not the hash I need:

```<code> public ActionResult SingleSignOn(string action)
 {
     // action returns "SingleSignOn"
     var querystring = Request.Url.Query; //returns "?action=123456789ABCDEFG"
     return RedirectToAction("Index");
 }
</code>```

I know I can just split open the querystring, but would prefer not to if possible.  It doesn't seem like a terribly complex problem, but I am just not finding the right route.

答:
You can use Request.QueryString["action"] to explicitly get the parameter value from your request url.

```<code>public ActionResult SingleSignOn(string action)
{
   var querystring = Request.QueryString["action"];
   // Do something with querystring
   return RedirectToAction("Index");
}
</code>```

Body:
I have a site entry controller that is used via a url generated by a single sign on manager.  The SSO manager appends an identifying hash as an action parameter to the url of the system it is attempting to sign on to.

So the url being generated by the SSO manager looks like:

http://mysite/Entry/SingleSignOn?action=123456789ABCDEFG

I think I just need to set up a better route, but I haven't been able to get it to work yet.  When I try to get the action from the url via standard MVC binding, it is giving me the name of the action, not the hash I need:

 public ActionResult SingleSignOn(string action)
 {
     // action returns "SingleSignOn"
     var querystring = Request.Url.Query; //returns "?action=123456789ABCDEFG"
     return RedirectToAction("Index");
 }

I know I can just split open the querystring, but would prefer not to if possible.  It doesn't seem like a terribly complex problem, but I am just not finding the right route.

Body:
You can use Request.QueryString["action"] to explicitly get the parameter value from your request url.

public ActionResult SingleSignOn(string action)
{
   var querystring = Request.QueryString["action"];
   // Do something with querystring
   return RedirectToAction("Index");
}


问:
Can someone explain one of the algorithms that solves this Google Code Jam problem?
I'm referring to Shopping Plan problem from the Practice Problems. Here is a link to the solutions page.</p>

答:
Without looking at the solutions, this appears to be a standard DP.

Each state is represented by the list of items left to buy (2^15 combinations) and current position of the car (50 stores + 1 original position = 51 possible options).

Transition from one state to others is easy.

```<code>def minCost(itemsLeft, currentPosition)
    current_minimum = INFINITY

    for (each store in the list) {
        if (store.containsSomeOf(itemsLeft)) {
            candidate = minCost(itemsLeft - store.items, store)
                     + cost_of_items_bought_at_store + cost_of_driving
            current_minimum = min(current_minimum, candidate)
        }
    }

    return current_minimum
end
</code>```

Naturally, itemList is represented as a bitmask and not an actual list.

You'll need to consider perishable items also, but that's purely technical.

Finally, you'll need to either apply memoization to recursion or rewrite it as pure DP.

ContentLicense: CC BY-SA 2.5

Body:
Without looking at the solutions, this appears to be a standard DP.

Each state is represented by the list of items left to buy (2^15 combinations) and current position of the car (50 stores + 1 original position = 51 possible options).

Transition from one state to others is easy.

def minCost(itemsLeft, currentPosition)
    current_minimum = INFINITY

    for (each store in the list) {
        if (store.containsSomeOf(itemsLeft)) {
            candidate = minCost(itemsLeft - store.items, store)
                     + cost_of_items_bought_at_store + cost_of_driving
            current_minimum = min(current_minimum, candidate)
        }
    }

    return current_minimum
end

Naturally, itemList is represented as a bitmask and not an actual list.

You'll need to consider perishable items also, but that's purely technical.

Finally, you'll need to either apply memoization to recursion or rewrite it as pure DP.


问:
java 8 stream API filter out empty value from map
i have a map, need to operate on each entry's value, and return the modified map. I managed to get it working, but the resulted map contains entries with empty value, and I want to remove those entries but cannot with Java 8 stream API.

here is my original code:

```<code>Map<String, List<Test>> filtered = Maps.newHashMap();
for (String userId : userTests.keySet()) {
    List<Test> tests = userTests.get(userId);
    List<Test> filteredTests = filterByType(tests, supportedTypes);

    if (!CollectionUtils.isEmpty(filteredTests)) {
        filtered.put(userId, filteredTests);
    }
}
return filtered;
</code>```

and here is my Java 8 stream API version:

```<code>userTests.entrySet().stream()
         .forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
        return userTests;
</code>```

how can i remove entries with empty/null value from the map?

is there better way to write the code in stream API, so far I don't see it's better than my original code

答:
You need to collect into a new Map (say)

e.g.

```<code> new HashMap<String, List<String>>().
                entrySet().
                stream().
                filter(entry -> !entry.getValue().isEmpty()).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
</code>```

As it currently stands you're simply returning a stream with the intermediate (filtering) operations. The terminal operation will execute this and give you the desired collection.

Body:
i have a map, need to operate on each entry's value, and return the modified map. I managed to get it working, but the resulted map contains entries with empty value, and I want to remove those entries but cannot with Java 8 stream API.

here is my original code:

Map<String, List<Test>> filtered = Maps.newHashMap();
for (String userId : userTests.keySet()) {
    List<Test> tests = userTests.get(userId);
    List<Test> filteredTests = filterByType(tests, supportedTypes);

    if (!CollectionUtils.isEmpty(filteredTests)) {
        filtered.put(userId, filteredTests);
    }
}
return filtered;

and here is my Java 8 stream API version:

userTests.entrySet().stream()
         .forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
        return userTests;

how can i remove entries with empty/null value from the map?

is there better way to write the code in stream API, so far I don't see it's better than my original code

Body:
You need to collect into a new Map (say)

e.g.

 new HashMap<String, List<String>>().
                entrySet().
                stream().
                filter(entry -> !entry.getValue().isEmpty()).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

As it currently stands you're simply returning a stream with the intermediate (filtering) operations. The terminal operation will execute this and give you the desired collection.


问:
mutate_at evaluation error when using group_by
mutate_at() shows an evaluation error when used with group_by() and when imputing a numerical vector for column position as the first (.vars) argument.

Issue shows up when using R3.4.2 and dplyr0.7.4 version

Works fine when using R3.3.2 and dplyr0.5.0

Works fine if .vars is character vector (column name)

Example:

```<code># Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_2', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)

# Define column to fill NAs
nacol = c('RWA')

# Fill NAs with last period
dftest_2 <- dftest %>%
  group_by(Id) %>%
  mutate_at(which(names(dftest) %in% nacol),
            funs(ifelse(is.na(.),0,.)))
</code>```

```<code>Error in mutate_impl(.data, dots) :
Evaluation error: object 'NA' not found.
</code>```

More sensible example demonstrating issue:

```<code># Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_3', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)

# Define column to fill NAs
nacol = c('RWA')

# Fill NAs with last period
dftest_2 <- dftest %>%
  group_by(Id) %>%
  mutate_at(which(names(dftest) %in% nacol),
            funs(na.locf(., na.rm=F)))
</code>```

答:
The reason we are getting NA values is that the output we get from which is 3, but we grouped by 'Id' and so there are only 2 columns after that.

```<code>dftest %>%
     group_by(Id) %>%
     mutate_at(which(names(dftest) %in% nacol)-1, funs(ifelse(is.na(.),0,.)))
# A tibble: 6 x 3
# Groups:   Id [6]
#      Id Month   RWA
#  <fctr> <dbl> <dbl>
#1   10_1     2 0.000
#2   10_2     3 0.000
#3   11_1     4 0.000
#4   11_2     6 1.579
#5   11_3     7 0.000
#6   12_1     8 0.379
</code>```

The group_by is part is not needed here as we are changing NA values in other columns to 0

```<code>dftest %>%
    mutate_at(which(names(dftest) %in% nacol), funs(ifelse(is.na(.),0,.)))
</code>```

It could be a bug and using the position based approach is sometimes risky.  Better option would be to go with names

```<code>dftest %>%
    group_by(Id) %>%
    mutate_at(intersect(names(.), nacol), funs(replace(., is.na(.), 0)))
</code>```

NOTE: In all these cases, the group_by is not needed

Another option is replace_na from tidyr

```<code>dftest %>%
    tidyr::replace_na(as.list(setNames(0, nacol)))
</code>```

Body:
mutate_at() shows an evaluation error when used with group_by() and when imputing a numerical vector for column position as the first (.vars) argument.

Issue shows up when using R3.4.2 and dplyr0.7.4 version

Works fine when using R3.3.2 and dplyr0.5.0

Works fine if .vars is character vector (column name)

Example:

# Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_2', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)

# Define column to fill NAs
nacol = c('RWA')

# Fill NAs with last period
dftest_2 <- dftest %>%
  group_by(Id) %>%
  mutate_at(which(names(dftest) %in% nacol),
            funs(ifelse(is.na(.),0,.)))

Error in mutate_impl(.data, dots) :
Evaluation error: object 'NA' not found.

More sensible example demonstrating issue:

# Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_3', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)

# Define column to fill NAs
nacol = c('RWA')

# Fill NAs with last period
dftest_2 <- dftest %>%
  group_by(Id) %>%
  mutate_at(which(names(dftest) %in% nacol),
            funs(na.locf(., na.rm=F)))

Body:
The reason we are getting NA values is that the output we get from which is 3, but we grouped by 'Id' and so there are only 2 columns after that.

dftest %>%
     group_by(Id) %>%
     mutate_at(which(names(dftest) %in% nacol)-1, funs(ifelse(is.na(.),0,.)))
# A tibble: 6 x 3
# Groups:   Id [6]
#      Id Month   RWA
#  <fctr> <dbl> <dbl>
#1   10_1     2 0.000
#2   10_2     3 0.000
#3   11_1     4 0.000
#4   11_2     6 1.579
#5   11_3     7 0.000
#6   12_1     8 0.379

The group_by is part is not needed here as we are changing NA values in other columns to 0

dftest %>%
    mutate_at(which(names(dftest) %in% nacol), funs(ifelse(is.na(.),0,.)))

It could be a bug and using the position based approach is sometimes risky.  Better option would be to go with names

dftest %>%
    group_by(Id) %>%
    mutate_at(intersect(names(.), nacol), funs(replace(., is.na(.), 0)))

NOTE: In all these cases, the group_by is not needed

Another option is replace_na from tidyr

dftest %>%
    tidyr::replace_na(as.list(setNames(0, nacol)))


问:
ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes:
I have a script that works in a bash shell.  I put it in Ansible and it causes the playbook to have an exception.

```<code>- name: add mnt to ignore_filesystems
  shell: |
    grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*'
    if [ $? -eq 0 ]; then
        echo 'do nothing';
     else
        echo 'no';
        items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}')
        if [ ${#items} -gt 1 ]; then
            echo 'making the change'
            sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }}
        else
            echo 'making the change'
            sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }}
        fi
    fi
  register: ignore_filesystems
  changed_when: '"making the change" in ignore_filesystems.stdout'
</code>```

I am getting the following message when trying to execute the playbook:

```<code>ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*'
if [ $? -eq 0 ]; then
    echo 'do nothing';
else
    echo 'no';
    items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}')
    if [ ${#items} -gt 1 ]; then
        echo 'making the change'
        sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }}
    else
        echo 'making the change'
        sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }}
    fi
fi

The error appears to have been in '/home/username/provisioning/provisioning/edit_nimbus.yml':
line 179, column 5, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  - name: add mnt to ignore_filesystems
    ^ here
</code>```

Any thoughts on why this might be failing?

=========================================================================

UPDATE:

Tried > as well as | and made all lines the same indentation level.  Still the same error

```<code>  - name: add mnt to ignore_filesystems
    shell: |
      grep 'ignore_filesystem' {{ cdm_path }}| awk -F'=' '{print $2}' | egrep '\^\\/mnt\*';
      if [ $? -eq 0 ]; then
      echo 'do nothing';
      else
      echo 'no';
      items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}');
      if [ ${#items} -gt 1 ]; then
      echo 'making the change';
      sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }};
      else
      echo 'making the change';
      sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }};
      fi;
      fi
register: ignore_filesystems
changed_when: '"making the change" in ignore_filesystems.stdout'
</code>```

答:
So this turned out to not be a problem with indentation but with the way ${#items} is interpreted.  I was able to get this working with the following code:</p>

```<code>- name: add mnt to ignore_filesystems
  shell: |
    grep 'ignore_filesystem' {{ cdm_path }}  | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*';
    if [ $? -eq 0 ]; then
        echo 'do nothing';
    else
        echo 'no';
        items=$(sudo grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}');
        len=$(echo -n $items | wc -m)
        if [ ${len} -gt 1 ]; then
            echo 'making the change';
            echo 'appending...';
            sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }};
        else
            echo 'making the change';
            echo 'replacing';
            sudo sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }};
        fi
    fi
  register: ignore_filesystems
  changed_when: '"making the change" in ignore_filesystems.stdout'
</code>```

Body:
I have a script that works in a bash shell.  I put it in Ansible and it causes the playbook to have an exception.

- name: add mnt to ignore_filesystems
  shell: |
    grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*'
    if [ $? -eq 0 ]; then
        echo 'do nothing';
     else
        echo 'no';
        items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}')
        if [ ${#items} -gt 1 ]; then
            echo 'making the change'
            sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }}
        else
            echo 'making the change'
            sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }}
        fi
    fi
  register: ignore_filesystems
  changed_when: '"making the change" in ignore_filesystems.stdout'

I am getting the following message when trying to execute the playbook:

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*'
if [ $? -eq 0 ]; then
    echo 'do nothing';
else
    echo 'no';
    items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}')
    if [ ${#items} -gt 1 ]; then
        echo 'making the change'
        sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }}
    else
        echo 'making the change'
        sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }}
    fi
fi

The error appears to have been in '/home/username/provisioning/provisioning/edit_nimbus.yml':
line 179, column 5, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  - name: add mnt to ignore_filesystems
    ^ here

Any thoughts on why this might be failing?

=========================================================================

UPDATE:

Tried > as well as | and made all lines the same indentation level.  Still the same error

  - name: add mnt to ignore_filesystems
    shell: |
      grep 'ignore_filesystem' {{ cdm_path }}| awk -F'=' '{print $2}' | egrep '\^\\/mnt\*';
      if [ $? -eq 0 ]; then
      echo 'do nothing';
      else
      echo 'no';
      items=$(grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}');
      if [ ${#items} -gt 1 ]; then
      echo 'making the change';
      sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }};
      else
      echo 'making the change';
      sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }};
      fi;
      fi
register: ignore_filesystems
changed_when: '"making the change" in ignore_filesystems.stdout'

Body:
So this turned out to not be a problem with indentation but with the way ${#items} is interpreted.  I was able to get this working with the following code:

- name: add mnt to ignore_filesystems
  shell: |
    grep 'ignore_filesystem' {{ cdm_path }}  | awk -F'=' '{print $2}' | egrep '\^\\/mnt\*';
    if [ $? -eq 0 ]; then
        echo 'do nothing';
    else
        echo 'no';
        items=$(sudo grep ignore_filesystem {{ cdm_path }} | awk -F'=' '{print $2}');
        len=$(echo -n $items | wc -m)
        if [ ${len} -gt 1 ]; then
            echo 'making the change';
            echo 'appending...';
            sed -ie  '/ignore_filesystem/ s~$~|^\\/mnt*~' {{ cdm_path }};
        else
            echo 'making the change';
            echo 'replacing';
            sudo sed -ie '/ignore_filesystem/ s~ignore_filesystem = *~ignore_filesystem = ^\\/mnt*~' {{ cdm_path }};
        fi
    fi
  register: ignore_filesystems
  changed_when: '"making the change" in ignore_filesystems.stdout'


问:
In javascript, when creating properties, which is the right way or better syntax?
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?
</code>```

答:
For me, it depends on how I will use the object.

If I'm going to use it like an associative array, a hash map, or where the dot syntax would be impossible, I use [ and ].

However, if I'm treating them like an object, I use the . syntax.

Body:
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?


问:
How to have value as an array in Javascript Map?
I need to have a map which has keys and the corresponding values as an array, How do I do that?

```<code>[
{
"language": "english",
"movie_name": "die-hard",
"movie_size": 89
},{
"language": "english",
"movie_name": "inception",
"movie_size": 40
},{
"language": "english",
"movie_name": "Lionking",
"movie_size": 50
},{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 10
},
{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 65
},{
"language": "english",
"movie_name": "inception",
"movie_size": 70
},{
"language": "english",
"movie_name": "die-hard",
"movie_size": 62
}
]
</code>```

The above is my data structure and with my code below I am able to form a map which prints the number of movies per language.

And I have a code fiddle which currently prints the following to the console

```<code> Map{
'english' => Map {'die-hard' => 2, 'inception' => 2, 'Lionking' => 1},
'spanish' => Map {'L'amour' => 2} }
</code>```

But I want to calculate percentile based on the movie size, for which I need all the movie_size for a particular movie_name based on the language. I am not sure how this could be achieved.

答:
Set the value as array [] and .push to add items to it:

array = [ { "language": "english", "movie_name": "die-hard-4k"   , "movie_size": 89 },
          { "language": "english", "movie_name": "inception-1080", "movie_size": 40 },
          { "language": "english", "movie_name": "Lionking-4k"   , "movie_size": 50 },
          { "language": "spanish", "movie_name": "L'amour-1080"  , "movie_size": 10 },
          { "language": "spanish", "movie_name": "L'amour-4k"    , "movie_size": 65 },
          { "language": "english", "movie_name": "inception-4k"  , "movie_size": 70 },
          { "language": "english", "movie_name": "die-hard-1080" , "movie_size": 62 } ]

result = {}
for (item of array) {
  language = result[item.language] || (result[item.language] = {})
  movie_name = item.movie_name.replace(/-[^-]*$/, '')
  movie_size = language[movie_name] || (language[movie_name] = [])
  movie_size.push(item.movie_size)
}

console.log(result)```

Body:
I need to have a map which has keys and the corresponding values as an array, How do I do that?

[
{
"language": "english",
"movie_name": "die-hard",
"movie_size": 89
},{
"language": "english",
"movie_name": "inception",
"movie_size": 40
},{
"language": "english",
"movie_name": "Lionking",
"movie_size": 50
},{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 10
},
{
"language": "spanish",
"movie_name": "L'amour",
"movie_size": 65
},{
"language": "english",
"movie_name": "inception",
"movie_size": 70
},{
"language": "english",
"movie_name": "die-hard",
"movie_size": 62
}
]

The above is my data structure and with my code below I am able to form a map which prints the number of movies per language.

And I have a code fiddle which currently prints the following to the console

 Map{
'english' => Map {'die-hard' => 2, 'inception' => 2, 'Lionking' => 1},
'spanish' => Map {'L'amour' => 2} }

But I want to calculate percentile based on the movie size, for which I need all the movie_size for a particular movie_name based on the language. I am not sure how this could be achieved.


问:
Fitnesse Maven Linux run
I am trying to run FitNesse in CentOS using this profile:

```<code>    <profile>
            <id>fitnesse</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>start-fitnesse</id>
                                <phase>test</phase>
                                <configuration>
                                    <tasks>
                                        <echo taskname="fitnesse" message="Starting FitNesse..." />
                                        <java classname="fitnesseMain.FitNesseMain"
                                            classpathref="maven.runtime.classpath" fork="true">
                                            <arg line="-p 9595" />
                                            <arg line="-d ." />
                                        </java>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.fitnesse.plugins</groupId>
                    <artifactId>maven-classpath-plugin</artifactId>
                    <version>1.6</version>
                    <scope>runtime</scope>
                </dependency>
            </dependencies>
        </profile>
</code>```

I am using maven.classpath to add the dependency jars into Fitnesse

```<code>         ${maven.classpath}
</code>```

But in this case i am getting

```<code>         undefined variable: maven.classpath
</code>```

Note: I am able to see FitNesse wiki page.

答:
To use the plugin you have to make sure it is available to the wiki (I usually use maven dependency plugin to copy it to the wiki's plugins directory). Just adding it as a maven dependency does not suffice.

```<code>        <plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <id>copy-plugins</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>org.fitnesse.plugins</groupId>
                                <artifactId>maven-classpath-plugin</artifactId>
                                <version>${maven-classpath-plugin.version}</version>
                                <classifier>jar-with-dependencies</classifier>
                                <overWrite>true</overWrite>
                            </artifactItem>
                        </artifactItems>
                        <outputDirectory>${project.basedir}/wiki/plugins</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Furthermore you have to (copied from the README):

Add the following line to plugins.properties:

SymbolTypes = fitnesse.wikitext.widgets.MavenClasspathSymbolType

Refer to the pom file as follows:

!pomFile /path/to/pom.xml

you can define the file as pom.xml@compile to include a specific scope.

Title: Fitnesse Maven Linux run

Body:
I am trying to run FitNesse in CentOS using this profile:

    <profile>
            <id>fitnesse</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>start-fitnesse</id>
                                <phase>test</phase>
                                <configuration>
                                    <tasks>
                                        <echo taskname="fitnesse" message="Starting FitNesse..." />
                                        <java classname="fitnesseMain.FitNesseMain"
                                            classpathref="maven.runtime.classpath" fork="true">
                                            <arg line="-p 9595" />
                                            <arg line="-d ." />
                                        </java>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <dependencies>
                <dependency>
                    <groupId>org.fitnesse.plugins</groupId>
                    <artifactId>maven-classpath-plugin</artifactId>
                    <version>1.6</version>
                    <scope>runtime</scope>
                </dependency>
            </dependencies>
        </profile>

I am using maven.classpath to add the dependency jars into Fitnesse

         ${maven.classpath}

But in this case i am getting

         undefined variable: maven.classpath

Note: I am able to see FitNesse wiki page.

Body:
To use the plugin you have to make sure it is available to the wiki (I usually use maven dependency plugin to copy it to the wiki's plugins directory). Just adding it as a maven dependency does not suffice.

        <plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <id>copy-plugins</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>org.fitnesse.plugins</groupId>
                                <artifactId>maven-classpath-plugin</artifactId>
                                <version>${maven-classpath-plugin.version}</version>
                                <classifier>jar-with-dependencies</classifier>
                                <overWrite>true</overWrite>
                            </artifactItem>
                        </artifactItems>
                        <outputDirectory>${project.basedir}/wiki/plugins</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Furthermore you have to (copied from the README):

Add the following line to plugins.properties:

SymbolTypes = fitnesse.wikitext.widgets.MavenClasspathSymbolType

Refer to the pom file as follows:

!pomFile /path/to/pom.xml

you can define the file as pom.xml@compile to include a specific scope.


问:
ReactJS - How to remove whole component , by using child button
I have problem , i want to create TODO app in ReactJS and there is functionality like this:

onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion ) - I done it.

In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox" - Can't figur it out :(

I'm greeny in React , my thinking about that library may be wrong.

My code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(
      <div>
        <div
          onClick={this.toggleHidden.bind(this)}
          className="addtask__btn">
          +
        </div>
        {this.state.isHidden && <AddTaskBox />}
      </div>
    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(
      <div className="addtask__box" >
        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>
      </div>
    );
  }
}

export {AddButton, AddTaskBox};
</code>```

Thanks for help :)

答:
You can pass your toggleHidden() function as prop to AddTasktBox component.

So your close button in AddTaskBox will be like

```<code>...
<button onClick={this.props.handleClick}> x </button>
...
</code>```

You can pass it like

```<code>{this.state.isHidden && <AddTaskBox handleClick={this.toggleHidden.bind(this)} />}
</code>```

Body:
I have problem , i want to create TODO app in ReactJS and there is functionality like this:

onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion ) - I done it.

In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox" - Can't figur it out :(

I'm greeny in React , my thinking about that library may be wrong.

My code:

import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(

          +

        {this.state.isHidden && <AddTaskBox />}

    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(

        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>

    );
  }
}

export {AddButton, AddTaskBox};

Thanks for help :)

Body:
You can pass your toggleHidden() function as prop to AddTasktBox component.

So your close button in AddTaskBox will be like

...
<button onClick={this.props.handleClick}> x </button>
...

You can pass it like

{this.state.isHidden && <AddTaskBox handleClick={this.toggleHidden.bind(this)} />}


问:
How to trace running instructions/taken branches on physical Android smartphone?
This is the situation: I have my own smartphone and I want to trace every time I make a service call with

```<code>adb shell service call ...
</code>```

which instructions are covered or which branches are taken in the service code (both java and c).

I tried to give a look to hardware solutions, but it read that vendors usually disable this debugging option.

Any ideas or useful tool for me?

答: Frida is able to do that now. .</p>

Body:
This is the situation: I have my own smartphone and I want to trace every time I make a service call with

adb shell service call ...

which instructions are covered or which branches are taken in the service code (both java and c).

I tried to give a look to hardware solutions, but it read that vendors usually disable this debugging option.

Any ideas or useful tool for me?

Body: Frida is able to do that now. .


问:
Convert a dictionary of equal length lists into a list of dictionaries
I want to write a function that is able to convert a dictionary of lists, that are of equal length lists, into a list of dictionaries.

EX:
{'a': [1, 2, 3], 'b': [3, 2, 1]}
=> [{'a': 1, 'b': 3}, {'a': 2, 'b': 2}, {'a': 3, 'b': 1}]

The thing I am caught on is how to code this without knowing the total length of the first dictionary, and being able to remove all hardcoded values out of the function.

My intuition was to try and use a defaultdict, but that didn't seem to help.

Any help would be much appreciated!

Body:
Zip values and zip keys + each item in that zip:

d = {'a': [1, 2, 3], 'b': [3, 2, 1]}

[dict(zip(d.keys(),i)) for i in zip(*d.values())]

Result:

[{'a': 1, 'b': 3}, {'a': 2, 'b': 2}, {'a': 3, 'b': 1}]


问:
Looking for the biggest number before and after 'i' in list
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

```<code>a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)
</code>```

答:
Try:

```<code>for i in range(len(a)):
    print(max(a[:i+1]))
    print(max(a[i:]))
</code>```

You are not iterating over the indices in your original code; and thus the partition does not make sense.

Body:
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)

Body:
Try:

for i in range(len(a)):
    print(max(a[:i+1]))
    print(max(a[i:]))

You are not iterating over the indices in your original code; and thus the partition does not make sense.


问:
Missing on-screen keyboard for Flash/Flex web application on Android?
I have an enterprise Flex web application, served up over https, that runs fine on Flash player 10.0 and beyond on a desktop computer/browser.

However, when I run it from my HTC Incredible with Android 2.2 the app loads fine, but there is no on-screen keyboard and so I cannot log in.  I can see the blinking cursor inside the username and password text fields.  I can switch between them.  I can even hit the login button and see an authentication error!

According to Adobe this should Just Work.  Any ideas?  I wanna show off our spanking new app to strangers at the bus stop!

答: Not a programming solution, but long press on the menu button brings up the keyboard if it doesn't pop up by itself (at least on my HTC Desire, 2.2 android).</p>


问:
multiple column layout inside a tabPanel
I generate a lot of input using renderUI, I would like to have a multicolumn display inside a tabPanel.

Of course the number of input is dynamic :-)

Any idea how do do this ?

```<code>   library(shiny)
ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
list(
  numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1)#, lot of other input
) # In my code this list is returned by a function
  })

  output$summary <- renderText("coucou")
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

not this :

but this :

答:
Just split your list in 2 with split, you can sort f argument in split if order matter :

```<code>library(shiny)

ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
                 uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
    x <- list(
      numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1),
      numericInput(inputId = "C24","C",1)
    )
    fluidRow(
      lapply(
        X = split(x, f = rep(c(1, 2), length.out = length(x))),
        FUN = column, width = 6
      )
    )
  })

  output$summary <- renderText("coucou")
}

shinyApp(ui = ui, server = server)
</code>```

Body:
I generate a lot of input using renderUI, I would like to have a multicolumn display inside a tabPanel.

Of course the number of input is dynamic :-)

Any idea how do do this ?

   library(shiny)
ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
list(
  numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1)#, lot of other input
) # In my code this list is returned by a function
  })

  output$summary <- renderText("coucou")
}

# Run the application
shinyApp(ui = ui, server = server)

not this :

but this :

Body:
Just split your list in 2 with split, you can sort f argument in split if order matter :

library(shiny)

ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
                 uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
    x <- list(
      numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1),
      numericInput(inputId = "C24","C",1)
    )
    fluidRow(
      lapply(
        X = split(x, f = rep(c(1, 2), length.out = length(x))),
        FUN = column, width = 6
      )
    )
  })

  output$summary <- renderText("coucou")
}

shinyApp(ui = ui, server = server)


问:
What does this "!string" mean?
I'm going through an old code library at my workplace to document it and re-use it for other projects.
The Library isn't documented at all (not even comments) but that's not a big deal.

I found this strange syntax and I can't find an explanation online to what it is...

```<code>public bool Validate()
    {
        return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State);
    }
</code>```

I get that the Exclamation point is the negation operator, but it's only possible to use it with Boolean variables. How is it possible to say not(string)? What does that exclamation point before the string keyword does? The tooltip didn't help either..

答: ! means not. IsNullOrWhiteSpace is a static method of String which returns a boolean value, so the code is returning whether both 'Code' and 'State' have a value.</p>

Title: What does this "!string" mean?

Body:
I'm going through an old code library at my workplace to document it and re-use it for other projects.
The Library isn't documented at all (not even comments) but that's not a big deal.

I found this strange syntax and I can't find an explanation online to what it is...

public bool Validate()
    {
        return !string.IsNullOrWhiteSpace(Code) && !string.IsNullOrWhiteSpace(State);
    }

I get that the Exclamation point is the negation operator, but it's only possible to use it with Boolean variables. How is it possible to say not(string)? What does that exclamation point before the string keyword does? The tooltip didn't help either..


问:
how to use collection of collection via using multimap (apache collection type)
How to use collection of collection via using multimap (apache collection type) .

I am using MultiMap but hibernate is not recognizing it as a collection type

答: Hibernate doesn't understand commons collection types. You either can write your own custom UserType or provide get/set that returns the equivalent of Java Collections.</p>


问:
React bootstrap not styling my react components
Just started out using React yesterday so setting up a demo app. Environment is:

Typescript

Webpack

React & React DOM

I'm trying to setup Bootstrap styles.

I followed this tutorial along but modified it to suit Typescript:

https://medium.com/@victorleungtw/how-to-use-webpack-with-react-and-bootstrap-b94d33765970

Everything works, the page displays the signin form and the Bootstrap HTMl is output by React-Bootstrap. But the styles are not applied to the elements, it's just a plain HTML page with none of the Bootstrap styles applied. I'm not sure what I'm missing from the config:

webpack.config.js

I've added the loaders through npm as mentioned in the tutorial, but also adjusted to setup Typescript modules from the css.

```<code>module.exports = {
    entry: {
        catalog: "./src/apps/CatalogApp.tsx",
        auth: "./src/apps/AuthApp.tsx"
    },
    output: {
        filename: "[name].bundle.js",
        publicPath: "/build/",
        path: __dirname + "/dist"
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader"
            },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            },

            // css loader
            {
                test: /\.css$/,
                loader: "typings-for-css-modules-loader?modules"
            },

            {
                test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff'
              },
              {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
              },
              {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'file-loader'
              },
              {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
              }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};
</code>```

AuthApp.tsx

This is my entry point for the application.

```<code>import * as React from "react";
import * as ReactDOM from "react-dom";

import { SigninForm } from "../components/users/SigninForm";
import { MiniCart } from '../components/cart/MiniCart';
import { UserMenu } from '../components/users/UserMenu';
import * as bs from 'bootstrap/dist/css/bootstrap.css';
import * as bst from 'bootstrap/dist/css/bootstrap-theme.css';

if (document.getElementById("signin-form")) {
    ReactDOM.render(
        <SigninForm />,
        document.getElementById("signin-form")
    );
}

if (document.getElementById('cart')) {
    ReactDOM.render(
        <MiniCart />,
        document.getElementById('cart')
    );
}

if (document.getElementById('user-menu')) {
    ReactDOM.render(
        <UserMenu />,
        document.getElementById('user-menu')
    );
}
</code>```

SigninForm.tsx

And the relevant UI for the signin form.

```<code>import * as React from 'react';
import * as ReactDOM from "react-dom";
import { Button, Col, Row } from 'react-bootstrap';

import { Spinner } from '../shared/Spinner';

interface SigninFormProps {
}

interface SigninFormState {
  email: string;
  password: string;
}

export class SigninForm extends React.Component<SigninFormProps, SigninFormState> {

  constructor(props: SigninFormProps) {
    super(props);
    this.state = {
      email: '',
      password: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event: any) {
    this.setState({ [event.target.name]: event.target.value });
  }

  handleSubmit(event: any) {
    event.preventDefault();
    console.log('Submitting form', this.state);
  }

  render() {
    return (
      <Row>
        <Col md={8}>
          <form className="signin-form" onSubmit={this.handleSubmit}>
            <div className="form-group">
              <label htmlFor="email">Email</label>
              <input id="email" name="email" type="email" value={this.state.email} onChange={this.handleChange} />
            </div>
            <div className="form-group">
              <label htmlFor="password">Password</label>
              <input id="password" name="password" type="password" value={this.state.password} onChange={this.handleChange} />
            </div>
            <Button>Submit</Button>
          </form>
        </Col>
        <Col md={4}>
          Right Side
      </Col>
      </Row>
    );
  }
}
</code>```

答:
The webpack config you use is a little different from the medium article.

In the medium article, the author uses style-loader and css-loader to process css file.

```<code>module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      ...
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      },
      ...
    ]
  },
};
</code>```

style-loader will inject the css code to

Body:
Just started out using React yesterday so setting up a demo app. Environment is:

Typescript

Webpack

React & React DOM

I'm trying to setup Bootstrap styles.

I followed this tutorial along but modified it to suit Typescript:

https://medium.com/@victorleungtw/how-to-use-webpack-with-react-and-bootstrap-b94d33765970

Everything works, the page displays the signin form and the Bootstrap HTMl is output by React-Bootstrap. But the styles are not applied to the elements, it's just a plain HTML page with none of the Bootstrap styles applied. I'm not sure what I'm missing from the config:

webpack.config.js

I've added the loaders through npm as mentioned in the tutorial, but also adjusted to setup Typescript modules from the css.

module.exports = {
    entry: {
        catalog: "./src/apps/CatalogApp.tsx",
        auth: "./src/apps/AuthApp.tsx"
    },
    output: {
        filename: "[name].bundle.js",
        publicPath: "/build/",
        path: __dirname + "/dist"
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader"
            },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            },

            // css loader
            {
                test: /\.css$/,
                loader: "typings-for-css-modules-loader?modules"
            },

            {
                test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=application/font-woff'
              },
              {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
              },
              {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'file-loader'
              },
              {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
              }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

AuthApp.tsx

This is my entry point for the application.

import * as React from "react";
import * as ReactDOM from "react-dom";

import { SigninForm } from "../components/users/SigninForm";
import { MiniCart } from '../components/cart/MiniCart';
import { UserMenu } from '../components/users/UserMenu';
import * as bs from 'bootstrap/dist/css/bootstrap.css';
import * as bst from 'bootstrap/dist/css/bootstrap-theme.css';

if (document.getElementById("signin-form")) {
    ReactDOM.render(
        <SigninForm />,
        document.getElementById("signin-form")
    );
}

if (document.getElementById('cart')) {
    ReactDOM.render(
        <MiniCart />,
        document.getElementById('cart')
    );
}

if (document.getElementById('user-menu')) {
    ReactDOM.render(
        <UserMenu />,
        document.getElementById('user-menu')
    );
}

SigninForm.tsx

And the relevant UI for the signin form.

import * as React from 'react';
import * as ReactDOM from "react-dom";
import { Button, Col, Row } from 'react-bootstrap';

import { Spinner } from '../shared/Spinner';

interface SigninFormProps {
}

interface SigninFormState {
  email: string;
  password: string;
}

export class SigninForm extends React.Component<SigninFormProps, SigninFormState> {

  constructor(props: SigninFormProps) {
    super(props);
    this.state = {
      email: '',
      password: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event: any) {
    this.setState({ [event.target.name]: event.target.value });
  }

  handleSubmit(event: any) {
    event.preventDefault();
    console.log('Submitting form', this.state);
  }

  render() {
    return (
      <Row>
        <Col md={8}>
          <form className="signin-form" onSubmit={this.handleSubmit}>

              Email
              <input id="email" name="email" type="email" value={this.state.email} onChange={this.handleChange} />

              Password
              <input id="password" name="password" type="password" value={this.state.password} onChange={this.handleChange} />

            <Button>Submit</Button>
          </form>
        </Col>
        <Col md={4}>
          Right Side
      </Col>
      </Row>
    );
  }
}

Body:
The webpack config you use is a little different from the medium article.

In the medium article, the author uses style-loader and css-loader to process css file.

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      ...
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      },
      ...
    ]
  },
};

style-loader will inject the css code to <style/> tag. So that is why the tutorial work

In your webpack config, you use typings-for-css-modules-loader to load css. With this loader, you need to pass the css class variable name to className.

It means you should write the code like (simplify some code):

import * as React from "react";
import * as bs from 'bootstrap/dist/css/bootstrap.css';
import * as bst from 'bootstrap/dist/css/bootstrap-theme.css';

import { Button, Col, Row } from 'react-bootstrap';

import { Spinner } from '../shared/Spinner';

export class SigninForm extends React.Component {
  ...
  render() {
    return (
      <Row>
        <Col md={8}>
          <form className={bt["signin-form"]} onSubmit={this.handleSubmit}>
            <div className={bt["form-group"]}>
              <label htmlFor="email">Email</label>
              <input id="email" name="email" type="email" value={this.state.email} onChange={this.handleChange} />
            </div>
            <Button>Submit</Button>
          </form>
        </Col>
        <Col md={4}>
          Right Side
      </Col>
      </Row>
    );
  }
}

Pass bt[classname] to className.

I think it will work.

btw, I find another medium article using typings-for-css-modules-loader -> link.


问:
MS Access: Hiding Columns in Datasheet View using GUI
I am trying to set some columns in a datasheet view of a form as hidden when the form is loaded.

This is possible via VBA code like:

```<code>   Private Sub Form_Load()

      Me.Product_ID.ColumnHidden = True
      Me.Carrier_ID.ColumnHidden = True
      Me.Currency_ID.ColumnHidden = True

   End Sub
</code>```

However, Is there a way to do it in the form design by default, so we do not need this VBA code?

I tried column width and/or visible properties but they do not work for datasheet view.

I am using Office360.

I read that this is used to be possible using the Format toolbar in GUI in old access versions.

My question:

Is that still available in access 2016?

If yes, where? cause I tried the Format ribbon when form is selected but every thing is dimmed and no commands for this purpose.

答: If you in normal view collapse/hide the columns manually and save the form and close it, the columns should remain hidden when you open the form again.

Body:
I am trying to set some columns in a datasheet view of a form as hidden when the form is loaded.

This is possible via VBA code like:

   Private Sub Form_Load()

      Me.Product_ID.ColumnHidden = True
      Me.Carrier_ID.ColumnHidden = True
      Me.Currency_ID.ColumnHidden = True

   End Sub

However, Is there a way to do it in the form design by default, so we do not need this VBA code?

I tried column width and/or visible properties but they do not work for datasheet view.

I am using Office360.

I read that this is used to be possible using the Format toolbar in GUI in old access versions.

My question:

Is that still available in access 2016?

If yes, where? cause I tried the Format ribbon when form is selected but every thing is dimmed and no commands for this purpose.


问:
Block executing specific .exe files based on their md5 hash
I want to write a simple program that blocks executing certain .exe files based on t their md5 hash value (like notepad.exe ...).

I searched for this problem and I found that I need to register a callback this method is the start PsSetCreateProcessNotifyRoutineEx and here is a sample callback:

```<code>VOID PsCreateProcessNotifyEx_CB(HANDLE ParentProcessId, HANDLE ProcessId, PPS_CREATE_NOTIFY_INFO CreateInfo)
{

    if (CreateInfo) // if the info is available
    {
        DbgPrint("Created Process info \r\n");
        DbgPrint("\tIs Sub-System Process: %wZ\r\n", CreateInfo->IsSubsystemProcess);
        if (!CreateInfo->IsSubsystemProcess) {
            DbgPrint("\tParent ProcessId: %d", CreateInfo->ParentProcessId);
            DbgPrint("\tFile name: %wZ \r\n", CreateInfo->FileObject->FileName);
            DbgPrint("\tImageFileName: %wZ \r\n", CreateInfo->ImageFileName);
            DbgPrint("\tCommandLine: %wZ \r\n", CreateInfo->CommandLine);
            DbgPrint("\tCreationStatus: %x \r\n", CreateInfo->CreationStatus);

            CreateInfo->CreationStatus = STATUS_ACCESS_DENIED;
        }
    }
}
</code>```

As you can see I set the CreationStatus to STATUS_ACCESS_DENIED which blocks execution of every process :), How can I conditionally block execution of certain processes? What if a have list of unallowed .exe files inside a SqLite database? How can I connect this callback with some service which tells which file should be run and which shouldn't?

I also have seen this recommendation by Microsoft which says:

Keep notify routines short and simple.

Do not make calls into a user mode service to validate the process, thread, or image.

Do not make registry calls.

Do not make blocking and/or Interprocess Communication (IPC) function calls.

Do not synchronize with other threads because it can lead to reentrancy deadlocks.

It kind of warns and limit us in this callback, so my question is how can I achieve my goal? (limiting execution of some .exe files based on their hash value stored in a SqlLite database?)

Any help is much appreciated.

答:
first of all your signature for PsCreateProcessNotifyEx_CB is incorrect - first parameter must be PEPROCESS Process (pointer to ne process object) but not HANDLE ParentProcessId. you copy-paste this from msdn page, but error here.

about solution - because PsCreateProcessNotifyEx_CB executed in critical region with normal kernel APCs disabled - we very restricted todo something here. but we can queue normal kernel APC to current thread. it will be executed just we leave critical region. and here, in Normal routine we already can free read data from file, wait, query user mode. for terminate process we can simply call ZwTerminateProcess

```<code>void* __cdecl operator new(size_t size, POOL_TYPE PoolType)
{
    return ExAllocatePool(PoolType, size);
}

void __cdecl operator delete(PVOID pv)
{
    ExFreePool(pv);
}

// asm routines: call corresponding *Routine and jmp ObfDereferenceObject for g_DriverObject
VOID CALLBACK RundownRoutine(PKAPC );
VOID CALLBACK KernelRoutine(PKAPC , PKNORMAL_ROUTINE *, PVOID * , PVOID * ,PVOID * );
VOID CALLBACK NormalRoutine(PVOID , PVOID ,PVOID );

VOID CALLBACK _NormalRoutine (
                      PVOID ,
                      PEPROCESS Process,
                      PFILE_OBJECT FileObject
                      )
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("NormalRoutine(%p, %p %s)\n", Process, FileObject, PsGetProcessImageFileName(Process));

    if (NeedTerminate(Process, FileObject))
    {
        HANDLE hProcess;
        if (0 <= ObOpenObjectByPointer(Process, 0, 0, PROCESS_TERMINATE, *PsProcessType, KernelMode, &hProcess))
        {
            status = ZwTerminateProcess(hProcess, STATUS_ACCESS_DENIED);
            ZwClose(hProcess);
        }
    }

    ObfDereferenceObject(FileObject);
    ObfDereferenceObject(Process);
}

VOID CALLBACK _RundownRoutine(PKAPC Apc);
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("--Apc<%p>\n", Apc);
    delete Apc;
}

VOID CALLBACK _KernelRoutine(
                             PKAPC Apc,
                             PKNORMAL_ROUTINE * /*NormalRoutine*/,
                             PVOID * /*NormalContext*/,
                             PVOID * /*SystemArgument1*/,
                             PVOID * /*SystemArgument2*/
                             )
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("KernelRoutine<%p>\n", Apc);

    ObfReferenceObject(g_DriverObject);//NormalRoutine will be called

    _RundownRoutine(Apc);
}

void CreateProcessNotifyRoutineEx(PEPROCESS Process, HANDLE ProcessId, PPS_CREATE_NOTIFY_INFO CreateInfo)
{
  PFILE_OBJECT FileObject;

    if (CreateInfo && !CreateInfo->IsSubsystemProcess && (PFILE_OBJECT FileObject = CreateInfo->FileObject))
    {
        // for do main job out of critical region
        if (PKAPC Apc = new(NonPagedPool) KAPC)
        {
            KeInitializeApc(Apc, KeGetCurrentThread(), OriginalApcEnvironment, KernelRoutine, RundownRoutine, NormalRoutine, KernelMode, 0);

            DbgPrint("++Apc<%p> \n", Apc);

            ObfReferenceObject(g_DriverObject);
            ObfReferenceObject(Process);
            ObfReferenceObject(FileObject);

            if (!KeInsertQueueApc(Apc, Process, FileObject, IO_NO_INCREMENT))
            {
                ObfDereferenceObject(FileObject);
                ObfDereferenceObject(Process);
                ObfDereferenceObject(g_DriverObject);
                delete Apc;
            }
        }
    }
}
</code>```

Body:
I want to write a simple program that blocks executing certain .exe files based on t their md5 hash value (like notepad.exe ...).

I searched for this problem and I found that I need to register a callback this method is the start PsSetCreateProcessNotifyRoutineEx and here is a sample callback:

VOID PsCreateProcessNotifyEx_CB(HANDLE ParentProcessId, HANDLE ProcessId, PPS_CREATE_NOTIFY_INFO CreateInfo)
{

    if (CreateInfo) // if the info is available
    {
        DbgPrint("Created Process info \r\n");
        DbgPrint("\tIs Sub-System Process: %wZ\r\n", CreateInfo->IsSubsystemProcess);
        if (!CreateInfo->IsSubsystemProcess) {
            DbgPrint("\tParent ProcessId: %d", CreateInfo->ParentProcessId);
            DbgPrint("\tFile name: %wZ \r\n", CreateInfo->FileObject->FileName);
            DbgPrint("\tImageFileName: %wZ \r\n", CreateInfo->ImageFileName);
            DbgPrint("\tCommandLine: %wZ \r\n", CreateInfo->CommandLine);
            DbgPrint("\tCreationStatus: %x \r\n", CreateInfo->CreationStatus);

            CreateInfo->CreationStatus = STATUS_ACCESS_DENIED;
        }
    }
}

As you can see I set the CreationStatus to STATUS_ACCESS_DENIED which blocks execution of every process :), How can I conditionally block execution of certain processes? What if a have list of unallowed .exe files inside a SqLite database? How can I connect this callback with some service which tells which file should be run and which shouldn't?

I also have seen this recommendation by Microsoft which says:

Keep notify routines short and simple.

Do not make calls into a user mode service to validate the process, thread, or image.

Do not make registry calls.

Do not make blocking and/or Interprocess Communication (IPC) function calls.

Do not synchronize with other threads because it can lead to reentrancy deadlocks.

It kind of warns and limit us in this callback, so my question is how can I achieve my goal? (limiting execution of some .exe files based on their hash value stored in a SqlLite database?)

Any help is much appreciated.

Body:
first of all your signature for PsCreateProcessNotifyEx_CB is incorrect - first parameter must be PEPROCESS Process (pointer to ne process object) but not HANDLE ParentProcessId. you copy-paste this from msdn page, but error here.

about solution - because PsCreateProcessNotifyEx_CB executed in critical region with normal kernel APCs disabled - we very restricted todo something here. but we can queue normal kernel APC to current thread. it will be executed just we leave critical region. and here, in Normal routine we already can free read data from file, wait, query user mode. for terminate process we can simply call ZwTerminateProcess

void* __cdecl operator new(size_t size, POOL_TYPE PoolType)
{
    return ExAllocatePool(PoolType, size);
}

void __cdecl operator delete(PVOID pv)
{
    ExFreePool(pv);
}

// asm routines: call corresponding *Routine and jmp ObfDereferenceObject for g_DriverObject
VOID CALLBACK RundownRoutine(PKAPC );
VOID CALLBACK KernelRoutine(PKAPC , PKNORMAL_ROUTINE *, PVOID * , PVOID * ,PVOID * );
VOID CALLBACK NormalRoutine(PVOID , PVOID ,PVOID );

VOID CALLBACK _NormalRoutine (
                      PVOID ,
                      PEPROCESS Process,
                      PFILE_OBJECT FileObject
                      )
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("NormalRoutine(%p, %p %s)\n", Process, FileObject, PsGetProcessImageFileName(Process));

    if (NeedTerminate(Process, FileObject))
    {
        HANDLE hProcess;
        if (0 <= ObOpenObjectByPointer(Process, 0, 0, PROCESS_TERMINATE, *PsProcessType, KernelMode, &hProcess))
        {
            status = ZwTerminateProcess(hProcess, STATUS_ACCESS_DENIED);
            ZwClose(hProcess);
        }
    }

    ObfDereferenceObject(FileObject);
    ObfDereferenceObject(Process);
}

VOID CALLBACK _RundownRoutine(PKAPC Apc);
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("--Apc<%p>\n", Apc);
    delete Apc;
}

VOID CALLBACK _KernelRoutine(
                             PKAPC Apc,
                             PKNORMAL_ROUTINE * /*NormalRoutine*/,
                             PVOID * /*NormalContext*/,
                             PVOID * /*SystemArgument1*/,
                             PVOID * /*SystemArgument2*/
                             )
{
    __pragma(message("extern " __FUNCDNAME__ " : PROC ; "  __FUNCSIG__))

    DbgPrint("KernelRoutine<%p>\n", Apc);

    ObfReferenceObject(g_DriverObject);//NormalRoutine will be called

    _RundownRoutine(Apc);
}

void CreateProcessNotifyRoutineEx(PEPROCESS Process, HANDLE ProcessId, PPS_CREATE_NOTIFY_INFO CreateInfo)
{
  PFILE_OBJECT FileObject;

    if (CreateInfo && !CreateInfo->IsSubsystemProcess && (PFILE_OBJECT FileObject = CreateInfo->FileObject))
    {
        // for do main job out of critical region
        if (PKAPC Apc = new(NonPagedPool) KAPC)
        {
            KeInitializeApc(Apc, KeGetCurrentThread(), OriginalApcEnvironment, KernelRoutine, RundownRoutine, NormalRoutine, KernelMode, 0);

            DbgPrint("++Apc<%p> \n", Apc);

            ObfReferenceObject(g_DriverObject);
            ObfReferenceObject(Process);
            ObfReferenceObject(FileObject);

            if (!KeInsertQueueApc(Apc, Process, FileObject, IO_NO_INCREMENT))
            {
                ObfDereferenceObject(FileObject);
                ObfDereferenceObject(Process);
                ObfDereferenceObject(g_DriverObject);
                delete Apc;
            }
        }
    }
}


问:
Beyond compare, update the command line
After updating beyond compare, in the application folder I have the updated BeyonCompare app. However if I start the application from the terminal with bcomp file1 file2 the older, not updated version is started.

How do I solve this?

答: Use the Beyond Compare menu's Install Command Line Tools command.  It creates a symlink, so that shouldn't be necessary after upgrading, but if your copy of BC was installed somewhere else previously, that will update it.

Title: Beyond compare, update the command line