问:
How to mount component only when i change class props
I have a ReactJS project where i get JSON from REST Django host and creating a table with filters for it. I have a Table class :

```<code>class MainTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      results: []
    };
  }

  componentDidMount(){
    axios.get(this.props.link)
      .then(res => {
        this.setState({results: res.data.results});
    });
  }

  render() {
    return (
      <Table hover striped bordered responsive size="sm">
        <thead>
          <tr>
            <th>Name</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {this.state.results.map(result =>
            <tr key={result.fileId}>
              <td>{result.Name}</td>
              <td>{result.Name}</td>
            </tr>
          )}
        </tbody>
      </Table>
    );
  }
}
</code>```

And Main where i run all filter classes :

```<code>class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      origin: '',
      limit: 10
    };

    this.handleChangeOrigin = this.handleChangeOrigin.bind(this);
    this.handleChangeLimit = this.handleChangeLimit.bind(this);
  }

  handleChangeLimit(event) {
    this.setState({limit: event.target.value});
  }
  handleChangeOrigin(event) {
    this.setState({origin: event.target.value});
  }

  render() {
    var link = `http://106.120.89.142:8000/database/?limit=${this.state.limit}&`;
    if (this.state.origin){
      link += `ORIGIN=${this.state.origin.toLowerCase()}`;
      console.log(link)
    }
    return (
      <div>
        <div>
          <h1 className="jumbotron-heading display-4">Here u got database *_*</h1>
        </div>
        <div>
          <Limit handleChange = {this.handleChangeLimit} />
        </div>
        <div>
          <OriginRow handleChange = {this.handleChangeOrigin} />
        </div>
        <div id="tableWrapper">
          <MainTable link={link} />
        </div>
      </div>
    );
  }
}
</code>```

And i have a problem with it, cause when i use componentDidMount(), my axios.get(my link to REST JSON) runs only once. When i use axios in Table class render(), it hits my server few times per second. Can i make mounting only when my props to Table class changed?

答:
You should take a look at the shouldComponentUpdate() life-cycle method, here.

shouldComponentUpdate()

```<code>shouldComponentUpdate(nextProps, nextState)
</code>```

Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Add the following snippet to your MainTable component. This will prevent it from re-rendering, unless the props have changed.

```<code>shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props) !== JSON.stringify(nextProps);
}
</code>```

this will check for all props. If you want to check against a specific prop, you can do:

```<code>shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props.link) !== JSON.stringify(nextProps.link);
}
</code>```

As pointed out in the comments, there is always a small chance that JSON.stringify(this.props) !== JSON.stringify(nextProps) will return false even when they are equal.

As such, if you want a more robust way of comparing the this.props object to the newProps object, you should take a look at this post.

Body:
I have a ReactJS project where i get JSON from REST Django host and creating a table with filters for it. I have a Table class :

class MainTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      results: []
    };
  }

  componentDidMount(){
    axios.get(this.props.link)
      .then(res => {
        this.setState({results: res.data.results});
    });
  }

  render() {
    return (

            Name
            Name

          {this.state.results.map(result =>

              {result.Name}
              {result.Name}

          )}

    );
  }
}

And Main where i run all filter classes :

class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      origin: '',
      limit: 10
    };

    this.handleChangeOrigin = this.handleChangeOrigin.bind(this);
    this.handleChangeLimit = this.handleChangeLimit.bind(this);
  }

  handleChangeLimit(event) {
    this.setState({limit: event.target.value});
  }
  handleChangeOrigin(event) {
    this.setState({origin: event.target.value});
  }

  render() {
    var link = `http://106.120.89.142:8000/database/?limit=${this.state.limit}&`;
    if (this.state.origin){
      link += `ORIGIN=${this.state.origin.toLowerCase()}`;
      console.log(link)
    }
    return (

Here u got database *_*

          <Limit handleChange = {this.handleChangeLimit} />

          <OriginRow handleChange = {this.handleChangeOrigin} />

          <MainTable link={link} />

    );
  }
}

And i have a problem with it, cause when i use componentDidMount(), my axios.get(my link to REST JSON) runs only once. When i use axios in Table class render(), it hits my server few times per second. Can i make mounting only when my props to Table class changed?

Body:
You should take a look at the shouldComponentUpdate() life-cycle method, here.

shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState)

Use shouldComponentUpdate() to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Add the following snippet to your MainTable component. This will prevent it from re-rendering, unless the props have changed.

shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props) !== JSON.stringify(nextProps);
}

this will check for all props. If you want to check against a specific prop, you can do:

shouldComponentUpdate(nextProps) {
  return JSON.stringify(this.props.link) !== JSON.stringify(nextProps.link);
}

As pointed out in the comments, there is always a small chance that JSON.stringify(this.props) !== JSON.stringify(nextProps) will return false even when they are equal.

As such, if you want a more robust way of comparing the this.props object to the newProps object, you should take a look at this post.


来源: stackexchange

问:
Need to use codeception parameters in test code
I have environment configuration in my acceptance.suite.yml config file.
One of the parameters is language. I need to know this parameter value in the actual test code to be able to drive test steps correctly.

acceptance.suite.yml config content:

```<code> class_name: WebGuy
modules:
    enabled:
        - WebDriver
        - WebHelper
        - Db
    config:
        WebDriver:
            browser: firefox
env:
    eng:
        modules:
            config:
                WebDriver:
                   url: 'localhost'
                   lang: en
   esp:
        modules:
            config:
                WebDriver:
                    url: 'localhost'
                    lang: es
</code>```

How can I get the language parameter value?

答:
The answer by @George will give you all the settings, but not the selected environment.

I struggled to get the current environment using getopt, but found this to work well enough for my needs. I was getting the baseUrl value so have included the tested code for that instead of editing it for "lang" as per the question but not testing it. It should just be a matter of changing the arrays which pick out the value.

```<code>// Default to no env
$env = '';
// If we have argv settings, go through each one
if (isset($_SERVER['argv'])) {
    foreach($_SERVER['argv'] as $key => $value) {
        // If the current value is --env and we have the next one, then take the next one as the setting
        if ($value == '--env' && isset($_SERVER['argv'][$key + 1])) {
            $env = $_SERVER['argv'][$key + 1];
        }
    }
}
// By this point we either found an --env and have its value, or we
// didn't and can assume we don't have one set.
// We look in a slightly difference place depending on whether we
// have an env or not
if ( empty( $env ) ) {
    $baseUrl = $apiSettings['modules']['config']['baseUrl'];
} else {
    $baseUrl = $apiSettings['env'][$env]['modules']['config']['baseUrl'];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have environment configuration in my acceptance.suite.yml config file.
One of the parameters is language. I need to know this parameter value in the actual test code to be able to drive test steps correctly.

acceptance.suite.yml config content:

 class_name: WebGuy
modules:
    enabled:
        - WebDriver
        - WebHelper
        - Db
    config:
        WebDriver:
            browser: firefox
env:
    eng:
        modules:
            config:
                WebDriver:
                   url: 'localhost'
                   lang: en
   esp:
        modules:
            config:
                WebDriver:
                    url: 'localhost'
                    lang: es

How can I get the language parameter value?

Body:
The answer by @George will give you all the settings, but not the selected environment.

I struggled to get the current environment using getopt, but found this to work well enough for my needs. I was getting the baseUrl value so have included the tested code for that instead of editing it for "lang" as per the question but not testing it. It should just be a matter of changing the arrays which pick out the value.

// Default to no env
$env = '';
// If we have argv settings, go through each one
if (isset($_SERVER['argv'])) {
    foreach($_SERVER['argv'] as $key => $value) {
        // If the current value is --env and we have the next one, then take the next one as the setting
        if ($value == '--env' && isset($_SERVER['argv'][$key + 1])) {
            $env = $_SERVER['argv'][$key + 1];
        }
    }
}
// By this point we either found an --env and have its value, or we
// didn't and can assume we don't have one set.
// We look in a slightly difference place depending on whether we
// have an env or not
if ( empty( $env ) ) {
    $baseUrl = $apiSettings['modules']['config']['baseUrl'];
} else {
    $baseUrl = $apiSettings['env'][$env]['modules']['config']['baseUrl'];
}


问:
Create multiple Facebook messenger bots with one app
The Facebook messenger bot API seems to require you create a Facebook app for each bot, for each page.  The Facebook app stores the webhook, and connects to the page.

Is there a way to have a single Facebook app for many bots connected to many pages?

If you create a bot to resell to clients as a service, you need to be able to do this. But there does not seem to be any way. You need to create a Facebook app for each client, and go through the Facebook app review process for each page which is very difficult.

How can this be avoided?
Can a single Facebook app have multiple webhooks, or access to multiple pages messages?

答:
You can create one chatbot and can use this bot in multiple Facebook pages. All you need is to store PAGE_ACCESS_TOKEN for each page and response messages to the user with right PAGE_ACCESS_TOKEN. You should get the necessary permissions to get page access tokens by Facebook Login. And then you need to subscribe the page to your chatbot(app): https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps

One important thing is Facebook generates a unique identifier for users for each page. Some user#A will have a different SENDER_ID/RECIPIENT_ID on different pages.


问:
JQgrid inline editing with asp.net and C#
I am using above below for viewing data and editing with it. First row is used for edit button, but whenever I click save button I am unable to capture that event.

I want to know how it works and how can I call a AJAX function to store that data to SQL Server.

```<code>$(function() {
    var grid_selector = "#grid-table-Labor";

    $("#grid-table-Labor").jqGrid({
        url: 'LaborApproval.aspx/GetLaborData', //asp function to get all data from data base to grid
        data: "{}",
        datatype: 'json',
        mtype: 'POST',
        serializeGridData: function(postData) {
            return JSON.stringify(postData);
        },
        ajaxGridOptions: {
            contentType: "application/json"
        },
        loadonce: true,
        colNames: [' ', 'Employee Code', 'Name', 'Contractor', 'DOJ', 'Police Verification', 'Gate Pass Valid Upto', 'Status', 'Remark'],
        colModel: [{
                name: 'myac',
                index: 'myac',
                width: 80,
                fixed: true,
                sortable: false,
                resize: false,
                formatter: 'actions',
                formatoptions: {
                    keys: true,
                    delbutton: false, //disable delete button

                    //delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback },
                    //editformbutton:true
                }
            },
            {
                name: 'EMPCODE',
                index: 'EMPCODE',
                width: 108,
                formatter: 'showlink',
                key: true
            },
            {
                name: 'NAME',
                index: 'NAME',
                width: 140
            },
            {
                name: 'CONTNAME',
                index: 'CONTNAME',
                width: 160
            },
            {
                name: 'DOJ',
                index: 'DOJ',
                width: 70,
                formatter: 'date',
                formatoptions: {
                    newformat: 'd-m-y'
                }
            },
            {
                name: 'POLICE_VRIFICATION',
                index: 'POLICE_VRIFICATION',
                width: 124
            },
            {
                name: 'GatePassValidUpto',
                index: 'GatePassValidUpto',
                editable: true,
                sorttype: "date",
                unformat: pickDate
            },
            {
                name: 'Approve',
                index: 'Approve',
                width: 148,
                editable: true,
                edittype: "select",
                editoptions: {
                    value: "1:Approve;0:Rejected"
                }
            },
            {
                name: 'REMARK',
                index: 'REMARK',
                width: 150,
                sortable: false,
                editable: true,
                edittype: "textarea",
                editoptions: {
                    rows: "2",
                    cols: "10"
                }
            }
        ],
        pager: '#grid-pager-Labor',
        altRows: true,
        cacheUrlData: true,
        //toppager: true,
        rowNum: 1,
        scrollOffset: 0, // to remove offset of scroll bar for imporved gui
        rowList: [10, 50, 100, 200, 300, 500, 800, 1000, 1500],
        //onSelectRow: editRow,
        viewrecords: true,
        emptyrecords: "Nothing to display",
        //multiselect: true,
        //multiboxonly: false,
        gridview: true,
        loadComplete: function() {
            var table = this;
            setTimeout(function() {
                //styleCheckbox(table);
                //updateActionIcons(table);
                updatePagerIcons(table);
                enableTooltips(table);
            }, 0);
        },
        jsonReader: {
            page: function(obj) {
                return 1;
            },
            total: function(obj) {
                return 1;
            },
            records: function(obj) {
                return obj.d.length;
            },
            root: function(obj) {
                return obj.d;
            },
            repeatitems: false,
            id: "0"
        },

        //editurl: "LaborApproval.aspx/PostLaborData",
        editurl: "",
        caption: 'Labor List',
        shrinkToFit: true,
        height: 'auto',
        //autowidth: true,
    });

    $('#grid-table-Labor').jqGrid('navGrid', '#grid-pager-Labor', {
        edit: false,
        del: false,
        search: true,
        searchtext: "Search",
        searchicon: 'ace-icon fa fa-search orange',
        view: true,
        viewtext: "View",
        viewicon: 'ace-icon fa fa-search-plus grey',
    })
});

function updatePagerIcons(table) {
    var replacement = {
        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    })
}

function enableTooltips(table) {
    $('.navtable .ui-pg-button').tooltip({
        container: 'body'
    });
    $(table).find('.ui-pg-div').tooltip({
        container: 'body'
    });
}

function pickDate(cellvalue, options, cell) {
    setTimeout(function() {
        $(cell).find('input[type=text]')
            .datepicker({
                format: 'dd-mm-yyyy',
                autoclose: true
            });
    }, 0);
}
</code>```

答:
It is important to note which version of jqGrid is used.
If you use Guriddo jqGrid you may need to use serializeRowData described in our documentation here the same  you use serializeGridData to get parameters from the grid.

Kind Regards

Body:
I am using above below for viewing data and editing with it. First row is used for edit button, but whenever I click save button I am unable to capture that event.

I want to know how it works and how can I call a AJAX function to store that data to SQL Server.

$(function() {
    var grid_selector = "#grid-table-Labor";

    $("#grid-table-Labor").jqGrid({
        url: 'LaborApproval.aspx/GetLaborData', //asp function to get all data from data base to grid
        data: "{}",
        datatype: 'json',
        mtype: 'POST',
        serializeGridData: function(postData) {
            return JSON.stringify(postData);
        },
        ajaxGridOptions: {
            contentType: "application/json"
        },
        loadonce: true,
        colNames: [' ', 'Employee Code', 'Name', 'Contractor', 'DOJ', 'Police Verification', 'Gate Pass Valid Upto', 'Status', 'Remark'],
        colModel: [{
                name: 'myac',
                index: 'myac',
                width: 80,
                fixed: true,
                sortable: false,
                resize: false,
                formatter: 'actions',
                formatoptions: {
                    keys: true,
                    delbutton: false, //disable delete button

                    //delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback },
                    //editformbutton:true
                }
            },
            {
                name: 'EMPCODE',
                index: 'EMPCODE',
                width: 108,
                formatter: 'showlink',
                key: true
            },
            {
                name: 'NAME',
                index: 'NAME',
                width: 140
            },
            {
                name: 'CONTNAME',
                index: 'CONTNAME',
                width: 160
            },
            {
                name: 'DOJ',
                index: 'DOJ',
                width: 70,
                formatter: 'date',
                formatoptions: {
                    newformat: 'd-m-y'
                }
            },
            {
                name: 'POLICE_VRIFICATION',
                index: 'POLICE_VRIFICATION',
                width: 124
            },
            {
                name: 'GatePassValidUpto',
                index: 'GatePassValidUpto',
                editable: true,
                sorttype: "date",
                unformat: pickDate
            },
            {
                name: 'Approve',
                index: 'Approve',
                width: 148,
                editable: true,
                edittype: "select",
                editoptions: {
                    value: "1:Approve;0:Rejected"
                }
            },
            {
                name: 'REMARK',
                index: 'REMARK',
                width: 150,
                sortable: false,
                editable: true,
                edittype: "textarea",
                editoptions: {
                    rows: "2",
                    cols: "10"
                }
            }
        ],
        pager: '#grid-pager-Labor',
        altRows: true,
        cacheUrlData: true,
        //toppager: true,
        rowNum: 1,
        scrollOffset: 0, // to remove offset of scroll bar for imporved gui
        rowList: [10, 50, 100, 200, 300, 500, 800, 1000, 1500],
        //onSelectRow: editRow,
        viewrecords: true,
        emptyrecords: "Nothing to display",
        //multiselect: true,
        //multiboxonly: false,
        gridview: true,
        loadComplete: function() {
            var table = this;
            setTimeout(function() {
                //styleCheckbox(table);
                //updateActionIcons(table);
                updatePagerIcons(table);
                enableTooltips(table);
            }, 0);
        },
        jsonReader: {
            page: function(obj) {
                return 1;
            },
            total: function(obj) {
                return 1;
            },
            records: function(obj) {
                return obj.d.length;
            },
            root: function(obj) {
                return obj.d;
            },
            repeatitems: false,
            id: "0"
        },

        //editurl: "LaborApproval.aspx/PostLaborData",
        editurl: "",
        caption: 'Labor List',
        shrinkToFit: true,
        height: 'auto',
        //autowidth: true,
    });

    $('#grid-table-Labor').jqGrid('navGrid', '#grid-pager-Labor', {
        edit: false,
        del: false,
        search: true,
        searchtext: "Search",
        searchicon: 'ace-icon fa fa-search orange',
        view: true,
        viewtext: "View",
        viewicon: 'ace-icon fa fa-search-plus grey',
    })
});

function updatePagerIcons(table) {
    var replacement = {
        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function() {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    })
}

function enableTooltips(table) {
    $('.navtable .ui-pg-button').tooltip({
        container: 'body'
    });
    $(table).find('.ui-pg-div').tooltip({
        container: 'body'
    });
}

function pickDate(cellvalue, options, cell) {
    setTimeout(function() {
        $(cell).find('input[type=text]')
            .datepicker({
                format: 'dd-mm-yyyy',
                autoclose: true
            });
    }, 0);
}


问:
How to change image permission mode to 777 using Java code?
I want to give permissions mode value "777" to image file using Java code. How can I give that using Java? Because I can't delete the image with default permission mode "664". </p>

答:
Here goes the code:-</p>

```<code>List<String> chPermList = new LinkedList<String>();
chPermList.add("/bin/chmod");
chPermList.add("777");
chPermList.add(Path_to_image_file);

    public void changePermission(List chPermList)
    {
        ProcessBuilder pb = null;
        pb = new ProcessBuilder(chPermList);
                pb.redirectErrorStream(true);

                Process p = pb.start();

                BufferedReader br = new BufferedReader(new InputStreamReader(p
                        .getInputStream()));

                p.waitFor();

                if(p.exitValue()!=0)
                {
                    strExpMsg = "The permission change failed with exit value" + p.exitValue();

                }
    }
</code>```

OwnerDisplayName: Raja D

Body:
Here goes the code:-

List<String> chPermList = new LinkedList<String>();
chPermList.add("/bin/chmod");
chPermList.add("777");
chPermList.add(Path_to_image_file);

    public void changePermission(List chPermList)
    {
        ProcessBuilder pb = null;
        pb = new ProcessBuilder(chPermList);
                pb.redirectErrorStream(true);

                Process p = pb.start();

                BufferedReader br = new BufferedReader(new InputStreamReader(p
                        .getInputStream()));

                p.waitFor();

                if(p.exitValue()!=0)
                {
                    strExpMsg = "The permission change failed with exit value" + p.exitValue();

                }
    }

ContentLicense: CC BY-SA 2.5


问:
MSMQ with asp.net and wcf
Currently i'm developing an apllication that sends sms via the asp.net. I'm using msmq for the queuing incase of multiple sending of sms. The wcf will then check for new queue and using teh queue to send out a sms. I've a few question.

How do i create a  new queue for the msmq  via asp.net

how do i schedule something in wcf ?

答:
1 . How do i create a new queue for the msmq via asp.net

In order to create queues on the fly, you can use System.Messaging in .NET - see e.g. this article on how to do it.

2 . how do i schedule something in wcf ?

Why do you need to schedule something in WCF? What are you trying to do, trying to achieve here??

WCF is a service-oriented framework - it's about messages and stuff like that - not scheduling.

Title: MSMQ with asp.net and wcf


问:
Switch statement with boolean is not working?
Why is my compiler telling me:

Incompatible Types:

Required: Boolean

Found: Int

under case 0 & case 1

For instance:

```<code>    public void test(boolean isOn){
    switch (isOn){
        case 0:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 1:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }
</code>```

}

Driver Class:

```<code>Club me = new Club();
me.test(true);
</code>```

答:
Just convert the boolean to number of 1 and 0.</p>

```<code>public void test(boolean isOn){
    int trueOrFalse;
    if(isOn == true){
      trueOrFalse = 1;
    }else{
      trueOrFalse = 0;
    }
    switch (trueOrFalse){
        case 1:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 0:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }
}
</code>```

Body:
Why is my compiler telling me:

Incompatible Types:

Required: Boolean

Found: Int

under case 0 & case 1

For instance:

    public void test(boolean isOn){
    switch (isOn){
        case 0:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 1:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }

}

Driver Class:

Club me = new Club();
me.test(true);

Body:
Just convert the boolean to number of 1 and 0.

public void test(boolean isOn){
    int trueOrFalse;
    if(isOn == true){
      trueOrFalse = 1;
    }else{
      trueOrFalse = 0;
    }
    switch (trueOrFalse){
        case 1:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 0:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }
}


问:
Body overflow when opening modal from modal
I have problem with bootstrap modals. When i open first modal, then body has class modal-open and thats ok, however when i am clicking the button which is closing first modal and opening another, class is removed from body even when there is modal opened. I was trying to fix that in that way but without any success:

```<code>openedModalsCount = 0;

    $('*').on('show.bs.modal', function() {
        openedModalsCount++;
        if(openedModalsCount > 0) {
            $('body').addClass('modal-open');
        }
    });

    $('*').on('hidden.bs.modal', function() {
        openedModalsCount--;
        if(openedModalsCount < 1) {
            $('body').removeClass('modal-open');
        }
    });
</code>```

any suggestions? Thanks in advance for any help

答:
I am not sure, but it may solve your problem.</p>

```<code>$('#myModal').on('show.bs.modal', function() {
    $('body').addClass('modal-open');
});

$('#myModal').on('hidden.bs.modal', function() {
    $('body').removeClass('modal-open');
});

//because myModal is unique id of the modal
</code>```

Body:
I have problem with bootstrap modals. When i open first modal, then body has class modal-open and thats ok, however when i am clicking the button which is closing first modal and opening another, class is removed from body even when there is modal opened. I was trying to fix that in that way but without any success:

openedModalsCount = 0;

    $('*').on('show.bs.modal', function() {
        openedModalsCount++;
        if(openedModalsCount > 0) {
            $('body').addClass('modal-open');
        }
    });

    $('*').on('hidden.bs.modal', function() {
        openedModalsCount--;
        if(openedModalsCount < 1) {
            $('body').removeClass('modal-open');
        }
    });

any suggestions? Thanks in advance for any help

Body:
I am not sure, but it may solve your problem.

$('#myModal').on('show.bs.modal', function() {
    $('body').addClass('modal-open');
});

$('#myModal').on('hidden.bs.modal', function() {
    $('body').removeClass('modal-open');
});

//because myModal is unique id of the modal


问:
Count specific word in file with
Im trying to count the number of occurrences of a word in a comma seperated file, using python.

I have a file that contains strings like this:

```<code>path/to/app1,app1,fail,my@email.com,logfile.log
path/to/app2,app2,success,my@email.com,logfile.log
</code>```

I want to find the out how many times "fail" is in the file.

I tried several things including

```<code>for line in lines:
   if line.split(',') == "fail":
       fails += 1
</code>```

答:
try this:

```<code>def specific_word_count(text, specific_word):
    return len(text.split(specific_word)) - 1
</code>```

input：

```<code>specific_word_count('abcdabcdabcd','a')
</code>```

output：

```<code>3
</code>```

Title: Count specific word in file with

Body:
Im trying to count the number of occurrences of a word in a comma seperated file, using python.

I have a file that contains strings like this:

path/to/app1,app1,fail,my@email.com,logfile.log
path/to/app2,app2,success,my@email.com,logfile.log

I want to find the out how many times "fail" is in the file.

I tried several things including

for line in lines:
   if line.split(',') == "fail":
       fails += 1

Body:
try this:

def specific_word_count(text, specific_word):
    return len(text.split(specific_word)) - 1

input：

specific_word_count('abcdabcdabcd','a')

output：

3


问:
How do I get an ISO 8601 date on iOS?
It's easy enough to get the ISO 8601 date string (for example, 2004-02-12T15:19:21+00:00) in PHP via date('c'), but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?

Here's the long way I found to do it:

```<code>NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);

// Output: ISO-8601 date: 2013-04-27T13:27:50-0700
</code>```

It seems an awful lot of rigmarole for something so central.

答:
An often overlooked issue is that strings in ISO 8601 format might have milliseconds and might not.

In other words, both "2016-12-31T23:59:59.9999999" and "2016-12-01T00:00:00" are legit, but if you are using static-typed date formatter, one of them won't be parsed.

Starting from iOS 10 you should use ISO8601DateFormatter that handles all variations of ISO 8601 date strings. See example below:

```<code>let date = Date()
var string: String

let formatter = ISO8601DateFormatter()
string = formatter.string(from: date)

let GMT = TimeZone(abbreviation: "GMT")
let options: ISO8601DateFormatOptions = [.withInternetDateTime, .withDashSeparatorInDate, .withColonSeparatorInTime, .withTimeZone]
string = ISO8601DateFormatter.string(from: date, timeZone: GMT, formatOptions: options)
</code>```

For iOS 9 and below use the following approach with multiple data formatters.

I haven't found an answer that covers both cases and abstracts away this subtle difference. Here is the solution that addresses it:

```<code>extension DateFormatter {

    static let iso8601DateFormatter: DateFormatter = {
        let enUSPOSIXLocale = Locale(identifier: "en_US_POSIX")
        let iso8601DateFormatter = DateFormatter()
        iso8601DateFormatter.locale = enUSPOSIXLocale
        iso8601DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        return iso8601DateFormatter
    }()

    static let iso8601WithoutMillisecondsDateFormatter: DateFormatter = {
        let enUSPOSIXLocale = Locale(identifier: "en_US_POSIX")
        let iso8601DateFormatter = DateFormatter()
        iso8601DateFormatter.locale = enUSPOSIXLocale
        iso8601DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        return iso8601DateFormatter
    }()

    static func date(fromISO8601String string: String) -> Date? {
        if let dateWithMilliseconds = iso8601DateFormatter.date(from: string) {
            return dateWithMilliseconds
        }

        if let dateWithoutMilliseconds = iso8601WithoutMillisecondsDateFormatter.date(from: string) {
            return dateWithoutMilliseconds
        }

        return nil
    }
}
</code>```

Usage:

```<code>let dateToString = "2016-12-31T23:59:59.9999999"
let dateTo = DateFormatter.date(fromISO8601String: dateToString)
// dateTo: 2016-12-31 23:59:59 +0000

let dateFromString = "2016-12-01T00:00:00"
let dateFrom = DateFormatter.date(fromISO8601String: dateFromString)
// dateFrom: 2016-12-01 00:00:00 +0000
</code>```

I also recommend checking Apple article about date formatters.

Title: How do I get an ISO 8601 date on iOS?

Body:
It's easy enough to get the ISO 8601 date string (for example, 2004-02-12T15:19:21+00:00) in PHP via date('c'), but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?

Here's the long way I found to do it:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);

// Output: ISO-8601 date: 2013-04-27T13:27:50-0700

It seems an awful lot of rigmarole for something so central.

Body:
An often overlooked issue is that strings in ISO 8601 format might have milliseconds and might not.

In other words, both "2016-12-31T23:59:59.9999999" and "2016-12-01T00:00:00" are legit, but if you are using static-typed date formatter, one of them won't be parsed.

Starting from iOS 10 you should use ISO8601DateFormatter that handles all variations of ISO 8601 date strings. See example below:

let date = Date()
var string: String

let formatter = ISO8601DateFormatter()
string = formatter.string(from: date)

let GMT = TimeZone(abbreviation: "GMT")
let options: ISO8601DateFormatOptions = [.withInternetDateTime, .withDashSeparatorInDate, .withColonSeparatorInTime, .withTimeZone]
string = ISO8601DateFormatter.string(from: date, timeZone: GMT, formatOptions: options)

For iOS 9 and below use the following approach with multiple data formatters.

I haven't found an answer that covers both cases and abstracts away this subtle difference. Here is the solution that addresses it:

extension DateFormatter {

    static let iso8601DateFormatter: DateFormatter = {
        let enUSPOSIXLocale = Locale(identifier: "en_US_POSIX")
        let iso8601DateFormatter = DateFormatter()
        iso8601DateFormatter.locale = enUSPOSIXLocale
        iso8601DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        return iso8601DateFormatter
    }()

    static let iso8601WithoutMillisecondsDateFormatter: DateFormatter = {
        let enUSPOSIXLocale = Locale(identifier: "en_US_POSIX")
        let iso8601DateFormatter = DateFormatter()
        iso8601DateFormatter.locale = enUSPOSIXLocale
        iso8601DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        return iso8601DateFormatter
    }()

    static func date(fromISO8601String string: String) -> Date? {
        if let dateWithMilliseconds = iso8601DateFormatter.date(from: string) {
            return dateWithMilliseconds
        }

        if let dateWithoutMilliseconds = iso8601WithoutMillisecondsDateFormatter.date(from: string) {
            return dateWithoutMilliseconds
        }

        return nil
    }
}

Usage:

let dateToString = "2016-12-31T23:59:59.9999999"
let dateTo = DateFormatter.date(fromISO8601String: dateToString)
// dateTo: 2016-12-31 23:59:59 +0000

let dateFromString = "2016-12-01T00:00:00"
let dateFrom = DateFormatter.date(fromISO8601String: dateFromString)
// dateFrom: 2016-12-01 00:00:00 +0000

I also recommend checking Apple article about date formatters.

ContentLicense: CC BY-SA 4.0


问:
jquery selecting child elements
The setup.

I am using MVC 5, and I have created a view with data sent in the form of a viewmodel.

With in this view I have rendered a List object as stacked div's, as seen below.

As you will see, I am displaying hidden fields, so that the viewModel send back the data to the controller on submit.

```<code><div class="row item-row">
    <div class="small-4 columns">
        objType
    </div>
    <div class="small-6 columns">
        <input id="object_0__Id" name="object[0].Id" type="hidden" value="999999">
        <input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
        <input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">
    </div>
    <div class="small-2 columns remove-item">
        <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(999999);">Remove</button>
    </div>
</div>
<div class="row item-row">
    <div class="small-4 columns">
        objType
    </div>
    <div class="small-6 columns">
        <input id="object_1__Id" name="object[1].Id" type="hidden" value="000001">
        <input id="object_1__Reference" name="object[1].Reference" type="hidden" value="myRef">myRef
        <input id="object_1__RecordChanged" name="object[1].RecordChanged" type="hidden" value="NoChange">
    </div>
    <div class="small-2 columns remove-item">
        <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>
    </div>
</div>
</code>```

Ok, so the javascript function RemoveItem is:

```<code>function RemoveItem(id)
{
    event.preventDefault();

    var element = $(event.target).closest('.item-row');

    $(element).closest('DeedReference_0__RecordChanged').val('Deleted');   ***** This is what I am trying to do.

    $(element).hide();
}
</code>```

From the above, when I click on say RemoveItem(00001), the variable element contains the following:

```<code><div class="small-4 columns">
    objType
</div>
<div class="small-6 columns">
    <input id="object_0__Id" name="object[0].Id" type="hidden" value="000001">
    <input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
    <input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">
</div>
<div class="small-2 columns remove-item">
    <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>
</div>
</code>```

The value I need to update is object[0].RecordChanged, but at this moment in time, I do not know the index value. So I was planning on using the ends with selector, but am not able to get it to work.

I have got as far as:

```<code>$(event.target).closest('.item-row').children()[1]
</code>```

But this gives me the div, since I have tried:

```<code>$(event.target).closest('.item-row').children()[1].Find('Id*"__RecordChanged"')
$(event.target).closest('.item-row [id*="RecordChanged"]')
$(event.target).closest('.item-row:[id*="RecordChanged"])
</code>```

And using the variable

```<code>$(element [id*="RecordChanged"])
$(element [id$="RecordChanged"])
</code>```

UPDATE

Fixed bug in code that was suggesting that I was looking at the wrong index.

Also, If I click the remove button for RemoveItem(000001), I am trying to update the value object_0__RecordChanged.

答:
Changed view model  to have an index property. Then changed placed the HTML.EditorFor within a foreach loop enabling me to populate the index property before it is rendered out.

Then the code was changed from:

```<code>function RemoveItem(id)
{
    event.preventDefault();

    var element = $(event.target).closest('.item-row');

    $(element).closest('DeedReference_0__RecordChanged').val('Deleted');   ***** This is what I am trying to do.

    $(element).hide();
}
</code>```

to:

```<code>function RemoveItem(id)
{
    event.preventDefault();
    var recordChanged = '#object_' + id + '__RecordChanged';
    $(recordChanged).val('Deleted');
    var element = $(event.target).closest('.item-row');
    $(element).hide();
}
</code>```

Much simpler!

Title: jquery selecting child elements

Body:
The setup.

I am using MVC 5, and I have created a view with data sent in the form of a viewmodel.

With in this view I have rendered a List object as stacked div's, as seen below.

As you will see, I am displaying hidden fields, so that the viewModel send back the data to the controller on submit.

        objType

        <input id="object_0__Id" name="object[0].Id" type="hidden" value="999999">
        <input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
        <input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">

        <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(999999);">Remove</button>

        objType

        <input id="object_1__Id" name="object[1].Id" type="hidden" value="000001">
        <input id="object_1__Reference" name="object[1].Reference" type="hidden" value="myRef">myRef
        <input id="object_1__RecordChanged" name="object[1].RecordChanged" type="hidden" value="NoChange">

        <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>

Ok, so the javascript function RemoveItem is:

function RemoveItem(id)
{
    event.preventDefault();

    var element = $(event.target).closest('.item-row');

    $(element).closest('DeedReference_0__RecordChanged').val('Deleted');   ***** This is what I am trying to do.

    $(element).hide();
}

From the above, when I click on say RemoveItem(00001), the variable element contains the following:

    objType

    <input id="object_0__Id" name="object[0].Id" type="hidden" value="000001">
    <input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
    <input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">

    <button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>

The value I need to update is object[0].RecordChanged, but at this moment in time, I do not know the index value. So I was planning on using the ends with selector, but am not able to get it to work.

I have got as far as:

$(event.target).closest('.item-row').children()[1]

But this gives me the div, since I have tried:

$(event.target).closest('.item-row').children()[1].Find('Id*"__RecordChanged"')
$(event.target).closest('.item-row [id*="RecordChanged"]')
$(event.target).closest('.item-row:[id*="RecordChanged"])

And using the variable

$(element [id*="RecordChanged"])
$(element [id$="RecordChanged"])

UPDATE

Fixed bug in code that was suggesting that I was looking at the wrong index.

Also, If I click the remove button for RemoveItem(000001), I am trying to update the value object_0__RecordChanged.

Body:
Changed view model  to have an index property. Then changed placed the HTML.EditorFor within a foreach loop enabling me to populate the index property before it is rendered out.

Then the code was changed from:

function RemoveItem(id)
{
    event.preventDefault();

    var element = $(event.target).closest('.item-row');

    $(element).closest('DeedReference_0__RecordChanged').val('Deleted');   ***** This is what I am trying to do.

    $(element).hide();
}

to:

function RemoveItem(id)
{
    event.preventDefault();
    var recordChanged = '#object_' + id + '__RecordChanged';
    $(recordChanged).val('Deleted');
    var element = $(event.target).closest('.item-row');
    $(element).hide();
}

Much simpler!


问:
RabbitConnectionFactory maven dependency
which dependencies that I need in order to use RabbitConnectionFactory? I have the below pom, but RabbitConnectionFactory cannot be resolved:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test.rabbit</groupId>
<artifactId>connector</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-cloudfoundry-connector</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-spring-service-connector</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-cloudfoundry-connector</artifactId>
    </dependency>
</dependencies>
</code>```

My repo is here:
https://github.com/pkid/rabbitconnectionfac

Thank you for your help in advance!

答:
There is no such class RabbitConnectionFactory.

Where are you seeing an error?

With spring-rabbit, you would generally use its CachingConnetionFactory. It uses an underlying ConnectionFactory from the amqp-client library, which is a transitive dependency.

spring-cloud-service-connector, in RabbitConnectionFactoryCreator creates instances of these objects.

Body:
which dependencies that I need in order to use RabbitConnectionFactory? I have the below pom, but RabbitConnectionFactory cannot be resolved:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test.rabbit</groupId>
<artifactId>connector</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-cloudfoundry-connector</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-spring-service-connector</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-cloudfoundry-connector</artifactId>
    </dependency>
</dependencies>

My repo is here:
https://github.com/pkid/rabbitconnectionfac

Thank you for your help in advance!


问:
Call function with angular when scrolling
Is there a way to detect, if a element was scrolled and call a function and do some stuff with angularJS? Something like a ng-scroll or so, which works simply like a ng-click? I didn't really find a solution...

This is what I would like to do:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.checkIfScrolling = function() {
    console.log("scrolled...");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box-scroll {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100px;
  background-color: lightgrey;
  overflow: auto;
}</code>```

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

```

答:
Nothing native, you'd have to wire up your own directive using the onscroll event:

https://developer.mozilla.org/en-US/docs/Web/Events/scroll

Body:
Is there a way to detect, if a element was scrolled and call a function and do some stuff with angularJS? Something like a ng-scroll or so, which works simply like a ng-click? I didn't really find a solution...

This is what I would like to do:

angular.module("myApp", []).controller("myController", function($scope) {
  $scope.checkIfScrolling = function() {
    console.log("scrolled...");
  }
});

.box-scroll {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100px;
  background-color: lightgrey;
  overflow: auto;
}

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll

I'm an item within box-scroll


问:
Using a CTE to split results across a CROSS APPLY
I have some data that I need to output as rows containing markup tags, which I'm doing inside a table valued function.

This has been working fine up to a point using code in the format below, using the search query to gather my data, and then inserting into my returned table using the output from results.

I now need to take a longer data field and split it up over a number of rows, and I'm at something of a loss as to how to achieve this.

I started with the idea that I wanted to use a CTE to process the data from my query, but I can't see a way to get the data from my search query into my CTE and from there into my results set.

I guess I can see an alternative way of doing this by creating another table valued function in the database that returns a results set if I feed it my comment_text column, but it seems like a waste to do it that way.

Does anyone see a route through to a solution?

Example "Real" Table:

```<code>DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text char(500)
);
</code>```

Add Comment Rows:

```<code>INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment', 'Text of Alice''s comment that is much longer and will need to be split over multiple rows.');
</code>```

Format of returned results table:

```<code>DECLARE @return_table TABLE
(
   comment_date DATETIME,
   commenter_name VARCHAR(101),
   markup VARCHAR(100)
);
</code>```

Naive query (Can't run because the variable comment_text in the SplitComment CTE can't be identified.

```<code>WITH SplitComment(note,start_idx) AS
(
   SELECT '<Note>'+SUBSTRING(comment_text,0,50)+'</Note>', 0
   UNION ALL
   SELECT '<Text>'+SUBSTRING(note,start_idx,50)+'</Text>', start_idx+50 FROM SplitComment WHERE (start_idx+50) < LEN(note)
)
INSERT INTO @return_table
SELECT results.* FROM
(
   SELECT
   comment_date,
   CAST(first_name+' '+last_name AS VARCHAR(101)) commenter,
   comment_title,
   comment_text
   FROM @Comments
) AS search
CROSS APPLY
(
           SELECT comment_date, commenter, '<title>'+comment_title+'</title>' markup
 UNION ALL SELECT comment_date, commenter, SplitComment
) AS results;

SELECT * FROM @return_table;
</code>```

Results (when the function is run without the CTE):

```<code>comment_date            commenter_name                                                                                markup
2017-07-07 11:53:57.240 Bob Example                                                                                <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Alice Example                                                                                <title>Alice's Comment</title>
</code>```

Ideally, I'd like to get one additional row for Bob's comment, and two rows for Alice's comment. Something like this:

```<code>comment_date            commenter_name   markup
2017-07-07 11:53:57.240 Bob Example      <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Bob Example      <Note>Bob's Comment</Note>
2017-07-07 11:53:57.240 Alice Example    <title>Alice's Comment</title>
2017-07-07 11:53:57.240 Alice Example    <Note>Text of Alice''s comment that is much longer and w</Note>
2017-07-07 11:53:57.240 Alice Example    <Text>ill need to be split over multiple rows.</Text>
</code>```

答:
May be you are looking for something like this (it' a simplified version, I used only first name and comment_date as "identifier").
I tested it using this data and - for the moment - imaging max len 50 to split text column.
Tip: change comment_text datatype to VARCHAR(500)

```<code>DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text VARCHAR(500)
);

    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment'
    , 'Text of Alice''s comment that is much longer and will need to be split over multiple rows aaaaaa bbbbbb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff ggggggggggggg.');

WITH CTE AS (SELECT comment_date, first_name, '<Note>'+CAST( SUBSTRING(comment_text, 1, 50) AS VARCHAR(500)) +'</Note>'comment_text, 1 AS RN
             FROM @Comments
             UNION ALL
             SELECT A.comment_date, A.first_name, '<Text>'+CAST( SUBSTRING(A.comment_text, B.RN*50+1, 50) AS VARCHAR(500)) +'</Text>'AS comment_text, B.RN+1 AS RN
             FROM @Comments A
             INNER JOIN CTE B ON A.comment_date=B.comment_date AND A.first_name=B.first_name
            WHERE  LEN(A.comment_text) > B.RN*50+1
             )
SELECT A.comment_date, A.first_name, '<title>'+ comment_title+'</title>' AS markup
FROM @Comments A
UNION ALL
SELECT B.comment_date, B.first_name, B.comment_text AS markup
FROM  CTE B ;
</code>```

Output:

```<code>    comment_date        first_name  markup
2017-07-07 14:30:51.117 Bob         <title>Bob's Comment</title>
2017-07-07 14:30:51.117 Alice       <title>Alice's Comment</title>
2017-07-07 14:30:51.117 Bob          <Note>Text of Bob's comment.</Note>
2017-07-07 14:30:51.117 Alice        <Note>Text of Alice's comment that is much longer and wi</Note>
2017-07-07 14:30:51.117 Alice        <Text>ll need to be split over multiple rows aaaaaa bbbb</Text>
2017-07-07 14:30:51.117 Alice        <Text>bb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff g</Text>
2017-07-07 14:30:51.117 Alice        <Text>gggggggggggg.</Text>
</code>```

Body:
I have some data that I need to output as rows containing markup tags, which I'm doing inside a table valued function.

This has been working fine up to a point using code in the format below, using the search query to gather my data, and then inserting into my returned table using the output from results.

I now need to take a longer data field and split it up over a number of rows, and I'm at something of a loss as to how to achieve this.

I started with the idea that I wanted to use a CTE to process the data from my query, but I can't see a way to get the data from my search query into my CTE and from there into my results set.

I guess I can see an alternative way of doing this by creating another table valued function in the database that returns a results set if I feed it my comment_text column, but it seems like a waste to do it that way.

Does anyone see a route through to a solution?

Example "Real" Table:

DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text char(500)
);

Add Comment Rows:

INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment', 'Text of Alice''s comment that is much longer and will need to be split over multiple rows.');

Format of returned results table:

DECLARE @return_table TABLE
(
   comment_date DATETIME,
   commenter_name VARCHAR(101),
   markup VARCHAR(100)
);

Naive query (Can't run because the variable comment_text in the SplitComment CTE can't be identified.

WITH SplitComment(note,start_idx) AS
(
   SELECT '<Note>'+SUBSTRING(comment_text,0,50)+'</Note>', 0
   UNION ALL
   SELECT '<Text>'+SUBSTRING(note,start_idx,50)+'</Text>', start_idx+50 FROM SplitComment WHERE (start_idx+50) < LEN(note)
)
INSERT INTO @return_table
SELECT results.* FROM
(
   SELECT
   comment_date,
   CAST(first_name+' '+last_name AS VARCHAR(101)) commenter,
   comment_title,
   comment_text
   FROM @Comments
) AS search
CROSS APPLY
(
           SELECT comment_date, commenter, '<title>'+comment_title+'</title>' markup
 UNION ALL SELECT comment_date, commenter, SplitComment
) AS results;

SELECT * FROM @return_table;

Results (when the function is run without the CTE):

comment_date            commenter_name                                                                                markup
2017-07-07 11:53:57.240 Bob Example                                                                                <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Alice Example                                                                                <title>Alice's Comment</title>

Ideally, I'd like to get one additional row for Bob's comment, and two rows for Alice's comment. Something like this:

comment_date            commenter_name   markup
2017-07-07 11:53:57.240 Bob Example      <title>Bob's Comment</title>
2017-07-07 11:53:57.240 Bob Example      <Note>Bob's Comment</Note>
2017-07-07 11:53:57.240 Alice Example    <title>Alice's Comment</title>
2017-07-07 11:53:57.240 Alice Example    <Note>Text of Alice''s comment that is much longer and w</Note>
2017-07-07 11:53:57.240 Alice Example    <Text>ill need to be split over multiple rows.</Text>

Body:
May be you are looking for something like this (it' a simplified version, I used only first name and comment_date as "identifier").
I tested it using this data and - for the moment - imaging max len 50 to split text column.
Tip: change comment_text datatype to VARCHAR(500)

DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text VARCHAR(500)
);

    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment'
    , 'Text of Alice''s comment that is much longer and will need to be split over multiple rows aaaaaa bbbbbb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff ggggggggggggg.');

WITH CTE AS (SELECT comment_date, first_name, '<Note>'+CAST( SUBSTRING(comment_text, 1, 50) AS VARCHAR(500)) +'</Note>'comment_text, 1 AS RN
             FROM @Comments
             UNION ALL
             SELECT A.comment_date, A.first_name, '<Text>'+CAST( SUBSTRING(A.comment_text, B.RN*50+1, 50) AS VARCHAR(500)) +'</Text>'AS comment_text, B.RN+1 AS RN
             FROM @Comments A
             INNER JOIN CTE B ON A.comment_date=B.comment_date AND A.first_name=B.first_name
            WHERE  LEN(A.comment_text) > B.RN*50+1
             )
SELECT A.comment_date, A.first_name, '<title>'+ comment_title+'</title>' AS markup
FROM @Comments A
UNION ALL
SELECT B.comment_date, B.first_name, B.comment_text AS markup
FROM  CTE B ;

Output:

    comment_date        first_name  markup
2017-07-07 14:30:51.117 Bob         <title>Bob's Comment</title>
2017-07-07 14:30:51.117 Alice       <title>Alice's Comment</title>
2017-07-07 14:30:51.117 Bob          <Note>Text of Bob's comment.</Note>
2017-07-07 14:30:51.117 Alice        <Note>Text of Alice's comment that is much longer and wi</Note>
2017-07-07 14:30:51.117 Alice        <Text>ll need to be split over multiple rows aaaaaa bbbb</Text>
2017-07-07 14:30:51.117 Alice        <Text>bb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff g</Text>
2017-07-07 14:30:51.117 Alice        <Text>gggggggggggg.</Text>


问:
adding Css and js file to content page
I am working on vb.net website. In this website i have master page and content page.when i am adding CSS and JS file to master page it's
working perfect. it is also working when i am give this CSS to another default page so it will be not execution problem of CSS and JS file.Now,my problem is when i am add CSS file and JS file in the content place holder of the content page it is not working. so where i can put this file so it will be be work?  I have searching on many places but i cant get the proper answer from anywhere.</p>

答:
It should be working, as long as the file is there in the view source. If the tag isn't there, then you have an other problem.

An other option is to put a content place holder in the head (or footer) of your master page.

```<code><asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</code>```

And then inside the content page put your file there.

```<code><asp:Content runat="server" ID="contentHead" ContentPlaceHolderID="head">
    ... put <style and <script here.
</asp:Content>
</code>```

Title: adding Css and js file to content page

Body:
It should be working, as long as the file is there in the view source. If the tag isn't there, then you have an other problem.

An other option is to put a content place holder in the head (or footer) of your master page.

<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>

And then inside the content page put your file there.

<asp:Content runat="server" ID="contentHead" ContentPlaceHolderID="head">
    ... put <style and <script here.
</asp:Content>


问:
Remove single br in paragraph but not double br?
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

```<code>p br {display:none}
</code>```

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

```<code>p br { content: ' '; }
</code>```

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

```<code><p> oremipsum lorem<br/>
orem blalgr<br/><br/>
loremg grthrt
</p>
</code>```

答:
You only need this CSS:  </p>

```<code>br + br { display:none; }
</code>```

Body:
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

p br {display:none}

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

p br { content: ' '; }

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

 oremipsum lorem

orem blalgr

loremg grthrt

Body:
You only need this CSS:

br + br { display:none; }


问:
Create a controller programmatically
It has been decided we should have a common upload http api across different applications. I have a file upload controller which I want to use in multiple webapi projects.

My upload controller looks something like this

```<code>namespace MyNamespace
{
    [Authorize("PolicyName")]
    [Route("Upload")]
    public class UploadController : Controller
    {
        [HttpPost]
        [Route("Upload")]
        public async Task<IActionResult> Upload(UploadModel model)
        {
             // impl..
             return Ok();
        }
    }
}
</code>```

Naively I thought I'd just extract this into a class library and I'd be able to register it, but I can't find how?

Regardless, I do not think this is the correct method to use. I want to be able to configure the Authorize policy name, and potentially the routes. So I'm thinking I want to perhaps build up the controller, its routes and authorize setting and register it some how?

My idea of an api would be like..

```<code>((IApplicationBuilder)app).UseUploadController(config => {
    config.PolicyName = "Whatever",
    config.UploadRoute = "UploadStuff"
});
</code>```

... this would create and register the controller. No idea where to start though. I have absolutely no clue on how controllers are discovered or if they can be registered programatically.

Anyone got any pointers or libraries to look at for inspiration?

答:
If you have a controller in a different assembly, then you can make your MVC application discover it by adding the proper reference and modifying routes, as explained in this answer

As for the configuration, values passed to attributes need to be compile-time constants, so you cannot dynamically set them while running the MVC app. You can create a custom attribute which implements your logic. So for Authorize you would have something like this:

```<code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SetPermissionsAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Get everyting you need, for example from Web.config
    }

    (...)
}
</code>```

As stated in the code snippet's comment, different applications can store dynamic values for example as Web.config settings, and you can read these values  inside the attribute.

Example of a custom AuthorizeAttribute:

Title: Create a controller programmatically

Body:
It has been decided we should have a common upload http api across different applications. I have a file upload controller which I want to use in multiple webapi projects.

My upload controller looks something like this

namespace MyNamespace
{
    [Authorize("PolicyName")]
    [Route("Upload")]
    public class UploadController : Controller
    {
        [HttpPost]
        [Route("Upload")]
        public async Task<IActionResult> Upload(UploadModel model)
        {
             // impl..
             return Ok();
        }
    }
}

Naively I thought I'd just extract this into a class library and I'd be able to register it, but I can't find how?

Regardless, I do not think this is the correct method to use. I want to be able to configure the Authorize policy name, and potentially the routes. So I'm thinking I want to perhaps build up the controller, its routes and authorize setting and register it some how?

My idea of an api would be like..

((IApplicationBuilder)app).UseUploadController(config => {
    config.PolicyName = "Whatever",
    config.UploadRoute = "UploadStuff"
});

... this would create and register the controller. No idea where to start though. I have absolutely no clue on how controllers are discovered or if they can be registered programatically.

Anyone got any pointers or libraries to look at for inspiration?

Body:
If you have a controller in a different assembly, then you can make your MVC application discover it by adding the proper reference and modifying routes, as explained in this answer

As for the configuration, values passed to attributes need to be compile-time constants, so you cannot dynamically set them while running the MVC app. You can create a custom attribute which implements your logic. So for Authorize you would have something like this:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SetPermissionsAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Get everyting you need, for example from Web.config
    }

    (...)
}

As stated in the code snippet's comment, different applications can store dynamic values for example as Web.config settings, and you can read these values  inside the attribute.

Example of a custom AuthorizeAttribute:


问:
Is there a way to set a score range (or a max score) for a query
I have a very simple query :

```<code>match: {
  field => {
    boost: 4,
    query: term,
    fuzziness: 'AUTO',
  }
}
</code>```

Composed with several (about 10) others queries most of them using constant_score. The problem is that on specific terms, my query has a too big score that cancel all others queries results.

Here is a part of the explain :

```<code>"details" => [
[0] {
      "value" => 63.656006,
"description" => "sum of:",
    "details" => [
    [0] {
              "value" => 63.656006,
        "description" => "weight(title.de:kandinsky in 1694239) [PerFieldSimilarity], result of:",
            "details" => [
            [0] {
                      "value" => 63.656006,
                "description" => "score(doc=1694239,freq=1.0 = termFreq=1.0\n), product of:",
                    "details" => [
                    [0] {
                              "value" => 4.0,
                        "description" => "boost",
                            "details" => []
                    },
                    [1] {
                              "value" => 11.3820715,
                        "description" => "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
[...]
</code>```

Has you can see, I have a score of 11.38 due to the IDF.
My others queries (with scores between 1 and 3) are totally useless.

My question is :

How can I set a max possible score for a query ?

Or, even better, can I set a range of score for my query ?

I would like to avoid a constant_score query for this field, I need a few TF/IDF and score notion for this field but not that strong.

I tried this :

```<code>function_score: {
  query: { match: {
    field => term,
  }},
  score_mode: :avg,
  script_score: {
    script: {
      inline: "4 * (1 + Math.log(2 + _score))",
    }
  },
}
</code>```

It's better but it can still perform a very high score on certain cases.

答:
have u tried using Function score query ?
 Here is the link for the same
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html</p>

Body:
I have a very simple query :

match: {
  field => {
    boost: 4,
    query: term,
    fuzziness: 'AUTO',
  }
}

Composed with several (about 10) others queries most of them using constant_score. The problem is that on specific terms, my query has a too big score that cancel all others queries results.

Here is a part of the explain :

"details" => [
[0] {
      "value" => 63.656006,
"description" => "sum of:",
    "details" => [
    [0] {
              "value" => 63.656006,
        "description" => "weight(title.de:kandinsky in 1694239) [PerFieldSimilarity], result of:",
            "details" => [
            [0] {
                      "value" => 63.656006,
                "description" => "score(doc=1694239,freq=1.0 = termFreq=1.0\n), product of:",
                    "details" => [
                    [0] {
                              "value" => 4.0,
                        "description" => "boost",
                            "details" => []
                    },
                    [1] {
                              "value" => 11.3820715,
                        "description" => "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
[...]

Has you can see, I have a score of 11.38 due to the IDF.
My others queries (with scores between 1 and 3) are totally useless.

My question is :

How can I set a max possible score for a query ?

Or, even better, can I set a range of score for my query ?

I would like to avoid a constant_score query for this field, I need a few TF/IDF and score notion for this field but not that strong.

I tried this :

function_score: {
  query: { match: {
    field => term,
  }},
  score_mode: :avg,
  script_score: {
    script: {
      inline: "4 * (1 + Math.log(2 + _score))",
    }
  },
}

It's better but it can still perform a very high score on certain cases.