问:
Regarding non-equal allocators in STL
I am reading Item 10 in Effective STL by Scott Meyers on allocators in C++.

Standard says that an implementation of the STL is permitted to assume
  that all allocator objects of the same type are equivalent and always
  compare equal.

That's all well and good, but the more you think about it. the more
  you'll realize just how draconian a restriction it is that STL
  implementations may assume that allocators of the same type are
  equivalent. It means that portable allocator objects — allocators that
  will function correctly under different STL implementations — may not
  have state. Let's be explicit about this: it means that portable
  allocators may not have any nonstatic data members, at least not any
  that affect their behavior. None. Nada. That means, for example, you
  can't have one SpecialAllocator that allocates from one heap and
  a different SpecialAllocator that allocates from a different
  heap. Such allocators wouldn't be equivalent, and STL implementations
  exist where attempts to use both allocators could lead to corrupt
  runtime data structures.

In fairness to the Standardization Committee, I should point out that
  it included the following statement immediately after the text that
  permits STL implementers to assume that allocators of the same type
  are equivalent:

Implementors are encouraged to supply libraries that ... support
  non-equal instances. In such implementations. ... the semantics of
  containers and algorithms when allocator instances compare non-equal
  are implementation-defined.

This is a lovely sentiment, but as a user of the STL who is
  considering the development of a custom allocator with state, it
  offers you next to nothing.  You can take advantage of this statement
  only if (1) you know that the STL implementations you are using
  support inequivalent allocators, (2) you are willing to delve into
  their documentation to determine whether the implementation-defined
  behavior of "non-equal" allocators is acceptable to you, and

(3) you're not concerned about porting your code to STL
  implementations that may take advantage of the latitude expressly
  extended to them by the Standard. In short, this paragraph — paragraph
  5 of section 20.1.5. for those who insist on knowing — is the
  Standard's "1 have a dream" speech for allocators. Until that dream
  becomes common reality, programmers concerned about portability will
  limit themselves to custom allocators with no state.

My question on above paragraph are

What does author mean by inequivalent or  non-equal allocators?

What does last paragraph in above text i.e, point 3 mean in simple terms?

答:
Two allocators should compare equal if memory allocated by one can be freed by the other. So, for example, an allocator object that allocates from a pool that it holds can allocate and free memory from that pool, but a different allocator object that has a different pool can't (without a great deal of extra bookkeeping) free memory allocated by the first object.

Making that work right was beyond what the standards committee wanted to take on when allocators were first introduced, which is why the words were so squishy. And that license has been revoked in more recent versions of the standard.

The last paragraph means that if you write an allocator whose objects rely on internal state (e.g., the pool allocator that I mentioned above), and the library you're using respects the equality operator (as in, it won't try to pass pointers around among allocators that don't compare equal), your code will break when you try to use it with a different implementation that doesn't pay attention to the equality operator.

Title: Regarding non-equal allocators in STL


来源: stackexchange

问:
How to conditionally convert Array to object
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

```<code>taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]
</code>```

Here expected output

```<code>taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}
</code>```

How do we conditionally convert Array to object

答:
Just use Object.assign method.

let taggedItems = [{id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},{id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},{id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'}]
console.log(Object.assign({},taggedItems.map((item) =>({ id:item.id, left:item.left, top:item.top, thumbSize:item.thumbSize }))));```

ContentLicense: CC BY-SA 3.0

Body:
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]

Here expected output

taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}

How do we conditionally convert Array to object


问:
How to pass the workspace path to a bazel rule
seems there is a make env variable workspace that keeps the path value of the original bazel workspace.

But I am not sure how to pass this variable to the bazel rule.

```<code>exports_files([
  "configure.py",
])

py_binary(
    name = "configure",
    srcs = [
        "configure.py",
    ],
    data = [
        "//tensorflow/tools/git:gen_git_source.py",
        "//tools",
    ],
    args = [
#        "--workspace=" + $(location workspace), # the path to the repository
        "--tf_workspace=$(location workspace)" , # the path to the
    ]
)
</code>```

答:
Unfortunately Bazel supports neither $(location workspace) nor $(workspace).

What makes you think it does?

Body:
seems there is a make env variable workspace that keeps the path value of the original bazel workspace.

But I am not sure how to pass this variable to the bazel rule.

exports_files([
  "configure.py",
])

py_binary(
    name = "configure",
    srcs = [
        "configure.py",
    ],
    data = [
        "//tensorflow/tools/git:gen_git_source.py",
        "//tools",
    ],
    args = [
#        "--workspace=" + $(location workspace), # the path to the repository
        "--tf_workspace=$(location workspace)" , # the path to the
    ]
)


问:
Out of memory in Spring Boot application
I have a spring boot application that can run out of memory when processing very large uploaded files. I'm encountering this when running ./gradlew bootRun and using embedded tomcat.

Is there a gradle option or some other configuration I can set in a TomcatEmbeddedServletContainerFactory to set the maximum memory allowed for the spring boot application? I'd like to have something in a configuration file or the build.gradle file itself, so it would work for all developers.

I've tried setting org.gradle.jvmargs=-Xmx12000m in gradle.properties, but seems to have no effect.

答:
There are a few Gradle properties that can speed up your builds a bit.

```<code> org.gradle.parallel=true
 org.gradle.daemon=true
 org.gradle.jvmargs=-Xms256m -Xmx1024m
</code>```

If you want to add more memory to your tomcat you should change the following lines in setenv.sh script on your tomcat directory under bin/:

```<code>export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
</code>```

Body:
There are a few Gradle properties that can speed up your builds a bit.

 org.gradle.parallel=true
 org.gradle.daemon=true
 org.gradle.jvmargs=-Xms256m -Xmx1024m

If you want to add more memory to your tomcat you should change the following lines in setenv.sh script on your tomcat directory under bin/:

export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"


问:
Passing Multiple URL's for OKhttp url Request type
Is there any way to Passing Multiple URL's for OKhttp url Request type. Actually i want pass multi url's like website, mobile request urls(Androd, mobile browser, tablet) </p>

```<code>Request request = new Request.Builder()
   .url("multi url" + ---
   .addheader(---).build();
</code>```

答:
No

The OkHttp Request object allows one and only one URL.

If you require several requests, create different requests:

```<code>Request stackoverflowRequest = new Request.Builder()
  .url("https://www.stackoverflow.com/")
  .addHeader(...)
  .build();
Request googleRequest= new Request.Builder()
  .url("https://www.google.com/")
  .addHeader(...)
  .build();
</code>```

If you don't want to write all the headers X times, you can use the following:

```<code>Request templateRequest = new Request.Builder()
  .url("https://www.example.com/")
  .addHeader(...)
  .build();
Request stackoverflowRequest = templateRequest.newBuilder()
  .url("https://www.stackoverflow.com/")
  .build();
Request googleRequest = templateRequest.newBuilder()
  .url("https://www.google.com/")
  .build();
</code>```

Body:
Is there any way to Passing Multiple URL's for OKhttp url Request type. Actually i want pass multi url's like website, mobile request urls(Androd, mobile browser, tablet)

Request request = new Request.Builder()
   .url("multi url" + ---
   .addheader(---).build();

Body:
No

The OkHttp Request object allows one and only one URL.

If you require several requests, create different requests:

Request stackoverflowRequest = new Request.Builder()
  .url("https://www.stackoverflow.com/")
  .addHeader(...)
  .build();
Request googleRequest= new Request.Builder()
  .url("https://www.google.com/")
  .addHeader(...)
  .build();

If you don't want to write all the headers X times, you can use the following:

Request templateRequest = new Request.Builder()
  .url("https://www.example.com/")
  .addHeader(...)
  .build();
Request stackoverflowRequest = templateRequest.newBuilder()
  .url("https://www.stackoverflow.com/")
  .build();
Request googleRequest = templateRequest.newBuilder()
  .url("https://www.google.com/")
  .build();


问:
How to find evenly divisible values in array javascript?
It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.

For example, given the following spreadsheet:

[5, 9, 2, 8]

[9, 4, 7, 3]

[3, 8, 6, 5]

In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
In the second row, the two numbers are 9 and 3; the result is 3.
In the third row, the result is 2.
In this example, the sum of the results would be 4 + 3 + 2 = 9.

Find the evenly divisible values in next array:

[1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
[1928, 2097,138, 1824, 198, 117, 1532, 2000, 1478 ,539, 1982]

how to use for loop or reduce in this case?

https://codepen.io/marinashumeyko/pen/EbreoJ?editors=1011

答:
If you're trying to find even numbers in the array, you can use the filter method of the array, and we can apply the standard CS Logic of Modulo here:

```<code>const newArr =  [1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361].filter(e => e % 2 == 0)
console.log(newArr)
</code>```

by e % 2 we are trying to find if the element e is divisible by 2 or not, if it is then e % 2 is = 0.

Body:
If you're trying to find even numbers in the array, you can use the filter method of the array, and we can apply the standard CS Logic of Modulo here:

const newArr =  [1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361].filter(e => e % 2 == 0)
console.log(newArr)

by e % 2 we are trying to find if the element e is divisible by 2 or not, if it is then e % 2 is = 0.


问:
jQuery Mobile - prevent pagecreate calling on select
Every time when I click on select, pagecreate event is triggered. Is there a way to prevent pagecreate calling.</p>

```<code><select name="guests" id="guests" data-native-menu="false">
</select>

$(document).on('pagecreate', function (event) {
});
</code>```

答:
This happens not every time, but just the first time you open your long select list:

The custom select uses a popup with a listview to display the menu.
  For long lists a dialog will be used. (This means: a page with role="dialog")

Filter it out:

```<code>$(document).on("pagecreate", function(e) {
  if($("#"+e.target.id).hasClass("ui-selectmenu")) return;
  // do whatever stuff for "true" pages
});
</code>```

Body:
Every time when I click on select, pagecreate event is triggered. Is there a way to prevent pagecreate calling.

<select name="guests" id="guests" data-native-menu="false">
</select>

$(document).on('pagecreate', function (event) {
});

Body:
This happens not every time, but just the first time you open your long select list:

The custom select uses a popup with a listview to display the menu.
  For long lists a dialog will be used. (This means: a page with role="dialog")

Filter it out:

$(document).on("pagecreate", function(e) {
  if($("#"+e.target.id).hasClass("ui-selectmenu")) return;
  // do whatever stuff for "true" pages
});


问:
Is there a way to include duplicates from MySQL query: select..from..where..id in (list)
I am trying to get the results for the query type

```<code>SELECT * FROM table WHERE id IN(2,4,6,1,1,2) ORDER BY field (id,2,4,6,1,1,2)
</code>```

and I want to get results in the same order as the list including : the duplicates. The above query retains the order but cuts out duplicates. I know I can post-process the results but just wondering if there is an easier way.

Thanks

答:
This will actually achieve what you want:</p>

```<code>SELECT * FROM table
inner join (
   select 1 as sort, 2 as value union all
   select 2, 4 union all
   select 3, 6 union all
   select 4, 1 union all
   select 5, 1 union all
   select 6, 2) X on X.value=table.id
ORDER BY X.sort
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get the results for the query type

SELECT * FROM table WHERE id IN(2,4,6,1,1,2) ORDER BY field (id,2,4,6,1,1,2)

and I want to get results in the same order as the list including : the duplicates. The above query retains the order but cuts out duplicates. I know I can post-process the results but just wondering if there is an easier way.

Thanks

Body:
This will actually achieve what you want:

SELECT * FROM table
inner join (
   select 1 as sort, 2 as value union all
   select 2, 4 union all
   select 3, 6 union all
   select 4, 1 union all
   select 5, 1 union all
   select 6, 2) X on X.value=table.id
ORDER BY X.sort


问:
What is the difference between supervised learning and unsupervised learning?
In terms of artificial intelligence and machine learning, what is the difference between supervised and unsupervised learning?
Can you provide a basic, easy explanation with an example? </p>

答:
I'll try to keep it simple.

Supervised Learning: In this technique of learning, we are given a data set and the system already knows the correct output of the data set. So here, our system learns by predicting a value of its own. Then, it does an accuracy check by using a cost function to check how close its prediction was to the actual output.

Unsupervised Learning: In this approach, we have little or no knowledge of what our result would be. So instead, we derive structure from the data where we don't know effect of variable.
We make structure by clustering the data based on relationship among the variable in data.
Here, we don't have a feedback based on our prediction.

ContentLicense: CC BY-SA 4.0


问:
Remove part of string but getting the deleted part as result
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

```<code>var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
</code>```

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

答:
Right way would be to deal with Date object instead, it will ensure that you get right year always.</p>

```<code>var newDate = new Date(teste);
console.log(((newDate.getFullYear()).toString()).substr(2,2));
</code>```

Body:
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

Body:
Right way would be to deal with Date object instead, it will ensure that you get right year always.

var newDate = new Date(teste);
console.log(((newDate.getFullYear()).toString()).substr(2,2));


问:
How to find which radio Button is selected after a div
How can I find which radio button is selected after a precise div?

This is an Example:

```<code><div class="largelines">
    <p class="line">OPTION 1</p>
    <div class="delete">
        <a href="#" title="Delete"></a>
    </div>
    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
        <input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
    </fieldset>
</div>
</code>```

Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?

Thanks in advance.

答:
If there is just bunch of radio button you would like to check are checked or not you can do something like this

```<code>$(document).ready(function(){
    $('.delete').on('click', function(){
        $(document).find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});
</code>```

Ofc in line 3 you can specify more about the radio button location. For exp $(document).find('.largelines input[type=radio]') "OR" if you need to find radio butons based on delete button you can modify the code like this:

```<code>$(document).ready(function(){
    $('.delete').on('click', function(){
        var $parent = $(this).parents('.largelines');
        $parent.find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});
</code>```

There is bunch of other ways to do that, another one is using next() or siblings() function:

```<code>$(document).ready(function(){
    $('.delete').on('click', function(){
        var $fieldset= $(this).next('fieldset');
        //var $fieldset= $(this).siblings('fieldset');// i comment this out [its alternative way]
        $fieldset.find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});
</code>```

Body:
How can I find which radio button is selected after a precise div?

This is an Example:

OPTION 1

    <fieldset>
        <input type="radio" id="option1" name="option1" value="option1">option1

        <input type="radio" id="option2" name="option2" value="option2">option2
    </fieldset>

Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?

Thanks in advance.

Body:
If there is just bunch of radio button you would like to check are checked or not you can do something like this

$(document).ready(function(){
    $('.delete').on('click', function(){
        $(document).find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});

Ofc in line 3 you can specify more about the radio button location. For exp $(document).find('.largelines input[type=radio]') "OR" if you need to find radio butons based on delete button you can modify the code like this:

$(document).ready(function(){
    $('.delete').on('click', function(){
        var $parent = $(this).parents('.largelines');
        $parent.find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});

There is bunch of other ways to do that, another one is using next() or siblings() function:

$(document).ready(function(){
    $('.delete').on('click', function(){
        var $fieldset= $(this).next('fieldset');
        //var $fieldset= $(this).siblings('fieldset');// i comment this out [its alternative way]
        $fieldset.find('input[type=radio]').each(function(){
            if($(this).get(0).checked){
                //do something
            }
        });
    });
});


问:
Using rel="noopener" in window.open()
So I know that I can apply rel="noopener in an a tag when using target="_blank". But I'm trying to pass it as an argument to window.open(), ie:

window.open('http://cats.com', '_blank', 'rel=noopener')

however it doesn't seem to be working the way that I expected, as the opener object still exists on the window after the user clicks on the link.

Is there something I'm missing? Or cannot it not be done the way that I'm intending?

I've found some great articles but they don't quite address my use case as far as I can tell.

https://developer.mozilla.org/en-US/docs/Web/API/Window/open
https://mathiasbynens.github.io/rel-noopener/

Much appreciated.

答:
As far as I know, this cannot be achieved with window.open() arguments.  There is, however, is a way to get the behavior:

```<code>var newWindow = window.open();
newWindow.opener = null;
newWindow.location = 'http://some.url';
</code>```

Title: Using rel="noopener" in window.open()

Body:
As far as I know, this cannot be achieved with window.open() arguments.  There is, however, is a way to get the behavior:

var newWindow = window.open();
newWindow.opener = null;
newWindow.location = 'http://some.url';


答:
Your polynomial is reversed: You need the coefficients for higher powers of x to be represented by the leftmost bits. Try reversing the bits of your polynomial (representing it as 1000000000000101) and I think you'll get the correct result.

You may also need to reverse your input and output, depending on how the particular implementation of CRC you're using is defined (LSB-first or MSB-first).

Title: CRC16 calculation not quite right

Body:
I am working from http://www.ross.net/crc/download/crc_v3.txt, and using the 16-bit polynomial 0x8005.

My message is 0xAE.

This site http://www.lammertbies.nl/comm/info/crc-calculation.html generates a correct calculation from other data I have.

This is the output from my code, describing each step.

Poly: 1010000000000001
Initial message: 01110101
Message: 011101010000000000000000 24
crcreg: 0000000000000000
crcreg: 0000000000000001
crcreg: 0000000000000011
crcreg: 0000000000000111
crcreg: 0000000000001110
crcreg: 0000000000011101
crcreg: 0000000000111010
crcreg: 0000000001110101
crcreg: 0000000011101010
crcreg: 0000000111010100
crcreg: 0000001110101000
crcreg: 0000011101010000
crcreg: 0000111010100000
crcreg: 0001110101000000
crcreg: 0011101010000000
crcreg: 0111010100000000
crcreg: 1110101000000000
crcreg: 1101010000000000  //Here we had a 1 pop off the shift reg, so we XOR in the poly.
^poly:  1010000000000001
=crcreg:0111010000000001

crcreg: 1110100000000010
crcreg: 1101000000000100
^poly:  1010000000000001
=crcreg:0111000000000101

crcreg: 1110000000001010
crcreg: 1100000000010100
^poly:  1010000000000001
=crcreg:0110000000010101

crcreg: 1100000000101010
crcreg: 1000000001010100
^poly:  1010000000000001
=crcreg:0010000001010101

CRC:    0010000001010101

4 aa
R-CRC:  1010101000000100   //Reversed, just in case MSB/LSB display got hosed.

55 20

The expected CRC16 is 0xBC81


问:
iterate a list and show bootstrap modal for each element one by one
I need to get user input for some list of questions through a popup. I tried to achieve this using bootstrap modal by iterating each questions from the list but I'm not getting the expected result. please see my code below,

Is any other best suitable looping approach will help to solve my problem?

var askUser = ["how are you?", "what is your age?", "where are you from?"];
index = 0;

iterate(askUser, index);

function iterate(askUser, index){
  if(index < askUser.length){
    showModal(askUser[index], index);

  }
}

function showModal(value, index) {
  $('.ask-user').html(value);
  $('#userData').modal('show');
}

$('#modal-submit').click(function() {
  console.log($('#input').value);
  $('#userData').modal('hide');
  iterate(askUser, index++);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="modal fade" id="userData" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <p class="ask-user">Question??</p>
                            <input type="text" id="input" class="form-control">
                            <button type="submit" id="modal-submit"class="btn btn-default pull-right">Submit</button>
                            <div class="clearfix"></div>
                        </div>
                    </div>
                </div>
            </div> </code>```

答:
Here's the working solution with bootstrap , As you see i made recursive call to the function that shows and hides the model after 2 sec

var askUser = ["how are you?", "what is your age?", "where are you from?"];
var $modal = $('#myModal');
var i = 0;

showModal(askUser)

function showModal(arr) {
  $modal.modal('hide');

  setTimeout(function() {
    if (i < arr.length) {
      $('.modal-body').html(arr[i]);
      $modal.modal('show');
      i++;
    }
  }, 400)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" id="next" class="btn btn-default" onclick="showModal(askUser)">next</button>
      </div>
    </div>

  </div>
</div></code>```

Body:
I need to get user input for some list of questions through a popup. I tried to achieve this using bootstrap modal by iterating each questions from the list but I'm not getting the expected result. please see my code below,

Is any other best suitable looping approach will help to solve my problem?

var askUser = ["how are you?", "what is your age?", "where are you from?"];
index = 0;

iterate(askUser, index);

function iterate(askUser, index){
  if(index < askUser.length){
    showModal(askUser[index], index);

  }
}

function showModal(value, index) {
  $('.ask-user').html(value);
  $('#userData').modal('show');
}

$('#modal-submit').click(function() {
  console.log($('#input').value);
  $('#userData').modal('hide');
  iterate(askUser, index++);
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Question??

                            <input type="text" id="input" class="form-control">
                            <button type="submit" id="modal-submit"class="btn btn-default pull-right">Submit</button>

Body:
Here's the working solution with bootstrap , As you see i made recursive call to the function that shows and hides the model after 2 sec

var askUser = ["how are you?", "what is your age?", "where are you from?"];
var $modal = $('#myModal');
var i = 0;

showModal(askUser)

function showModal(arr) {
  $modal.modal('hide');

  setTimeout(function() {
    if (i < arr.length) {
      $('.modal-body').html(arr[i]);
      $modal.modal('show');
      i++;
    }
  }, 400)
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" id="next" class="btn btn-default" onclick="showModal(askUser)">next</button>
      </div>
    </div>

  </div>
</div>


问:
Move to the beginning of line while in Insert mode
I know that I can use either:

Home in insert mode

Esc + i to exit insert mode and enter it again, effectively going to the beginning of line.

But neither satisfies me. In first case I have  to tilt my head to hit Home, because I can't blindly hit it. In second case my left arm has to leave the home row to hit Esc, which is annoying too.

Any thoughts?

答:
```<code>ctrl+o then 0
     |      |
  letter  number
</code>```

Body:
ctrl+o then 0
     |      |
  letter  number


问:
Angular 4 bind select option to controller
I get a list of categories from my service, and i want to bind the category of my controller with the option selected in my select, what i tried:

```<code><select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()">
          {{category.name}}
        </option>
</select>
</code>```

My controller:

```<code>category : Category = new Category(0, '', '', 0);

constructor(private categoryservice : CategoryService) { }

ngOnInit() {
}
</code>```

With this code i get the error:
If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

But i'm not using ngModel within a form, so i don't know what could be the problem.

Thanks!

答:
Just add a name attribute to your select

```<code>    <select class="form-control" name="categoryDrpDown" id="category"
 [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()" [ngValue]="category">>
          {{category.name}}
        </option>
     </select>
</code>```

Also you need to call the method getCategories() inside ngOninit and use the categories array only in template.

```<code><select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categories">
          {{category?.name}}
        </option>
</select>
</code>```

and inside component

```<code>category : Category = new Category(0, '', '', 0);
categories : Category[] = []
constructor(private categoryservice : CategoryService) { }

ngOnInit() {
   this.categoryservice.getCategories().subscribe((response) => {
        this.categories = response;
   });
}
</code>```

Body:
I get a list of categories from my service, and i want to bind the category of my controller with the option selected in my select, what i tried:

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()">
          {{category.name}}
        </option>
</select>

My controller:

category : Category = new Category(0, '', '', 0);

constructor(private categoryservice : CategoryService) { }

ngOnInit() {
}

With this code i get the error:
If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

But i'm not using ngModel within a form, so i don't know what could be the problem.

Thanks!

Body:
Just add a name attribute to your select

    <select class="form-control" name="categoryDrpDown" id="category"
 [(ngModel)]="category">
        <option *ngFor="let category of categoryservice.getCategories()" [ngValue]="category">>
          {{category.name}}
        </option>
     </select>

Also you need to call the method getCategories() inside ngOninit and use the categories array only in template.

<select class="form-control" id="category" [(ngModel)]="category">
        <option *ngFor="let category of categories">
          {{category?.name}}
        </option>
</select>

and inside component

category : Category = new Category(0, '', '', 0);
categories : Category[] = []
constructor(private categoryservice : CategoryService) { }

ngOnInit() {
   this.categoryservice.getCategories().subscribe((response) => {
        this.categories = response;
   });
}


问:
Fetching specific value for nested object in a queryset for serializing
I have two models in my django project which are Followup and User, every followup has a user instance mapped to it [actor field]. What happens is when I run this code I get the primary key for actors by default I need to get the first_name field which is in user model for all the rows fetched from followups

```<code>result = Followup.objects.filter(lead_name = lead).only('lead_name','followup','comments','actor')
plan = PlanType.objects.filter(lead_id = lead)
response["followup"] = serializers.serialize('json', result)
</code>```

Followup model

```<code>class Followup(TimeStampedModel):
lead_name = models.ForeignKey(
    LeadInfo,
    on_delete=models.CASCADE,
    null=True
)
followup = models.DateField(
    blank=False,
    verbose_name='Follow up date'
)
comments = models.TextField(blank=True, verbose_name='Comments')
actor = models.ForeignKey(
    User,
    blank=True,
    limit_choices_to={'is_staff': True},
    on_delete=models.CASCADE,
    null=True,
    verbose_name='Actor'
)
class Meta:
    verbose_name = 'followup'
    verbose_name_plural = 'followups'

def __str__(self):
    return '{}'.format(self.lead_name)
</code>```

User model

```<code>class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(_('First Name'), max_length=120, blank=True)
last_name = models.CharField(_('Last Name'), max_length=120, blank=True)
email = models.EmailField(_('email address'), unique=True, db_index=True)
is_staff = models.BooleanField(_('staff status'), default=False,
                               help_text='Designates whether the user can log into this admin site.')

is_active = models.BooleanField('active', default=True,
                                help_text='Designates whether this user should be treated as '
                                          'active. Unselect this instead of deleting accounts.')
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

USERNAME_FIELD = 'email'
objects = UserManager()

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')
    ordering = ('-date_joined', )

def __str__(self):
    return str(self.email)

def get_full_name(self):
    """
    Returns the first_name plus the last_name, with a space in between.
    """
    full_name = '{} {}'.format(self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    "Returns the short name for the user."
    return self.first_name.strip()
</code>```

答:
Since django does'nt support serializing related fields. Try out Django Rest, which I think will satisfy your needs.
Django Rest Serializers

In your case maybe:
Django Rest Method fields

Body:
I have two models in my django project which are Followup and User, every followup has a user instance mapped to it [actor field]. What happens is when I run this code I get the primary key for actors by default I need to get the first_name field which is in user model for all the rows fetched from followups

result = Followup.objects.filter(lead_name = lead).only('lead_name','followup','comments','actor')
plan = PlanType.objects.filter(lead_id = lead)
response["followup"] = serializers.serialize('json', result)

Followup model

class Followup(TimeStampedModel):
lead_name = models.ForeignKey(
    LeadInfo,
    on_delete=models.CASCADE,
    null=True
)
followup = models.DateField(
    blank=False,
    verbose_name='Follow up date'
)
comments = models.TextField(blank=True, verbose_name='Comments')
actor = models.ForeignKey(
    User,
    blank=True,
    limit_choices_to={'is_staff': True},
    on_delete=models.CASCADE,
    null=True,
    verbose_name='Actor'
)
class Meta:
    verbose_name = 'followup'
    verbose_name_plural = 'followups'

def __str__(self):
    return '{}'.format(self.lead_name)

User model

class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(_('First Name'), max_length=120, blank=True)
last_name = models.CharField(_('Last Name'), max_length=120, blank=True)
email = models.EmailField(_('email address'), unique=True, db_index=True)
is_staff = models.BooleanField(_('staff status'), default=False,
                               help_text='Designates whether the user can log into this admin site.')

is_active = models.BooleanField('active', default=True,
                                help_text='Designates whether this user should be treated as '
                                          'active. Unselect this instead of deleting accounts.')
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

USERNAME_FIELD = 'email'
objects = UserManager()

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')
    ordering = ('-date_joined', )

def __str__(self):
    return str(self.email)

def get_full_name(self):
    """
    Returns the first_name plus the last_name, with a space in between.
    """
    full_name = '{} {}'.format(self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    "Returns the short name for the user."
    return self.first_name.strip()


答:
You can use Array.prototype.reduce() for it. On each iteration, your convert curr into a new object.

const taggedItems = [
  { id: 0, left: 100, top: 100, thumbSize: 100, image: 'b', url: 'y' },
  { id: 1, left: 150, top: 150, thumbSize: 100, image: 'd', url: 'x' },
  { id: 2, left: 200, top: 200, thumbSize: 100, image: 'f', url: 'w' },
]

const yourObject = taggedItems.reduce((prev, curr) => ({
  ...prev,
  [curr.id]: {
    id: curr.id,
    left: curr.left,
    top: curr.top,
    thumbSize: curr.thumbSize,
  }
}), {})

console.log(yourObject)```

Title: How to conditionally convert Array to object

Body:
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]

Here expected output

taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}

How do we conditionally convert Array to object


问:
CSS hover tag not working on link
I'm really new to coding and trying to do a very informal website mockup. I'm trying to get a piece of text to reveal itself when the mouse hovers over a link. I know hover is working since the link goes bold as I've directed it to, but I can't get the text to reveal itself.

this is my html code: I've got two div classes to differentiate what I want seen and hidden

this is my css. I know the first .hidden works at the text disappears, but for the life of me I can't get it to show up

If anyone has a suggestion that would be great! I've tried to follow very similar code to what everyone else here has posted in suggestion.

here is the whole html code if that's helpful:

答:
Your CSS/HTML is wrong.

.show-me:hover .hidden {} will work on the .hidden class that it expects to be inside .show-me. So you hover over .show-me, and it shows .hidden

Instead, your two divs are siblings of each other. The simplest solution is to put hidden inside of show-me.

```<code><div class="show-me">
  <a href="#">Pasta</a>
  <div class="hidden">Vegetarian</div>
</div>
</code>```

Edit:

Thinking about it, you could use sibling selectors (JSBin):

```<code><div class="show-me"><a href="#">Pasta</a></div>
<div class="hidden">Vegetarian</div>
</code>```

```<code>.hidden {
  display: none;
}

.show-me:hover +.hidden {
  display: block;
}
</code>```

Title: CSS hover tag not working on link

Body:
Your CSS/HTML is wrong.

.show-me:hover .hidden {} will work on the .hidden class that it expects to be inside .show-me. So you hover over .show-me, and it shows .hidden

Instead, your two divs are siblings of each other. The simplest solution is to put hidden inside of show-me.

<div class="show-me">
  <a href="#">Pasta</a>
  <div class="hidden">Vegetarian</div>
</div>

Edit:

Thinking about it, you could use sibling selectors (JSBin):

<div class="show-me"><a href="#">Pasta</a></div>
<div class="hidden">Vegetarian</div>

.hidden {
  display: none;
}

.show-me:hover +.hidden {
  display: block;
}


问:
Hide div on click with Javascript (a click that already show other div)
I've built a feedback function to be used on the bottom of pages on our company website. The visitor can vote YES or NO on the question, "Was this information useful to you?" The click show a div (feedbackDiv1/feedbackDiv2) via Javascript.

The function works, but I want the question and the answer buttons to disappear after the visitor has voted, I.e. hide the div #pagefeedback.

I've tried all my tools, but I cant get this to work.

Help would be very much appreciated!

This is the JavaScript used:

```<code>function showFeedback1() {
   document.getElementById('feedbackDiv1').style.display = "block";

function showFeedback2() {
   document.getElementById('feedbackDiv2').style.display = "block";}
</code>```

This is the HTML used:

```<code><div class="greycontentbox">

<div id="pagefeedback">
<h4 style="text-align: center;">Was this information useful to you?</h4>
<table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
  <tbody>
    <tr>
      <td align="center"><a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback1()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES</a></td>
      <td align="center"><a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback2()"><i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO</a></td>
    </tr>
  </tbody>
</table></div>

<div align="center"><div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">POSITIVE FEEDBACK</div></div>
<div align="center"><div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">NEGATIVE FEEDBACK</div></div>
</div>
</code>```

Kind regards,
Pete

答:
If you give your table an ID it's fairly easy to just change it's display css to none.  Also you can accomplish the same with 1 function and simply pass an argument to it that you can use in a conditional statement to show your appropriate feedback.

function showFeedback(feedback) {
   if (feedback == 'yes') {
     document.getElementById('feedbackDiv1').style.display = "block";
   } else {
     document.getElementById('feedbackDiv2').style.display = "block";
   }
   document.getElementById('options').style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="greycontentbox">
  <div id="pagefeedback">
    <h4 style="text-align: center;">
      Was this information useful to you?
    </h4>
    <table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
      <tbody id="options">
        <tr>
          <td align="center">

              <i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES

            </td>
            <td align="center">

              <i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO

            </td>
        </tr>
      </tbody>
    </table>
  </div>
  <div align="center">
    <div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">
      POSITIVE FEEDBACK
    </div>
  </div>
  <div align="center">
    <div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">
      NEGATIVE FEEDBACK
    </div>
  </div>
</div></code>```

Body:
I've built a feedback function to be used on the bottom of pages on our company website. The visitor can vote YES or NO on the question, "Was this information useful to you?" The click show a div (feedbackDiv1/feedbackDiv2) via Javascript.

The function works, but I want the question and the answer buttons to disappear after the visitor has voted, I.e. hide the div #pagefeedback.

I've tried all my tools, but I cant get this to work.

Help would be very much appreciated!

This is the JavaScript used:

function showFeedback1() {
   document.getElementById('feedbackDiv1').style.display = "block";

function showFeedback2() {
   document.getElementById('feedbackDiv2').style.display = "block";}

This is the HTML used:

Was this information useful to you?

      YES
      NO

POSITIVE FEEDBACK

NEGATIVE FEEDBACK

Kind regards,
Pete

Body:
If you give your table an ID it's fairly easy to just change it's display css to none.  Also you can accomplish the same with 1 function and simply pass an argument to it that you can use in a conditional statement to show your appropriate feedback.

function showFeedback(feedback) {
   if (feedback == 'yes') {
     document.getElementById('feedbackDiv1').style.display = "block";
   } else {
     document.getElementById('feedbackDiv2').style.display = "block";
   }
   document.getElementById('options').style.display = "none";
}

<div class="greycontentbox">
  <div id="pagefeedback">
    <h4 style="text-align: center;">
      Was this information useful to you?
    </h4>
    <table align="center" width="70%" border="0" cellspacing="2" cellpadding="5">
      <tbody id="options">
        <tr>
          <td align="center">
            <a class="knappfeedbackyes knappsmall" href="#" onclick="showFeedback('yes')">
              <i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>YES
            </a>
            </td>
            <td align="center">
            <a class="knappfeedbackno knappsmall" href="#" onclick="showFeedback('no')">
              <i style="margin-right: 10px;" class="fa fa-thumbs-up"></i>NO
            </a>
            </td>
        </tr>
      </tbody>
    </table>
  </div>
  <div align="center">
    <div id="feedbackDiv1" style="display:none;" class="negativefeedback answer_list">
      POSITIVE FEEDBACK
    </div>
  </div>
  <div align="center">
    <div id="feedbackDiv2" style="display:none;" class="positivefeedback answer_list">
      NEGATIVE FEEDBACK
    </div>
  </div>
</div>


问:
How to conditionally convert Array to object
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

```<code>taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]
</code>```

Here expected output

```<code>taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}
</code>```

How do we conditionally convert Array to object

答:
You can map into each element to return the expected properties...

var taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

].map(e => {
  return {
   id:e.id,
   left:e.left,
   top:e.top,
   thumbSize:e.thumbSize
  }
});

//Second method to have only one object
var res = {}
var taggedItems2 = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

].forEach((e,i) => {
  return res[i]=e
});

console.log(taggedItems);
console.log(res)```


问:
generate a date sequence of last day of month in R
If I give a start date and end date, and a frequency I should be able to generate a sequence of dates from start to end such that

1) the dates are the last day of the month.
2) I can set the frequency of sequence to any factor of 12 (wrt 12 months). Say if the frequency is 3, it means there is an interval or gap of 4 months.

For (1) the following function gives me an output with an interval of 3 months (ie quarterly)but it doesn't give the dates with last day of the month.

```<code>    DateSeq<-function(st,en, freq){
    seq(st, en, by = paste(as.character(12/freq), "months"))
    }
    DateSeq(as.Date("2015-01-01"),as.Date("2018-03-03"),4)
</code>```

how to convert this to a sequence that gives me last day.? Give me a simple code.

答:
This gives a sequence of end-of-month dates from the year/month of st to the year/month of en.

```<code>library(zoo)
as.Date(seq(as.yearmon(st), as.yearmon(en), by = 1 / freq), frac = 1)
</code>```

In the above st and en could be any class that converts to yearmon including yearmon itself, Date, character strings or numeric.  For example, "2000-02-01", "2000-02", as.Date("2000-02-01"), 2000+1/12.

If en is a date and the end date of the sequence should be no later than en then replace as.yearmon(en) with the following which subtracts 1/12 if en is not at the end of the month.

```<code>as.yearmon(en) - (as.Date(en) < as.Date(as.yearmon(en), frac = 1)) / 12
</code>```

Similarly if st is a date and the starting date of the sequence should be no later than st use the same idea to subtract 1/12 if st is not at the end of the month replacing as.yearmon(st) with

```<code>as.yearmon(st) - (as.Date(st) < as.Date(as.yearmon(st), frac = 1)) / 12
</code>```

There is some question regarding whether we really need dates at all since they are always at the end of the month.  It seems that the point is to create a year/month sequence and the end-of-month dates are just a way to represent that.
 A simpler way would be this yearmon sequence directly.

```<code>seq(as.yearmon(st), as.yearmon(en), by = 1 / freq)
</code>```

Body:
If I give a start date and end date, and a frequency I should be able to generate a sequence of dates from start to end such that

1) the dates are the last day of the month.
2) I can set the frequency of sequence to any factor of 12 (wrt 12 months). Say if the frequency is 3, it means there is an interval or gap of 4 months.

For (1) the following function gives me an output with an interval of 3 months (ie quarterly)but it doesn't give the dates with last day of the month.

    DateSeq<-function(st,en, freq){
    seq(st, en, by = paste(as.character(12/freq), "months"))
    }
    DateSeq(as.Date("2015-01-01"),as.Date("2018-03-03"),4)

how to convert this to a sequence that gives me last day.? Give me a simple code.

Body:
This gives a sequence of end-of-month dates from the year/month of st to the year/month of en.

library(zoo)
as.Date(seq(as.yearmon(st), as.yearmon(en), by = 1 / freq), frac = 1)

In the above st and en could be any class that converts to yearmon including yearmon itself, Date, character strings or numeric.  For example, "2000-02-01", "2000-02", as.Date("2000-02-01"), 2000+1/12.

If en is a date and the end date of the sequence should be no later than en then replace as.yearmon(en) with the following which subtracts 1/12 if en is not at the end of the month.

as.yearmon(en) - (as.Date(en) < as.Date(as.yearmon(en), frac = 1)) / 12

Similarly if st is a date and the starting date of the sequence should be no later than st use the same idea to subtract 1/12 if st is not at the end of the month replacing as.yearmon(st) with

as.yearmon(st) - (as.Date(st) < as.Date(as.yearmon(st), frac = 1)) / 12

There is some question regarding whether we really need dates at all since they are always at the end of the month.  It seems that the point is to create a year/month sequence and the end-of-month dates are just a way to represent that.
 A simpler way would be this yearmon sequence directly.

seq(as.yearmon(st), as.yearmon(en), by = 1 / freq)


问:
How to place the last
 on the right side of my page?
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div></code>```

i want to move this image to right side which is in div. here it is.

```<code><li>
    <div class="flagChangeCountry">
        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
    </div>
</li>
</code>```

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

答:
Have you tried clear:left; before setting it float: right;

```<code>.navbar-collapse ul li:last-child {
         clear:left;
         float: right;
    }
</code>```

Title: How to place the last <li> on the right side of my page?

Body:
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

Home

About

Contact

                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

i want to move this image to right side which is in div. here it is.

        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

Body:
Have you tried clear:left; before setting it float: right;

.navbar-collapse ul li:last-child {
         clear:left;
         float: right;
    }


问:
TSQL Merge Performance
Scenario:

I have a table with roughly 24 million records.  The table has pricing history related to individual customers and is computed daily.  There are on average 6 million records for each day. Every morning a the price list is generated and a merge statement is ran to reflect the changes in their pricing.

The merge statement begins with the previous day's previous data being inserted into a variable table, that table is then merged into the actual table.  The main problem is that the merge statement takes pretty long.

My real question centers around the performance of using a variable table vs physical table vs temp table. What is the best practice for large merges like this?

答:
Thoughts

I'd consider a temp table: these have statistics which will help. A table variable is always assumed to have one row. Also, the IO can be shunted onto separate drives (assuming you have tempdb separately)

If a single transaction is not required, I'd split the MERGE too into a DELETE, UPDATE, INSERT sequence to reduce the amount of work needed in each action (which reduces the amount of rollback info needed and the amount of locking etc

Title: TSQL Merge Performance


问:
When would I use target_compile_definitions(...) vs set(COMPILE_DEFINITIONS ...)
I'm having trouble understanding when to use target_compile_definitions(...) vs set(COMPILE_DEFINITIONS ...). Is the difference that target_compile_definitions will only affect a specific target?

答:
One thing to realize is that set(COMPILE_DEFINITIONS ...) does not alter any target in any way.

What does it mean? Well, you just create a new variable (called COMPILE_OPTIONS), which will be cached after the first configuration run. That's all. Nothing else happens.

Now, next thing to realize is that there exist properties, and that is what you meant. Properties are some different "context", "payload" for targets, directories, source files, etc. Documentation says that there are:

Properties of Global Scope

Properties on Directories

Properties on Targets

Properties on Tests

Properties on Source Files

Properties on Cache Entries

Properties on Installed Files

Documentation also says that COMPILE_DEFINITIONS is a property that exists for both directory scope and target scope. It means that every directory that you have and every target you've declared has this property, and the property value can be different for each of them. One uses set_property() to set a property for the needed scope.

Now, what is target_compile_definitions()? That's just the equivalent of set_property(TARGET ... PROPERTY COMPILE_DEFINITIONS ...).

So, in essence, all these target_ functions are just doing that, but have a distinct function for it. However, CMake doesn't have a function for every property, so here's again some inconsistency to deal with.

But, just remember that what set() does and what a property is are two orthogonal things.


问:
Are immutable objects good practice?
Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?

答:
The immutable Eric Lippert has written a whole series of blog posts on the topic. Part one is here.

Quoting from the earlier post that he links to:

ASIDE: Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change. Since they cannot be modified, they are automatically threadsafe. Since they cannot be modified, you can maintain a stack of past “snapshots” of the structure, and suddenly undo-redo implementations become trivial. On the down side, they do tend to chew up memory, but hey, that’s what garbage collection was invented for, so don’t sweat it.

Title: Are immutable objects good practice?


问:
How to Add Extra Tab Using Template Language Twig In OpenCart 3.x
I want an extra description tag termed "Overview" for the product page under the nav nav-tabs class.

This is the complete Twig template code:

```<code><ul class="nav nav-tabs">
        <li class="active"><a href="#tab-description" data-toggle="tab">{{ tab_description }}</a></li>
        {% if attribute_groups %}
        <li><a href="#tab-specification" data-toggle="tab">{{ tab_attribute }}</a></li>
        {% endif %}
        {% if review_status %}
        <li><a href="#tab-review" data-toggle="tab">{{ tab_review }}</a></li>
        {% endif %}
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="tab-description">{{ description }}</div>
        {% if attribute_groups %}
        <div class="tab-pane" id="tab-specification">
          <table class="table table-bordered">
            {% for attribute_group in attribute_groups %}
            <thead>
              <tr>
                <td colspan="2"><strong>{{ attribute_group.name }}</strong></td>
              </tr>
            </thead>
            <tbody>
            {% for attribute in attribute_group.attribute %}
            <tr>
              <td>{{ attribute.name }}</td>
              <td>{{ attribute.text }}</td>
            </tr>
            {% endfor %}
              </tbody>
            {% endfor %}
          </table>
        </div>
        {% endif %}
        {% if review_status %}
        <div class="tab-pane" id="tab-review">
          <form class="form-horizontal" id="form-review">
            <div id="review"></div>
            <h2>{{ text_write }}</h2>
            {% if review_guest %}
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label" for="input-name">{{ entry_name }}</label>
                <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />
              </div>
            </div>
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label" for="input-review">{{ entry_review }}</label>
                <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>
                <div class="help-block">{{ text_note }}</div>
              </div>
            </div>
            <div class="form-group required">
              <div class="col-sm-12">
                <label class="control-label">{{ entry_rating }}</label>
                    {{ entry_bad }}
                <input type="radio" name="rating" value="1" />

                <input type="radio" name="rating" value="2" />

                <input type="radio" name="rating" value="3" />

                <input type="radio" name="rating" value="4" />

                <input type="radio" name="rating" value="5" />
                 {{ entry_good }}</div>
            </div>
            {{ captcha }}
            <div class="buttons clearfix">
              <div class="pull-right">
                <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>
              </div>
            </div>
            {% else %}
            {{ text_login }}
            {% endif %}
          </form>
        </div>
        {% endif %}</div>
    </div>
</code>```

With this code, the page looks like this:

I want one more tab there saying OVERVIEW with different content.

Can anyone help me out here with this?

P.S: I did read this: how to add extra tab without any extension in product page in opencart
But, I'm not sure where to find this piece of code (I've tried looking product TPL files as well).

答:
You have just add two things

in ul tag add this li

```<code><li><a href="#tab-overview" data-toggle="tab">My Tab</a></li>
</code>```

and add one div for tab-content

```<code><div class="tab-pane" id="tab-overview">
     <h1>My Tab Content</h1>
     <!-- Your HTML and twig code here-->
</div>
</code>```

Body:
I want an extra description tag termed "Overview" for the product page under the nav nav-tabs class.

This is the complete Twig template code:

{{ tab_description }}

        {% if attribute_groups %}

{{ tab_attribute }}

        {% endif %}
        {% if review_status %}

{{ tab_review }}

        {% endif %}

{{ description }}

        {% if attribute_groups %}

            {% for attribute_group in attribute_groups %}

                {{ attribute_group.name }}

            {% for attribute in attribute_group.attribute %}

              {{ attribute.name }}
              {{ attribute.text }}

            {% endfor %}

            {% endfor %}

        {% endif %}
        {% if review_status %}

          <form class="form-horizontal" id="form-review">

{{ text_write }}

            {% if review_guest %}

                {{ entry_name }}
                <input type="text" name="name" value="{{ customer_name }}" id="input-name" class="form-control" />

                {{ entry_review }}
                <textarea name="text" rows="5" id="input-review" class="form-control"></textarea>

{{ text_note }}

                {{ entry_rating }}
                    {{ entry_bad }}
                <input type="radio" name="rating" value="1" />

                <input type="radio" name="rating" value="2" />

                <input type="radio" name="rating" value="3" />

                <input type="radio" name="rating" value="4" />

                <input type="radio" name="rating" value="5" />
                 {{ entry_good }}

            {{ captcha }}

                <button type="button" id="button-review" data-loading-text="{{ text_loading }}" class="btn btn-primary">{{ button_continue }}</button>

            {% else %}
            {{ text_login }}
            {% endif %}
          </form>

        {% endif %}

With this code, the page looks like this:

I want one more tab there saying OVERVIEW with different content.

Can anyone help me out here with this?

P.S: I did read this: how to add extra tab without any extension in product page in opencart
But, I'm not sure where to find this piece of code (I've tried looking product TPL files as well).

Body:
You have just add two things

in ul tag add this li

<li><a href="#tab-overview" data-toggle="tab">My Tab</a></li>

and add one div for tab-content

<div class="tab-pane" id="tab-overview">
     <h1>My Tab Content</h1>
     <!-- Your HTML and twig code here-->
</div>


问:
F# Type provider looks for sample file in referencing project, not referenced project
I have a library where I use FSharp.Data's JsonProvider to construct a type from a JSON file. However, when I reference this project in a console application and try to access the generated type, it does not compile, but looks for the sample file in the directory of the console application, yielding an error like

```<code>Cannot read sample JSON from 'sample.json': Could not find file 'C:\Some\Where\TheSolution\ConsoleApp\sample.json
</code>```

Do I really have to copy the sample file to each referencing project, or do I have to add this as a DLL to get this working, or am I doing anything wrong?

答:
When you use an F# Data type provider in a library and you reference the library, the compiler will try to access the sample - this is because the types are erased and are recreated each time they are used. (They are also lazily generated, and so they are generated on the fly as they are being used, so this is the only option.)

If you can copy the files with your library, that's probably the best option, but we tried to address this issue - you can embed the sample as a resource and tell the type provider to look for a resource first. See Using JSON provider in a library in the F# Data docs:

```<code>type WB = JsonProvider<"../data/WorldBank.json",
  EmbeddedResource="MyLib, worldbank.json">
</code>```

This is used, for example, in the F# Data Toolbox library. Alas getting this to work well is a bit fiddly.

Body:
I have a library where I use FSharp.Data's JsonProvider to construct a type from a JSON file. However, when I reference this project in a console application and try to access the generated type, it does not compile, but looks for the sample file in the directory of the console application, yielding an error like

Cannot read sample JSON from 'sample.json': Could not find file 'C:\Some\Where\TheSolution\ConsoleApp\sample.json

Do I really have to copy the sample file to each referencing project, or do I have to add this as a DLL to get this working, or am I doing anything wrong?

Body:
When you use an F# Data type provider in a library and you reference the library, the compiler will try to access the sample - this is because the types are erased and are recreated each time they are used. (They are also lazily generated, and so they are generated on the fly as they are being used, so this is the only option.)

If you can copy the files with your library, that's probably the best option, but we tried to address this issue - you can embed the sample as a resource and tell the type provider to look for a resource first. See Using JSON provider in a library in the F# Data docs:

type WB = JsonProvider<"../data/WorldBank.json",
  EmbeddedResource="MyLib, worldbank.json">

This is used, for example, in the F# Data Toolbox library. Alas getting this to work well is a bit fiddly.


问:
Java synthetic method and bridge method confusion
As stated in this Java Tutorial a bridge method implies that it is also a synthetic method. The question is, is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object, i.e., if a method is synthetic does it imply that it is also a bridge method?

It's not exactly the same but the source code for isSynthetic and isBridge methods looks like below:

```<code>static final int SYNTHETIC = 0x00001000;
public boolean isSynthetic() {
    return (getModifiers() & SYNTHETIC) != 0;
}

static final int BRIDGE = 0x00000040;
public boolean isBridge() {
    return (getModifiers() & BRIDGE) != 0;
}
</code>```

Why isBridge method body is not like return isSynthetic();?

答:
If you are simply looking for an example of such:

```<code>Function<String, Integer> func = s -> s.length();

Arrays.stream(DeleteMe.class.getDeclaredMethods())
     .peek(m -> System.out.println(m.getName() + " isSynth : " + m.isSynthetic() + " isBridge : " + m.isBridge()))
     .forEach(System.out::println);
</code>```

There will be entries like:

```<code>lambda$0 isSynth : true isBridge : false
lambda$1 isSynth : true isBridge : false
</code>```

Body:
As stated in this Java Tutorial a bridge method implies that it is also a synthetic method. The question is, is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object, i.e., if a method is synthetic does it imply that it is also a bridge method?

It's not exactly the same but the source code for isSynthetic and isBridge methods looks like below:

static final int SYNTHETIC = 0x00001000;
public boolean isSynthetic() {
    return (getModifiers() & SYNTHETIC) != 0;
}

static final int BRIDGE = 0x00000040;
public boolean isBridge() {
    return (getModifiers() & BRIDGE) != 0;
}

Why isBridge method body is not like return isSynthetic();?

Body:
If you are simply looking for an example of such:

Function<String, Integer> func = s -> s.length();

Arrays.stream(DeleteMe.class.getDeclaredMethods())
     .peek(m -> System.out.println(m.getName() + " isSynth : " + m.isSynthetic() + " isBridge : " + m.isBridge()))
     .forEach(System.out::println);

There will be entries like:

lambda$0 isSynth : true isBridge : false
lambda$1 isSynth : true isBridge : false


问:
AttributeError when calling instance method I defined
I coded this in python 3 and it is showing an attribute error.code is
as following:

```<code>import datetime

class MessageUser():
  User_Details = []
  Messages = []
  base_message = """Hi {name}!
  Thank you for the purchase on {date}.
  We hope you are exicted about using it. Just as a
  reminder the purcase total was ${total}.
  Have a great time!

  from Pritom_Mazhi
  """

  def add_user(self, name, amount, email=None):
    name = name[0].upper() + name[1:].lower() #Capitalizing the first letter of all names - formatted name
    amount = "%.2f" %(amount) #formatted amount
    detail = {
      "name" : name,
      "amount" : amount,
    }
    today = datetime.date.today()
    date_text = '{tday.day}/{tday.month}/{tday.year}'.format(tday=today) #formatted date
    detail["date"] = date_text
    if email is not None:
      detail["email"] = email
    self.User_Details.append(detail)

    def get_details(self):
      return self.User_Details

    def make_message(self):
      if len(self.User_Details) > 0:
        for detail in self.get_details():  #for detail in self.User_Details
          name = detail["name"]
          amount = detail["amount"]
          date = detail["date"]
          email = detail["email"]
          message = self.base_message
          formatted_message = message.format(
            name = name,
            total = amount,
            date = date,
            )
          self.Messages.append(formatted_message)
          return self.Messages
      else:
          return []

obj = MessageUser()
obj.add_user("Pritom", 123.32, email='hello@teamcfe.com')
obj.add_user("jon Snow", 94.23)
obj.add_user("Sean", 93.23)
obj.add_user("Emilee", 193.23)
obj.add_user("Marie", 13.23)
obj.get_details()

obj.make_message()
</code>```

when i run it i get this error:

```<code>File "Class_StringFormat.py", line 57, in <module>
    obj.get_details()
AttributeError: 'MessageUser' object has no attribute 'get_details'
</code>```

i simply can't find what wrong i did there and so can't manage to fix it.

答:
If your indentation is reproduced correctly in the question, get_details is defined inside add_user and is not visible from outside.

You should unindent the definition of get_details and make_message to be on the same level as add_user:

```<code>def add_user(self, name, amount, email=None):
   # method body...

def get_details(self):
   return self.User_Details

def make_message(self):
   # method body
</code>```

Body:
I coded this in python 3 and it is showing an attribute error.code is
as following:

import datetime

class MessageUser():
  User_Details = []
  Messages = []
  base_message = """Hi {name}!
  Thank you for the purchase on {date}.
  We hope you are exicted about using it. Just as a
  reminder the purcase total was ${total}.
  Have a great time!

  from Pritom_Mazhi
  """

  def add_user(self, name, amount, email=None):
    name = name[0].upper() + name[1:].lower() #Capitalizing the first letter of all names - formatted name
    amount = "%.2f" %(amount) #formatted amount
    detail = {
      "name" : name,
      "amount" : amount,
    }
    today = datetime.date.today()
    date_text = '{tday.day}/{tday.month}/{tday.year}'.format(tday=today) #formatted date
    detail["date"] = date_text
    if email is not None:
      detail["email"] = email
    self.User_Details.append(detail)

    def get_details(self):
      return self.User_Details

    def make_message(self):
      if len(self.User_Details) > 0:
        for detail in self.get_details():  #for detail in self.User_Details
          name = detail["name"]
          amount = detail["amount"]
          date = detail["date"]
          email = detail["email"]
          message = self.base_message
          formatted_message = message.format(
            name = name,
            total = amount,
            date = date,
            )
          self.Messages.append(formatted_message)
          return self.Messages
      else:
          return []

obj = MessageUser()
obj.add_user("Pritom", 123.32, email='hello@teamcfe.com')
obj.add_user("jon Snow", 94.23)
obj.add_user("Sean", 93.23)
obj.add_user("Emilee", 193.23)
obj.add_user("Marie", 13.23)
obj.get_details()

obj.make_message()

when i run it i get this error:

File "Class_StringFormat.py", line 57, in <module>
    obj.get_details()
AttributeError: 'MessageUser' object has no attribute 'get_details'

i simply can't find what wrong i did there and so can't manage to fix it.

Body:
If your indentation is reproduced correctly in the question, get_details is defined inside add_user and is not visible from outside.

You should unindent the definition of get_details and make_message to be on the same level as add_user:

def add_user(self, name, amount, email=None):
   # method body...

def get_details(self):
   return self.User_Details

def make_message(self):
   # method body


问:
Getting the highest value of a column in MongoDB
I've been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I'm pretty sure there is a better way to do it.

I tried the following (and different combinations):

```<code>transactions.find("id" => x).max({"sellprice" => 0})
</code>```

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!

答:
If the column's indexed then a sort should be OK, assuming Mongo just uses the index to get an ordered collection. Otherwise it's more efficient to iterate over the collection, keeping note of the largest value seen. e.g.

```<code>max = nil
coll.find("id" => x).each do |doc|
    if max == nil or doc['sellprice'] > max then
        max = doc['sellprice']
    end
end
</code>```

(Apologies if my Ruby's a bit ropey, I haven't used it for a long time - but the general approach should be clear from the code.)

Body:
I've been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I'm pretty sure there is a better way to do it.

I tried the following (and different combinations):

transactions.find("id" => x).max({"sellprice" => 0})

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!

Body:
If the column's indexed then a sort should be OK, assuming Mongo just uses the index to get an ordered collection. Otherwise it's more efficient to iterate over the collection, keeping note of the largest value seen. e.g.

max = nil
coll.find("id" => x).each do |doc|
    if max == nil or doc['sellprice'] > max then
        max = doc['sellprice']
    end
end

(Apologies if my Ruby's a bit ropey, I haven't used it for a long time - but the general approach should be clear from the code.)


问:
Auto Increment field in Composer
Is there any auto_increment field type is available when creating an Asset instance.
For example, Asset id should be autogenerated field and should be created at runtime, instead of mentioning the value at the application level.
I can achieve it by creating a transaction processor function to check the list of asset and add 1 to increment as an alternative.

Looking for new a feature which will help multiple developers while building an application.

Regards,

Pradeep P

答:
Also another description of why this isn't a good idea has been added to the issue you created, referencing here for completeness.
https://github.com/hyperledger/composer/issues/2931</p>

Title: Auto Increment field in Composer


问:
How to Remove Specific object from firebase Realtime Database
How to remove specific object from Firebase DB. I want to remove fine message from champdecay@gmail.com username.

I have tried following code and i got proper object but remove() not works.

```<code>abcd = ref.orderByChild('message').equalTo('fine');
abcd.on('value', function(abcdSnap){
    console.log(abcdSnap.val());
})
</code>```

above Code returns -L-Kl8ctoi5j4TtMWTsc but now how to remove this object. i tried to remove() as follows but not working...

```<code>abcd = ref.orderByChild('message').equalTo('fine').remove();

abcd.on('value', function(abcdSnap){
   abcdSnap.remove();
})
</code>```

答:
Okay Finally Got the Answer.</p>

```<code>abcd = ref.orderByChild('message').equalTo(msg);
abcd.on('value', function(abcdSnap){
    var a = abcdSnap.val();
    var b = Object.keys(a)[0];
    ref.child(b).remove();
})
</code>```

Body:
How to remove specific object from Firebase DB. I want to remove fine message from champdecay@gmail.com username.

I have tried following code and i got proper object but remove() not works.

abcd = ref.orderByChild('message').equalTo('fine');
abcd.on('value', function(abcdSnap){
    console.log(abcdSnap.val());
})

above Code returns -L-Kl8ctoi5j4TtMWTsc but now how to remove this object. i tried to remove() as follows but not working...

abcd = ref.orderByChild('message').equalTo('fine').remove();

abcd.on('value', function(abcdSnap){
   abcdSnap.remove();
})

Body:
Okay Finally Got the Answer.

abcd = ref.orderByChild('message').equalTo(msg);
abcd.on('value', function(abcdSnap){
    var a = abcdSnap.val();
    var b = Object.keys(a)[0];
    ref.child(b).remove();
})


问:
Ruby on Rails - Multisite - Custom Locale YML files
We are running a white label type site where several websites run from one codebase.

I would like to have the locales files with all of the site text loaded from a different folder based on a parameter.

Lets say we have these two sites:

site1@example.com (site1)

site2@example.com (site2)

We are reading the host and determining the brand_name from our site model.

So in the locales files I would like to load them from the correct folder, i.e.

config/locales/site1/**/*.yml

config/locales/site2/**/*.yml

I can not seem to do this dynamically. I can make the change in the config/application.rb file manually and it works fine. However I want to be able to determine which set of locale files to load in my application_controller.rb

Am I able to set the the path of the locale files or is this too late?

答:
You should be able to do something like this:

application.rb

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', request.host, *.{rb,yml}').to_s]

This will only load locale files in a folder with the domain name.  If a user goes to site2.com it will load files in config/locales/site2.com/*.yml


问:
How can I send an email using PHP?
I am using PHP on a website and I want to add emailing functionality.

I have WampServer installed.

How do I send an email using PHP?

答:
Sent the Email with this script

```<code><h2>Test Mail</h2>
<?php

if (!isset($_POST["submit"]))
  {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Click To send mail">
  </form>
  <?php
  }

else

  {

  if (isset($_POST["from"]))
    {
    $from = $_POST["from"]; // sender
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    $message = wordwrap($message, 70);

    mail("Test@example.com",$subject,$message,"From: $from\n");
    echo "Thank you for sending an email";
    }
  }
?>
</code>```

Once you press the Send email button, the email will be sent to Test@example.com

Title: How can I send an email using PHP?

Body:
Sent the Email with this script

<h2>Test Mail</h2>
<?php

if (!isset($_POST["submit"]))
  {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Click To send mail">
  </form>
  <?php
  }

else

  {

  if (isset($_POST["from"]))
    {
    $from = $_POST["from"]; // sender
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    $message = wordwrap($message, 70);

    mail("Test@example.com",$subject,$message,"From: $from\n");
    echo "Thank you for sending an email";
    }
  }
?>

Once you press the Send email button, the email will be sent to Test@example.com


问:
Putting text on a border with css html
How can i hide border behind MON and give some space like in this pic

https://www.screencast.com/t/SJmg63NZuF

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 0px;
  padding: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h2>MON</h2>
  <p>7am - yeah</p>
</div></code>```

答:
I think you're trying to achieve this. The convention of using <legend> tags which is a child of <fieldset> is usually applied and used for forms but you can achieve the same as shown below. I tweaked the code a bit and added a background to show you how you may achieve what you're looking for as the screenshot you posted.
Hope, it helps.

body {
  background-image: url("https://ak9.picdn.net/shutterstock/videos/21522739/thumb/1.jpg");
}

fieldset {
  width: 100px;
  border: 2px solid white;
  text-align: center;
}

h2 {
  color: white;
}

p {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <legend align="center">
    <h2>MON</h2>
  </legend>
  <p>7am - yeah</p>
  <p>8am - yeah</p>
  <p>9am - yeah</p>
</fieldset></code>```

Title: Putting text on a border with css html

Body:
How can i hide border behind MON and give some space like in this pic

https://www.screencast.com/t/SJmg63NZuF

div {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

h2 {
  width: 50px;
  margin-top: -15px;
  margin-left: 0px;
  padding: 0 10px;
}

MON

7am - yeah

Body:
I think you're trying to achieve this. The convention of using <legend> tags which is a child of <fieldset> is usually applied and used for forms but you can achieve the same as shown below. I tweaked the code a bit and added a background to show you how you may achieve what you're looking for as the screenshot you posted.
Hope, it helps.

body {
  background-image: url("https://ak9.picdn.net/shutterstock/videos/21522739/thumb/1.jpg");
}

fieldset {
  width: 100px;
  border: 2px solid white;
  text-align: center;
}

h2 {
  color: white;
}

p {
  color: white;
}

<fieldset>
  <legend align="center">
    <h2>MON</h2>
  </legend>
  <p>7am - yeah</p>
  <p>8am - yeah</p>
  <p>9am - yeah</p>
</fieldset>


问:
Different readers on same service bus queue?
Lets say we have 4 different kind of messages: Type1, Type2, Type3 and Type 4.

We have a service bus queue with sessions because of nessesaty of FIFO functionality.

We also have two message writers. First message writer takes care of creating messages of type type1 and type2, where writer #2 takes care of creating messages of type type3 and type4. This is the easy part.

Now i want to be able to create two readers, reader1 and reader2.

Reader1 must read messages of type type1 and type2.
Reader2 must read messages of type type3 and type4.

But i cant figure out how to achieve this. Because if reader1 reades message of type3, it needs to abanadon it, since reader1 cant only take care of messages of type type1 and type2. In worst case reader1 will be stuck with the message until it is thrown to deadletter queue.

Reason to create two different readers is because they are in two completly different domains, with completly different functionality.

How can i achieve the requered functionality?

答:
You need to use Service Bus Topics and Subscriptions for this.

Writers publish messages to a Topic. Then both readers subscribe to that topic, and each subscription can filter based on message type.

See "Topics and subscriptions" in the docs.


问:
DefaultModelBinder and binding action parameters from values in a table row
What I am doing is this.  I have a basic table with a button at the end of each row for "selection" of that row for further actions.  My action method has two simple parameters I'll call them id1 and id2 so:

public ActionResult DoSomething(int id1, int id2)

id1 will be bound from a hidden form field outside the scope of the table, this works fine.

id2 needs to come from a hidden column from an individual row in the table depending on the button clicked representing the row that requires further processing.  Make sense?

When the form posts back to the action method, id1 is set perfectly, no problem, but id2 is always the value of the hidden column from row 1.  How do I detect/make DefaultModelBinder pull the hidden column value from the row from which the button is being clicked?

Thanks for the assist as I am actively trying to figure this out.

Here is the hidden table column that is rendered per row that I want to capture it's value on the post from the row from which the button was clicked:

```<code><td style="display:none;">@Html.Hidden("id2", viewModel.id2)</td>
</code>```

答:
You could use simple hyper links instead of forms on each row. Like this:

```<code>@Html.ActionLink("link text", "DoSomething", "SomeController", new {
    id1 = viewModel.id1, id2 = viewModel.id2
}, null)
</code>```

which assuming default routes should generate the following link:

```<code>/somecontroller/DoSomething?id1=123&id2=456
</code>```

and when you click on it the DoSomething action will be invoked with correct parameters.

If you want to do this with POST you will need multiple forms, one for each row:

```<code>@using (Html.BeginForm("DoSomething", "somecontroller"))
{
    @Html.Hidden("id1", viewModel.id1)
    @Html.Hidden("id2", viewModel.id2)
    <input type="submit" value="OK" />
}
</code>```

Body:
What I am doing is this.  I have a basic table with a button at the end of each row for "selection" of that row for further actions.  My action method has two simple parameters I'll call them id1 and id2 so:

public ActionResult DoSomething(int id1, int id2)

id1 will be bound from a hidden form field outside the scope of the table, this works fine.

id2 needs to come from a hidden column from an individual row in the table depending on the button clicked representing the row that requires further processing.  Make sense?

When the form posts back to the action method, id1 is set perfectly, no problem, but id2 is always the value of the hidden column from row 1.  How do I detect/make DefaultModelBinder pull the hidden column value from the row from which the button is being clicked?

Thanks for the assist as I am actively trying to figure this out.

Here is the hidden table column that is rendered per row that I want to capture it's value on the post from the row from which the button was clicked:

@Html.Hidden("id2", viewModel.id2)

Body:
You could use simple hyper links instead of forms on each row. Like this:

@Html.ActionLink("link text", "DoSomething", "SomeController", new {
    id1 = viewModel.id1, id2 = viewModel.id2
}, null)

which assuming default routes should generate the following link:

/somecontroller/DoSomething?id1=123&id2=456

and when you click on it the DoSomething action will be invoked with correct parameters.

If you want to do this with POST you will need multiple forms, one for each row:

@using (Html.BeginForm("DoSomething", "somecontroller"))
{
    @Html.Hidden("id1", viewModel.id1)
    @Html.Hidden("id2", viewModel.id2)
    <input type="submit" value="OK" />
}


问:
Why does Task Scheduler open AutoHotKey script with Notepad++ instead of actually run it?
I use Task Scheduler to autorun an AutoHotKey script at logon with highest privileges. But recently it suddenly switches to open Notepad++ on the script, instead of actually running it. Double click on the script still works as expected.

What is happening? And how to fix this?

The xml export of the task:

```<code><?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2017-08-16T17:26:03.6121892</Date>
    <Author>OOKER-LAPTOP\Ooker</Author>
    <URI>\AutoHotkey</URI>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-21-3621221271-3088881583-359884916-1002</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>D:\Data\Config\Essential.ahk</Command>
    </Exec>
  </Actions>
</Task>
</code>```

The registry export from HKEY_CLASSES_ROOT\AutoHotkeyScript:

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\AutoHotkeyScript]
@="AutoHotkey Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\DefaultIcon]
@="C:\\Program Files\\AutoHotkey\\AutoHotkey.exe,1"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell]
@="Open"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Compile]
@="Compile Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Compile\Command]
@="\"C:\\Program Files\\AutoHotkey\\Compiler\\Ahk2Exe.exe\" /in \"%l\""

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit]

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit\Command]
@="C:\\Program Files (x86)\\Notepad++\\notepad++.exe %1"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Open]
@="Run Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Open\Command]
@="\"C:\\Program Files\\AutoHotkey\\AutoHotkey.exe\" \"%1\" %*"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\RunAs]

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\RunAs\Command]
@="\"C:\\Program Files\\AutoHotkey\\AutoHotkey.exe\" \"%1\" %*"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\ShellEx]
</code>```

答:
I don't know what the problem is but you can solve it by starting the script with the AutoHotkey program directly:</p>

```<code>"C:\Program Files\AutoHotkey\AutoHotkey.exe" D:\Data\Config\Essential.ahk
</code>```

Body:
I use Task Scheduler to autorun an AutoHotKey script at logon with highest privileges. But recently it suddenly switches to open Notepad++ on the script, instead of actually running it. Double click on the script still works as expected.

What is happening? And how to fix this?

The xml export of the task:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2017-08-16T17:26:03.6121892</Date>
    <Author>OOKER-LAPTOP\Ooker</Author>
    <URI>\AutoHotkey</URI>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-21-3621221271-3088881583-359884916-1002</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>D:\Data\Config\Essential.ahk</Command>
    </Exec>
  </Actions>
</Task>

The registry export from HKEY_CLASSES_ROOT\AutoHotkeyScript:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\AutoHotkeyScript]
@="AutoHotkey Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\DefaultIcon]
@="C:\\Program Files\\AutoHotkey\\AutoHotkey.exe,1"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell]
@="Open"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Compile]
@="Compile Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Compile\Command]
@="\"C:\\Program Files\\AutoHotkey\\Compiler\\Ahk2Exe.exe\" /in \"%l\""

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit]

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit\Command]
@="C:\\Program Files (x86)\\Notepad++\\notepad++.exe %1"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Open]
@="Run Script"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Open\Command]
@="\"C:\\Program Files\\AutoHotkey\\AutoHotkey.exe\" \"%1\" %*"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\RunAs]

[HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\RunAs\Command]
@="\"C:\\Program Files\\AutoHotkey\\AutoHotkey.exe\" \"%1\" %*"

[HKEY_CLASSES_ROOT\AutoHotkeyScript\ShellEx]

Body:
I don't know what the problem is but you can solve it by starting the script with the AutoHotkey program directly:

"C:\Program Files\AutoHotkey\AutoHotkey.exe" D:\Data\Config\Essential.ahk