问:
Incrementing a column by one in trigger?
I want to add let's say another student to a class.

Basically I have two tables: Students and Classes.

I want the trigger to add +1 to the student count when I add a student with that class ID to the Students table.

```<code>CREATE TRIGGER updatestudentcount
ON ENROLLED
AFTER INSERT
AS
BEGIN
    UPDATE Classes
    SET enrolled_students = (enrolled_students + 1)
    WHERE class_id = old.class_id;
END
</code>```

But Old.Class_id doesn't work.

Would appreciate any help or tips.

Cheers!

答:
You almost got it. This doesn't work because old (but I believed it should be inserted as I recall) is a row not an variable object.

So :

```<code>declare @class_id int --- I presume
select @class_id = class_id from old
UPDATE Classes SET enrolled_students = (enrolled_students + 1) where class_id = @class_id;
</code>```

But if  if there was other delete-operations before the insert. Then your count would be wrong.

Or What if the insert was a insert into .. select from :

```<code>insert into students select * from #x
</code>```

So if you want to keep track of the correct count, this should do it :

```<code>CREATE TRIGGER updatestudentcount

ON ENROLLED

AFTER INSERT , DELETE

Update e
    set e.enrolled_students = b.enrolled_students
    from Classes e join (
                        select class_id, count(1) as enrolled_students
                        from ENROLLED
                        group by class_id
                        ) b
    on a.class_id = b.class_id

if exists(select top 1 from Classes where enrolled_students > 5)
begin
    print 'maximum reached'
end
</code>```

P/s : keep in mind that I haven't tested these code, may need a bit of modification but generally speaking, I think this is the correct way to do it.

Body:
I want to add let's say another student to a class.

Basically I have two tables: Students and Classes.

I want the trigger to add +1 to the student count when I add a student with that class ID to the Students table.

CREATE TRIGGER updatestudentcount
ON ENROLLED
AFTER INSERT
AS
BEGIN
    UPDATE Classes
    SET enrolled_students = (enrolled_students + 1)
    WHERE class_id = old.class_id;
END

But Old.Class_id doesn't work.

Would appreciate any help or tips.

Cheers!

Body:
You almost got it. This doesn't work because old (but I believed it should be inserted as I recall) is a row not an variable object.

So :

declare @class_id int --- I presume
select @class_id = class_id from old
UPDATE Classes SET enrolled_students = (enrolled_students + 1) where class_id = @class_id;

But if  if there was other delete-operations before the insert. Then your count would be wrong.

Or What if the insert was a insert into .. select from :

insert into students select * from #x

So if you want to keep track of the correct count, this should do it :

CREATE TRIGGER updatestudentcount

ON ENROLLED

AFTER INSERT , DELETE

Update e
    set e.enrolled_students = b.enrolled_students
    from Classes e join (
                        select class_id, count(1) as enrolled_students
                        from ENROLLED
                        group by class_id
                        ) b
    on a.class_id = b.class_id

if exists(select top 1 from Classes where enrolled_students > 5)
begin
    print 'maximum reached'
end

P/s : keep in mind that I haven't tested these code, may need a bit of modification but generally speaking, I think this is the correct way to do it.


来源: stackexchange

问:
How to ignore last row in filter suggestion in MS Excel?

Here Two columns filter contain its data, Data1 column filter contain 2,2,3,4 and 11. but 11 is a sum of that column using formula. How can i ignore it from filter suggestion?

答:
I agree with prextor, table formatting is the way to go.

But if you aren't formatting as a table a quick fix could just be to add a row before the totals row you have, then the filter will ignore the totals row.

Also, as prextor suggested, instead of using a SUM() on the totals row, you should use SUBTOTAL(9,B3:B6) and SUBTOTAL(9,C3:C6)

Screenshot (1)

Screenshot (2)

ContentLicense: CC BY-SA 3.0


问:
Python - Error with boolean condition(?)

Hi,

I'm trying to get return_3, return_6 and return_9 to check if the total value returned from all_return_values_func is above 20. The problem is that when I run the script return_3 it instantly prints "The total number of the returned values are too high".

How come all_return_values_func/return_value calculates as being above 20 the first time return_3 is run?

The point of the script is to go from each of return_3/return_6/return_9 scripts and make each of these functions add to the function all_return_values_func, and that functions value is later being checked if above 20 in function return_value

```<code>from sys import exit
import time

def all_return_values_func():
    combined_return_values = return_3() + return_6() + return_9()
    return combined_return_values

def return_value(i):
    if i > 20:
        print "The value is above 20"
        time.sleep(2)
        exit()

def return_3():

    return_value(all_return_values_func)
    print "Returns integer value: 3 and then jumps to function: return_6"
    time.sleep(2)
    return_6()
    return 3

def return_6():

    return_value(all_return_values_func)
    print "Returns integer value: 6 and then jumps to function: return_9"
    time.sleep(2)
    return_9()
    return 6

def return_9():

    return_value(all_return_values_func)
    print "Returns integer value: 9"
    time.sleep(2)
    return_3()
    return 9

return_3()
</code>```

Cheers,

Simon

答:
The problem is here:

```<code>return_value(all_return_values_func)
</code>```

You're not calling all_return_values_func so in return_value(), you are comparing whether the function itself is larger than 20. In Python 2.x, which you are using, this is always true: any function is larger than any integer. (This comparison throws an error in Python 3.x, which is a good deal less mystifying.)

The solution is to actually call the function:

```<code>return_value(all_return_values_func())
</code>```

However, that's not really a solution, because calling the function will cause the program to enter a recursive loop. all_return_values_func() calls return_3() which calls all_return_values_func() which calls return_3() which calls all_return_values_func()... Python will throw a RuntimeError when the stack hits 1000 calls deep.

Your program doesn't seem to do anything useful, or even make much sense. Perhaps address that before proceeding further.

Body:
Hi,

I'm trying to get return_3, return_6 and return_9 to check if the total value returned from all_return_values_func is above 20. The problem is that when I run the script return_3 it instantly prints "The total number of the returned values are too high".

How come all_return_values_func/return_value calculates as being above 20 the first time return_3 is run?

The point of the script is to go from each of return_3/return_6/return_9 scripts and make each of these functions add to the function all_return_values_func, and that functions value is later being checked if above 20 in function return_value

from sys import exit
import time

def all_return_values_func():
    combined_return_values = return_3() + return_6() + return_9()
    return combined_return_values

def return_value(i):
    if i > 20:
        print "The value is above 20"
        time.sleep(2)
        exit()

def return_3():

    return_value(all_return_values_func)
    print "Returns integer value: 3 and then jumps to function: return_6"
    time.sleep(2)
    return_6()
    return 3

def return_6():

    return_value(all_return_values_func)
    print "Returns integer value: 6 and then jumps to function: return_9"
    time.sleep(2)
    return_9()
    return 6

def return_9():

    return_value(all_return_values_func)
    print "Returns integer value: 9"
    time.sleep(2)
    return_3()
    return 9

return_3()

Cheers,

Simon

Body:
The problem is here:

return_value(all_return_values_func)

You're not calling all_return_values_func so in return_value(), you are comparing whether the function itself is larger than 20. In Python 2.x, which you are using, this is always true: any function is larger than any integer. (This comparison throws an error in Python 3.x, which is a good deal less mystifying.)

The solution is to actually call the function:

return_value(all_return_values_func())

However, that's not really a solution, because calling the function will cause the program to enter a recursive loop. all_return_values_func() calls return_3() which calls all_return_values_func() which calls return_3() which calls all_return_values_func()... Python will throw a RuntimeError when the stack hits 1000 calls deep.

Your program doesn't seem to do anything useful, or even make much sense. Perhaps address that before proceeding further.


问:
Using Switch-blocks to Parse input for a Text Adventure?
Okay, I have a goal right now to make a basic text adventure. To do this, however, I would need/want to have a switch statement that can do the following:

Check to see if a string has a word SOMEWHERE inside.

Check to see if a string has two words in any combination somewhere inside.

How would I accomplish this? Could you show me coding for this specific example:

A user is prompted for data. A switch statement checks for "look box" as one case, and "sleep" as another. The program doesn't care what order any words are in, but does care about the order of the letters.

Please explain everything in detail. I just started coding.

EDIT: Thank you for all the answers. I understand there are better, more complicated, and more useful ways of handling this, but it just isn't at my level yet.

答:
Considering you're starting at, we can look at this in the simple case first, but you can't use a switch statement to achieve this.

Let's assume, for the purposes of simplicity, that your commands are limited to 1 or 2 words and that the first word is a verb and the second would, if present is a noun.  This gives us quite a few possibilities:

```<code>North
South
Examine
Take
Drop
</code>```

etc...

Given that we have an input string of strInput:

```<code>string strInput = "examine hat";
</code>```

We want to first split this up.  We can do this using String.Split:

```<code>string[] arguments = strInput.Split(' ');
</code>```

Which will give us a string array:

arguments [0] is examine

arguments [1] is hat

Note, we don't always have a the 2nd one, if the user typed:

```<code>`North`
</code>```

then:

arguments [0] is North

We'll need to check for this!  Now, the horrible (but simple) way to check for this is:

```<code>if(arguments[0] == "North")
{
    // code to go North
}
else if(arguments[0] == "Take")
{
    // code to work with Take.  We'd check on arguments[1] here!
}
// etc...
</code>```

Unfortunately, this code is going to get long, complex and unusable.  How do you know what you can and can't do at any stage?  How do you add new command?  So let's use the wonderful delegate feature of C#, and also introduce the Dictionary.  A dictionary allows us to map one type (a key) to another (in this case, a delegate).  Using this method, we can create delegates to handle different kinds of commands.

```<code>public delegate void HandleCommand(string[] _input);
</code>```

Here, we delegated a delegate.  Don't worry about it yet, but let's introduce some functions that will work with commands:

```<code>public void Handle_North(string[] _input)
{
    // code to go North.  This function could just as easily be something that handles
    // *all* directions and checks _input[0] to see where to go!
}

public void Handle_Take(string[] _input)
{
    if(_input.Length > 1) // Did the user specify an object to take?
    {
        // code to handle Take.
    }
}
</code>```

And so on.  Now we need to create a dictionary to map the commands to these functions:

```<code>Dictionary<String, HandleCommand> map = new Dictionary<String, HandleCommand>();
</code>```

Here, we declare a dictionary that maps strings to our delegate type HandleCommand.  Now we need to populate it!

```<code>map["north"] = Handle_North;
map["take"]  = Handle_Take;
// and the rest of our commands
</code>```

Now, given our earlier example, let's split the string up as before, and call the right handler!

```<code>string[] arguments = strInput.Split(' ');
if(arguments.Length > 0 && map.ContainsKey(arguments[0]))
    map[arguments[0]](arguments);  // calls our function!
</code>```

Now we have an extensible system.  It is easy to add new commands and handlers!  It gets more complicated, but in essence this is a good way to do what you want.

EDIT: I am aware that your question said that it should not care about the order of the words.  If you're writing a text adventure game, you'd do well to form some grammer of Verb/Noun or some such rather than allowing things to be typed randomly.

Body:
Considering you're starting at, we can look at this in the simple case first, but you can't use a switch statement to achieve this.

Let's assume, for the purposes of simplicity, that your commands are limited to 1 or 2 words and that the first word is a verb and the second would, if present is a noun.  This gives us quite a few possibilities:

North
South
Examine
Take
Drop

etc...

Given that we have an input string of strInput:

string strInput = "examine hat";

We want to first split this up.  We can do this using String.Split:

string[] arguments = strInput.Split(' ');

Which will give us a string array:

arguments [0] is examine

arguments [1] is hat

Note, we don't always have a the 2nd one, if the user typed:

`North`

then:

arguments [0] is North

We'll need to check for this!  Now, the horrible (but simple) way to check for this is:

if(arguments[0] == "North")
{
    // code to go North
}
else if(arguments[0] == "Take")
{
    // code to work with Take.  We'd check on arguments[1] here!
}
// etc...

Unfortunately, this code is going to get long, complex and unusable.  How do you know what you can and can't do at any stage?  How do you add new command?  So let's use the wonderful delegate feature of C#, and also introduce the Dictionary.  A dictionary allows us to map one type (a key) to another (in this case, a delegate).  Using this method, we can create delegates to handle different kinds of commands.

public delegate void HandleCommand(string[] _input);

Here, we delegated a delegate.  Don't worry about it yet, but let's introduce some functions that will work with commands:

public void Handle_North(string[] _input)
{
    // code to go North.  This function could just as easily be something that handles
    // *all* directions and checks _input[0] to see where to go!
}

public void Handle_Take(string[] _input)
{
    if(_input.Length > 1) // Did the user specify an object to take?
    {
        // code to handle Take.
    }
}

And so on.  Now we need to create a dictionary to map the commands to these functions:

Dictionary<String, HandleCommand> map = new Dictionary<String, HandleCommand>();

Here, we declare a dictionary that maps strings to our delegate type HandleCommand.  Now we need to populate it!

map["north"] = Handle_North;
map["take"]  = Handle_Take;
// and the rest of our commands

Now, given our earlier example, let's split the string up as before, and call the right handler!

string[] arguments = strInput.Split(' ');
if(arguments.Length > 0 && map.ContainsKey(arguments[0]))
    map[arguments[0]](arguments);  // calls our function!

Now we have an extensible system.  It is easy to add new commands and handlers!  It gets more complicated, but in essence this is a good way to do what you want.

EDIT: I am aware that your question said that it should not care about the order of the words.  If you're writing a text adventure game, you'd do well to form some grammer of Verb/Noun or some such rather than allowing things to be typed randomly.

ContentLicense: CC BY-SA 2.5


问:
SOAP or REST interface to JMS broker. "JMS over SOAP"
My company long time ago decided to expose a JMS queue to customers in order to exchange data. We're in the process to migrate application server and we have to update all the client libraries. So we thought to expose a more "standard" interface.

We're looking to a simple way to expose a JMS queue through a standard SOAP or REST protocol. It's not SOAP over JMS, it would rather be the opposite "JMS over SOAP".

Seem that ActiveMQ(Artemis) has a REST protocol. It is a viable solution for us since we're migrating to Wildfly 10, but it's a bit complicated (see for instance posting a message requires 2 calls: see Posting Messages), and it is ActiveMQ-specific. We have to implement it again for the old Weblogic servers.

The solution we're searching for should have the same reliability of JMS, in respect of the CAP theorem (providing message deduplication on send, and idempotent reads). Any suggestion?

答:
As per my understanding this is anti pattern where we want to combine both REST/Webservice and JMS or creating hybrid model.

JMS has strong reliability,performance,monitoring,exception handling, async response and guaranteed delivery in compared to REST/Webservice.
The only weaker point of JMS is external firewall access that can be overcomed by creating hybrid model.
Restful JMS.
http://activemq.apache.org/rest.html
http://activemq.apache.org/activesoap.html

Thanks


答:
Try this </p>

```<code>CREATE TRIGGER updatestudentcount
ON ENROLLED
AFTER INSERT
AS
BEGIN
    UPDATE Classes
    SET enrolled_students = (enrolled_students + 1)
    WHERE class_id IN (SELECT class_id FROM INSERTED);
END
</code>```

Title: Incrementing a column by one in trigger?

Body:
Try this

CREATE TRIGGER updatestudentcount
ON ENROLLED
AFTER INSERT
AS
BEGIN
    UPDATE Classes
    SET enrolled_students = (enrolled_students + 1)
    WHERE class_id IN (SELECT class_id FROM INSERTED);
END


问:
Properly filter an observable of an array of objects by whether a particular property on each index is true?
So I have an Observable of type Student[]. That is to say an observable of an array of objects. Student has a property id: number .How do I filter out indices of the student array based on a property. For example lets say students$ is an observable of type Observable[Student] and I'd like to remove a student from the Observable<Student[]> based on their "bannedId", I tried:

```<code>students$.filter(student => student.id !== bannedId)
</code>```

however I got the error that id is not a property of Student[]. If I supply an index i.e. student[0].id it recognizes the property but obviously won't do what I want. How would I go about filtering this?

答:
Have you tried Observable.map(...)?

students$.map(studentList => studentList.filter(student => student.id !== bannedId))

It produces a new Observable on which you can expect the elements to not have student object with the banned id.

Body:
So I have an Observable of type Student[]. That is to say an observable of an array of objects. Student has a property id: number .How do I filter out indices of the student array based on a property. For example lets say students$ is an observable of type Observable[Student] and I'd like to remove a student from the Observable<Student[]> based on their "bannedId", I tried:

students$.filter(student => student.id !== bannedId)

however I got the error that id is not a property of Student[]. If I supply an index i.e. student[0].id it recognizes the property but obviously won't do what I want. How would I go about filtering this?


问:
Ordered delivery BizTalk performance
Is there an alternative to the "ordered delivery" on a send port in BizTalk? The sequence of the message is very important to me, so I created an orchestration that suspends the message when it is not in sequence, and resumes it when it is in sequence. I use a long running orchestration and direct port binding.

Now some messages are processed faster in the send pipeline, so it happens that sometimes the messages aren't in sequence (I use file adapter...).
Now when I check the "ordered delivery" the messages are in sequence no matter what, but the performance is really really bad (messages get bulked up in the send ports), so I need to find an alternative for the ordered delivery in the send port.

Any suggestions?

thx

答:
Now ordered delivery does obviously add a lot of overhead with the FIFO pattern.  Take a look at this article and look a the FIFO article in the first issue.  Also take a look at BizTalk performance in general to help speed up some of the other areas on your solution.  Now I've seen a few people try their own custom solution to ordering via .net and SQL and performance wasn't that much better because the ordering pattern takes time to process.  ALso take a look at these resources around performance in general:

Considersations when planning a perf test -
http://msdn2.microsoft.com/en-us/library/aa972201.aspx

BizTalk 2006 adapter performance numbers -
http://msdn2.microsoft.com/en-us/library/aa972200.aspx

If your transport in or out is SOAP, read this scalability study -
http://msdn2.microsoft.com/en-us/library/aa972198.aspx

Good proof points for BizTalk performance with relation to infrastructure
setup - http://msdn2.microsoft.com/en-us/library/ms864801.aspx

Title: Ordered delivery BizTalk performance


问:
Start multiple processes in Bash and time how long they take
How do I start multiple processes in bash and time how long they take?
From this question I know how to start multiple processes in a bash script but using time script.sh doesn't work because the processes spawned end after the script ends.
I tried using wait but that didn't change anything.
Here is the script in its entirety:

```<code>for i in `seq $1`
do
    ( ./client & )
done
wait # This doesn't seem to change anything
</code>```

I'm trying to get the total time for all the processes to finish and not the time for each process.

答:
Why the parentheses around client invocation?  That's going to run the command in a subshell.  Since the background job isn't in the top level shell, that's why the wait is ineffective (there's no jobs in this shell to wait for).

Then you can add time back inside the for loop and it should work.

Body:
How do I start multiple processes in bash and time how long they take?
From this question I know how to start multiple processes in a bash script but using time script.sh doesn't work because the processes spawned end after the script ends.
I tried using wait but that didn't change anything.
Here is the script in its entirety:

for i in `seq $1`
do
    ( ./client & )
done
wait # This doesn't seem to change anything

I'm trying to get the total time for all the processes to finish and not the time for each process.


问:
Rails grid view
I trying Ruby on Rails after Yii2 and my question is:
is there something like yii2 grid view? Yii2 lets me make admin panel faster and useful for searching content with filters.

Thx a lot!

答:
Not really. You can use Bootstrap to make .rows and .cols for formatting.

You can use ActiveAdmin for generating admin interfaces quit easily though, even easier than Yii2.

Here is a tutorial http://railscasts.com/episodes/284-active-admin?autoplay=true

Title: Rails grid view


问:
How to migrate Postgres array data in Rails

I need to change an array of ids in postgres from being integers to being uuids.  It's in a Rails app, and there are other parts to this, but I can't figure this out.

I could do it in ActiveRecord, but I can't figure out how to get the sql to do this.

```<code>add_column :templates, :uuids, :uuid, array: true
Template.find_each do |template|
  new_ids = template.conversations.map do |conversation_id|
    conversation = Conversation.find_by(id: conversation_id)
    conversation.uuid
  end
  template.update_column(:uuids, new_ids)
end
remove_column :templates, :conversations
rename_column :templates, :uuids, :conversations
</code>```

I would expect this to work, but it tells me that no column uuids exists on templates.

答:
Running:

```<code>Template.reset_column_information
</code>```

After the column is created and before the data migration should refresh the cache and discover the new column.
This is the same for any single migration file which does both column manipulation and data migrations.

The alternative is to split this over 2-3 migrations. Like so:

Create column

Data migration

Column remove & rename

This second approach has the added benefit that if your data migration fails for any reason you’re not left in a pseudo-state where the first column has been created already. This state means that trying to rerun the migration will fail as the column already exists.

Body:
I need to change an array of ids in postgres from being integers to being uuids.  It's in a Rails app, and there are other parts to this, but I can't figure this out.

I could do it in ActiveRecord, but I can't figure out how to get the sql to do this.

add_column :templates, :uuids, :uuid, array: true
Template.find_each do |template|
  new_ids = template.conversations.map do |conversation_id|
    conversation = Conversation.find_by(id: conversation_id)
    conversation.uuid
  end
  template.update_column(:uuids, new_ids)
end
remove_column :templates, :conversations
rename_column :templates, :uuids, :conversations

I would expect this to work, but it tells me that no column uuids exists on templates.

Body:
Running:

Template.reset_column_information

After the column is created and before the data migration should refresh the cache and discover the new column.
This is the same for any single migration file which does both column manipulation and data migrations.

The alternative is to split this over 2-3 migrations. Like so:

Create column

Data migration

Column remove & rename

This second approach has the added benefit that if your data migration fails for any reason you’re not left in a pseudo-state where the first column has been created already. This state means that trying to rerun the migration will fail as the column already exists.


问:
HTML/CSS/Javascript: Open/Close Menu when Clicking Button
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}</code>```

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

```

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

答:
Try this:

```<code>function dropDown() {
    var dropDown = document.querySelector(".dropdown-content");
    if (dropDown.style.display === 'block') {
        dropDown.style.display = "none";
    } else {
        dropDown.style.display = 'block'
    }
}
</code>```

Body:
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

Body:
Try this:

function dropDown() {
    var dropDown = document.querySelector(".dropdown-content");
    if (dropDown.style.display === 'block') {
        dropDown.style.display = "none";
    } else {
        dropDown.style.display = 'block'
    }
}


问:
Segment fault while reading a string into a char* array
I am trying to read some strings and then print them into a matrix form.

```<code>int main(int argc, char **argv)
{
    char *buffer[BUFFER_SIZE];
    for(size_t i = 0; i < BUFFER_SIZE; i++)
    {
        scanf("%s",buffer[i]);  /**This line is causing segment fault **/
    }

    for(size_t i = 0; i < BUFFER_SIZE; i++)
    {
        for(size_t j = 0; j < strnlen(buffer[i], MAX); j++ )
        {
            printf("%c ",buffer[i][j]);
        }
        printf("\n");
    }

}
</code>```

Any suggestion what I am missing here?

答: char *buffer[BUFFER_SIZE] is an array of character pointers. The way your code is now, buffer[i] is a char * that is uninitialized at the time you scanf("%s",buffer[i]). You need to allocate memory (malloc, perhaps) for scanf to store the string of characters prior to this point.

Body:
I am trying to read some strings and then print them into a matrix form.

int main(int argc, char **argv)
{
    char *buffer[BUFFER_SIZE];
    for(size_t i = 0; i < BUFFER_SIZE; i++)
    {
        scanf("%s",buffer[i]);  /**This line is causing segment fault **/
    }

    for(size_t i = 0; i < BUFFER_SIZE; i++)
    {
        for(size_t j = 0; j < strnlen(buffer[i], MAX); j++ )
        {
            printf("%c ",buffer[i][j]);
        }
        printf("\n");
    }

}

Any suggestion what I am missing here?


问:
PHP Mobile Detect Script Slowdown
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

```<code><?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>
</code>```

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?

答: The script you have included might be doing some cpu intensive calculations (which might be slowing it down), the only way is to find better script, OR If you want you can write your own code in PHP of 5-6 lines that can detect if user is on mobile. You can get more details on that here is this answer : Mobile device detection in PHP</p>

Title: PHP Mobile Detect Script Slowdown

Body:
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

<?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?


问:
Should I ask my web host to use PHP Version 5.3.5 on my VPS
Situation:: My current web host has given me a brand new VPS today with PHP 5.2.9 (released: Feb 2009).

What I did: I asked my web host to upgrade it to latest PHP 5.3.5 so I can get all security vulnerabilities fixed.

What web host replied: No, you should not. Your PHP scripts will break. Instead you can use PHP 5.2.17.

My Question: Should I force my web host to install PHP 5.3.5 on my VPS? What problem can possibly I get by upgrading. I currently do not use any PHP 5.3 features but may use those in future. My main concern is to get fully secure from known vulnerabilities.

Please don't close this question. It's not directly related to programming but is related to PHP which only PHP experts at SO can answer, I guess.

答:
An old release date does not means that it has vulnerabilities. For instance most Linux distributions keep the same PHP version forever (for the lifetime of the distribution's release), but they fix vulnerabilities as they are discovered.

Just make sure that all your distribution's packages are up to date.


问:
How to pass parameters to spark-SQL, not spark-scala?
I'd like to run spark-sql from command line with a parameter:

```<code>$ spark-sql myscript.sql hdfs://mydir/myfile.tsv
</code>```

In myscript.sql the parameter should be used

```<code>LOAD DATA LOCAL INPATH $PARAM1 INTO TABLE T;
</code>```

PS: I know how to do that in spark-shell and spark-submit. But that is not what I'm looking for.

答:
Pass a parameter by -d option in spark-sql. You can pass multiple params using several -d.

```<code>$ spark-sql -d INPUT=hdfs://mydir/myfile.tsv
</code>```

Then you can use this INPUT variable in SQL code:

```<code>CREATE TABLE MyTable (
    ID              STRING,
    VALUE           STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    "separatorChar" = "\,",
    "quoteChar"     = "\""
)
STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH '${INPUT}' INTO TABLE MyTable;
</code>```

Body:
I'd like to run spark-sql from command line with a parameter:

$ spark-sql myscript.sql hdfs://mydir/myfile.tsv

In myscript.sql the parameter should be used

LOAD DATA LOCAL INPATH $PARAM1 INTO TABLE T;

PS: I know how to do that in spark-shell and spark-submit. But that is not what I'm looking for.

Body:
Pass a parameter by -d option in spark-sql. You can pass multiple params using several -d.

$ spark-sql -d INPUT=hdfs://mydir/myfile.tsv

Then you can use this INPUT variable in SQL code:

CREATE TABLE MyTable (
    ID              STRING,
    VALUE           STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    "separatorChar" = "\,",
    "quoteChar"     = "\""
)
STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH '${INPUT}' INTO TABLE MyTable;


问:
Google Contacts feed is breaking gdata-contacts-3.0-1.47.1
This is for Google API folks.

Not sure when exactly the feed has changed but very recently (today or a couple of days ago). the GDATA library can't process Google Contacts feed anymore, failing with this:

com.yoxel.sync.core.exceptions.SyncException: com.google.gdata.util.ParseException: [Line 30, Column 86, element gContact:website] Invalid value for attribute : 'rel'

value=http://schemas.google.com/g/2005#profile

GDATA library seems to be expecting capital PROFILE but the feed started to send lowercase!

```<code>for (Enum enumValue : (Enum[])enumClass.getEnumConstants()) {
   if (enumToAttributeValue.getAttributeValue(enumValue).equals(value){
    return enumValue;
 }
}
</code>```

Is there more recent gdata library available?

Thank you.

10/9/20 Update:

For those migrating to the new People API check out our new unified API platform Aurinko.io

答:
Seems like Google contacts feed API is currently broken when creating/updating contacts if a contact has relations/events/websites.

Ticket is already filed at https://issuetracker.google.com/u/0/issues/70209603

ContentLicense: CC BY-SA 4.0

Body:
This is for Google API folks.

Not sure when exactly the feed has changed but very recently (today or a couple of days ago). the GDATA library can't process Google Contacts feed anymore, failing with this:

com.yoxel.sync.core.exceptions.SyncException: com.google.gdata.util.ParseException: [Line 30, Column 86, element gContact:website] Invalid value for attribute : 'rel'

value=http://schemas.google.com/g/2005#profile

GDATA library seems to be expecting capital PROFILE but the feed started to send lowercase!

for (Enum enumValue : (Enum[])enumClass.getEnumConstants()) {
   if (enumToAttributeValue.getAttributeValue(enumValue).equals(value){
    return enumValue;
 }
}

Is there more recent gdata library available?

Thank you.

10/9/20 Update:

For those migrating to the new People API check out our new unified API platform Aurinko.io


问:
How to design a Data Model for a Servant Management System with Roles
I am trying to manage roles but I am stuck in role management. I am working on servant management system.  I have servant in my system , user and admin

I have created a role table and manage role table

```<code>user table
-----------
user_id   user_name   user_pass
  1          abc        xyz
</code>```

this is my role table

```<code>role table
-----------
r_id  r_name
  1   customer
  2   servant
  3   admin
</code>```

and manage role table

```<code>manage role table
------------------
r_id  u_id
  1    1
  1    2
  2    3
</code>```

Now the problem is i have a hire table i want to see which user has hire which servant

```<code>hire table
----------
c_id , s_id
</code>```

what is the best way to represent hire table because I want to see which customer has hire which servant through id?

答:
First of All: there is no need to Reinventing the wheel.

In Data Modeling world, we have some patterns to your problem:

Context-based access control (CBAC)

Data-centric security

Discretionary access control (DAC)

Graph-based access control (GBAC)

Lattice-based access control (LBAC)

Mandatory access control (MAC)

Organisation-based access control (OrBAC)

Role-based access control (RBAC)

Rule-set-based access control (RSBAC)

Attribute-based-access-control (ABAC)

I offer to use RBAC (Role-Based Access Control).

And now:

After applying RBAC in your project, you have 2 ways to use RBAC data into your project's tables:

If you want to save a user that performs something (e.g. hire), just add user_id as foreign key into that table.

If user has more than 1 role, just add user_id and role_id as foreign keys into that table.

to your final question: just add their id's as foreign keys to new table.

Body:
I am trying to manage roles but I am stuck in role management. I am working on servant management system.  I have servant in my system , user and admin

I have created a role table and manage role table

user table
-----------
user_id   user_name   user_pass
  1          abc        xyz

this is my role table

role table
-----------
r_id  r_name
  1   customer
  2   servant
  3   admin

and manage role table

manage role table
------------------
r_id  u_id
  1    1
  1    2
  2    3

Now the problem is i have a hire table i want to see which user has hire which servant

hire table
----------
c_id , s_id

what is the best way to represent hire table because I want to see which customer has hire which servant through id?


问:
Firestore permissions
How do I configure permissions so that a user can only read and write documents where they are the owner?
my documents have a top level attribute called owner.

I read these docs

https://firebase.google.com/docs/firestore/security/secure-data?authuser=0#the_resource_variable

and it seems like this should work?

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.email == resource.data.owner
    }
  }
}
</code>```

however this doesn't seem to work. i continuously get insufficient permission error.
What do i need to change?

Update:

After reading the docs @Doug Stevenson linked I decided to go with

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.uid == resource.data.owner_uid;
    }
  }
}
</code>```

So my original intent was that when we do a list operation:

a. only those documents belonging to a user are returned

b. only documents a user owns can be read or written by that user.

With the above configuration b. is accomplished.

how do I do accomplish a. ?

答:
To answer your update question part (a):

I has a similar issue - I had my rules set correctly to allow that user to read and write. However, Firestore needs us to have our queries match the firestore database rules. So the query on the front should match what that user has access to. So my issue was I was asking for all products in the collection. What I needed to change it to was asking for all products in the collection where the "owner" of the product matched the logged in user, like this:

```<code>db.collection('products').where('owner', '==', firebase.auth().currentUser.uid).get()
</code>```

Hope this helps

Title: Firestore permissions

Body:
How do I configure permissions so that a user can only read and write documents where they are the owner?
my documents have a top level attribute called owner.

I read these docs

https://firebase.google.com/docs/firestore/security/secure-data?authuser=0#the_resource_variable

and it seems like this should work?

service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.email == resource.data.owner
    }
  }
}

however this doesn't seem to work. i continuously get insufficient permission error.
What do i need to change?

Update:

After reading the docs @Doug Stevenson linked I decided to go with

service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.uid == resource.data.owner_uid;
    }
  }
}

So my original intent was that when we do a list operation:

a. only those documents belonging to a user are returned

b. only documents a user owns can be read or written by that user.

With the above configuration b. is accomplished.

how do I do accomplish a. ?

Body:
To answer your update question part (a):

I has a similar issue - I had my rules set correctly to allow that user to read and write. However, Firestore needs us to have our queries match the firestore database rules. So the query on the front should match what that user has access to. So my issue was I was asking for all products in the collection. What I needed to change it to was asking for all products in the collection where the "owner" of the product matched the logged in user, like this:

db.collection('products').where('owner', '==', firebase.auth().currentUser.uid).get()

Hope this helps


问:
YOLO - tensorflow works on cpu but not on gpu
I've used YOLO detection with trained model using my GPU - Nvidia 1060 3Gb, and everything worked fine.

Now I am trying to generate my own model, with param --gpu 1.0. Tensorflow can see my gpu, as I can read at start those communicates:
"name: GeForce GTX 1060 major: 6 minor: 1 memoryClockRate(GHz): 1.6705"
"totalMemory: 3.00GiB freeMemory: 2.43GiB"

Anyway, later on, when program loads data, and is trying to start learning i got following error:
"failed to allocate 832.51M (872952320 bytes) from device: CUDA_ERROR_OUT_OF_MEMORY"

I've checked if it tries to use my other gpu (Intel 630) , but it doesn't.

As i run the train process without "--gpu" mode option, it works fine, but slowly.
( I've tried also --gpu 0.8, 0.4 ect.)

Any idea how to fix it?

答: Problem solved. Changing batch size and image size in config file didn't seem to help as they didn't load correctly. I had to go to defaults.py file and change them up there to lower, to make it possible for my GPU to calculate the steps.</p>


问:
table body and multiple headers alignment
I am trying to keep a table's thead columns and tbody columns aligned while keeping tbody scrollable. I had thead display set to table-header-group and tbody set to table-row-group to fix alignment but then I could not scroll.

Here is the jsfiddle. I am trying to set the column width for just the first column while keeping the whole thing aligned.

I cannot set a width for every column since this table is dynamically generated (using angular ng-repeat) and could have as little as 3 columns and as many as 12

any pointers would be helpful JsFiddle

.table {
  border-collapse: collapse;
  width: 100%;
}

.table td {
  font-size: 14px;
  padding: 10px 20px;
  overflow: hidden;
  word-break: normal;
  color: #333;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  background-color: #FFFFFF;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
}

.table th {
  font-weight: bold;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
  font-size: 14px;
  border: 1px solid #ccc;
  border-bottom: 2px solid #ccc;
  padding: 10px 20px;
  word-break: normal;
  color: #333;
  background-color: #F0F0F0;
}

tbody {
  overflow-y: scroll;
  overflow-x: hidden;
  height: 100px;
  display: block;
}

thead {
  display: table;
  width: calc(100% - 17px);
  table-layout: fixed;
  /* position: sticky; */
}

tbody tr {
  table-layout: fixed;
  display: table;
  width: 100%;
}

tbody tr td:first-child {
  width: 40%;
}

thead tr:nth-child(2) th:first-child {
  width: 40%;
}

td {
  white-space: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
  <thead>
    <tr>
      <th colspan=2>Course ID</th>
      <th colspan=1>Course Name</th>
      <th colspan=1>Course Name</th>
    </tr>
    <tr>
      <th>Course ID</th>
      <th>Course ID2</th>
      <th>Course Name</th>
      <th>Course Name2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>hello theresdfdsfsfsafdsafdsafdsafdsadfsadfsafd</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
  </tbody>
</table></code>```

答:
I have replaced both your nth-child css code with the following and it works.

.table {
  border-collapse: collapse;
  width: 100%;
}

.table td {
  font-size: 14px;
  padding: 10px 20px;
  overflow: hidden;
  word-break: normal;
  color: #333;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  background-color: #FFFFFF;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
}

.table th {
  font-weight: bold;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
  font-size: 14px;
  border: 1px solid #ccc;
  border-bottom: 2px solid #ccc;
  padding: 10px 20px;
  word-break: normal;
  color: #333;
  background-color: #F0F0F0;
}

tbody {
  overflow-y: scroll;
  overflow-x: hidden;
  height: 100px;
  display: block;
}

thead {
  display: table;
  width: calc(100% - 17px);
  table-layout: fixed;
  /* position: sticky; */
}

tbody tr {
  table-layout: fixed;
  display: table;
  width: 100%;
}

td {
  white-space: normal;
}

th:nth-child(1) {width:50%;}

td:nth-child(-n + 2) {
    width:25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
  <thead>
    <tr>
      <th colspan=2>Course ID</th>
      <th colspan=1>Course Name</th>
      <th colspan=1>Course Name</th>
    </tr>
    <tr>
      <th>Course ID</th>
      <th>Course ID2</th>
      <th>Course Name</th>
      <th>Course Name2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>hello theresdfdsfsfsafdsafdsafdsafdsadfsadfsafd</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
  </tbody>
</table></code>```

This sets the first th to a 50% value (you can change that to suit your preference).

```<code>th:nth-child(1) {
 width:50%;
}
</code>```

And this, sets your first 2 td to a width of 25% (half of the above width which is currently set at 50%, so change it accordingly to half of any number you set in the above css.).

```<code>td:nth-child(-n + 2) {
 width:25%;
}
</code>```

Hope this was helpful!

Body:
I am trying to keep a table's thead columns and tbody columns aligned while keeping tbody scrollable. I had thead display set to table-header-group and tbody set to table-row-group to fix alignment but then I could not scroll.

Here is the jsfiddle. I am trying to set the column width for just the first column while keeping the whole thing aligned.

I cannot set a width for every column since this table is dynamically generated (using angular ng-repeat) and could have as little as 3 columns and as many as 12

any pointers would be helpful JsFiddle

.table {
  border-collapse: collapse;
  width: 100%;
}

.table td {
  font-size: 14px;
  padding: 10px 20px;
  overflow: hidden;
  word-break: normal;
  color: #333;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  background-color: #FFFFFF;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
}

.table th {
  font-weight: bold;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
  font-size: 14px;
  border: 1px solid #ccc;
  border-bottom: 2px solid #ccc;
  padding: 10px 20px;
  word-break: normal;
  color: #333;
  background-color: #F0F0F0;
}

tbody {
  overflow-y: scroll;
  overflow-x: hidden;
  height: 100px;
  display: block;
}

thead {
  display: table;
  width: calc(100% - 17px);
  table-layout: fixed;
  /* position: sticky; */
}

tbody tr {
  table-layout: fixed;
  display: table;
  width: 100%;
}

tbody tr td:first-child {
  width: 40%;
}

thead tr:nth-child(2) th:first-child {
  width: 40%;
}

td {
  white-space: normal;
}

      Course ID
      Course Name
      Course Name

      Course ID
      Course ID2
      Course Name
      Course Name2

      hello theresdfdsfsfsafdsafdsafdsafdsadfsadfsafd
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

      hello there
      hello
      there
      world

Body:
I have replaced both your nth-child css code with the following and it works.

.table {
  border-collapse: collapse;
  width: 100%;
}

.table td {
  font-size: 14px;
  padding: 10px 20px;
  overflow: hidden;
  word-break: normal;
  color: #333;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  background-color: #FFFFFF;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
}

.table th {
  font-weight: bold;
  font-family: "Courier New", Courier, monospace !important;
  text-align: center;
  font-size: 14px;
  border: 1px solid #ccc;
  border-bottom: 2px solid #ccc;
  padding: 10px 20px;
  word-break: normal;
  color: #333;
  background-color: #F0F0F0;
}

tbody {
  overflow-y: scroll;
  overflow-x: hidden;
  height: 100px;
  display: block;
}

thead {
  display: table;
  width: calc(100% - 17px);
  table-layout: fixed;
  /* position: sticky; */
}

tbody tr {
  table-layout: fixed;
  display: table;
  width: 100%;
}

td {
  white-space: normal;
}

th:nth-child(1) {width:50%;}

td:nth-child(-n + 2) {
    width:25%;
}

<table class="table">
  <thead>
    <tr>
      <th colspan=2>Course ID</th>
      <th colspan=1>Course Name</th>
      <th colspan=1>Course Name</th>
    </tr>
    <tr>
      <th>Course ID</th>
      <th>Course ID2</th>
      <th>Course Name</th>
      <th>Course Name2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>hello theresdfdsfsfsafdsafdsafdsafdsadfsadfsafd</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
    <tr>
      <td>hello there</td>
      <td>hello</td>
      <td>there</td>
      <td>world</td>
    </tr>
  </tbody>
</table>

This sets the first th to a 50% value (you can change that to suit your preference).

th:nth-child(1) {
 width:50%;
}

And this, sets your first 2 td to a width of 25% (half of the above width which is currently set at 50%, so change it accordingly to half of any number you set in the above css.).

td:nth-child(-n + 2) {
 width:25%;
}

Hope this was helpful!


答: If its a VPS do you have root access? If so you could upgrade yourself. I imagine it should be possible with a little work to install both versions.</p>

Title: Should I ask my web host to use PHP Version 5.3.5 on my VPS

Body:
Situation:: My current web host has given me a brand new VPS today with PHP 5.2.9 (released: Feb 2009).

What I did: I asked my web host to upgrade it to latest PHP 5.3.5 so I can get all security vulnerabilities fixed.

What web host replied: No, you should not. Your PHP scripts will break. Instead you can use PHP 5.2.17.

My Question: Should I force my web host to install PHP 5.3.5 on my VPS? What problem can possibly I get by upgrading. I currently do not use any PHP 5.3 features but may use those in future. My main concern is to get fully secure from known vulnerabilities.

Please don't close this question. It's not directly related to programming but is related to PHP which only PHP experts at SO can answer, I guess.


问:
what tag should i use for text? html5
What tag should i use for small amount of text. For example it is good practise to use p tag for every "small" text like here "username" and pasword" or for day/month/year, should i use also p tag? </p>

```<code><div class="login-area">
    <p>Username:</p>
    <input type="text">
    <p>Password:</p>
    <input type="password">
</div>
</code>```

答:
As Others have suggested  tag is other option that you can use.

Some of it's use cases are as follows:

<input type="text" id="lastname" />
Last Name```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
   Name : <input type="text" name="lastname" />
</label></code>```

Last Name
<input type="text" id="lastname" />```

Title: what tag should i use for text? html5

Body:
What tag should i use for small amount of text. For example it is good practise to use p tag for every "small" text like here "username" and pasword" or for day/month/year, should i use also p tag?

Username:

    <input type="text">

Password:

    <input type="password">

Body:
As Others have suggested <label></label> tag is other option that you can use.

Some of it's use cases are as follows:

<input type="text" id="lastname" />
<label for="lastname">Last Name</label>

<label>
   Name : <input type="text" name="lastname" />
</label>

<label for="lastname">Last Name</label>
<input type="text" id="lastname" />


问:
how to remove light effect on BABYLON Lines
I try to develop a board game with BABYLON.js
I have a board and an ArcRotateCamera.

My light is an HemisphericLight

When I draw Lines on my board I would like that these line have all the same aspect.  Now when I move the camera, the light have an effect on these lines and some of them disappear by changing color too close to the background color.

How i can define that my line doesn't are affected by the light ?

答:
Apart from the method mentioned of excluding it from the lights (for which you can also use light.excludedMeshes.push(mesh);) you can try removing the glare which makes a material look metallic and too shiny. Depending on what you want, one or the other will work better.

This is how you remove the glare:

```<code>light.specular = new BABYLON.Color3(0,0,0);
</code>```

Body:
Apart from the method mentioned of excluding it from the lights (for which you can also use light.excludedMeshes.push(mesh);) you can try removing the glare which makes a material look metallic and too shiny. Depending on what you want, one or the other will work better.

This is how you remove the glare:

light.specular = new BABYLON.Color3(0,0,0);


问:
All support libraries must use the exact same version specification.Found 27.0.1.26.1.0
I am struggling with gradle build error i followed this this and this but none working for me. It was working fine but once i update Exoplayer lib to 2.6 from current but even after reverse i am getting same error. Also when i tried to followed First answer i am getting 7000+ errors in gradle build.

My libraries

答:
Use 27.0.1 instead of 26.1.0.  Do this for all current dependencies and if the error still pops up, add the 26.1.0 library it mentions to your build.gradle as version 27.0.1

Continue until the error is fixed


问:
JOIN 2 tables and select specific rows
I use Wordpress table to populate the javafx TableView.
In WP db I have 2 tables wp_posts & wp_postmeta and I need JOIN the table by ID (post_id in wp_postmeta) and select specific rows from wp_postmeta (not all).

For Exampe:
wp_postmeta structure post_id, meta_key, meta_value. In meta_key there is 3 rows - _yoast_wpseo_title, ._yoast_wpseo_metadesc, ._yoast_wpseo_focuskeywords
and I need this rows value from column meta_value.

My code:

```<code>ResultSet rs = connection.createStatement().executeQuery(" SELECT wp_postmeta._yoast_wpseo_title, wp_postmeta._yoast_wpseo_metadesc, wp_postmeta._yoast_wpseo_focuskeywords, wp_posts.post_title, wp_posts.post_name FROM wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id ");
</code>```

And of course I receive error that columns _yoast_wpseo_title, _yoast_wpseo_metadesc, _yoast_wpseo_focuskeywords not found because thay are rows.

How I can do this? (I use java9, javafx, mysql jdbc). Or may be I must use PreparedStatement?

Screenshot:

答:
Since you want to filter your query based on the content of the meta_key field, you use a WHERE clause:

```<code>SELECT wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.post_title
   FROM wp_postmeta INNER JOIN  wp_posts ON wp_posts.ID = wp_postmeta.post_id
   WHERE wp_postmeta.meta_key IN ('_yoast_wpseo_title', '_yoast_wpseo_metadesc', '_yoast_wpseo_focuskeywords')
</code>```

You are providing a list of the meta keys you want to match. This will give (up to) three rows for each post.

If you want only one row for each post, things get more complicated (and probably aren't worth the trouble). You can use GROUP BY post_id and then study the Aggregate functions.

Title: JOIN 2 tables and select specific rows

Body:
I use Wordpress table to populate the javafx TableView.
In WP db I have 2 tables wp_posts & wp_postmeta and I need JOIN the table by ID (post_id in wp_postmeta) and select specific rows from wp_postmeta (not all).

For Exampe:
wp_postmeta structure post_id, meta_key, meta_value. In meta_key there is 3 rows - _yoast_wpseo_title, ._yoast_wpseo_metadesc, ._yoast_wpseo_focuskeywords
and I need this rows value from column meta_value.

My code:

ResultSet rs = connection.createStatement().executeQuery(" SELECT wp_postmeta._yoast_wpseo_title, wp_postmeta._yoast_wpseo_metadesc, wp_postmeta._yoast_wpseo_focuskeywords, wp_posts.post_title, wp_posts.post_name FROM wp_postmeta INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id ");

And of course I receive error that columns _yoast_wpseo_title, _yoast_wpseo_metadesc, _yoast_wpseo_focuskeywords not found because thay are rows.

How I can do this? (I use java9, javafx, mysql jdbc). Or may be I must use PreparedStatement?

Screenshot:

Body:
Since you want to filter your query based on the content of the meta_key field, you use a WHERE clause:

SELECT wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.post_title
   FROM wp_postmeta INNER JOIN  wp_posts ON wp_posts.ID = wp_postmeta.post_id
   WHERE wp_postmeta.meta_key IN ('_yoast_wpseo_title', '_yoast_wpseo_metadesc', '_yoast_wpseo_focuskeywords')

You are providing a list of the meta keys you want to match. This will give (up to) three rows for each post.

If you want only one row for each post, things get more complicated (and probably aren't worth the trouble). You can use GROUP BY post_id and then study the Aggregate functions.


问:
Compile Flex 4 theme in Flash Builder 4
How to compile Flex theme SWC from file.css and additional skin classes in Flash Builder 4?

I've tried creating simple Flex Library project but it does not seem to use CSS file because resulting SWC does not work as theme.

答: It has started working after adding defaults.css to the library assets and mx|Button class declaration. Seems like a bug for me.

Title: Compile Flex 4 theme in Flash Builder 4


问:
In a MTKView How to get pixel information ( RGB and Alpha values ) of a given point in 3D (x,y,z)?
Ok we have draw several things in a MTKView We can move and turn around them using Metal, MetalKit functions but we are unable to get pixel information of a given point in 3D (x,y,z). We searched several hours and could not find any solution for that.

答:
This seems like a classic case of trying to consult your view (in the Model-View-Controller paradigm sense of the term) for information held by the model. Consult your model directly.

A 3D rendering technology like Metal is all about flattening 3D information to 2D and efficiently throwing away information not relevant to that 2D representation. Neither Metal nor the MTKView has any information about points in 3D by the end of the render.

Also note, your model probably doesn't have information for arbitrary 3D points. Most likely all of your 3D models (in the other sense of the term) are shells. They have no interiors, just surfaces. So, unless a 3D point falls exactly on the surface and not at all inside nor outside of the model, it has no color.


问:
How to plot lines around images in Matplotlib
I have two lists with the coordinates of points that I want to draw using matplotlib: hx and hy, and i have a function which draws these points as images: plotImage.

Now I would like to plot a line between these points, but the line should go somehow around the pictures. It doesn't have to go excctly by the borders of the images, the important thing is that it doesn't overlap with the pictures.

Here is an example, the green line is what I have now (its the convex hull), and the red line is an example of how the line should look like.

Here's my code:

```<code>def plotImage(xData, yData, im):
    for x, y in zip(xData, yData):
        bb = Bbox.from_bounds(x,y,10,10)
        bb2 = TransformedBbox(bb,ax.transData)
        bbox_image = BboxImage(bb2,
                            norm = None,
                            origin=None,
                            clip_on=False)

        bbox_image.set_data(im)
        ax.add_artist(bbox_image)

fig=plt.figure()
ax=fig.add_subplot(111)
img = plt.imread('pic.png')

gx = list(map(lambda x: x - 5, hx)) #  so the center of the picture is in the point I want to plot
gy = list(map(lambda y: y - 5, hy)) #(without this, the image is drawn so that the picture's left bottom corner is in my point)

plotImage(gx,gy,img)
plt.plot(hx, hy, 'g-', markersize=10)
</code>```

So my question is: how to calculate this red hull?

答:
A example using Incrementing area of convex hull can be applied to your case.</p>

```<code>from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import numpy as np

gx = [-2, 2, -2, 2, 1, -0.5]
gy = [3, 4, -2, -1, -1, 0.5]

points = np.array((gx, gy)).T
convh = ConvexHull(points)
stretchCoef = 1.2
pointsStretched = points[convh.vertices]*stretchCoef

gx_new = pointsStretched[..., 0]
gy_new = pointsStretched[..., 1]
</code>```

Body:
I have two lists with the coordinates of points that I want to draw using matplotlib: hx and hy, and i have a function which draws these points as images: plotImage.

Now I would like to plot a line between these points, but the line should go somehow around the pictures. It doesn't have to go excctly by the borders of the images, the important thing is that it doesn't overlap with the pictures.

Here is an example, the green line is what I have now (its the convex hull), and the red line is an example of how the line should look like.

Here's my code:

def plotImage(xData, yData, im):
    for x, y in zip(xData, yData):
        bb = Bbox.from_bounds(x,y,10,10)
        bb2 = TransformedBbox(bb,ax.transData)
        bbox_image = BboxImage(bb2,
                            norm = None,
                            origin=None,
                            clip_on=False)

        bbox_image.set_data(im)
        ax.add_artist(bbox_image)

fig=plt.figure()
ax=fig.add_subplot(111)
img = plt.imread('pic.png')

gx = list(map(lambda x: x - 5, hx)) #  so the center of the picture is in the point I want to plot
gy = list(map(lambda y: y - 5, hy)) #(without this, the image is drawn so that the picture's left bottom corner is in my point)

plotImage(gx,gy,img)
plt.plot(hx, hy, 'g-', markersize=10)

So my question is: how to calculate this red hull?

Body:
A example using Incrementing area of convex hull can be applied to your case.

from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import numpy as np

gx = [-2, 2, -2, 2, 1, -0.5]
gy = [3, 4, -2, -1, -1, 0.5]

points = np.array((gx, gy)).T
convh = ConvexHull(points)
stretchCoef = 1.2
pointsStretched = points[convh.vertices]*stretchCoef

gx_new = pointsStretched[..., 0]
gy_new = pointsStretched[..., 1]


问:
mockito does not mock in the actual method
I am mocking AuthService in the test below and setting authService.checkAuthority(any(UserAuthority.class))as "true". It is actually getting set but in the actual method(authService.checkAuthority(UserAuthority.COMMENT_ACCESS))  it is getting the value as false.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(ApplicationRunner.class)
@WebAppConfiguration
@Transactional
public class TagsTest extends BaseWebTest {
    @Autowired
    private TagService tagService;
    @Autowired
    private TagRepository repository;
    UserDetailsDto currentUser;
    @Autowired
    protected AuthService authService;
    @Autowired
    protected StringRedisTemplate stringRedisTemplate;
    @Autowired
    protected FilterChainProxy filterChainProxy;
    @Autowired
    protected WebApplicationContext context;
    protected static MockMvc mvc;

    @Before
    @Override
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context)
                .dispatchOptions(true)
                .addFilters(filterChainProxy)
                .build();
        authService = Mockito.mock(AuthService.class);
        Mockito.reset(authService);

        when(authService.getCurrentUser()).then(i->(getCurrentUser()));
        when(authService.checkAuthority(any(UserAuthority.class))).
                                        thenReturn(true);

        login(WORKFLOW_USER);
    }
</code>```

Any help is appreciated. Thanks in advance !

答:
Your specific issue might be solved just by removing this assignment:

```<code>authService = Mockito.mock(AuthService.class);
</code>```

Your goal here is to use SpringJUnit4ClassRunner to create some of the dependencies in your graph, and use Mockito to mock other dependencies. However, as in this SO answer, anything marked with @Autowired in your test is created before the @Before method is run. This means that your call to replace authService above will only overwrite the field in your test; it won't adjust or change any of the other @Autowired fields, which have already been created, and which are already using the authService that you've bound in your Spring configuration.

Unit tests

If this is a unit test, and you're simply testing TagsService and TagsRepository, you might want to create those objects manually by calling their constructor with a combination of @Mock and @Autowired fields:

```<code>TagRepository repository = new TagRepository(/*mock*/ authService);
TagService tagService = new TagService(/*mock*/ authService, /*real*/ repository);
</code>```

(Mockito provides a way to automate the creation of mocks using @InjectMocks, but because it fails silently if it can't detect an appropriate mock, you might want to avoid that and call a constructor instead. See this article for some good reasons and solutions.)

Note that the above is only when you are working directly with objects in unit tests, not when you're relying on Spring's autowiring to inject objects deeper into your graph.

Integration tests

The test you posted looks like a web or integration test, so it looks like you want to replace the instances of authService with your mock during their creation. Typically this means making a change to the configuration XML or your ApplicationRunner, in order to instruct Spring to use a Mockito mock instead of your real AuthService. Though there are lots of ways to do this, you might want to favor using a Mockito-centric FactoryBean as in this article.

But wait! You may be using an ApplicationRunner that is already customized for Mockito. The line authService = Mockito.mock(AuthService.class); looks very much out-of-place for three reasons:

you are overwriting an @Autowired field, which rarely makes sense

you call Mockito.mock manually despite the existence of MockitoAnnotations.initMocks(this), which is generally preferred

you immediately reset the mock you create

This suggests to me that your @Autowired authService may already be a mock, and may already have stubbing, which is why you have a leftover reset. If so, then your problem isn't anything about Mockito, other than that you (or someone) have overwritten the field and stubbed your local copy instead of the one that Spring installs throughout your web test. That'd make it an easy fix: Delete your field reassignment and you may be good to go.

Body:
I am mocking AuthService in the test below and setting authService.checkAuthority(any(UserAuthority.class))as "true". It is actually getting set but in the actual method(authService.checkAuthority(UserAuthority.COMMENT_ACCESS))  it is getting the value as false.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(ApplicationRunner.class)
@WebAppConfiguration
@Transactional
public class TagsTest extends BaseWebTest {
    @Autowired
    private TagService tagService;
    @Autowired
    private TagRepository repository;
    UserDetailsDto currentUser;
    @Autowired
    protected AuthService authService;
    @Autowired
    protected StringRedisTemplate stringRedisTemplate;
    @Autowired
    protected FilterChainProxy filterChainProxy;
    @Autowired
    protected WebApplicationContext context;
    protected static MockMvc mvc;

    @Before
    @Override
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context)
                .dispatchOptions(true)
                .addFilters(filterChainProxy)
                .build();
        authService = Mockito.mock(AuthService.class);
        Mockito.reset(authService);

        when(authService.getCurrentUser()).then(i->(getCurrentUser()));
        when(authService.checkAuthority(any(UserAuthority.class))).
                                        thenReturn(true);

        login(WORKFLOW_USER);
    }

Any help is appreciated. Thanks in advance !

Body:
Your specific issue might be solved just by removing this assignment:

authService = Mockito.mock(AuthService.class);

Your goal here is to use SpringJUnit4ClassRunner to create some of the dependencies in your graph, and use Mockito to mock other dependencies. However, as in this SO answer, anything marked with @Autowired in your test is created before the @Before method is run. This means that your call to replace authService above will only overwrite the field in your test; it won't adjust or change any of the other @Autowired fields, which have already been created, and which are already using the authService that you've bound in your Spring configuration.

Unit tests

If this is a unit test, and you're simply testing TagsService and TagsRepository, you might want to create those objects manually by calling their constructor with a combination of @Mock and @Autowired fields:

TagRepository repository = new TagRepository(/*mock*/ authService);
TagService tagService = new TagService(/*mock*/ authService, /*real*/ repository);

(Mockito provides a way to automate the creation of mocks using @InjectMocks, but because it fails silently if it can't detect an appropriate mock, you might want to avoid that and call a constructor instead. See this article for some good reasons and solutions.)

Note that the above is only when you are working directly with objects in unit tests, not when you're relying on Spring's autowiring to inject objects deeper into your graph.

Integration tests

The test you posted looks like a web or integration test, so it looks like you want to replace the instances of authService with your mock during their creation. Typically this means making a change to the configuration XML or your ApplicationRunner, in order to instruct Spring to use a Mockito mock instead of your real AuthService. Though there are lots of ways to do this, you might want to favor using a Mockito-centric FactoryBean as in this article.

But wait! You may be using an ApplicationRunner that is already customized for Mockito. The line authService = Mockito.mock(AuthService.class); looks very much out-of-place for three reasons:

you are overwriting an @Autowired field, which rarely makes sense

you call Mockito.mock manually despite the existence of MockitoAnnotations.initMocks(this), which is generally preferred

you immediately reset the mock you create

This suggests to me that your @Autowired authService may already be a mock, and may already have stubbing, which is why you have a leftover reset. If so, then your problem isn't anything about Mockito, other than that you (or someone) have overwritten the field and stubbed your local copy instead of the one that Spring installs throughout your web test. That'd make it an easy fix: Delete your field reassignment and you may be good to go.


问:
Webpack doesn't bundle files required within AMD module
I'm migrating an existing website that uses requirejs over to webpack. I thought I would be able to replace the requirejs config with webpack.config.js and be done with it. However, webpack isn't including any of the dependencies required by any AMD modules. All of my modules are of the form:

define(require => {
    const dep1 = require('models/dep1');
    const dep2 = require('models/dep2');
    ...
    const Utils = {
        function doStuff() {
            ...
        },
    };

    return Utils;
});
```

<p>Here's a simplified version of my webpack config:</p>

<pre class="lang-js prettyprint-override"><code>const webpack = require('webpack');

const sourcePath = __dirname;
const outputPath = './dist';

module.exports = (env) => {
  return {
    context: sourcePath,
    entry: {
      app: './src/index.js',
    },
    output: {
      path: outputPath,
      filename: '[name].bundle.js',
      chunkFilename: '[id].[chunkhash].js',
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: [
            'babel-loader',
          ],
        },
      ],
    },
  };
};
</code>```

And my .babelrc:

```<code>{
  "presets": [
    ["babel-preset-env", {
      "targets": {
        "browsers": [
          "last 2 Chrome versions",
          "last 2 Firefox versions"
        ]
      },
      "modules": false
    }],
    "react"
  ],
}
</code>```

If I remove the define wrapper from the file and replace the require statements with import statements, then it figures out how to include the dependencies in the bundle.

Is there an extra configuration I need in order to make webpack include the dependencies in the bundle? Is it possible webpack doesn't understand the arrow function style of the define define(require => as opposed to define(function(require) { ?

答: Turns out this was a bug. I ended up sending a pull request to webpack to fix it and it was released in 3.9.0.</p>

Body:
I'm migrating an existing website that uses requirejs over to webpack. I thought I would be able to replace the requirejs config with webpack.config.js and be done with it. However, webpack isn't including any of the dependencies required by any AMD modules. All of my modules are of the form:

define(require => {
    const dep1 = require('models/dep1');
    const dep2 = require('models/dep2');
    ...
    const Utils = {
        function doStuff() {
            ...
        },
    };

    return Utils;
});

Here's a simplified version of my webpack config:

const webpack = require('webpack');

const sourcePath = __dirname;
const outputPath = './dist';

module.exports = (env) => {
  return {
    context: sourcePath,
    entry: {
      app: './src/index.js',
    },
    output: {
      path: outputPath,
      filename: '[name].bundle.js',
      chunkFilename: '[id].[chunkhash].js',
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: [
            'babel-loader',
          ],
        },
      ],
    },
  };
};

And my .babelrc:

{
  "presets": [
    ["babel-preset-env", {
      "targets": {
        "browsers": [
          "last 2 Chrome versions",
          "last 2 Firefox versions"
        ]
      },
      "modules": false
    }],
    "react"
  ],
}

If I remove the define wrapper from the file and replace the require statements with import statements, then it figures out how to include the dependencies in the bundle.

Is there an extra configuration I need in order to make webpack include the dependencies in the bundle? Is it possible webpack doesn't understand the arrow function style of the define define(require => as opposed to define(function(require) { ?


问:
travis error: The command "go get -u -v github.com/spf13/hugo" failed and exited with 1 during
I receive the following error while trying to build my hugo blog with travis:

The command "go get -u -v github.com/spf13/hugo" failed and exited with 1 during .

I have tried to create a makefile with an empty recipe as suggested here, but had no success. Here is the build log.

Any suggestions on how to avoid this error?

答:
go get doesn't really work with Hugo -- or to be more precise: The behaviour is undefined.

Hugo vendors its dependencies, but does not commit those to the GitHub repo. So you would have to use dep and mage(a Go variant of Make) -- and the easiest way is to look at this Travis setup:

https://github.com/gohugoio/hugo/blob/master/.travis.yml

Note that if this is to get a working CI setup to build Hugo sites, I would recommend just to fetch one of the releases from here via curl or wget:

https://github.com/gohugoio/hugo/releases


问:
Code golf: combining multiple sorted lists into a single sorted list
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

```<code>input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)
</code>```

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

```<code>sorted(sum(lists,[])) # cheating: out of bounds!
</code>```

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

答:
Ruby:

41 significant chars, 3 significant whitespace chars in the body of the merge method.

arrs is an array of arrays

```<code>
  def merge_sort(arrs)
    o = Array.new
    arrs.each do |a|
      o = o | a
    end
    o.sort!
  end
</code>```

To test in irb:

```<code>
  arrs = [ [ 90, 4, -2 ], [ 5, 6, -100 ], [ 5, 7, 2 ] ]
  merge_sort(arrs)
</code>```

Returns:
   [-100, -2, 2, 4, 5, 6, 7, 90]

Edit: Used the language provided merge/sort because it is likely backed by C code and meets the 'faster' requirement.  I'll think about the solution without later (it's the weekend here and I am on holiday).

OwnerDisplayName: jamesbrady

Body:
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

sorted(sum(lists,[])) # cheating: out of bounds!

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

LastEditorDisplayName: Alabaster Codify

Body:
Ruby:

41 significant chars, 3 significant whitespace chars in the body of the merge method.

arrs is an array of arrays

  def merge_sort(arrs)
    o = Array.new
    arrs.each do |a|
      o = o | a
    end
    o.sort!
  end

To test in irb:

  arrs = [ [ 90, 4, -2 ], [ 5, 6, -100 ], [ 5, 7, 2 ] ]
  merge_sort(arrs)

Returns:
   [-100, -2, 2, 4, 5, 6, 7, 90]

Edit: Used the language provided merge/sort because it is likely backed by C code and meets the 'faster' requirement.  I'll think about the solution without later (it's the weekend here and I am on holiday).

OwnerDisplayName: Adam Hawes

LastEditorDisplayName: Adam Hawes


问:
PHP regexp for /prefix/action(/id)
I'm trying to build a regexp that would match both strings:

```<code>/prefix/action
</code>```

and

```<code>/prefix/action/43
</code>```

but not

```<code>/prefix/action/
</code>```

or

```<code>/prefix/action43
</code>```

where 43 can be anything like [0-9]+, only if preceded by a slash

I also want to capture the number (not the slash), if any, as a named group.

```<code>~/prefix/action/?(?P<itemID>[0-9]+)?~
</code>```

This expression does match, except for a condition that numbers must be preceded by a slash, all my attempts at adding lookahead or lookbehind assertions failed on this one.

I do understand that with additional external processing the task can be solved, but I'm looking for a regexp solution only. Thank you for understanding.

Your suggestions are greatly appreciated.

Solved by:

```<code>~/prefix/action(?:/(?P<itemID>[0-9]+))?~
</code>```

答:
How about making both the / and the following number optional?

```<code>^/prefix/action(?:/[0-9]+)?$
</code>```

To capture the optional number in a named group add (?P<itemID>...) around the number regex:

```<code>^/prefix/action(?:/(?P<itemID>[0-9]+))?$
</code>```

Also note that I've added start and end anchors, which were missing in your regex. Without them you'll get a match if you have a sub-string of the input that matches the regex.

Title: PHP regexp for /prefix/action(/id)

Body:
I'm trying to build a regexp that would match both strings:

/prefix/action

and

/prefix/action/43

but not

/prefix/action/

or

/prefix/action43

where 43 can be anything like [0-9]+, only if preceded by a slash

I also want to capture the number (not the slash), if any, as a named group.

~/prefix/action/?(?P<itemID>[0-9]+)?~

This expression does match, except for a condition that numbers must be preceded by a slash, all my attempts at adding lookahead or lookbehind assertions failed on this one.

I do understand that with additional external processing the task can be solved, but I'm looking for a regexp solution only. Thank you for understanding.

Your suggestions are greatly appreciated.

Solved by:

~/prefix/action(?:/(?P<itemID>[0-9]+))?~

Body:
How about making both the / and the following number optional?

^/prefix/action(?:/[0-9]+)?$

To capture the optional number in a named group add (?P<itemID>...) around the number regex:

^/prefix/action(?:/(?P<itemID>[0-9]+))?$

Also note that I've added start and end anchors, which were missing in your regex. Without them you'll get a match if you have a sub-string of the input that matches the regex.