问:
GetColumnDisplayRectangle no value if no rows
In winforms I need to retrieve the position of each column in my DataGridView, to do this I use this function:

```<code>Rectangle rec = dgv.GetColumnDisplayRectangle(getColumnIndexByName(entry.Key), true);
</code>```

and give me the rec of the column, but if I have a table with no records, the function get a rec with 0 value...

How can I solve this??

here is what I have if the grid has rows:

in the blue panel I've got some textbox that I use as filter of the value of the column below

Now if the grid has some rows, it works perfectly, I get right the column rectangle, I obtain the left and width and I'm able to place the filters above the header.. but if I set a wrong filter and the query retrieve 0 records, I don't know where place the textboxes

Edit: the code of getColumnIndexByName:

```<code>protected int getColumnIndexByName(string name)
{
    foreach (DataGridViewColumn col in dgv.Columns)
    {
        if (col.Name.ToLower().Trim() == name.ToLower().Trim()) return col.Index;
    }
    return -1;
}
</code>```

thanks

答:
GetColumnDisplayRectangle returns Rectangle.Empty if the column is not Displayed.

You may also want to take a look at source code for GetColumnDisplayRectanglePrivate method which is used by DataGridView to calculate rectangle of the given column.

The method contains following code:

```<code>if (!this.Columns[columnIndex].Displayed)
{
    return Rectangle.Empty;
}
</code>```

Workaround

If you are looking for a workaround, you can use the following code which gets a list of rectangles without any flicker:

```<code>this.SuspendLayout();
var width = this.dataGridView1.Width;
this.dataGridView1.Width = 8388607;
var rectangles = this.dataGridView1.Columns.Cast<DataGridViewColumn>()
    .Select(x => dataGridView1.GetColumnDisplayRectangle(x.Index, false))
    .ToList();
this.dataGridView1.Width = width;
this.ResumeLayout();
</code>```

Body:
In winforms I need to retrieve the position of each column in my DataGridView, to do this I use this function:

Rectangle rec = dgv.GetColumnDisplayRectangle(getColumnIndexByName(entry.Key), true);

and give me the rec of the column, but if I have a table with no records, the function get a rec with 0 value...

How can I solve this??

here is what I have if the grid has rows:

in the blue panel I've got some textbox that I use as filter of the value of the column below

Now if the grid has some rows, it works perfectly, I get right the column rectangle, I obtain the left and width and I'm able to place the filters above the header.. but if I set a wrong filter and the query retrieve 0 records, I don't know where place the textboxes

Edit: the code of getColumnIndexByName:

protected int getColumnIndexByName(string name)
{
    foreach (DataGridViewColumn col in dgv.Columns)
    {
        if (col.Name.ToLower().Trim() == name.ToLower().Trim()) return col.Index;
    }
    return -1;
}

thanks

Body:
GetColumnDisplayRectangle returns Rectangle.Empty if the column is not Displayed.

You may also want to take a look at source code for GetColumnDisplayRectanglePrivate method which is used by DataGridView to calculate rectangle of the given column.

The method contains following code:

if (!this.Columns[columnIndex].Displayed)
{
    return Rectangle.Empty;
}

Workaround

If you are looking for a workaround, you can use the following code which gets a list of rectangles without any flicker:

this.SuspendLayout();
var width = this.dataGridView1.Width;
this.dataGridView1.Width = 8388607;
var rectangles = this.dataGridView1.Columns.Cast<DataGridViewColumn>()
    .Select(x => dataGridView1.GetColumnDisplayRectangle(x.Index, false))
    .ToList();
this.dataGridView1.Width = width;
this.ResumeLayout();


来源: stackexchange

问:
Swift Namespacing Issue
I have created a class named Bundle, which I'd really like to remain named that way, as it perfectly describes what it's for in my project.

Now, I'm using Swift's Bundle in some code and now those names are conflicting. I had this issue before when I created the class Set. I was able to solve that by putting Swift.Set when I wanted to use the standard Set class, as I found in this answer on exactly this matter.

I also tried to apply that solution my Bundle problem, but Xcode complains:

Module 'Swift' has no member named 'Bundle'

Any idea why it does work for Set, but not Bundle?

Thanks!

答:
Bundle is defined in the Foundation library, not in the Swift standard
library:

```<code>let mainBundle = Foundation.Bundle.main
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swift Namespacing Issue

Body:
Bundle is defined in the Foundation library, not in the Swift standard
library:

let mainBundle = Foundation.Bundle.main


问:
Changing CSS attribute with JQuery
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

```<code><script  type="text/javascript">
    jQuery(document.body) ({font-size:5em;});
</script>
</code>```

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

答:
How about:</p>

```<code><script  type="text/javascript">
$("body").css("font-size","70%");
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Changing CSS attribute with JQuery

Body:
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

Body:
How about:

<script  type="text/javascript">
$("body").css("font-size","70%");
</script>


问:
Issue with my var getting undefined
I am trying to create a reverse function to the String type in javascript. My code is like

```<code>String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length;i>=0;i--){
            s+=this[i];
    }
    return s;
}
</code>```

When I try to use it on for example like "test".reverse();

instead of giving "tset" it's giving "undefinedtset"

I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?

答:
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :

```<code>String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length-1;i>=0;i--){
            s+=this[i];
    }
    return s;
}
</code>```

Title: Issue with my var getting undefined

Body:
I am trying to create a reverse function to the String type in javascript. My code is like

String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length;i>=0;i--){
            s+=this[i];
    }
    return s;
}

When I try to use it on for example like "test".reverse();

instead of giving "tset" it's giving "undefinedtset"

I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?

Body:
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :

String.prototype.reverse = function () {
    var s = "";
    for(var i=this.length-1;i>=0;i--){
            s+=this[i];
    }
    return s;
}


问:
Turing Machines Basic Operations
In this problem, you are expected to construct several Turing machines. For each Turing machine,
provide a high-level description how it works and provide the graph representation. (You can leave
out the formal definition if the graph is complete.)

a)  Write a Turing machine
T
inc
that can add 1 to a binary encoded number stored on the tape
of the Turing machine.  The binary number is enclosed by the symbol
$
and you can assume
that the binary number starts with a 0 (i.e., there is no overflow to consider). For example, the
input
$0100$
is transformed by
T
inc
into
$0101$
and the input
$0111$
is transformed by
T
inc
into
$1000$
. The turing machine starts with the head located at the
$
sign left of the number.

b)  Write a Turing machine
T
dec
that can subtract 1 from a binary encoded number stored on the
tape of the Turing machine. The binary number is enclosed by the symbol
$
. For example, the
input
$0100$
is transformed by
T
dec
into
$0011$
and the input
$0111$
is transformed by
T
dec
into
$0110$
. The turing machine starts with the head located at the
$
sign left of the number.
Hint:  You can invert all bits of the number, then add one to the number, then invert all bits of
the number again.

c)  Write a Turing machine
T
add
that can add two binary encoded numbers on the tape of the
Turing machine. The binary numbers are each enclosed by the symbol
$
and you can assume
that the binary numbers have a sufficient number of leading 0s to hold the sum (i.e.,  there
is no overflow to consider).  For example, the input
$0100$0010$
is transformed by
T
add
into
$0000$0110$
, i.e., the first number was added to the second number.

Hint: You can construct
T
add
out of
T
inc
and
T
dec
: While the first number is not zero, decrement
the first number and increment the second number.  Please name your states such that it is
clear to which part of your textual description they belong.
You may find it useful to write a Haskell program to simulate your Turing machines (i.e., following
the example shown in class).  This way you can run tests against your Turing machine to verify it
is working correctly. Feel free to submit your Haskell code so that we can verify your design of the
turing machines.
Note that it is your responsibility to document things properly. If you hand in something we cannot
understand, you will likely get zero points.

答:
(a) To add 1 to a number in binary, you start with the least significant digit (looks like this is the last one on your tape), add 1 with carry, move left, and repeat with the carry from the previous step until the carry is 0. It is guaranteed the carry will be 0 at least once since the problem assumes you start with a 0 on the front of the tape. A TM might look like this:

```<code>Q    T    Q'    T'    D
-----------------------
// read the leading $
// reject if not there
q0   $    q1    $     right
q0   0    hR    0     same
q0   1    hR    1     same

// go to the last digit
q1   $    q2    $     left
q1   0    q1    0     right
q1   1    q1    1     right

// add 1 by swapping digit values
// reject if overflow
// accept if carry becomes 0
q2   $    hR    $     same
q2   0    hA    1     same
q2   1    q2    0     left
</code>```

b) To subtract 1 from a number in binary, you start with the least significant digit, subtract 1 with borrow, move left, and repeat with the borrow from the previous step until the borrow is 0. This is either a trick question or it was ill-posed: given a number in this encoding, even with the assumption from part (a), it is not guaranteed that it is possible to subtract one: when presented with the encoding of zero, the required behavior of the TM is undefined. Assuming the number is greater than zero:

```<code>Q    T    Q'    T'    D
-----------------------
// read the leading $
// reject if not there
q0   $    q1    $     right
q0   0    hR    0     same
q0   1    hR    1     same

// go to the last digit
q1   $    q2    $     left
q1   0    q1    0     right
q1   1    q1    1     right

// subtract 1 by swapping digit values
// reject if underflow
// accept if borrow becomes 0
q2   $    hR    $     same
q2   0    q2    1     same
q2   1    hA    0     left
</code>```

c) Forget the hint and just implement binary addition directly. It is not stated but heavily implied that the numbers have the same number of digits, or at least that the second number has more digits than the first. Add the least significant digits of both numbers, with carry, marking digits of the first and second numbers as you go, and finish when you run out of digits. Then, unmark the digits. Here's how your TM should process the example:

```<code>$0100$0010$
$0100C0010$
$010AC0010$
$010AC001A$
$01AAC001A$
$01AAC00BA$
$0BAAC00BA$
$0BAAC0BBA$
$ABAAC0BBA$
$ABAACABBA$
$0BAACABBA$
$00AACABBA$
$000ACABBA$
$0000CABBA$
$0000$ABBA$
$0000$0BBA$
$0000$01BA$
$0000$011A$
$0000$0110$
</code>```

Title: Turing Machines Basic Operations

Body:
(a) To add 1 to a number in binary, you start with the least significant digit (looks like this is the last one on your tape), add 1 with carry, move left, and repeat with the carry from the previous step until the carry is 0. It is guaranteed the carry will be 0 at least once since the problem assumes you start with a 0 on the front of the tape. A TM might look like this:

Q    T    Q'    T'    D
-----------------------
// read the leading $
// reject if not there
q0   $    q1    $     right
q0   0    hR    0     same
q0   1    hR    1     same

// go to the last digit
q1   $    q2    $     left
q1   0    q1    0     right
q1   1    q1    1     right

// add 1 by swapping digit values
// reject if overflow
// accept if carry becomes 0
q2   $    hR    $     same
q2   0    hA    1     same
q2   1    q2    0     left

b) To subtract 1 from a number in binary, you start with the least significant digit, subtract 1 with borrow, move left, and repeat with the borrow from the previous step until the borrow is 0. This is either a trick question or it was ill-posed: given a number in this encoding, even with the assumption from part (a), it is not guaranteed that it is possible to subtract one: when presented with the encoding of zero, the required behavior of the TM is undefined. Assuming the number is greater than zero:

Q    T    Q'    T'    D
-----------------------
// read the leading $
// reject if not there
q0   $    q1    $     right
q0   0    hR    0     same
q0   1    hR    1     same

// go to the last digit
q1   $    q2    $     left
q1   0    q1    0     right
q1   1    q1    1     right

// subtract 1 by swapping digit values
// reject if underflow
// accept if borrow becomes 0
q2   $    hR    $     same
q2   0    q2    1     same
q2   1    hA    0     left

c) Forget the hint and just implement binary addition directly. It is not stated but heavily implied that the numbers have the same number of digits, or at least that the second number has more digits than the first. Add the least significant digits of both numbers, with carry, marking digits of the first and second numbers as you go, and finish when you run out of digits. Then, unmark the digits. Here's how your TM should process the example:

$0100$0010$
$0100C0010$
$010AC0010$
$010AC001A$
$01AAC001A$
$01AAC00BA$
$0BAAC00BA$
$0BAAC0BBA$
$ABAAC0BBA$
$ABAACABBA$
$0BAACABBA$
$00AACABBA$
$000ACABBA$
$0000CABBA$
$0000$ABBA$
$0000$0BBA$
$0000$01BA$
$0000$011A$
$0000$0110$


问:
WPF binding object to template
I have two classes defined which look like this:

```<code>public class Task {

    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
    public List<Job> listofjobs = new List<Job>();

}

public class Job
{
    public string ID { get; set; }
    public string Name { get; set; }

}
</code>```

After generating the data I have several Task objects in a List:

```<code>public static List<Task> tasklist = new List<Task>();
</code>```

Each of those tasks has several jobs in it. This list gets databound to a listbox. like this:

```<code>        Task newTask = new Task();
        Job newJob = new Job();
        Job newJob2 = new Job();

        newTask.Description = "Task 1";
        newJob.job_name = "Job 1";
        newJob.job_name = "Job 2";

        newTask.listofjobs.Add(newJob);
        newTask.listofjobs.Add(newJob2);
        tasklist.Add(newTask);
        joblist.ItemsSource = tasklist;
</code>```

The XAML looks like this:

```<code><ListBox Name="joblist" HorizontalContentAlignment="Stretch" >
      <ListBox.ItemTemplate>

                    <DataTemplate>
              <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">

                  <Expander.ContentTemplate>
                      <DataTemplate>
                          <Border>
                             <WrapPanel>
                                  <Label Content="{Binding Path=ID, RelativeSource={RelativeSource AncestorType=local:Job}}"></Label>
                             </WrapPanel>
                          </Border>
                      </DataTemplate>
                  </Expander.ContentTemplate>
              </Expander>

           </DataTemplate>

      </ListBox.ItemTemplate>
</ListBox>
</code>```

Generating the expanders by Databinding works flawlessly. Generating the the content of the expanders on the other hand just does now want to work.

I want to achieve that the jobs within the Task objects get generated by databinding to the WrapPanels within the designated expander Content.

The result should be that i have several expanders (the Task objects) with several wrappanels in the content (the Job objects of the Parent task).

Does anyone know what I am doing wrong here / how to achieve this?

EDIT:

With the anwers provided I tried:

```<code>  <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical">
                                            <Label Content="{Binding Path=Name}"></Label>

                                        </StackPanel>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </Expander>
</code>```

and also:

```<code>                        <DataTemplate>
                        <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                        <StackPanel Orientation="Vertical">
                                            <Label Content="{Binding Path=Name}"></Label>

                                        </StackPanel>
                            </ListView>
                        </Expander>
                    </DataTemplate>
</code>```

But both does not seem to work. What am i missing here?

EDIT2:

There are several binding errors showing up:

```<code>System.Windows.Data Error: 40 : BindingExpression path error: 'listofjobs' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Name' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
</code>```

答:
Since you are binding Description successfully your binding  must be List<Task> tasklist.

Imagine your visual tree like that:

```<code>- ListBox                                               - Binds List<Task>
    - ListBoxItem  (Expander)                           - Binds Task
        - ListBoxItem (ExpanderContent)- ListView       - Binds Task.Jobs (List<Job>)
            - ListView.ItemTemplate                     - Binds Job
</code>```

So you can only access properies of Task.

Your Expanders ControlTemplate should be something to show the collection of Jobs:

```<code><Expander.ContentTemplate>
    <DataTemplate>
         <ListView ItemsSource="{Binding Jobs}" >
             <ListView.ItemTemplate>
                  <DataTemplate>
                      <TextBlock Text="{Binding Name}" />
                  </DataTemplate>
             </ListView.ItemTemplate>
         </ListView>
    </DataTemplate>
</Expander.ContentTemplate>
</code>```

OR

You only bind one job like this:

```<code><Label Content="{Binding Path=Jobs[0].ID" />
</code>```

You don't need any RelativeSource here.

Make sure every property you bind to has a getter/setter {get; set;} !

```<code>public List<Job> ListOfJobs {get; set;} = new List<Job>();
</code>```

Title: WPF binding object to template

Body:
I have two classes defined which look like this:

public class Task {

    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
    public List<Job> listofjobs = new List<Job>();

}

public class Job
{
    public string ID { get; set; }
    public string Name { get; set; }

}

After generating the data I have several Task objects in a List:

public static List<Task> tasklist = new List<Task>();

Each of those tasks has several jobs in it. This list gets databound to a listbox. like this:

        Task newTask = new Task();
        Job newJob = new Job();
        Job newJob2 = new Job();

        newTask.Description = "Task 1";
        newJob.job_name = "Job 1";
        newJob.job_name = "Job 2";

        newTask.listofjobs.Add(newJob);
        newTask.listofjobs.Add(newJob2);
        tasklist.Add(newTask);
        joblist.ItemsSource = tasklist;

The XAML looks like this:

<ListBox Name="joblist" HorizontalContentAlignment="Stretch" >
      <ListBox.ItemTemplate>

                    <DataTemplate>
              <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">

                  <Expander.ContentTemplate>
                      <DataTemplate>
                          <Border>
                             <WrapPanel>

                             </WrapPanel>
                          </Border>
                      </DataTemplate>
                  </Expander.ContentTemplate>
              </Expander>

           </DataTemplate>

      </ListBox.ItemTemplate>
</ListBox>

Generating the expanders by Databinding works flawlessly. Generating the the content of the expanders on the other hand just does now want to work.

I want to achieve that the jobs within the Task objects get generated by databinding to the WrapPanels within the designated expander Content.

The result should be that i have several expanders (the Task objects) with several wrappanels in the content (the Job objects of the Parent task).

Does anyone know what I am doing wrong here / how to achieve this?

EDIT:

With the anwers provided I tried:

  <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical">

                                        </StackPanel>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </Expander>

and also:

                        <DataTemplate>
                        <Expander Name="jobgroup" Header="{Binding Path=Description}" HorizontalAlignment="Stretch" Padding="5" FontSize="16" VerticalAlignment="Top">
                            <ListView ItemsSource="{Binding Path=listofjobs}" >
                                        <StackPanel Orientation="Vertical">

                                        </StackPanel>
                            </ListView>
                        </Expander>
                    </DataTemplate>

But both does not seem to work. What am i missing here?

EDIT2:

There are several binding errors showing up:

System.Windows.Data Error: 40 : BindingExpression path error: 'listofjobs' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=listofjobs; DataItem='Task' (HashCode=49998812); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Name' property not found on 'object' ''Task' (HashCode=49998812)'. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 20 : BindingExpression cannot retrieve value due to missing information. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 21 : BindingExpression cannot retrieve value from null data item. This could happen when binding is detached or when binding to a Nullable type that has no value. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=Name; DataItem='Task' (HashCode=49998812); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

Body:
Since you are binding Description successfully your binding  must be List<Task> tasklist.

Imagine your visual tree like that:

- ListBox                                               - Binds List<Task>
    - ListBoxItem  (Expander)                           - Binds Task
        - ListBoxItem (ExpanderContent)- ListView       - Binds Task.Jobs (List<Job>)
            - ListView.ItemTemplate                     - Binds Job

So you can only access properies of Task.

Your Expanders ControlTemplate should be something to show the collection of Jobs:

<Expander.ContentTemplate>
    <DataTemplate>
         <ListView ItemsSource="{Binding Jobs}" >
             <ListView.ItemTemplate>
                  <DataTemplate>
                      <TextBlock Text="{Binding Name}" />
                  </DataTemplate>
             </ListView.ItemTemplate>
         </ListView>
    </DataTemplate>
</Expander.ContentTemplate>

OR

You only bind one job like this:

<Label Content="{Binding Path=Jobs[0].ID" />

You don't need any RelativeSource here.

Make sure every property you bind to has a getter/setter {get; set;} !

public List<Job> ListOfJobs {get; set;} = new List<Job>();


问:
Working with hybrid auth and codeigniter
I am trying to build a project using CodeIgniter and for sign up purposes, I am using Hybrid Auth library. I am using a link similar to "http://localhost/project/hauth/endpoint?hauth.done=Google" as my redirect URI for facebook and google.

app is working fine with it. But the problem is I can't understand what this "hauth.done" means.

As soon as I allow the permission, it redirects me to the above provided link where I don't know how to receive data/userprofile information.

答:
Here is updated library which works with the latest HybridAuth (v2.10) and CodeIgniter (v3.x)

https://github.com/ApacheEx/CodeIgniter-HybridAuth

hauth.done uses for finishing authorization via Hybrid_Endpoint::process(); which calls processAuthDone to save all needed tokens for later API requests.


问:
Parsing and Mapping a JSON Object with Dynamic Properties
So through research on Stackoverflow, especially this topic, I've determined that I have a JSON object dictionary embedded in an otherwise working getter/setter setup. When I make a call to the API, the traditional getter/setters for the properties work well, but that's because I know what the names of the properties are. How can I get this working for unknown properties of an object called errors, and what format is this object in (Map<String,List>)?

API Response:

```<code>{
    "success":false,
    "response_code":1,
    "status_message":"One or more errors has occurred.",
    "errors":{
        "171":["Some error message."],
        "555":["Some other error message."]
    }
}
</code>```

My POJO:

```<code>public class APIResponse {
    private boolean success;
    private int response_code;
    private String status_message;
    private Map<String, List> errors = new HashMap<>();
    ...
}
</code>```

How can I set the getter/setters and the correct dictionary format (Looks like maybe it's Map<String,List>) so that I can start receiving this dynamic errors object?

I'm using an Invocation.Builder to parse out the API response into an object.

```<code>Response response= invocationBuilder.post(Entity.entity(APIRequest, MediaType.APPLICATION_JSON));
APIResponse formattedResponse = response.readEntity(APIResponse.class);
</code>```

答:
My solution was a tiered one.

First, the discovery that Moxy just doesn't do maps was frightening, but rather reliving once I found that the be the issue. So I had to change my default serializer from Moxy to Jackson. This was done easily by changing the pom.xml:

```<code><dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey.version}</version>
</dependency>
</code>```

Second, my attempt had it a bit wrong, instead of:

private Map<String, List> errors = new HashMap<>();

I really needed:

private HashMap<String, ArrayList<String>>;

Throwing the constructor right in line with it would always wipe out the data. Instead I just initialize the map and then created the normal getter/setters on the POJO.

Body:
So through research on Stackoverflow, especially this topic, I've determined that I have a JSON object dictionary embedded in an otherwise working getter/setter setup. When I make a call to the API, the traditional getter/setters for the properties work well, but that's because I know what the names of the properties are. How can I get this working for unknown properties of an object called errors, and what format is this object in (Map<String,List>)?

API Response:

{
    "success":false,
    "response_code":1,
    "status_message":"One or more errors has occurred.",
    "errors":{
        "171":["Some error message."],
        "555":["Some other error message."]
    }
}

My POJO:

public class APIResponse {
    private boolean success;
    private int response_code;
    private String status_message;
    private Map<String, List> errors = new HashMap<>();
    ...
}

How can I set the getter/setters and the correct dictionary format (Looks like maybe it's Map<String,List>) so that I can start receiving this dynamic errors object?

I'm using an Invocation.Builder to parse out the API response into an object.

Response response= invocationBuilder.post(Entity.entity(APIRequest, MediaType.APPLICATION_JSON));
APIResponse formattedResponse = response.readEntity(APIResponse.class);

Body:
My solution was a tiered one.

First, the discovery that Moxy just doesn't do maps was frightening, but rather reliving once I found that the be the issue. So I had to change my default serializer from Moxy to Jackson. This was done easily by changing the pom.xml:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey.version}</version>
</dependency>

Second, my attempt had it a bit wrong, instead of:

private Map<String, List> errors = new HashMap<>();

I really needed:

private HashMap<String, ArrayList<String>>;

Throwing the constructor right in line with it would always wipe out the data. Instead I just initialize the map and then created the normal getter/setters on the POJO.


答:
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.

The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).

Try with:

```<code>for (var i = this.length - 1; i >= 0; i--) {
    s += this[i];
}
</code>```

Title: Issue with my var getting undefined

Body:
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.

The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).

Try with:

for (var i = this.length - 1; i >= 0; i--) {
    s += this[i];
}


问:
Apache proxypass configuration for Apache and JBoss application installed on same server node
If I hit - http://10.157.128.170/oneapp  application should load index.html from Apache content

And ALL API calls like http://10.157.128.170:25003/oneapp/*  (where * could be any API Call) should redirect calls to JBOSS on port :25003/oneapp

What could be the Apache configuration for this requirement ?

My current Configuration is :

```<code>ProxyPassMatch      ^/oneapp/$            !
ProxyPass            /oneapp/index.html   !
ProxyPass            /oneapp              http://10.157.128.170:25003/oneapp
ProxyPassReverse     /oneapp              http://10.157.128.170:25003/oneapp
</code>```

where I need to hit : http://10.157.128.170/index.html for going to index.html but I need that to be http://10.157.128.170/oneapp

File I've on Apache Content directory

```<code>index.html
app.css
app.js
images
</code>```

答:
Just add a trailing slash to fix the issue

```<code>ProxyPassMatch      ^/oneapp/$            !
ProxyPass            /oneapp/index.html   !
ProxyPass /oneapp/ http://10.157.128.170:25003/oneapp/
ProxyPassReverse /oneapp/ http://10.157.128.170:25003/oneapp/
</code>```

Also make sure that mod_proxy and mod_proxy_http are enabled.

Body:
If I hit - http://10.157.128.170/oneapp  application should load index.html from Apache content

And ALL API calls like http://10.157.128.170:25003/oneapp/*  (where * could be any API Call) should redirect calls to JBOSS on port :25003/oneapp

What could be the Apache configuration for this requirement ?

My current Configuration is :

ProxyPassMatch      ^/oneapp/$            !
ProxyPass            /oneapp/index.html   !
ProxyPass            /oneapp              http://10.157.128.170:25003/oneapp
ProxyPassReverse     /oneapp              http://10.157.128.170:25003/oneapp

where I need to hit : http://10.157.128.170/index.html for going to index.html but I need that to be http://10.157.128.170/oneapp

File I've on Apache Content directory

index.html
app.css
app.js
images

Body:
Just add a trailing slash to fix the issue

ProxyPassMatch      ^/oneapp/$            !
ProxyPass            /oneapp/index.html   !
ProxyPass /oneapp/ http://10.157.128.170:25003/oneapp/
ProxyPassReverse /oneapp/ http://10.157.128.170:25003/oneapp/

Also make sure that mod_proxy and mod_proxy_http are enabled.


问:
What is the difference between if( pointer == NULL) and if(!pointer)?
What is the difference in between using:

```<code>if( pointer == NULL)
</code>```

And

```<code>if(!pointer)
</code>```

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.

答:
Assuming pointer is a pointer type, if (pointer == NULL) is anachronistic and poor C++ since the the null pointer value in C++ is nullptr in C++ with type nullptr_t.

if (!pointer) is the much preferred idiom.

Body:
What is the difference in between using:

if( pointer == NULL)

And

if(!pointer)

I am concerned with the differences between the two in respect to the following points:

 1. Are they different for the compiler? If yes, then how?

 2. Which of the two is the recommended coding style for general use and why?

 3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.


问:
How can I sort a Java list using two different values?
```<code>public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}
</code>```

This code sorts two lists based on the value of the object called points. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

答:
```<code>public int compare(LeagueTableItem o1, LeagueTableItem o2) {
        if (o2.getPoints() == o1.getPoints()) {

            return o2.goalsScored() - o1.goalsScored();
        } else {
            return o2.getPoints() - o1.getPoints();
        }
    }
</code>```

First it gets the o1 and o2's points and compare them. If they are equal, the if statement proceed to calculate which o has more goals scored and returns the result, else if the points are NOT equal it returns the result.

Body:
public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}

This code sorts two lists based on the value of the object called points. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

Body:
public int compare(LeagueTableItem o1, LeagueTableItem o2) {
        if (o2.getPoints() == o1.getPoints()) {

            return o2.goalsScored() - o1.goalsScored();
        } else {
            return o2.getPoints() - o1.getPoints();
        }
    }

First it gets the o1 and o2's points and compare them. If they are equal, the if statement proceed to calculate which o has more goals scored and returns the result, else if the points are NOT equal it returns the result.


问:
C# how to get a list of open "TcpListeners"
I want to add multiplayersupport to one of my games, so i created a "Create Server" button which opens a TcpListener and listens to connecting requests, and a "Join Server" button, I want this button to display a List of all open TcpListeners (so the user can click on them an connect)
are there any in-built functions for this in c#?</p>

答:
You want a list of all listeners, on all machines on the network (or the entire internet)? Then the answer is no, there's no built-in function for that.

On a small LAN, you might be able to get away with the servers broadcasting their presence. This is how games usually did it before the internet came along.

Nowadays, they usually connect to a central server, which has a list of all servers that are hosting the actual games.

Either way, you'll have some work to do.


问:
How to determine C# compiler version in command line
Is there any command to get the C# compiler version?
The csc command seams has no option to show compiler version.

P.S
when I enter csc command in Developer Command Prompt For VS2015 it returns:

```<code>Microsoft (R) Visual C# Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.
</code>```

However I pretty sure my C# compiler is newer than 1.3!

答:
Do keep in mind that you'll have a least 2 versions of csc.exe on your machine.  One is shipped as part of the .NET Framework install, like it always was, and follows the version numbering of the framework.  Stored in c:\windows\microsoft.net\framework\v4.0.30319, it is retained there for compatibility with System.CodeDom and sgen.exe.  Frozen at C# language version 5.  Most programmers right now will have version 4.7.x.0 when they have .NET v4.7 on their machine.

The other one got spun-off as part of the Roslyn project and is stored in the MSBuild directory.  With a version number reset that start numbering again from 1.  You'll run that one when you use the Developer Command Prompt.  The most likely reason for the version number reset is their desire to not get locked into the framework release cadence, Roslyn suffered from a very large number of bugs that required intermediate releases to get fixed.  A notable problem caused by the decoupling was the addition of the new ValueTuple type in C# v7, required by the much improved tuple support.  The compiler shipped before the framework was available and programmers had to fall back to using a Nuget package for a while.

Version number resets don't happen very often.  But another good example that everybody knows about is .NETCore, it got reset from 5.0 back to 1.0.  I never saw a solid justification for that beyond "avoids confusion", I think it was a move to make it look fresh.

Body:
Is there any command to get the C# compiler version?
The csc command seams has no option to show compiler version.

P.S
when I enter csc command in Developer Command Prompt For VS2015 it returns:

Microsoft (R) Visual C# Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

However I pretty sure my C# compiler is newer than 1.3!


问:
Error displaying Info Dialog in GTK3+
I am trying to display a info dialog window when the gtk_drawing_area is clicked.

Here is the code I am using:

```<code>#include <cairo.h>
#include <gtk/gtk.h>

void show_dialog_window(GtkWidget *widget, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *darea;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
  gtk_window_set_title(GTK_WINDOW(window), "Click me to show an Info_Dialog");

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER(window), darea);

  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);
  g_signal_connect(window, "button-press-event",
      G_CALLBACK(show_dialog_window), (gpointer) window);

  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}
</code>```

When I compile and run this code using the command gcc dialog.c pkg-config --cflags gtk+-3.0 --libs --libs cairo -lm -o dialog && ./dialog I get the following on the terminal:

Segmentation fault (core dumped)

Any suggestion as to what I am doing wrong?

答:
The problem resides on the callback function. You are using the following prototype:

```<code>void user_function(GtkWidget *widget, gpointer window)
</code>```

and it should be, as documented in the API reference:

```<code>gboolean user_function(GtkWidget *widget, GdkEvent *event, gpointer user_data)
</code>```

Adapting your callback, it should be something like this:

```<code>gboolean show_dialog_window(GtkWidget *widget, GdkEvent *event, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
  return TRUE;
}
</code>```

Returning TRUE will cease signal propagation.

After the change, the program should work fine. You can access event information in event, such as which button was pressed, etc.

Title: Error displaying Info Dialog in GTK3+

Body:
I am trying to display a info dialog window when the gtk_drawing_area is clicked.

Here is the code I am using:

#include <cairo.h>
#include <gtk/gtk.h>

void show_dialog_window(GtkWidget *widget, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *darea;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
  gtk_window_set_title(GTK_WINDOW(window), "Click me to show an Info_Dialog");

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER(window), darea);

  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);
  g_signal_connect(window, "button-press-event",
      G_CALLBACK(show_dialog_window), (gpointer) window);

  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}

When I compile and run this code using the command gcc dialog.c pkg-config --cflags gtk+-3.0 --libs --libs cairo -lm -o dialog && ./dialog I get the following on the terminal:

Segmentation fault (core dumped)

Any suggestion as to what I am doing wrong?

Body:
The problem resides on the callback function. You are using the following prototype:

void user_function(GtkWidget *widget, gpointer window)

and it should be, as documented in the API reference:

gboolean user_function(GtkWidget *widget, GdkEvent *event, gpointer user_data)

Adapting your callback, it should be something like this:

gboolean show_dialog_window(GtkWidget *widget, GdkEvent *event, gpointer window) {

  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_DESTROY_WITH_PARENT,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "Hello dialog!");
  gtk_window_set_title(GTK_WINDOW(dialog), "Information");
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
  return TRUE;
}

Returning TRUE will cease signal propagation.

After the change, the program should work fine. You can access event information in event, such as which button was pressed, etc.


问:
Browser does not download the CSV file i created
I am working on a web project. I use Spring Boot and Angular 2. I want to create CSV file and download this file on client pc from server. I use Apache Poi to create the CSV file. When I click on the 'Export CSV' button I can pass from frontend to backend via service and I can create the CSV file on the server successfully. Here is service code:

```<code>exportCSVFileTest(parameter: string): Observable<any> {
    return this.httpService.post( super.getAddrApi() + parameter , null )
        .catch( err => {
            if (!err.status) {
                err = {
                    status: Observable.throw(401)
                };
            }
            return Observable.throw(err);
        });
}
</code>```

After I use this service, I create the CSV file on server and I try to download this file on client's pc from server:

```<code>response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + file.getName());
        FileInputStream is = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] outputByte = new byte[4096];
        while(is.read(outputByte, 0, 4096) != -1)
        {
            out.write(outputByte, 0, 4096);
        }

        is.close();
        out.flush();
        out.close();
</code>```

After that I don't get any error. Everything seems fine however the window that should appear for the file uploading process does not appear. I tried different methods, for example I set content type application/csv or text/csv. And I tried 'OutputStream', 'response.getWriter().write()' vs. What am I doing wrong?

答:
To download a file you need to tell the browser it is a download, I know 2 ways to do this:

1 - Download the file using a link in the HTML

```<code><a [routerLink]="['url/to/download/the/file']">Download CSV</a>
</code>```

2 - Get the file using your service and downloading with saveAs library

```<code>import {saveAs} from 'file-saver';

this.service.exportCSVFileTest('parameter').subscribe(response => {
    const filename = 'name of the file.csv';
    saveAs(response.blob(), filename);
})
</code>```

Hope this help.

Body:
I am working on a web project. I use Spring Boot and Angular 2. I want to create CSV file and download this file on client pc from server. I use Apache Poi to create the CSV file. When I click on the 'Export CSV' button I can pass from frontend to backend via service and I can create the CSV file on the server successfully. Here is service code:

exportCSVFileTest(parameter: string): Observable<any> {
    return this.httpService.post( super.getAddrApi() + parameter , null )
        .catch( err => {
            if (!err.status) {
                err = {
                    status: Observable.throw(401)
                };
            }
            return Observable.throw(err);
        });
}

After I use this service, I create the CSV file on server and I try to download this file on client's pc from server:

response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + file.getName());
        FileInputStream is = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] outputByte = new byte[4096];
        while(is.read(outputByte, 0, 4096) != -1)
        {
            out.write(outputByte, 0, 4096);
        }

        is.close();
        out.flush();
        out.close();

After that I don't get any error. Everything seems fine however the window that should appear for the file uploading process does not appear. I tried different methods, for example I set content type application/csv or text/csv. And I tried 'OutputStream', 'response.getWriter().write()' vs. What am I doing wrong?

Body:
To download a file you need to tell the browser it is a download, I know 2 ways to do this:

1 - Download the file using a link in the HTML

<a [routerLink]="['url/to/download/the/file']">Download CSV</a>

2 - Get the file using your service and downloading with saveAs library

import {saveAs} from 'file-saver';

this.service.exportCSVFileTest('parameter').subscribe(response => {
    const filename = 'name of the file.csv';
    saveAs(response.blob(), filename);
})

Hope this help.


问:
add scss (bootstrap) compilation with output css file in react project
I have a react/express project
I want to be able to customize the Bootstrap 4 and output a CSS file which will contain the customized boostrap.css.

I have npm installed the loaders bootstrap needs ( postcss-loader,sass-loader,style-loader etc), although in web I saw an example with ExtractTextPlugin in order to get output file

when I run the webpack config I get an error
" throw new Error("'output.filename' is required, either in config file or as --output-filename");"

Any tutorial/help how to accomplish compiling customized bootstrap in seperate output file?

```<code>webpack config

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

  //root file for the client/browser app
  entry: './src/client/client.js',

  //output file and its location
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'public'),
  },

  //run babel for every filename
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets:
          [
            'react',
            'stage-0',
            [
              'env',
              {
                targets:
                {
                  browsers:
                  ['last 2 versions']
                }
              }
            ]
          ]
        }
      }
    ]
  },
};
module.exports = {
  //  root file for the client/browser app
  entry: './src/client/styles/main.scss',

  //  output file and its location
  output: {
    filename: 'styles2.css',
    path: path.resolve(__dirname,'public'),
  },
  module: {
    loaders: [
      // ...
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css!sass')
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('public/style.css', {
      allChunks: true,
    })
  ]
};
</code>```

答:
You need to remove the extra module.exports. I do not see the need to have two of these as you can simply achieve the same thing inside a single module.exports.

You can achieve this like so:

```<code>const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  //root file for the client/browser app
  entry: [
    './src/client/client.js',
    './src/client/styles/main.scss'
  ],

  //output file and its location
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'public'),
  },

  //run babel for every filename
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets:[
           'react',
           'stage-0',
           [
             'env',
              {
                targets:
               {
                browsers:
                ['last 2 versions']
              }
            }
          ]
        ]
      }
    },
    {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract('css-loader!sass-loader')
    }
  ],
  plugins: [
      new ExtractTextPlugin('public/style.css', {
      allChunks: true,
    })
   ]
 },};
</code>```

Body:
I have a react/express project
I want to be able to customize the Bootstrap 4 and output a CSS file which will contain the customized boostrap.css.

I have npm installed the loaders bootstrap needs ( postcss-loader,sass-loader,style-loader etc), although in web I saw an example with ExtractTextPlugin in order to get output file

when I run the webpack config I get an error
" throw new Error("'output.filename' is required, either in config file or as --output-filename");"

Any tutorial/help how to accomplish compiling customized bootstrap in seperate output file?

webpack config

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

  //root file for the client/browser app
  entry: './src/client/client.js',

  //output file and its location
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'public'),
  },

  //run babel for every filename
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets:
          [
            'react',
            'stage-0',
            [
              'env',
              {
                targets:
                {
                  browsers:
                  ['last 2 versions']
                }
              }
            ]
          ]
        }
      }
    ]
  },
};
module.exports = {
  //  root file for the client/browser app
  entry: './src/client/styles/main.scss',

  //  output file and its location
  output: {
    filename: 'styles2.css',
    path: path.resolve(__dirname,'public'),
  },
  module: {
    loaders: [
      // ...
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css!sass')
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('public/style.css', {
      allChunks: true,
    })
  ]
};

Body:
You need to remove the extra module.exports. I do not see the need to have two of these as you can simply achieve the same thing inside a single module.exports.

You can achieve this like so:

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  //root file for the client/browser app
  entry: [
    './src/client/client.js',
    './src/client/styles/main.scss'
  ],

  //output file and its location
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'public'),
  },

  //run babel for every filename
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets:[
           'react',
           'stage-0',
           [
             'env',
              {
                targets:
               {
                browsers:
                ['last 2 versions']
              }
            }
          ]
        ]
      }
    },
    {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract('css-loader!sass-loader')
    }
  ],
  plugins: [
      new ExtractTextPlugin('public/style.css', {
      allChunks: true,
    })
   ]
 },};


问:
I want to select two dates in this program, if I try to execute it is showing datepicker is not a function
I want to select two dates in this program here, if I try to execute it is showing:

datepicker is not a function

Code:

```<code>  var startDate;
    $("#validFrom").datetimepicker({
        timepicker: true,
        closeOnDateSelect: false,
        closeOnTimeSelect: true,
        initTime: true,
        format: 'd-m-Y H:m',
        minDate: 0,
        roundTime: 'ceil',
        onChangeDateTime: function (dp, $input) {
            startDate = $("#validFrom").val();
        }
    });
    $("#validTill").datetimepicker({
        timepicker: true,
        closeOnDateSelect: false,
        closeOnTimeSelect: true,
        initTime: true,
        format: 'd-m-Y H:m',
        onClose: function (current_time, $input) {
            var endDate = $("#validTill").val();
            if (startDate > endDate) {
                alert('Please select correct date');
            }
        }
    });
</code>```

答:
You need to connect a library for use, something like that
https://cdnjs.com/libraries/bootstrap-datetimepicker</p>

Body:
I want to select two dates in this program here, if I try to execute it is showing:

datepicker is not a function

Code:

  var startDate;
    $("#validFrom").datetimepicker({
        timepicker: true,
        closeOnDateSelect: false,
        closeOnTimeSelect: true,
        initTime: true,
        format: 'd-m-Y H:m',
        minDate: 0,
        roundTime: 'ceil',
        onChangeDateTime: function (dp, $input) {
            startDate = $("#validFrom").val();
        }
    });
    $("#validTill").datetimepicker({
        timepicker: true,
        closeOnDateSelect: false,
        closeOnTimeSelect: true,
        initTime: true,
        format: 'd-m-Y H:m',
        onClose: function (current_time, $input) {
            var endDate = $("#validTill").val();
            if (startDate > endDate) {
                alert('Please select correct date');
            }
        }
    });


答:
Java 8's enhancements to the Comparator interface give you a pretty elegant way of achieving this:

```<code>table.sort(Comparator.comparingInt(LeagueTableItem::getPoints)
                     .thenComparingInt(LeagueTableItem::goalScored));
</code>```

Title: How can I sort a Java list using two different values?

Body:
Java 8's enhancements to the Comparator interface give you a pretty elegant way of achieving this:

table.sort(Comparator.comparingInt(LeagueTableItem::getPoints)
                     .thenComparingInt(LeagueTableItem::goalScored));


问:
System.AggregateException in await Task.WhenAll()
I have a process which retrieves from the DB a list of rows, and per each row must execute a list of long-running operations:

Upload a file to a FTP server

Check every 1 minute if a particular file (that is created based on the uploaded in 1) is available in such FTP server

Download the file found in step 2, once available

Save content of the file downloaded in the DB

I've implemented a method which does all these steps following the sequence mentioned above: I want to call that method multiple times in parallel (asynchronously): The amount of times to call it will depend of the number of rows retrieved at the beginning of the workflow.

An extraction of the main method follows:

```<code>List<Model> ftpModels = _service.CreateFtpModel(rowsFromDB);
List<Task> asyncTasks = new List<Task>();

ftpModels.AsParallel().ForAll(p =>
{
    asyncTasks.Add(DoStepsAsync(p));
});
// Wait for all the tasks to finish.
await Task.WhenAll(asyncTasks.Where(p => p != null));
</code>```

First, a list of Models is created based on the rows retrieved from the DB,
then an empty list of Tasks is created and then iterates through the models created to execute the async method "DoStepsAsync" which retrieves a task to insert into the asyncTasks list. Finally, it calls Tasks.WhellAll for all the tasks.

This approach is working properly usually, but I happened to find that sometimes (randomly so thread related issue) the next exception is thrown on the WhenAll method:

System.AggregateException: One or more errors occurred. ---> System.ArgumentException: The tasks argument included a null value.

Which clearly indicates me that any of the tasks above returned null (instead of a task) while they were being executed. Then I read the logs I'm writing but I did not find any exception anywhere, just the flow interrupted out of the blue falling next into the System.AggregateException

I was googling and reading a lot, and this issue happens when:

At least one of the Task instances was canceled. If a task was canceled, the AggregateException exception contains an OperationCanceledException exception in its AggregateException.InnerExceptions collection.
-or-
An exception was thrown during the execution of at least one of the Task instances.

But no exception was thrown as I have try-catch blocks implemented accordingly. Therefore, i don't know what the hell is happening.

Any suggestion?

Just to give more info about what happens within the DoStepsAsync() method, there are asynchronous calls to the FTP client (thread safe), writing logs and stuff like that. What really surprises me is that no exception is caught anywhere even with all the catch blocks mentioned above.

Any suggestion really appreciated.

答:
Found the issue: As soon as I iterate through the models list via AsParallel().ForAll , it might happen (depends on the CPU workload) that the task to create (async) has not been yet created but is being accessed by the WhenAll method (async too), therefore throws the exception mentioned above. This happens sometimes, as I said, according to the CPU workload: In order to easily reproduce the issue , I've created a unit test which calls the problematic method up to 50 times, and usually fails within the first 10 runs.
To solve the issue, I I've replaced the useless (because in this scenario does not bring anything relevant)  function AsParallel().ForAll by ForEach and the issue does not happen anymore because the tasks are always created following a sequence (not executed though, they are executed asynchronously), no matter the CPU workload. Code will be as follows, to solve the issue:

```<code>List<Model> ftpModels = _service.CreateFtpModel(rowsFromDB);
List<Task> asyncTasks = new List<Task>();

ftpModels.ForEach(p =>
{
    asyncTasks.Add(DoStepsAsync(p));
});
// Wait for all the tasks to finish.
await Task.WhenAll(asyncTasks.Where(p => p != null));
</code>```

I hope it helps in the future to other people.

Body:
I have a process which retrieves from the DB a list of rows, and per each row must execute a list of long-running operations:

Upload a file to a FTP server

Check every 1 minute if a particular file (that is created based on the uploaded in 1) is available in such FTP server

Download the file found in step 2, once available

Save content of the file downloaded in the DB

I've implemented a method which does all these steps following the sequence mentioned above: I want to call that method multiple times in parallel (asynchronously): The amount of times to call it will depend of the number of rows retrieved at the beginning of the workflow.

An extraction of the main method follows:

List<Model> ftpModels = _service.CreateFtpModel(rowsFromDB);
List<Task> asyncTasks = new List<Task>();

ftpModels.AsParallel().ForAll(p =>
{
    asyncTasks.Add(DoStepsAsync(p));
});
// Wait for all the tasks to finish.
await Task.WhenAll(asyncTasks.Where(p => p != null));

First, a list of Models is created based on the rows retrieved from the DB,
then an empty list of Tasks is created and then iterates through the models created to execute the async method "DoStepsAsync" which retrieves a task to insert into the asyncTasks list. Finally, it calls Tasks.WhellAll for all the tasks.

This approach is working properly usually, but I happened to find that sometimes (randomly so thread related issue) the next exception is thrown on the WhenAll method:

System.AggregateException: One or more errors occurred. ---> System.ArgumentException: The tasks argument included a null value.

Which clearly indicates me that any of the tasks above returned null (instead of a task) while they were being executed. Then I read the logs I'm writing but I did not find any exception anywhere, just the flow interrupted out of the blue falling next into the System.AggregateException

I was googling and reading a lot, and this issue happens when:

At least one of the Task instances was canceled. If a task was canceled, the AggregateException exception contains an OperationCanceledException exception in its AggregateException.InnerExceptions collection.
-or-
An exception was thrown during the execution of at least one of the Task instances.

But no exception was thrown as I have try-catch blocks implemented accordingly. Therefore, i don't know what the hell is happening.

Any suggestion?

Just to give more info about what happens within the DoStepsAsync() method, there are asynchronous calls to the FTP client (thread safe), writing logs and stuff like that. What really surprises me is that no exception is caught anywhere even with all the catch blocks mentioned above.

Any suggestion really appreciated.

Body:
Found the issue: As soon as I iterate through the models list via AsParallel().ForAll , it might happen (depends on the CPU workload) that the task to create (async) has not been yet created but is being accessed by the WhenAll method (async too), therefore throws the exception mentioned above. This happens sometimes, as I said, according to the CPU workload: In order to easily reproduce the issue , I've created a unit test which calls the problematic method up to 50 times, and usually fails within the first 10 runs.
To solve the issue, I I've replaced the useless (because in this scenario does not bring anything relevant)  function AsParallel().ForAll by ForEach and the issue does not happen anymore because the tasks are always created following a sequence (not executed though, they are executed asynchronously), no matter the CPU workload. Code will be as follows, to solve the issue:

List<Model> ftpModels = _service.CreateFtpModel(rowsFromDB);
List<Task> asyncTasks = new List<Task>();

ftpModels.ForEach(p =>
{
    asyncTasks.Add(DoStepsAsync(p));
});
// Wait for all the tasks to finish.
await Task.WhenAll(asyncTasks.Where(p => p != null));

I hope it helps in the future to other people.


问:
Random but Regular Polygon Generator
I'm looking for a way to generate a set of random sided, but regular, polygons, inside a given rectangle or sector of a circle.  To better explain, my given 2d space should have a random arrangement of regular polygons with various numbers of sides, so, e.g, if two hexagons are separated by a rectangle equal in length to their sides, the whole space cannot be filled with only more hexagons, some triangles may be required, etc.

I'm looking for one segment of a sort of kaleidoscope effect.

答: See:  "Heuristics for Generation of Random Polygons"</p>

OwnerDisplayName: ProfK

Title: Random but Regular Polygon Generator


问:
Measure server HttpRequest's performance
How to measure server HttpRequest's performance?

I think it's important task and many peoples solved this challenge.

I will explain.
I have many user server requests which calls in parallel and i want measure some Performance metrics of identical requests.

For example:

```<code>10:00:00AM request 1 duration 200 ms: /some_request/data
...
11:00:00AM request 2 duration 700 ms: /some_request/data
...
11:30:00AM request 3 duration 300 ms: /some_request/data
...
</code>```

As you can see the general problem is that duration of requests always jumped, and we can't say about real change of request performance. Difference between duration of identical request's (note: with same json data 1-1) can be unpredictable.

In example i try measure requests duration like that:

```<code>public class PerformanceFilter : IActionFilter
{
    private Stopwatch timer = new Stopwatch();

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        timer.Reset();
        timer.Start();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        timer.Stop();
        var duration = timer.ElapsedMilliseconds;
    }
}
</code>```

May be it's wrong way? Or for detecting of request performance change we can use other request characteristics?

答:
Have you considered the w3c HTTP log value time-taken as an objective method for collecting your timing data?  This is taken at the server and misses only the last ack on the finish of the send as a part of the time collection.

One thing you will want to be particularly careful of is when your sample agent or your server is inside of a virtual machine as this impacts clock precision and integrity.  The virtual machine clock is unpinned from the hardware clock and "floats."  In this float period the clock does slow/degrade slightly and periodically has to be resync'd to the hardware clock.  Invariably this will happen when you are timing an event on the virtual machine.  This results in an apparent jump in the timed event.

This is a well known problem in the performance testing community which has to design around clock float issues related to timing precision on performance tests where virtual machines are used as load generators.

Body:
How to measure server HttpRequest's performance?

I think it's important task and many peoples solved this challenge.

I will explain.
I have many user server requests which calls in parallel and i want measure some Performance metrics of identical requests.

For example:

10:00:00AM request 1 duration 200 ms: /some_request/data
...
11:00:00AM request 2 duration 700 ms: /some_request/data
...
11:30:00AM request 3 duration 300 ms: /some_request/data
...

As you can see the general problem is that duration of requests always jumped, and we can't say about real change of request performance. Difference between duration of identical request's (note: with same json data 1-1) can be unpredictable.

In example i try measure requests duration like that:

public class PerformanceFilter : IActionFilter
{
    private Stopwatch timer = new Stopwatch();

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        timer.Reset();
        timer.Start();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        timer.Stop();
        var duration = timer.ElapsedMilliseconds;
    }
}

May be it's wrong way? Or for detecting of request performance change we can use other request characteristics?


问:
Countdown timer for different time zones
I need to develop a countdown timer hour for the company offices:

One office is in Brazil and the other is in Japan

Brazil = UTC-03:00
JAPAN = UTC+09:00

Both offices open at 8 AM and closes 8 PM, when Brazilian office is opening, the Japanese office is closing.

How can i configure to a japanese see the brazilian office closed and japanese office open and vice versa

Follow the link: http://lickslegal.webflow.io/teste/relogio

My javascript code:

```<code>function getTimeRemaining(endtime){

  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(endtime, clock_location, status, add_class, remove_class){

  clock_location.find('.relogio_status').removeClass(remove_class);
  clock_location.find('.relogio_status').addClass(add_class);

  var timeinterval = setInterval(function(){
    var t = getTimeRemaining(endtime);

    var show_message = ' '+status+' in ';

    if (t.days > 0) {
        show_message += t.days+" d ";
    }

    show_message += (t.hours < 10 ? '0':'')+t.hours+":"+(t.minutes < 10 ? '0':'')+t.minutes+":"+(t.seconds < 10 ? '0':'')+t.seconds;

    clock_location.find('.status_clock_text').html(show_message);

    if(t.total==0){
      // clearInterval(timeinterval);
      // location.reload();
      clock_city('rio_de_janeiro');
    }
  },1000);
}

function when_monday(){
    var will_monday = new Date();
    will_monday.setDate(will_monday.getDate() + (1 + 7 - will_monday.getDay()) % 7);

    return {
        'year': will_monday.getFullYear(),
        'month': (will_monday.getMonth() +1),
        'date': will_monday.getDate(),
        'full': will_monday,
        'open_or_close': will_monday.getFullYear()+"-"+(will_monday.getMonth() +1)+"-"+will_monday.getDate()
    };
}

function go_tomorrow(){
    var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

    return {
        'year': tomorrow.getFullYear(),
        'month': (tomorrow.getMonth() +1),
        'date': tomorrow.getDate(),
        'full': tomorrow,
        'open_or_close': tomorrow.getFullYear()+"-"+(tomorrow.getMonth() +1)+"-"+tomorrow.getDate()
    };
}

function clock_city(city_id){
    var today = new Date();

    var y = today.getFullYear();
    var m = (today.getMonth() +1);
    var d = today.getDate();

    var location_city = $("#"+city_id);

    var city_open_time = location_city.find('.open_time').text();
    var city_close_time = location_city.find('.close_time').text();
    var city_close_date = location_city.find('.close_date').text();

    // var city_open_deadline = y+"-"+m+"-"+d+" "+city_open_time;
    var city_close_deadline = y+"-"+m+"-"+d+" "+city_close_time;

    var hora_atual = (today.getHours() < 10 ? '0':'')+today.getHours()+':'+today.getMinutes();

    if (hora_atual >= city_open_time && hora_atual < city_close_time){
        //ABERTO
        console.log('aberto');
        initializeClock(city_close_deadline, location_city, 'closing', 'office_open', 'office_closed');
    }else{
        //FECHADO
        console.log('fechado');

        //Verifica se for SEXTA ou FDS
        if ( (today.getDay() +1) == 6 || today.getDay() == 6 || today.getDay() == 0) {
            var city_open_deadline = when_monday().open_or_close+" "+city_open_time;
        }else{
            var city_open_deadline = go_tomorrow().open_or_close+" "+city_open_time;
        }
        initializeClock(city_open_deadline, location_city, 'opening', 'office_closed', 'office_open');
    }
}

$(document).ready(function() {
    clock_city('rio_de_janeiro');
    clock_city('tokyo');
});
</code>```

答:
The UTC offset can be added to the current UTC date and time:

console.log( 'Z+0:',           new Date            )  // current UTC time
console.log( 'Z-3:', new Date( new Date -3 * 36e5) )  // current UTC time minus 3 hours
console.log( 'Z+8:', new Date(+new Date +8 * 36e5) )  // + used to convert to number

console.log( 'Tests:' )
console.log( 'Z+0:',           new Date(0)            )  // "1970-01-01T00:00:00.000Z"
console.log( 'Z-3:', new Date( new Date(0) -3 * 36e5) )  // "1969-12-31T21:00:00.000Z"
console.log( 'Z+8:', new Date(+new Date(0) +8 * 36e5) )  // "1970-01-01T08:00:00.000Z"```

Body:
I need to develop a countdown timer hour for the company offices:

One office is in Brazil and the other is in Japan

Brazil = UTC-03:00
JAPAN = UTC+09:00

Both offices open at 8 AM and closes 8 PM, when Brazilian office is opening, the Japanese office is closing.

How can i configure to a japanese see the brazilian office closed and japanese office open and vice versa

Follow the link: http://lickslegal.webflow.io/teste/relogio

My javascript code:

function getTimeRemaining(endtime){

  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(endtime, clock_location, status, add_class, remove_class){

  clock_location.find('.relogio_status').removeClass(remove_class);
  clock_location.find('.relogio_status').addClass(add_class);

  var timeinterval = setInterval(function(){
    var t = getTimeRemaining(endtime);

    var show_message = ' '+status+' in ';

    if (t.days > 0) {
        show_message += t.days+" d ";
    }

    show_message += (t.hours < 10 ? '0':'')+t.hours+":"+(t.minutes < 10 ? '0':'')+t.minutes+":"+(t.seconds < 10 ? '0':'')+t.seconds;

    clock_location.find('.status_clock_text').html(show_message);

    if(t.total==0){
      // clearInterval(timeinterval);
      // location.reload();
      clock_city('rio_de_janeiro');
    }
  },1000);
}

function when_monday(){
    var will_monday = new Date();
    will_monday.setDate(will_monday.getDate() + (1 + 7 - will_monday.getDay()) % 7);

    return {
        'year': will_monday.getFullYear(),
        'month': (will_monday.getMonth() +1),
        'date': will_monday.getDate(),
        'full': will_monday,
        'open_or_close': will_monday.getFullYear()+"-"+(will_monday.getMonth() +1)+"-"+will_monday.getDate()
    };
}

function go_tomorrow(){
    var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

    return {
        'year': tomorrow.getFullYear(),
        'month': (tomorrow.getMonth() +1),
        'date': tomorrow.getDate(),
        'full': tomorrow,
        'open_or_close': tomorrow.getFullYear()+"-"+(tomorrow.getMonth() +1)+"-"+tomorrow.getDate()
    };
}

function clock_city(city_id){
    var today = new Date();

    var y = today.getFullYear();
    var m = (today.getMonth() +1);
    var d = today.getDate();

    var location_city = $("#"+city_id);

    var city_open_time = location_city.find('.open_time').text();
    var city_close_time = location_city.find('.close_time').text();
    var city_close_date = location_city.find('.close_date').text();

    // var city_open_deadline = y+"-"+m+"-"+d+" "+city_open_time;
    var city_close_deadline = y+"-"+m+"-"+d+" "+city_close_time;

    var hora_atual = (today.getHours() < 10 ? '0':'')+today.getHours()+':'+today.getMinutes();

    if (hora_atual >= city_open_time && hora_atual < city_close_time){
        //ABERTO
        console.log('aberto');
        initializeClock(city_close_deadline, location_city, 'closing', 'office_open', 'office_closed');
    }else{
        //FECHADO
        console.log('fechado');

        //Verifica se for SEXTA ou FDS
        if ( (today.getDay() +1) == 6 || today.getDay() == 6 || today.getDay() == 0) {
            var city_open_deadline = when_monday().open_or_close+" "+city_open_time;
        }else{
            var city_open_deadline = go_tomorrow().open_or_close+" "+city_open_time;
        }
        initializeClock(city_open_deadline, location_city, 'opening', 'office_closed', 'office_open');
    }
}

$(document).ready(function() {
    clock_city('rio_de_janeiro');
    clock_city('tokyo');
});


问:
how can I tell cmake to find Windows Media Foundation?
To get cmake to link to (for example) boost::thread I can write:

```<code>find_package(Boost REQUIRED COMPONENTS thread)
</code>```

and then:

```<code>target_link_librarie(${target}
    PRIVATE
    Boost::thread
)
</code>```

How do I do this with Windows Media Foundation libraries?

答:
@ComicSansMS, didn't see WMF on the list. What I did to solve this was the following.

```<code>set(wmf_libs dxva2.lib evr.lib mf.lib mfplat.lib mfplay.lib mfreadwrite.lib mfuuid.lib)

target_link_libraries(${target}
    PRIVATE
    ${wmf_libs}
)
</code>```

I knew all along that this would do the trick (windows is at least wise enough to know where its own libraries are, so no paths need to be discovered), but I wanted  to know if there is a more CMake-y/stylistically 'correct' way to do it.

Body:
To get cmake to link to (for example) boost::thread I can write:

find_package(Boost REQUIRED COMPONENTS thread)

and then:

target_link_librarie(${target}
    PRIVATE
    Boost::thread
)

How do I do this with Windows Media Foundation libraries?

Body:
@ComicSansMS, didn't see WMF on the list. What I did to solve this was the following.

set(wmf_libs dxva2.lib evr.lib mf.lib mfplat.lib mfplay.lib mfreadwrite.lib mfuuid.lib)

target_link_libraries(${target}
    PRIVATE
    ${wmf_libs}
)

I knew all along that this would do the trick (windows is at least wise enough to know where its own libraries are, so no paths need to be discovered), but I wanted  to know if there is a more CMake-y/stylistically 'correct' way to do it.


问:
Manipulate var in jquery by doing find and text
I use a WYSIWYG editor in my page. I collect the HTML in a callback function. I would like now change the content with jQuery. For that I do a find() to select the text I want to replace. Then I want to replace it, but I'm stuck!

$('.save').click(function() {
  var html = $('#edit').editor('get_html');
  console.log(html)
  var ma_societe_OLD = $(html).find('.ma_societe').attr('data');
  var ma_societe = $(html).find('.ma_societe').text();
  if (ma_societe === ma_societe_OLD) {
    $(html).find('.ma_societe').text('dfdsfsdfds');
  }
  console.log(html);
});
```

As you can see, I want to replace the content of the span with my own text. But it's not working.

答:
The issue is because you're making amendments to the jQuery object, but you never store those changes anywhere. You either create a new jQuery object containing the original, unchanged html, or return the html string directly.

Instead, create $(html) in a variable, make your changes to it, then work with it as needed. Something like this:

$('.save').click(function() {
  var html = $('#edit').editor('get_html');
  var $html = $(html);
  var $maSociete = $html.find('.ma_societe')
  if ($maSociete.text() === $maSociete.attr('data')) {
    $maSociete.text('dfdsfsdfds');
  }

  var result = $html[0].outerHTML
  console.log(result);
});
```

Body:
I use a WYSIWYG editor in my page. I collect the HTML in a callback function. I would like now change the content with jQuery. For that I do a find() to select the text I want to replace. Then I want to replace it, but I'm stuck!

$('.save').click(function() {
  var html = $('#edit').editor('get_html');
  console.log(html)
  var ma_societe_OLD = $(html).find('.ma_societe').attr('data');
  var ma_societe = $(html).find('.ma_societe').text();
  if (ma_societe === ma_societe_OLD) {
    $(html).find('.ma_societe').text('dfdsfsdfds');
  }
  console.log(html);
});

As you can see, I want to replace the content of the span with my own text. But it's not working.


问:
ExtJS 6.x Add Custom Click Event To Component For ViewController
For ExtJS 6.5+ Modern, how do you add a click event to an component so that you can access it in a view controller.

The example below doesn't work.  I have also tried adding a listener directly to the sub-element.

Example Template:

```<code>Ext.define('TestController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.test-controller',

    control: {
        '[reference=someComponent]': {
            click: 'someComponentClick'
        }
    },

    someComponentClick: function() {
       console.log('it worked!')
    }
})

Ext.define('TestContainer', {
    extend: 'Ext.Container',
    xtype: 'test-container',
    controller: 'test-controller',
    items: [
        {
            xtype: 'component',
            reference: 'someComponent'
            html: 'CLICK HERE TO TEST'
        }
    ]
})
</code>```

Update

Based on priyadarshi answer, the following on the element calls the function in the controller.  I would prefer however to pick the event up normally in the controller by just listening to the click event.   Is there anyway to attach event listeners to the dom from the controller or at least fire an event from the element so that you can pick it up in the controller (without it explicitly calling functions on the controller).

```<code> Ext.define('TestController', {
     extend: 'Ext.app.ViewController',
     alias: 'controller.test-controller',

     control: {
         '[reference=someComponent]': {
             click: 'someComponentClick'
         }
     },

     someComponentClick: function() {
        console.log('it worked!')
     },
     someFuncOnController: function() {
         console.log('someFuncOnController') // << This runs
     }
 })

 Ext.define('TestContainer', {
     extend: 'Ext.Container',
     xtype: 'test-container',
     controller: 'test-controller',
     items: [
         {
             xtype: 'component',
             reference: 'someComponent'
             html: 'CLICK HERE TO TEST',
             listeners: [
                 element: 'element',
                 click: 'someFuncOnController'
             ]
         }
     ]
 })
</code>```

答:
Containers do not have a click event. You need to target the DOM element to attach the event. Do something like this.</p>

```<code>      var container = Ext.create('Ext.Container', {
      renderTo: Ext.getBody(),
      html: 'Click Me!',
      listeners: {
        click: function(){
            Ext.Msg.alert('Success!', 'I have been clicked!')
          }
        }
     });

    container.getEl().on('click', function(){
      this.fireEvent('click', container);
    }, container);</code>```

Body:
For ExtJS 6.5+ Modern, how do you add a click event to an component so that you can access it in a view controller.

The example below doesn't work.  I have also tried adding a listener directly to the sub-element.

Example Template:

Ext.define('TestController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.test-controller',

    control: {
        '[reference=someComponent]': {
            click: 'someComponentClick'
        }
    },

    someComponentClick: function() {
       console.log('it worked!')
    }
})

Ext.define('TestContainer', {
    extend: 'Ext.Container',
    xtype: 'test-container',
    controller: 'test-controller',
    items: [
        {
            xtype: 'component',
            reference: 'someComponent'
            html: 'CLICK HERE TO TEST'
        }
    ]
})

Update

Based on priyadarshi answer, the following on the element calls the function in the controller.  I would prefer however to pick the event up normally in the controller by just listening to the click event.   Is there anyway to attach event listeners to the dom from the controller or at least fire an event from the element so that you can pick it up in the controller (without it explicitly calling functions on the controller).

 Ext.define('TestController', {
     extend: 'Ext.app.ViewController',
     alias: 'controller.test-controller',

     control: {
         '[reference=someComponent]': {
             click: 'someComponentClick'
         }
     },

     someComponentClick: function() {
        console.log('it worked!')
     },
     someFuncOnController: function() {
         console.log('someFuncOnController') // << This runs
     }
 })

 Ext.define('TestContainer', {
     extend: 'Ext.Container',
     xtype: 'test-container',
     controller: 'test-controller',
     items: [
         {
             xtype: 'component',
             reference: 'someComponent'
             html: 'CLICK HERE TO TEST',
             listeners: [
                 element: 'element',
                 click: 'someFuncOnController'
             ]
         }
     ]
 })

Body:
Containers do not have a click event. You need to target the DOM element to attach the event. Do something like this.

      var container = Ext.create('Ext.Container', {
      renderTo: Ext.getBody(),
      html: 'Click Me!',
      listeners: {
        click: function(){
            Ext.Msg.alert('Success!', 'I have been clicked!')
          }
        }
     });

    container.getEl().on('click', function(){
      this.fireEvent('click', container);
    }, container);