问:
Sql query to display earnings increase or decrease - in percentages
I'd like to write an sql query that would display the earnings of a month compared to another, in percentages.

For example I'd need to calculate sum of price field entries for orders that have been added in November 2016 (i got a date field, timestamp type)

then calculate the sum of price field entries from December 2016 and so on till today (January, February, March..etc)

then display the comparison results in percentages, let's say for example December compared to November had a 10% increase in earnings while January compared to December had an 8% decrease in earnings and so on..my aim is to display these increases between months, in percentages.

Current sql query(not much):

```<code>SELECT SUM(price) AS Earnings FROM orders WHERE date LIKE '2016-12-%'
</code>```

Query works and is displaying the sum of price for the Year & Month
  specified.

How do I move forward from here and do what I mentioned above?

I'd appreciate any pointers!
Please let me know If I've forgot to mention something or haven't been clear with my question, I'll edit.

Using MysQL

Table name is orders, fields are named price (int), date (timestamp) and others (id, etc..)

答:
This will return you the sum of the orders grouped by month

```<code>select  year(date) as year, month(date) as month, sum(price) as total
from    orders
group by year(date), month(date)
</code>```

Displaying the percentage variation between each month and the previous one would require joining the query above with itself, like

```<code>select  t1.month, t1.year, t1.total, (t1.total / t2.total - 1) * 100 as variation
from    (
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t1
join    (
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t2
on      t2.year = case when t1.month = 1 then t1.year - 1 else t1.year end and
        t2.month = case when t1.month = 1 then 12 else t1.month - 1 end;
</code>```

Edit

In your table you only have data for October and December 2016 and February and March of 2017, so the only couple of consecutive months is Feb / Mar; that's why only March is shown.

The increment is big because the monthly sum went from less than 100 to almost 1000, hence that percentage. I fixed the formula though, it should be more precise now.

Btw, you can see the query working with fake data here

Edit 2

I found a way to make the query work with missing months too. The logic of the join is moved inside a relationship table that links each month to the closest previous one.

```<code>select  t1.year, t1.month, t1.total, (t1.total / t2.total - 1) * 100 as variation
from    (
            /* month results */
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t1
join    (
            /* relationship between months and previous months */
            select  year(t1.date) * 100 + month(t1.date) t1_calc,
                    max(year(t2.date) * 100 + month(t2.date)) t2_calc
            from    orders t1
            join    orders t2
            on      year(t1.date)*100 + month(t1.date) > year(t2.date)*100 + month(t2.date)
            group by month(t1.date)
        ) rel
on      t1.year * 100 + t1.month = rel.t1_calc
join    (
            /* previous month results */
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t2
on      t2.year * 100 + t2.month = rel.t2_calc;
</code>```

You can see it in action here

Body:
I'd like to write an sql query that would display the earnings of a month compared to another, in percentages.

For example I'd need to calculate sum of price field entries for orders that have been added in November 2016 (i got a date field, timestamp type)

then calculate the sum of price field entries from December 2016 and so on till today (January, February, March..etc)

then display the comparison results in percentages, let's say for example December compared to November had a 10% increase in earnings while January compared to December had an 8% decrease in earnings and so on..my aim is to display these increases between months, in percentages.

Current sql query(not much):

SELECT SUM(price) AS Earnings FROM orders WHERE date LIKE '2016-12-%'

Query works and is displaying the sum of price for the Year & Month
  specified.

How do I move forward from here and do what I mentioned above?

I'd appreciate any pointers!
Please let me know If I've forgot to mention something or haven't been clear with my question, I'll edit.

Using MysQL

Table name is orders, fields are named price (int), date (timestamp) and others (id, etc..)

Body:
This will return you the sum of the orders grouped by month

select  year(date) as year, month(date) as month, sum(price) as total
from    orders
group by year(date), month(date)

Displaying the percentage variation between each month and the previous one would require joining the query above with itself, like

select  t1.month, t1.year, t1.total, (t1.total / t2.total - 1) * 100 as variation
from    (
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t1
join    (
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t2
on      t2.year = case when t1.month = 1 then t1.year - 1 else t1.year end and
        t2.month = case when t1.month = 1 then 12 else t1.month - 1 end;

Edit

In your table you only have data for October and December 2016 and February and March of 2017, so the only couple of consecutive months is Feb / Mar; that's why only March is shown.

The increment is big because the monthly sum went from less than 100 to almost 1000, hence that percentage. I fixed the formula though, it should be more precise now.

Btw, you can see the query working with fake data here

Edit 2

I found a way to make the query work with missing months too. The logic of the join is moved inside a relationship table that links each month to the closest previous one.

select  t1.year, t1.month, t1.total, (t1.total / t2.total - 1) * 100 as variation
from    (
            /* month results */
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t1
join    (
            /* relationship between months and previous months */
            select  year(t1.date) * 100 + month(t1.date) t1_calc,
                    max(year(t2.date) * 100 + month(t2.date)) t2_calc
            from    orders t1
            join    orders t2
            on      year(t1.date)*100 + month(t1.date) > year(t2.date)*100 + month(t2.date)
            group by month(t1.date)
        ) rel
on      t1.year * 100 + t1.month = rel.t1_calc
join    (
            /* previous month results */
            select  year(date) as year, month(date) as month, sum(price) as total
            from    orders
            group by year(date), month(date)
        ) t2
on      t2.year * 100 + t2.month = rel.t2_calc;

You can see it in action here


来源: stackexchange

问:
Disable clicks on all day slot
I am using FullCalendar 3.2.0 for showing a calendar in my web app. I have turned on all day event slots. However I do not want them to be clickable. I am using select callback for selecting the empty slot, while I am using eventClick for detecting clicks on the event. I want them both to be disabled for all day event. How can I disable click only on all day events and slots?

Here's how I am setting up my calendar

```<code>var calendar = $('#calendar').fullCalendar({
    weekends: true,
    selectable: true,
    allDaySlot: true,
    timezone: 'local',
    defaultView: 'agendaMonth',
    header: {
        left: 'prev',
        center: 'title',
        right: 'next',
        height: headerHeight
    },
    overlap: false,
    editable: false,
    slotEventOverlap: false,
    eventSources: events,
    eventLimit: duration,
    defaultEventMinutes: duration,
    select: onSelect,
    eventClick: onEventClick,
    viewRender: onViewRender
});
</code>```

Update:

Refer to this fiddle for more complete example.

答:
This is a partial solution for your problems mentioned above. You can disable click on the all day event by using

```<code> var onEventClick = function (event, jsEvent, view){
    if(event.allDay){
        return false;
    }
    alert(event.title);
  }
</code>```

and specifying allDay: true in event like

```<code>{
    title: 'Long Event',
    start: new Date(y, m, d-5),
    end: new Date(y, m, d-2),
    allDay: true
},
</code>```

Updated Fiddle for your reference.

ContentLicense: CC BY-SA 3.0

Title: Disable clicks on all day slot

Body:
I am using FullCalendar 3.2.0 for showing a calendar in my web app. I have turned on all day event slots. However I do not want them to be clickable. I am using select callback for selecting the empty slot, while I am using eventClick for detecting clicks on the event. I want them both to be disabled for all day event. How can I disable click only on all day events and slots?

Here's how I am setting up my calendar

var calendar = $('#calendar').fullCalendar({
    weekends: true,
    selectable: true,
    allDaySlot: true,
    timezone: 'local',
    defaultView: 'agendaMonth',
    header: {
        left: 'prev',
        center: 'title',
        right: 'next',
        height: headerHeight
    },
    overlap: false,
    editable: false,
    slotEventOverlap: false,
    eventSources: events,
    eventLimit: duration,
    defaultEventMinutes: duration,
    select: onSelect,
    eventClick: onEventClick,
    viewRender: onViewRender
});

Update:

Refer to this fiddle for more complete example.

Body:
This is a partial solution for your problems mentioned above. You can disable click on the all day event by using

 var onEventClick = function (event, jsEvent, view){
    if(event.allDay){
        return false;
    }
    alert(event.title);
  }

and specifying allDay: true in event like

{
    title: 'Long Event',
    start: new Date(y, m, d-5),
    end: new Date(y, m, d-2),
    allDay: true
},

Updated Fiddle for your reference.


问:
How to add leading zeros in sybase ase
Need to add leading zeros to column values(varchar) and update it in same table.
ex: 431 as 000431, 5431 as 005431, 64531 as 064531, basically i need to substitute zeros to the data so that it is 6 digits. this is in sybase ase.

thanks

答:
If you can't use LPAD(), and the source number is an integer, this solution is maybe a little nicer than yours:

```<code>RIGHT(1000000+Number, 6)
</code>```

But, as yours, it produces unexpected results if the value is negative or has more than 6 digits.

Title: How to add leading zeros in sybase ase

Body:
If you can't use LPAD(), and the source number is an integer, this solution is maybe a little nicer than yours:

RIGHT(1000000+Number, 6)

But, as yours, it produces unexpected results if the value is negative or has more than 6 digits.


问:
Checkout a git submodule in Xcode 8 Build Phase script
I have a git repo on BitBucket for a utility project and i use it as a git submodule in other projects. I wrote an Xcode Build Phase script that clones, initializes and updates the submodule but it fails cloning with this error:

```<code>Cloning into '[Location of my working copy]'...
ssh_askpass: exec(/usr/X11R6/bin/ssh-askpass): No such file or directory
Permission denied (publickey).
fatal: Could not read from remote repository.
</code>```

I can do a checkout from Xcode's interface, i can do a checkout from the command line, and i can even run the same script from the command line myself, and everything works, i get prompted for my passphrase. Except when the script is run by Xcode.

I contacted BitBucket support and they pointed it out that according to the error Xcode is trying to use /usr/X11R6/bin/ssh-askpass to prompt me for the passphrase of my private key but it can't find the file (i also found that /usr/X11R6 is just a symlink to /opt/X11). They suggested that i check the following links:

https://support.rstudio.com/hc/en-us/community/posts/200660237-Using-Git-with-password-authentication-on-OS-X

https://github.com/markcarver/mac-ssh-askpass

https://github.com/theseal/ssh-askpass

I installed the missing binary from the last link using Homebrew, symlinked it to the location Xcode needs it to be and got a seemingly broken dialog box:

I also tried copying the binary instead of symlinking but it didn't make a difference.

Any ideas?

Just to make sure i ran this test to see if there's a problem with my SSH configs...

```<code>$ ssh -vT git@bitbucket.org
</code>```

...but according to the results everything is OK.

答:
The guys over at https://github.com/theseal/ssh-askpass/ helped me figure this out.

I had to install the missing ssh-askpass then add my SSH key to the agent with ssh-add -c before Xcode was launched. Adding the key while Xcode was running resulted in the Build Phase script always returning an error:

sign_and_send_pubkey: signing failed: agent refused operation

You can read the troubleshooting details here.

Body:
I have a git repo on BitBucket for a utility project and i use it as a git submodule in other projects. I wrote an Xcode Build Phase script that clones, initializes and updates the submodule but it fails cloning with this error:

Cloning into '[Location of my working copy]'...
ssh_askpass: exec(/usr/X11R6/bin/ssh-askpass): No such file or directory
Permission denied (publickey).
fatal: Could not read from remote repository.

I can do a checkout from Xcode's interface, i can do a checkout from the command line, and i can even run the same script from the command line myself, and everything works, i get prompted for my passphrase. Except when the script is run by Xcode.

I contacted BitBucket support and they pointed it out that according to the error Xcode is trying to use /usr/X11R6/bin/ssh-askpass to prompt me for the passphrase of my private key but it can't find the file (i also found that /usr/X11R6 is just a symlink to /opt/X11). They suggested that i check the following links:

https://support.rstudio.com/hc/en-us/community/posts/200660237-Using-Git-with-password-authentication-on-OS-X

https://github.com/markcarver/mac-ssh-askpass

https://github.com/theseal/ssh-askpass

I installed the missing binary from the last link using Homebrew, symlinked it to the location Xcode needs it to be and got a seemingly broken dialog box:

I also tried copying the binary instead of symlinking but it didn't make a difference.

Any ideas?

Just to make sure i ran this test to see if there's a problem with my SSH configs...

$ ssh -vT git@bitbucket.org

...but according to the results everything is OK.


问:
Return certain record based on criteria (2)
I asked this question previously, but missed a vital part of my problem.

Return certain record based on criteria

Take this list of results

```<code>Client  |   Date     | YESorNO
-------------------------------
A1      | 01/01/2001 | NO
A1      | 01/01/2002 | NO
A1      | 01/01/2003 | YES
A1      | 01/01/2004 | NO
A1      | 01/01/2005 | NO
A1      | 01/01/2006 | NO
A1      | 01/01/2007 | YES
A1      | 01/01/2008 | YES
A1      | 01/01/2009 | YES

A2      | 01/01/2001 | NO
A2      | 01/01/2002 | NO
A2      | 01/01/2003 | YES
A2      | 01/01/2004 | NO
A2      | 01/01/2005 | YES
A2      | 01/01/2006 | YES

A3      | 01/01/2001 | NO

           ...etc...
</code>```

The list is ordered chronologically and I cannot sort this is any other way other than descending / ascending.

I cannot sort for Yes | NO and find the First() or Last() as this won't give me the required value.

I want to be able to return the first 'YES' after all 'NO's have been accounted for, per Client.

In the above example for Client[A1] row 7 is the record I want returned (on 01/01/2007).

Client[A2] - row 5 (01/01/2005) ..etc

My code is as follows

```<code>var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Client = m.Client,
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);
</code>```

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

User @RenéVogt advised that

```<code>var result = query.AsEnumerable()
                  .TakeWhile(x => x.YESorNO == "YES")
                  .LastOrDefault();
</code>```

would get the job done and it does, but I forgot to add that the query will be returning many Clients and I need the first 'YES' for each Client, therefore the above code won't suffice.

Iterating over my results would be hugely time consuming and whilst that is a solution I would prefer this logic to be within the database query itself (if possible)

Many thanks

答:
I can provide a little sql query

```<code>;WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY Client DESC) AS rn
    FROM [dbo].[tblSkaterhaz]
)
,gte AS (
    SELECT Client,max(rn) mx FROM cte
    WHERE YesOrNo = 'NO'
    GROUP BY Client
)
SELECT cte.* FROM gte
INNER JOIN cte on cte.Client = gte.Client and cte.rn = gte.mx + 1
</code>```

Although it is not the required solution, but it yields the required result. You can create a stored proc and use it in your code.

NOTE: This is tested against the same table (and data) mentioned in question above

I hope this will be helpful for you.

Body:
I asked this question previously, but missed a vital part of my problem.

Return certain record based on criteria

Take this list of results

Client  |   Date     | YESorNO
-------------------------------
A1      | 01/01/2001 | NO
A1      | 01/01/2002 | NO
A1      | 01/01/2003 | YES
A1      | 01/01/2004 | NO
A1      | 01/01/2005 | NO
A1      | 01/01/2006 | NO
A1      | 01/01/2007 | YES
A1      | 01/01/2008 | YES
A1      | 01/01/2009 | YES

A2      | 01/01/2001 | NO
A2      | 01/01/2002 | NO
A2      | 01/01/2003 | YES
A2      | 01/01/2004 | NO
A2      | 01/01/2005 | YES
A2      | 01/01/2006 | YES

A3      | 01/01/2001 | NO

           ...etc...

The list is ordered chronologically and I cannot sort this is any other way other than descending / ascending.

I cannot sort for Yes | NO and find the First() or Last() as this won't give me the required value.

I want to be able to return the first 'YES' after all 'NO's have been accounted for, per Client.

In the above example for Client[A1] row 7 is the record I want returned (on 01/01/2007).

Client[A2] - row 5 (01/01/2005) ..etc

My code is as follows

var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Client = m.Client,
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

User @RenéVogt advised that

var result = query.AsEnumerable()
                  .TakeWhile(x => x.YESorNO == "YES")
                  .LastOrDefault();

would get the job done and it does, but I forgot to add that the query will be returning many Clients and I need the first 'YES' for each Client, therefore the above code won't suffice.

Iterating over my results would be hugely time consuming and whilst that is a solution I would prefer this logic to be within the database query itself (if possible)

Many thanks

Body:
I can provide a little sql query

;WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY Client DESC) AS rn
    FROM [dbo].[tblSkaterhaz]
)
,gte AS (
    SELECT Client,max(rn) mx FROM cte
    WHERE YesOrNo = 'NO'
    GROUP BY Client
)
SELECT cte.* FROM gte
INNER JOIN cte on cte.Client = gte.Client and cte.rn = gte.mx + 1

Although it is not the required solution, but it yields the required result. You can create a stored proc and use it in your code.

NOTE: This is tested against the same table (and data) mentioned in question above

I hope this will be helpful for you.


问:
Appending to $(this)
Within a function loop, I need to traverse further into the DOM.

```<code>$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */
</code>```

This is similar to what I'm trying to do in a function

```<code>$(this) = $('.panel_wrapper .panel');
$(this) .foo
</code>```

The following is a better example:

```<code>$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});
</code>```

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

```<code>$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});
</code>```

答:
To append a class you should use

```<code>$(this).addclass("foo")
</code>```

it really depends on what you're trying to do
if you want direct access to the DOM element itself you shouldn't wrap it at all

```<code>this.foo =...
</code>```

will add foo to the DOM element itself (inside the .each function)

ContentLicense: CC BY-SA 2.5

Title: Appending to $(this)

Body:
Within a function loop, I need to traverse further into the DOM.

$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */

This is similar to what I'm trying to do in a function

$(this) = $('.panel_wrapper .panel');
$(this) .foo

The following is a better example:

$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});

Body:
To append a class you should use

$(this).addclass("foo")

it really depends on what you're trying to do
if you want direct access to the DOM element itself you shouldn't wrap it at all

this.foo =...

will add foo to the DOM element itself (inside the .each function)


问:
Why use wrappers around the actual iterator functions in LINQ extension methods?
When looking at Microsoft's implementation of various C# LINQ methods, I noticed that the public extension methods are mere wrappers that return the actual implementation in the form of a separate iterator function.

For example (from System.Linq.Enumerable.cs):

```<code>public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    return ConcatIterator<TSource>(first, second);
}

static IEnumerable<TSource> ConcatIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second) {
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}
</code>```

What is the reason for wrapping the iterator like that instead of combining them into one and return the iterator directly?

Like this:

```<code>public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}
</code>```

答:
Wrappers are used to check method arguments immediately (i.e. when you call LINQ extension method). Otherwise arguments will not be checked until you start to consume iterator (i.e. use query in foreach loop or call some extension method which executes query - ToList, Count etc). This approach is used for all extension methods with deferred type of execution.

If you will use approach without wrapper then:

```<code>int[] first = { 1, 2, 3 };
int[] second = null;

var all = first.Concat(second); // note that query is not executed yet
// some other code
...
var name = Console.ReadLine();
Console.WriteLine($"Hello, {name}, we have {all.Count()} items!"); // boom! exception here
</code>```

With argument-checking wrapper method you will get exception at first.Concat(second) line.

Body:
When looking at Microsoft's implementation of various C# LINQ methods, I noticed that the public extension methods are mere wrappers that return the actual implementation in the form of a separate iterator function.

For example (from System.Linq.Enumerable.cs):

public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    return ConcatIterator<TSource>(first, second);
}

static IEnumerable<TSource> ConcatIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second) {
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}

What is the reason for wrapping the iterator like that instead of combining them into one and return the iterator directly?

Like this:

public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) {
    if (first == null) throw Error.ArgumentNull("first");
    if (second == null) throw Error.ArgumentNull("second");
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}

Body:
Wrappers are used to check method arguments immediately (i.e. when you call LINQ extension method). Otherwise arguments will not be checked until you start to consume iterator (i.e. use query in foreach loop or call some extension method which executes query - ToList, Count etc). This approach is used for all extension methods with deferred type of execution.

If you will use approach without wrapper then:

int[] first = { 1, 2, 3 };
int[] second = null;

var all = first.Concat(second); // note that query is not executed yet
// some other code
...
var name = Console.ReadLine();
Console.WriteLine($"Hello, {name}, we have {all.Count()} items!"); // boom! exception here

With argument-checking wrapper method you will get exception at first.Concat(second) line.


问:
Installing QuantLib in Anaconda on the Spyder Editor (Windows)
How do I install the QuantLib Package in Anaconda. I have tried the following code;

```<code>import QuantLib as ql
</code>```

but I am getting the following result;

```<code>ModuleNotFoundError: No module named 'QuantLib'
</code>```

Can anyone assist me

答:
You first need to install the QuantLib package. The easiest way I found is to install Anaconda 4.3.1 (link), open a Command Prompt as Admin and run:

pip install QuantLib-Python

For me, this only worked on the latest version of Anaconda including Python 3.6, think the QuantLib-Python package was implemented in PIP only very recently. This might work for other recent installations of Python as well, but it did not work for me on older versions of Anaconda or Python 3.5.

Body:
How do I install the QuantLib Package in Anaconda. I have tried the following code;

import QuantLib as ql

but I am getting the following result;

ModuleNotFoundError: No module named 'QuantLib'

Can anyone assist me


问:
Unit Testing Dapper with Inline Queries
I know there are several question similar to mine.

Dapper: Unit Testing SQL Queries

Testing Dapper Queries

butI don't think both of above question has clear answer that fit my requirement.

Right now I develop a new WebAPI project and split between WebAPI project and DataAccess technology. I not have a problem test the Controller for WebAPI since I can mock the data access class.

But for DataAccess class that's a different stories, since I'm using Dapper with inline queries in it, I'm a bit confuse how can I test it by using Unit Test. I've asked some of my friends and they prefer to do Integration test instead of Unit Test.

What I want to know is, is it possible to unit test the DataAccess class that use Dapper and Inline queries in it.

Let's say I have a class like this (this is a generic repository class, since a lot of the codes have similar queries differentiate by table name and field)

```<code>public abstract class Repository<T> : SyncTwoWayXI, IRepository<T> where T : IDatabaseTable
{
       public virtual IResult<T> GetItem(String accountName, long id)
       {
            if (id <= 0) return null;

            SqlBuilder builder = new SqlBuilder();
            var query = builder.AddTemplate("SELECT /**select**/ /**from**/ /**where**/");

            builder.Select(string.Join(",", typeof(T).GetProperties().Where(p => p.CustomAttributes.All(a => a.AttributeType != typeof(SqlMapperExtensions.DapperIgnore))).Select(p => p.Name)));
            builder.From(typeof(T).Name);
            builder.Where("id = @id", new { id });
            builder.Where("accountID = @accountID", new { accountID = accountName });
            builder.Where("state != 'DELETED'");

            var result = new Result<T>();
            var queryResult = sqlConn.Query<T>(query.RawSql, query.Parameters);

            if (queryResult == null || !queryResult.Any())
            {
                result.Message = "No Data Found";
                return result;
            }

            result = new Result<T>(queryResult.ElementAt(0));
            return result;
       }

       // Code for Create, Update and Delete
  }
</code>```

And the implementation for above code is like

```<code>public class ProductIndex: IDatabaseTable
{
        [SqlMapperExtensions.DapperKey]
        public Int64 id { get; set; }

        public string accountID { get; set; }
        public string userID { get; set; }
        public string deviceID { get; set; }
        public string deviceName { get; set; }
        public Int64 transactionID { get; set; }
        public string state { get; set; }
        public DateTime lastUpdated { get; set; }
        public string code { get; set; }
        public string description { get; set; }
        public float rate { get; set; }
        public string taxable { get; set; }
        public float cost { get; set; }
        public string category { get; set; }
        public int? type { get; set; }
}

public class ProductsRepository : Repository<ProductIndex>
{
   // ..override Create, Update, Delete method
}
</code>```

答:
I adapted what @Mikhail did because I had issues when adding the OrmLite packages.

```<code>internal class InMemoryDatabase
{
    private readonly IDbConnection _connection;

    public InMemoryDatabase()
    {
        _connection = new SQLiteConnection("Data Source=:memory:");
    }

    public IDbConnection OpenConnection()
    {
        if (_connection.State != ConnectionState.Open)
            _connection.Open();
        return _connection;
    }

    public void Insert<T>(string tableName, IEnumerable<T> items)
    {
        var con = OpenConnection();

        con.CreateTableIfNotExists<T>(tableName);
        con.InsertAll(tableName, items);
    }
}
</code>```

I've created a DbColumnAttribute so we can specify a specific column name for a classes property.

```<code>public sealed class DbColumnAttribute : Attribute
{
    public string Name { get; set; }

    public DbColumnAttribute(string name)
    {
        Name = name;
    }
}
</code>```

I added some IDbConnection extensions for the CreateTableIfNotExists and InsertAll methods.

This is very rough so I've not mapped types correctly

```<code>internal static class DbConnectionExtensions
{
    public static void CreateTableIfNotExists<T>(this IDbConnection connection, string tableName)
    {
        var columns = GetColumnsForType<T>();
        var fields = string.Join(", ", columns.Select(x => $"[{x.Item1}] TEXT"));
        var sql = $"CREATE TABLE IF NOT EXISTS [{tableName}] ({fields})";

        ExecuteNonQuery(sql, connection);
    }

    public static void Insert<T>(this IDbConnection connection, string tableName, T item)
    {
        var properties = typeof(T)
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .ToDictionary(x => x.Name, y => y.GetValue(item, null));
        var fields = string.Join(", ", properties.Select(x => $"[{x.Key}]"));
        var values = string.Join(", ", properties.Select(x => EnsureSqlSafe(x.Value)));
        var sql = $"INSERT INTO [{tableName}] ({fields}) VALUES ({values})";

        ExecuteNonQuery(sql, connection);
    }

    public static void InsertAll<T>(this IDbConnection connection, string tableName, IEnumerable<T> items)
    {
        foreach (var item in items)
            Insert(connection, tableName, item);
    }

    private static IEnumerable<Tuple<string, Type>> GetColumnsForType<T>()
    {
        return from pinfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            let attribute = pinfo.GetCustomAttribute<DbColumnAttribute>()
            let columnName = attribute?.Name ?? pinfo.Name
            select new Tuple<string, Type>(columnName, pinfo.PropertyType);
    }

    private static void ExecuteNonQuery(string commandText, IDbConnection connection)
    {
        using (var com = connection.CreateCommand())
        {
            com.CommandText = commandText;
            com.ExecuteNonQuery();
        }
    }

    private static string EnsureSqlSafe(object value)
    {
        return IsNumber(value)
            ? $"{value}"
            : $"'{value}'";
    }

    private static bool IsNumber(object value)
    {
        var s = value as string ?? "";

        // Make sure strings with padded 0's are not passed to the TryParse method.
        if (s.Length > 1 && s.StartsWith("0"))
            return false;

        return long.TryParse(s, out long l);
    }
}
</code>```

You can still use it the same way as @Mikhail mentions in Step 3.

Title: Unit Testing Dapper with Inline Queries

Body:
I know there are several question similar to mine.

Dapper: Unit Testing SQL Queries

Testing Dapper Queries

butI don't think both of above question has clear answer that fit my requirement.

Right now I develop a new WebAPI project and split between WebAPI project and DataAccess technology. I not have a problem test the Controller for WebAPI since I can mock the data access class.

But for DataAccess class that's a different stories, since I'm using Dapper with inline queries in it, I'm a bit confuse how can I test it by using Unit Test. I've asked some of my friends and they prefer to do Integration test instead of Unit Test.

What I want to know is, is it possible to unit test the DataAccess class that use Dapper and Inline queries in it.

Let's say I have a class like this (this is a generic repository class, since a lot of the codes have similar queries differentiate by table name and field)

public abstract class Repository<T> : SyncTwoWayXI, IRepository<T> where T : IDatabaseTable
{
       public virtual IResult<T> GetItem(String accountName, long id)
       {
            if (id <= 0) return null;

            SqlBuilder builder = new SqlBuilder();
            var query = builder.AddTemplate("SELECT /**select**/ /**from**/ /**where**/");

            builder.Select(string.Join(",", typeof(T).GetProperties().Where(p => p.CustomAttributes.All(a => a.AttributeType != typeof(SqlMapperExtensions.DapperIgnore))).Select(p => p.Name)));
            builder.From(typeof(T).Name);
            builder.Where("id = @id", new { id });
            builder.Where("accountID = @accountID", new { accountID = accountName });
            builder.Where("state != 'DELETED'");

            var result = new Result<T>();
            var queryResult = sqlConn.Query<T>(query.RawSql, query.Parameters);

            if (queryResult == null || !queryResult.Any())
            {
                result.Message = "No Data Found";
                return result;
            }

            result = new Result<T>(queryResult.ElementAt(0));
            return result;
       }

       // Code for Create, Update and Delete
  }

And the implementation for above code is like

public class ProductIndex: IDatabaseTable
{
        [SqlMapperExtensions.DapperKey]
        public Int64 id { get; set; }

        public string accountID { get; set; }
        public string userID { get; set; }
        public string deviceID { get; set; }
        public string deviceName { get; set; }
        public Int64 transactionID { get; set; }
        public string state { get; set; }
        public DateTime lastUpdated { get; set; }
        public string code { get; set; }
        public string description { get; set; }
        public float rate { get; set; }
        public string taxable { get; set; }
        public float cost { get; set; }
        public string category { get; set; }
        public int? type { get; set; }
}

public class ProductsRepository : Repository<ProductIndex>
{
   // ..override Create, Update, Delete method
}

Body:
I adapted what @Mikhail did because I had issues when adding the OrmLite packages.

internal class InMemoryDatabase
{
    private readonly IDbConnection _connection;

    public InMemoryDatabase()
    {
        _connection = new SQLiteConnection("Data Source=:memory:");
    }

    public IDbConnection OpenConnection()
    {
        if (_connection.State != ConnectionState.Open)
            _connection.Open();
        return _connection;
    }

    public void Insert<T>(string tableName, IEnumerable<T> items)
    {
        var con = OpenConnection();

        con.CreateTableIfNotExists<T>(tableName);
        con.InsertAll(tableName, items);
    }
}

I've created a DbColumnAttribute so we can specify a specific column name for a classes property.

public sealed class DbColumnAttribute : Attribute
{
    public string Name { get; set; }

    public DbColumnAttribute(string name)
    {
        Name = name;
    }
}

I added some IDbConnection extensions for the CreateTableIfNotExists and InsertAll methods.

This is very rough so I've not mapped types correctly

internal static class DbConnectionExtensions
{
    public static void CreateTableIfNotExists<T>(this IDbConnection connection, string tableName)
    {
        var columns = GetColumnsForType<T>();
        var fields = string.Join(", ", columns.Select(x => $"[{x.Item1}] TEXT"));
        var sql = $"CREATE TABLE IF NOT EXISTS [{tableName}] ({fields})";

        ExecuteNonQuery(sql, connection);
    }

    public static void Insert<T>(this IDbConnection connection, string tableName, T item)
    {
        var properties = typeof(T)
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .ToDictionary(x => x.Name, y => y.GetValue(item, null));
        var fields = string.Join(", ", properties.Select(x => $"[{x.Key}]"));
        var values = string.Join(", ", properties.Select(x => EnsureSqlSafe(x.Value)));
        var sql = $"INSERT INTO [{tableName}] ({fields}) VALUES ({values})";

        ExecuteNonQuery(sql, connection);
    }

    public static void InsertAll<T>(this IDbConnection connection, string tableName, IEnumerable<T> items)
    {
        foreach (var item in items)
            Insert(connection, tableName, item);
    }

    private static IEnumerable<Tuple<string, Type>> GetColumnsForType<T>()
    {
        return from pinfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            let attribute = pinfo.GetCustomAttribute<DbColumnAttribute>()
            let columnName = attribute?.Name ?? pinfo.Name
            select new Tuple<string, Type>(columnName, pinfo.PropertyType);
    }

    private static void ExecuteNonQuery(string commandText, IDbConnection connection)
    {
        using (var com = connection.CreateCommand())
        {
            com.CommandText = commandText;
            com.ExecuteNonQuery();
        }
    }

    private static string EnsureSqlSafe(object value)
    {
        return IsNumber(value)
            ? $"{value}"
            : $"'{value}'";
    }

    private static bool IsNumber(object value)
    {
        var s = value as string ?? "";

        // Make sure strings with padded 0's are not passed to the TryParse method.
        if (s.Length > 1 && s.StartsWith("0"))
            return false;

        return long.TryParse(s, out long l);
    }
}

You can still use it the same way as @Mikhail mentions in Step 3.


问:
string.compare and string for comparison
I have my code like this

```<code>private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }
</code>```

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

答:
MSDN have really good explanation about the string.compare method..
you just have to write

```<code>String.Compare (String, String)
</code>```

to compare your strings.. used with a Switch-case instruction it will be ok..

Use

```<code>String.Compare (String, String, boolean)
</code>```

To set the case comparaison

Body:
I have my code like this

private void btnStartAnalysis_Click(object sender, EventArgs e)

            {

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables")
            {
            //This is the function call for the primary key checking in DB
            GetPrimaryKeyTable();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonPrimaryKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetForeignKeyTables();
            }

        //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
        if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetNonForeignKeyTables();
            }

        if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithUpperCaseName();
            }

        if((string) (cmbOperations.SelectedItem) == "lowercasedtables")
            {
            //This is the function call for the nonPrimary key checking in DB
            GetTablesWithLowerCaseName();
            }
        }

But here using (string) makes problem in case sensitiveness.So I want to use string.comapare in place of (string).

Can anybody give me any hint how to use it.

Body:
MSDN have really good explanation about the string.compare method..
you just have to write

String.Compare (String, String)

to compare your strings.. used with a Switch-case instruction it will be ok..

Use

String.Compare (String, String, boolean)

To set the case comparaison


问:
Mock window.location.reload in Jasmine testing
I have created a window.location.reload function in my javascript.

I need to mock the reload function while testing in Jasmine since it keeps on looping.

The test goes well when I run grunt jenkins. But not while testing in the browser (mozilla/chrome).

Here is my code snippet.

Javascript:

```<code>window.location.reload();
</code>```

Jasmine Test:

```<code>spyOn(window.location, 'reload').and.callFake(function(){});
</code>```

Can anyone please help me on this?

答:
You can always do:

```<code>beforeAll(() => {
  window.reload = () => console.log('Mock redirect');
});
</code>```

Respectively:

```<code>beforeAll(() => {
  window.onbeforeunload = () => console.log('Mock redirect');
  window.open = () => console.log('Mock redirect');
});
</code>```

Body:
I have created a window.location.reload function in my javascript.

I need to mock the reload function while testing in Jasmine since it keeps on looping.

The test goes well when I run grunt jenkins. But not while testing in the browser (mozilla/chrome).

Here is my code snippet.

Javascript:

window.location.reload();

Jasmine Test:

spyOn(window.location, 'reload').and.callFake(function(){});

Can anyone please help me on this?

Body:
You can always do:

beforeAll(() => {
  window.reload = () => console.log('Mock redirect');
});

Respectively:

beforeAll(() => {
  window.onbeforeunload = () => console.log('Mock redirect');
  window.open = () => console.log('Mock redirect');
});


问:
Displaying React components on one page only
I am building my first SPA with React but my React theory is not there yet. I have a Main component which renders a Header component. The Header component renders three components, Navigation, Claim and Bars. The problem is that Claim and Bars should be rendered only on homepage an not on other pages. Not really sure how to do it, I know I have to take it out from Main but not sure if I should work on the routes, if I put everything on the Homepage component or if there is a best practice for this.

Routes.js

```<code>var routes = (
  <BrowserRouter>
    <Main>
      <Route exact path="/" component={Home}/>
      <Route exact path="/services" component={Services}/>
    </Main>
 </BrowserRouter>
);
</code>```

Main.js component

```<code>var Main = React.createClass({
  render: function(){
   return (
      <div className="wfp-grid" role="main">
        <div className="wfp-u-1">
          <Header />
          <div className="wavy"></div>
          {this.props.children}
        </div>
      </div>
    );
  }
});
</code>```

Header.js component

```<code>var Header = React.createClass({
  render: function(){
    return (
      <header className="wfp-header-int">
        <Navigation />
        <Claim />
        <Bars />
     </header>
   );
  }
});
</code>```

答:
In your Header component you need to get current URL from the router and then render specific components according to the url

```<code>var Header = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render: () => {
        let curLocation = this.context.router.getCurrentLocation().pathname

        return (
            <header className="wfp-header-int">
            <Navigation />
            { curLocation === '/' && <Claim /> }
            { curLocation === '/' && <Bars /> }
         </header>
        )
    }
})
</code>```

ps) this approach works for react-router v3, not sure if it works for v4

Body:
I am building my first SPA with React but my React theory is not there yet. I have a Main component which renders a Header component. The Header component renders three components, Navigation, Claim and Bars. The problem is that Claim and Bars should be rendered only on homepage an not on other pages. Not really sure how to do it, I know I have to take it out from Main but not sure if I should work on the routes, if I put everything on the Homepage component or if there is a best practice for this.

Routes.js

var routes = (
  <BrowserRouter>

      <Route exact path="/" component={Home}/>
      <Route exact path="/services" component={Services}/>

 </BrowserRouter>
);

Main.js component

var Main = React.createClass({
  render: function(){
   return (

          {this.props.children}

    );
  }
});

Header.js component

var Header = React.createClass({
  render: function(){
    return (

        <Navigation />
        <Claim />
        <Bars />

   );
  }
});

Body:
In your Header component you need to get current URL from the router and then render specific components according to the url

var Header = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render: () => {
        let curLocation = this.context.router.getCurrentLocation().pathname

        return (
            <header className="wfp-header-int">
            <Navigation />
            { curLocation === '/' && <Claim /> }
            { curLocation === '/' && <Bars /> }
         </header>
        )
    }
})

ps) this approach works for react-router v3, not sure if it works for v4


问:
bash one liner to combine text files line by line except for the first line in every file except for the first file
I am currently doing it using this script:

```<code>head -1 file001.txt > all.txt; tail -n +2 -q *.txt >> all.txt
</code>```

it is doing alright, gettting the header from first file and then concatenating the others.

Problem is:

the other lines are all in one line, rather than each being in separate line. Please help to correct this problem.

if you have any other one liner that does the job, perfect, it is welcome.

the desired answer will be:

get the header from any of the files with that extension, I don't want to give any specific file name like file001.txt, i'd prefer it to take it from any file, because anyway they have the same headers. But it is possible that my file names don't be the pattern file001.txt, that is why I say any file with that extension.

答:
try this and it might work for you:</p>

```<code>sed -e '2,${/^YOUR_HEADER/d' -e '}' *.txt > all.txt
</code>```

Body:
I am currently doing it using this script:

head -1 file001.txt > all.txt; tail -n +2 -q *.txt >> all.txt

it is doing alright, gettting the header from first file and then concatenating the others.

Problem is:

the other lines are all in one line, rather than each being in separate line. Please help to correct this problem.

if you have any other one liner that does the job, perfect, it is welcome.

the desired answer will be:

get the header from any of the files with that extension, I don't want to give any specific file name like file001.txt, i'd prefer it to take it from any file, because anyway they have the same headers. But it is possible that my file names don't be the pattern file001.txt, that is why I say any file with that extension.

Body:
try this and it might work for you:

sed -e '2,${/^YOUR_HEADER/d' -e '}' *.txt > all.txt


问:
width/height of SVG image messed up by IE10
I have an SVG image with clickable SVG polygons on it and some hover image effects on top of that. works perfectly fine in every browser, except - of course - in IE. actually edge (12 + 13) and IE 11 are fine. Even IE10 (Metro) - but not IE10 Latest (as tested in Browserstack).

Since this has to be seen with the images I put up a working example here (well working apart from IE10):
SVG clickable images

so following that link you can see what it should look like (again, except IE10) and this is a screenshot from Browserstack of what it looks like in IE10 Latest:

So in this specific case, the black & white-image (background) - instead of having a 7.5% margin-left and 85% width like the rest of the svg stuff - is resized by the height, which seems to be 100%, thus resulting in incorrect layering of the SVGs.

i really don't know what's causing this - any help is much appreciated!

答:
It looks like you are only supplying a width for the <svg> element (ie. no height).  So it is probably IEs SVG scaling bug that is your problem.  See the following question for a workaround.

SVGs not scaling properly in IE - has extra space


问:
file.write(line) not writing all of the lines in the file
I have the code below to check whether .txt files in a directory contain words from a chosen word list, it also prints to the console and writes the results to the out.txt file. However when there is more than one .txt file in the directory it only writes the last one checked to the out.txt file instead of all of them.</p>

```<code>    self.wordopp = askdirectory(title="Select chat log directory")
    path = self.wordopp
    files = os.listdir(path)
    paths = []
    wordlist = self.wordop
    word = open(wordlist)
    l = set(w.strip().lower() for w in word)
    inchat = []
    for file in files:
        paths.append(os.path.join(path, file))
        with open(paths[-1]) as f:
            found = False
            file = open("out.txt", "w")
            for line in f:
                line = line.lower()
                if any(w in line for w in l):
                    found = True
                    print (line)
                    file.write(line)
                    if not found:
                        print("not here")
</code>```

答:
The problem  is in line: file = open("out.txt", "w") where you open out.txt for writing. The content of the file is erased.

Use file = open("out.txt", "a") instead and the file will be opened for appending the previously written content.

As stated in python documentation:

'w' for only writing (an existing file with the same name will be erased)

'a' opens the file for appending; any data written to the file is automatically added to the end

P.s. Don't forget to call file.close()

Body:
I have the code below to check whether .txt files in a directory contain words from a chosen word list, it also prints to the console and writes the results to the out.txt file. However when there is more than one .txt file in the directory it only writes the last one checked to the out.txt file instead of all of them.

    self.wordopp = askdirectory(title="Select chat log directory")
    path = self.wordopp
    files = os.listdir(path)
    paths = []
    wordlist = self.wordop
    word = open(wordlist)
    l = set(w.strip().lower() for w in word)
    inchat = []
    for file in files:
        paths.append(os.path.join(path, file))
        with open(paths[-1]) as f:
            found = False
            file = open("out.txt", "w")
            for line in f:
                line = line.lower()
                if any(w in line for w in l):
                    found = True
                    print (line)
                    file.write(line)
                    if not found:
                        print("not here")


问:
How do I handle table that generates values dynamically using Web Driver?
Problem: How do I find the value from the table column and depending upon that value how do I select the adjacent checkbox.

Description: The table consist of 8 column. The first column (Column name is 'Select') consist of checkboxes. On last column (column name is 'Amount')
we have amounts. I want web driver to click on checkbox when the adjacent amount column consists of the value (let's say) 3380.
(Means if particular amount is present in amount section then click on check box associated with that amount row)

Note: The values are dynamic in nature.

HTML Code:

```<code><table width="760" cellspacing="0" cellpadding="0" background="../images/bground_title_row.gif" height="25">
<tr valign="top"><td>
<table width="760" align="center" cellpadding="0" cellspacing="1">
<div align="center"><span class="noninputtextfields">Select</span></div>
<td height="25" width="50"><div align="center"><span class="noninputtextfields">Select</span></div></td>
<td height="25" width="50"> <span class="noninputtextfields">Date</span></td>
<td height="25" width="150"> <span class="noninputtextfields">Handler</span></td>
<td height="25" width="100"> <span class="noninputtextfields">Payee</span></td>
<td height="25" width="50" valign="center" nowrap=""> <span class="noninputtextfields">Ind</span></td>
<td height="25" width="210" valign="center"> <span class="noninputtextfields">Claim/Claimant</span></td>
<td height="25" width="100"> <span class="noninputtextfields">Insured</span></td>
<td height="25" width="50"><div align="right"><span class="noninputtextfields">Amount €</span> </div></td>
</tr>

<tr>
<td><input type="checkbox" name="bulk_CHKpayment" value="0" onclick="this.checked=false;></td>
<td height="25" nowrap=""> <span class="inputtextfields">01/03/2017 08:40:41</span></td>
<td height="25"> <span class="inputtextfields">Peter Collins </span></td>
<td height="25"> <span class="inputtextfields">FirstName </span></td>
<td height="25"> <span class="inputtextfields">N </span></td>
<td height="25"> <span class="inputtextfields">FL </span></td>
<td height="25"> <span class="inputtextfields">FirstName</span></td>
<td><div align="right"><span class="inputtextfields">5045.17 </span></div></td>
</tr>

<tr>
<td><input type="checkbox" name="bulk_CHKpayment" value="0" onclick="this.checked=false;></td>
<td height="25" nowrap=""> <span class="inputtextfields">01/03/2017 08:40:41</span></td>
<td height="25"> <span class="inputtextfields">David Dessy </span></td>
<td height="25"> <span class="inputtextfields">FirstName </span></td>
<td height="25"> <span class="inputtextfields">N </span></td>
<td height="25"> <span class="inputtextfields">FL </span></td>
<td height="25"> <span class="inputtextfields">FirstName</span></td>
<td><div align="right"><span class="inputtextfields">1000 </span></div></td>
<tr>
.
.
.
</table>
</code>```

答:
it easier to do with xpath.
Actual Xpath might differ as I haven't got a change to test. But the idea is you find the matching TD with text and then go to parent element, which is ROW and then first td and then input. </p>

```<code>public void selectValue(String value){
    String xpath =  "//td[contains(text(),'"+value+"')]/../td[1]/input";
    WebElement checkbox = driver.findElement(By.xpath(xpath));
    checkbox.click();

}
</code>```

Body:
Problem: How do I find the value from the table column and depending upon that value how do I select the adjacent checkbox.

Description: The table consist of 8 column. The first column (Column name is 'Select') consist of checkboxes. On last column (column name is 'Amount')
we have amounts. I want web driver to click on checkbox when the adjacent amount column consists of the value (let's say) 3380.
(Means if particular amount is present in amount section then click on check box associated with that amount row)

Note: The values are dynamic in nature.

HTML Code:

Select

Select

 Date
 Handler
 Payee
 Ind
 Claim/Claimant
 Insured

Amount €

<input type="checkbox" name="bulk_CHKpayment" value="0" onclick="this.checked=false;>
 01/03/2017 08:40:41
 Peter Collins
 FirstName
 N
 FL
 FirstName

5045.17

<input type="checkbox" name="bulk_CHKpayment" value="0" onclick="this.checked=false;>
 01/03/2017 08:40:41
 David Dessy
 FirstName
 N
 FL
 FirstName

1000

.
.
.

Body:
it easier to do with xpath.
Actual Xpath might differ as I haven't got a change to test. But the idea is you find the matching TD with text and then go to parent element, which is ROW and then first td and then input.

public void selectValue(String value){
    String xpath =  "//td[contains(text(),'"+value+"')]/../td[1]/input";
    WebElement checkbox = driver.findElement(By.xpath(xpath));
    checkbox.click();

}


问:
./zkServer.sh status Error contacting service. It is probably not running
I have installed zookeeper 3.4.9 version

and my zoo.cfg file configuration is as following

```<code>initLimit=10

syncLimit=5

dataDir=/usr/local/zookeeper/

clientPort=2181

DataLogDir=/usr/local/log/

server.1=hadoop-master:2888:3888

server.2=hadoop-slave-1:2889:3889

server.3=hadoop-slave-2:2890:3890
</code>```

and ofcourse I have initiated myid file under /usr/local/zookeeper/data/myid in three nodes

and it contains the value 1 in hadoop-master server
and 2 in hadoop-slave-1

and 3 in hadoop-slave-2

my slaves file is as following

```<code>hadoop-slave-1

hadoop-slave-2

hadoop-master
</code>```

i have issued the command ./zkServer.sh start in all three nodes
and it gives me the out put

```<code>ZooKeeper JMX enabled by default

Using config: /usr/local/zookeeper-3.4.9/bin/../conf/zoo.cfg

Starting zookeeper ... STARTED
</code>```

but issuing the command ./zkServer.sh status

gives me the output

```<code>Using config: /usr/local/zookeeper-3.4.9/bin/../conf/zoo.cfg

Error contacting service. It is probably not running.
</code>```

why am i getting this output?

and jps command doesn't view

```<code>QuorumPeerMain
</code>```

my .bashrc file is

```<code>export JAVA_HOME=/usr/local/java-1.7.0/

export PATH=$PATH:$JAVA_HOME/bin

export HADOOP_HOME=/usr/local/hadoop/

export HADOOP_MAPRED_HOME=$HADOOP_HOME

export HADOOP_COMMON_HOME=$HADOOP_HOME

export HADOOP_HDFS_HOME=$HADOOP_HOME

export YARN_HOME=$HADOOP_HOME

export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native

export HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=/usr/local/hadoop
/lib/native"

export HADOOP_PREFIX=/usr/local/hadoop/

export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

export HADOOP_INSTALL=$HADOOP_HOME
</code>```

答:
The Zookeeper servers are not able to find their myid file under the dataDir.
Here the dataDir is set as /usr/local/zookeeper/, Create the myid files directly under the defined dataDir.

Restart Zookeeper servers after making the changes.

Body:
I have installed zookeeper 3.4.9 version

and my zoo.cfg file configuration is as following

initLimit=10

syncLimit=5

dataDir=/usr/local/zookeeper/

clientPort=2181

DataLogDir=/usr/local/log/

server.1=hadoop-master:2888:3888

server.2=hadoop-slave-1:2889:3889

server.3=hadoop-slave-2:2890:3890

and ofcourse I have initiated myid file under /usr/local/zookeeper/data/myid in three nodes

and it contains the value 1 in hadoop-master server
and 2 in hadoop-slave-1

and 3 in hadoop-slave-2

my slaves file is as following

hadoop-slave-1

hadoop-slave-2

hadoop-master

i have issued the command ./zkServer.sh start in all three nodes
and it gives me the out put

ZooKeeper JMX enabled by default

Using config: /usr/local/zookeeper-3.4.9/bin/../conf/zoo.cfg

Starting zookeeper ... STARTED

but issuing the command ./zkServer.sh status

gives me the output

Using config: /usr/local/zookeeper-3.4.9/bin/../conf/zoo.cfg

Error contacting service. It is probably not running.

why am i getting this output?

and jps command doesn't view

QuorumPeerMain

my .bashrc file is

export JAVA_HOME=/usr/local/java-1.7.0/

export PATH=$PATH:$JAVA_HOME/bin

export HADOOP_HOME=/usr/local/hadoop/

export HADOOP_MAPRED_HOME=$HADOOP_HOME

export HADOOP_COMMON_HOME=$HADOOP_HOME

export HADOOP_HDFS_HOME=$HADOOP_HOME

export YARN_HOME=$HADOOP_HOME

export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native

export HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=/usr/local/hadoop
/lib/native"

export HADOOP_PREFIX=/usr/local/hadoop/

export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

export HADOOP_INSTALL=$HADOOP_HOME


问:
Strange behaviour with for loop and size_t
```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = 0; i < size; i++) {
    printf("%d ", i);
 }
</code>```

The above code (using gcc) outptus

4

0 1 2 3

```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < size; i++) {
    printf("%d ", i);
 }
</code>```

This code (i is initialized to -1) outputs only 4 and nothing in the loop.

```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < (int) size; i++) {
    printf("%d ", i);
 }
</code>```

Adding a cast makes the code run fine again. The output is

4

-1 0 1 2 3

What's going wrong in the second code? Why doesn't printf go wrong anywhere?

答:
```<code>i < size
</code>```

When i is signed and size is unsigned, then i is converted to unsigned before the comparison is performed.  This is part of what are called the usual arithmetic conversions.

When -1 is converted to an unsigned type, the result is the largest possible value representable by the unsigned type, thus i < size is false when i is -1 for any value of size.

When you use i < (int)size instead, both operands of < are of type int, so no conversions need to be performed and since both operands are signed, you get the expected result.

Body:
 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = 0; i < size; i++) {
    printf("%d ", i);
 }

The above code (using gcc) outptus

4

0 1 2 3

 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < size; i++) {
    printf("%d ", i);
 }

This code (i is initialized to -1) outputs only 4 and nothing in the loop.

 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < (int) size; i++) {
    printf("%d ", i);
 }

Adding a cast makes the code run fine again. The output is

4

-1 0 1 2 3

What's going wrong in the second code? Why doesn't printf go wrong anywhere?

Body:
i < size

When i is signed and size is unsigned, then i is converted to unsigned before the comparison is performed.  This is part of what are called the usual arithmetic conversions.

When -1 is converted to an unsigned type, the result is the largest possible value representable by the unsigned type, thus i < size is false when i is -1 for any value of size.

When you use i < (int)size instead, both operands of < are of type int, so no conversions need to be performed and since both operands are signed, you get the expected result.


问:
when exactly does onBatchScanResults get called
I call:

```<code>bleScanner.startScan(leScanCallback);
</code>```

And I do get onScanResults.

However I never do get the onBatchScanResults, so I was wondering when does this get called. I am asking because I am worried that the function might get called in different conditions (i.e. when a lot of bluetooth devices are found).

答:
you have to call different method to start scan.

```<code>startScan (List<ScanFilter> filters,
                ScanSettings settings,
                ScanCallback callback)
</code>```

use ScanSettings.Builder to create scansetting object and set the scan mode type as SCAN_MODE_LOW_POWER

Body:
I call:

bleScanner.startScan(leScanCallback);

And I do get onScanResults.

However I never do get the onBatchScanResults, so I was wondering when does this get called. I am asking because I am worried that the function might get called in different conditions (i.e. when a lot of bluetooth devices are found).

Body:
you have to call different method to start scan.

startScan (List<ScanFilter> filters,
                ScanSettings settings,
                ScanCallback callback)

use ScanSettings.Builder to create scansetting object and set the scan mode type as SCAN_MODE_LOW_POWER


问:
Undefined index when defining PHP POST inside JQuery variable
Ok so i am using Ajax to display a note on the screen when people click on a note name on the left and the note will show on the right.

Now when a user edits the note they should be able to click a button and it saves the new text back to the ID the note was originally loaded from.

Basically i can get the note id in PHP but then how do i pass that ID to jquery to then use.

My script:

```<code><?php include 'connectionDetails.php'; ?>

<?php

    if (isset($_POST['noteid']))
    {
        $showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
        $stmt = sqlsrv_query($conn, $showNoteInfo);
    }

    if (isset($_POST['noteid']))
    {
        if (empty($_POST['noteid']))
        {
            $notes = 'No Data';
        }
        if (sqlsrv_has_rows($stmt))
        {
            $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);

            echo "<div class='custom-font title-container'>
                    <div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
                    <div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editGeneralNote()'>   </div>" . $data['NoteName'] . " <div class='save-note fa fa-thumbs-up' onclick='saveGeneralNote(); submitNoteText();'></div></div>
                  </div>";
            echo "<textarea spellcheck='false' readonly id='ta1'>" . $data['Note'] . "</textarea>";
        }
        else
        {
            echo "No data found";
        }
    }
?>

<script type="text/javascript">

    // Submit generalNote to the database

function submitNoteText()
{
    var noteid = <?php echo $_POST['noteid']; ?>;
    var notetext = $("#ta1").val();

    var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;

    console.log("NoteID: " + noteid);

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "phpFiles_Notes/submitNoteText.php",
            data: dataString,
            cache: false,
            success: function(result){
                alert(result);
            }
        });
    }
    return false;
};

</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
</code>```

As you can see im trying to put the function in the same php file so i can directly use $_POST['noteid'] which holds the id i want.

So why is it saying that in my function the Index is Undefined when at the top it has an 'isset' on the id and retrieves the ID no problem?

答:
You can use like this... </p>

```<code>var noteid = <?php if(isset$_POST['noteid']){ echo $_POST['noteid'];} ?>;
</code>```

Body:
Ok so i am using Ajax to display a note on the screen when people click on a note name on the left and the note will show on the right.

Now when a user edits the note they should be able to click a button and it saves the new text back to the ID the note was originally loaded from.

Basically i can get the note id in PHP but then how do i pass that ID to jquery to then use.

My script:

<?php include 'connectionDetails.php'; ?>

<?php

    if (isset($_POST['noteid']))
    {
        $showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
        $stmt = sqlsrv_query($conn, $showNoteInfo);
    }

    if (isset($_POST['noteid']))
    {
        if (empty($_POST['noteid']))
        {
            $notes = 'No Data';
        }
        if (sqlsrv_has_rows($stmt))
        {
            $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);

            echo "

" . $data['NoteName'] . "

";
            echo "<textarea spellcheck='false' readonly id='ta1'>" . $data['Note'] . "</textarea>";
        }
        else
        {
            echo "No data found";
        }
    }
?>

As you can see im trying to put the function in the same php file so i can directly use $_POST['noteid'] which holds the id i want.

So why is it saying that in my function the Index is Undefined when at the top it has an 'isset' on the id and retrieves the ID no problem?

Body:
You can use like this...

var noteid = <?php if(isset$_POST['noteid']){ echo $_POST['noteid'];} ?>;


问:
Incorrect syntax near '79000'
I have this comamand and that error, in data i have zip code 79000 and table name site

```<code>   private void Crt_clck_Click(object sender, EventArgs e)
    {

        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code'" + Zipcode.Text + "'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
</code>```

can you help me with this

答:
Change your sql statement to

```<code>cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code = '" + Zipcode.Text + "'";
</code>```

You are missing the = which is needed for the syntax to be correct.

But you should think about using parameter instead to avoid SQL Injection.

Why do we always prefer using parameters in SQL statements? could be interesting for this, too.

Title: Incorrect syntax near '79000'

Body:
I have this comamand and that error, in data i have zip code 79000 and table name site

   private void Crt_clck_Click(object sender, EventArgs e)
    {

        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code'" + Zipcode.Text + "'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }

can you help me with this

Body:
Change your sql statement to

cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code = '" + Zipcode.Text + "'";

You are missing the = which is needed for the syntax to be correct.

But you should think about using parameter instead to avoid SQL Injection.

Why do we always prefer using parameters in SQL statements? could be interesting for this, too.


问:
Remove duplicate rows by considering two columns and ignore the order
I have a dataframe with three columns. Column 1, Column 2 and third column is Value. Data frame is sorted according to the value (desc). In the below case, I want to remove third row because A>B is already there, so I don't want to consider B>A. How can I remove third column (such instances). This applies to all, for example, A>C is already present, so C>A should be removed.</p>

```<code>Column1 Column2 Value
A       B       10
A       C       8
B       A       6
</code>```

答:
We can use duplicated after sorting by rows for the subset of columns i.e. using the columns of interest, 1 & 2, and then with the logical vector subset the rows

```<code>df1[!duplicated(t(apply(df1[1:2], 1, sort))),]
#   Column1 Column2 Value
#1       A       B    10
#2       A       C     8
</code>```

Body:
I have a dataframe with three columns. Column 1, Column 2 and third column is Value. Data frame is sorted according to the value (desc). In the below case, I want to remove third row because A>B is already there, so I don't want to consider B>A. How can I remove third column (such instances). This applies to all, for example, A>C is already present, so C>A should be removed.

Column1 Column2 Value
A       B       10
A       C       8
B       A       6

Body:
We can use duplicated after sorting by rows for the subset of columns i.e. using the columns of interest, 1 & 2, and then with the logical vector subset the rows

df1[!duplicated(t(apply(df1[1:2], 1, sort))),]
#   Column1 Column2 Value
#1       A       B    10
#2       A       C     8


问:
While accessing the same angular 2 app on 2 different system ,when i scroll on 1 system, it gets scroll dat same page on another system automatically
My question seems confusing, but pardon me , I am having this dilemma that,
I made an angular2 app, and am running the same app on two different system and while doing so, when I am accessing a page , scrolling it then that same page if opened on another system getting scrolled at the same time automatically.
I dont want my app to work like this.
I have provided a snapshot to support my question.

Scrolling bar happening at the same time on another system for the same page

P.S: I am beginner in Angular 2

答:
Think you need to do something like this, replace your browserSync call with the below and change init of browser sync. More options here

```<code>var browserSync = require("browser-sync").create();

gulp.task('default', function () {
    browserSync.init({
        server: {
            baseDir: "./app",
            ghostMode: false
        }
    });

    gulp.watch('./app/scss/*.scss', ['sass']);
    gulp.watch('./app/*.html',      ['html-watch']);
});
</code>```

Edit: You can just call false for ghost mode without setting each value.

Body:
Think you need to do something like this, replace your browserSync call with the below and change init of browser sync. More options here

var browserSync = require("browser-sync").create();

gulp.task('default', function () {
    browserSync.init({
        server: {
            baseDir: "./app",
            ghostMode: false
        }
    });

    gulp.watch('./app/scss/*.scss', ['sass']);
    gulp.watch('./app/*.html',      ['html-watch']);
});

Edit: You can just call false for ghost mode without setting each value.


问:
What is the easiest way on a binary image to check, if two pixels are connected? (In Matlab)
Consider this binary image:

0 1 0 0 0

0 1 0 0 0

0 1 1 0 0

0 0 0 0 0

0 0 0 1 0

I am looking for a function with two coordinates as parameters, and a boolean return value, which states, if the two pixels are connected (by 4- or 8-connectivity), like this:

f([1,2],[3,3]) -> true;

f([1,2],[5,4]) -> false;

I know, that there must be an easy algorithm, and there are some functions in Matlab, which do much more (bwdist, bwconncomp), but I'm looking for a simpler way.

Thanks for the help!

答:
Your alternatives are to flood fill from one pixel, then check the other, to label all connected components and check the label, or to do A* pathfinding. A* will probably produce the fastest results if most of the pairs are close together but in large shapes, it's also the most complicated of the three methods.

Matlab has labelconnected components built in. It's not a particularly complicated algorithm. If you check my binary image processing library you can find implementations in C of all three methods.

https://github.com/MalcolmMcLean/binaryimagelibrary


问:
Redirect php to youtube app ios
I need to directly link a URL to a youtube video. The idea is if you put the link in a mobile, I must be opened in youtube APP. I didn’t start to try it in an Andriod phone until now. In iOS, I’m not able to open directly in the APP.
I tried it in PHP and in Javascript.

In PHP I used header to make the redirect. But it didn’t work. I also used youtube scheme.

```<code>header("Location: http://www.youtube.com/v/T0WepLbWyq0");
header("Location: https://www.youtube.com/watch?v=T0WepLbWyq0");
header("Location: youtube://www.youtube.com/v/ T0WepLbWyq0");
</code>```

In javascript, I tried the same but with windows.location:

```<code><script>
window.location = "http://www.youtube.com/v/E91WD7sr_hU";

</script>
</code>```

I discovered that if I put a “usual” link () it opens the APP as I want. Then I thought that maybe generating a click in javascript I will solve my issue. But It doesn’t work neither.

```<code> <a id="link-youtube" target="_blank" href="https://www.youtube.com/watch?v=T0WepLbWyq0">
<script>
  document.getElementById("link-youtube").click();
  </script>
</code>```

Can somebody help me, please?

Thanks!

答:
Try with

```<code><script>
window.location = "youtube://E91WD7sr_hU";
</script>
</code>```

Where E91WD7sr_hU is the video path of http://www.youtube.com/v/E91WD7sr_hU

Title: Redirect php to youtube app ios

Body:
I need to directly link a URL to a youtube video. The idea is if you put the link in a mobile, I must be opened in youtube APP. I didn’t start to try it in an Andriod phone until now. In iOS, I’m not able to open directly in the APP.
I tried it in PHP and in Javascript.

In PHP I used header to make the redirect. But it didn’t work. I also used youtube scheme.

header("Location: http://www.youtube.com/v/T0WepLbWyq0");
header("Location: https://www.youtube.com/watch?v=T0WepLbWyq0");
header("Location: youtube://www.youtube.com/v/ T0WepLbWyq0");

In javascript, I tried the same but with windows.location:

I discovered that if I put a “usual” link () it opens the APP as I want. Then I thought that maybe generating a click in javascript I will solve my issue. But It doesn’t work neither.

Can somebody help me, please?

Thanks!

Body:
Try with

<script>
window.location = "youtube://E91WD7sr_hU";
</script>

Where E91WD7sr_hU is the video path of http://www.youtube.com/v/E91WD7sr_hU


问:
I can not change src of imageview from inside non-activity class in Android
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

```<code> LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);
</code>```

Updated: Complete class

```<code>public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}
</code>```

答:
```<code>runOnUiThread(new Runnable() {

   @Override
   public void run() {
       LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View view = inflater.inflate( R.layout.control_address_fragment, null );

    ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

    okaddress.setImageResource(R.drawable.clear);
   }
});
</code>```

Move your UI changes to MainThread. Only these will be reflected

Make use of functino runOnUIThread() this will channel your instructions to mainthread and thus will update UI. You can also move your UI related logic in this api

Body:
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);

Updated: Complete class

public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}

Body:
runOnUiThread(new Runnable() {

   @Override
   public void run() {
       LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View view = inflater.inflate( R.layout.control_address_fragment, null );

    ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

    okaddress.setImageResource(R.drawable.clear);
   }
});

Move your UI changes to MainThread. Only these will be reflected

Make use of functino runOnUIThread() this will channel your instructions to mainthread and thus will update UI. You can also move your UI related logic in this api


问:
Flatbutton(Input handler) doesn't seems to work
I try to use file uploader from materila-ui, but it doesn't seems to work and get the input from selecting file.
 Anyone have any advice how to get the input from file selector and handle it. </p>

```<code><FlatButton
            icon={<i className="material-icons">attachment</i>}
            onclick={e => this._handleChange(e)}
            onchange={e => this._openFileDialog(e)}
          >
            <input type="file" style={styles.uploadInput} />
          </FlatButton>
</code>```

<p>http://material-ui.com/#/components/flat-button </p>

答:
You should wrap the button in a label, and point it at the file input which can be hidden.

```<code><label htmlFor={id}>
  <FlatButton />
</label>
<input type="file" id={id} onChange={(e) => {
  const file = e.target.files[0];
  // do stuff
}}
</code>```

Generate a random id in constructor to use here.

Body:
I try to use file uploader from materila-ui, but it doesn't seems to work and get the input from selecting file.
 Anyone have any advice how to get the input from file selector and handle it.

<FlatButton
            icon={attachment}
            onclick={e => this._handleChange(e)}
            onchange={e => this._openFileDialog(e)}
          >
            <input type="file" style={styles.uploadInput} />
          </FlatButton>

http://material-ui.com/#/components/flat-button

Body:
You should wrap the button in a label, and point it at the file input which can be hidden.

<label htmlFor={id}>
  <FlatButton />
</label>
<input type="file" id={id} onChange={(e) => {
  const file = e.target.files[0];
  // do stuff
}}

Generate a random id in constructor to use here.


问:
iOS Swift Storing Alamofire Response To Realm
I need to store alamofire JSON response to realm storage directly. Here is the response tat I get from alamofire JSON.

```<code>{
  "all": [
    {
      "date": "2017-03-30T00:00:00.000Z",
      "subject": "loe",
      "desc": "",
      "id": 13,
      "number": "19/312/2012",
      "title": "loe",
      "name": "Supreme",
      "type": "Event",
      "practice": 20,
      "contact": "",
      "object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
    },
    {
      "date": "2017-03-30T00:30:00.000Z",
      "subject": "user",
      "desc": "Loe",
      "id": 138,
      "number": "19/312/2012",
      "title": "loe user",
      "name": "Supreme India",
      "type": "Appointment",
      "practice": 6,
      "contact": 91,
      "object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
    }
</code>```

And Here is the code that I have used for realm storage

```<code>class PracticeArea:Object,Mappable
{
    dynamic var contact = 0
    dynamic var id = ""
    dynamic var number = ""
    dynamic var title = ""
    dynamic var name = ""
    dynamic var date = ""
    dynamic var description2 = ""
    dynamic var object = ""
    dynamic var practice = 0
    dynamic var subject = ""
    dynamic var type = ""

    override static func primaryKey() -> String?
    {
        return "contact"
    }

    //Impl. of Mappable protocol
    required convenience init?(map: Map)
    {
        self.init()
    }

    func mapping(map: Map)
    {
        contact    <- map["contact"]
        id <- map["id"]
        number <- map["number"]
        title <- map["title"]
        name <- map["name"]
        date <- map["date"]
        description2 <- map["description"]
        object <- map["object"]
        practice <- map["practice"]
        subject <- map["subject"]
        type <- map["type"]
    }
}
</code>```

Code Used for Storing Values:

```<code>let PracticeTestValues = response.result.value!
let realm:Realm = try! Realm()
                        try! realm.write
                        {
                                for all in PracticeTestValues as! [Any]
                                {
                                    realm.add(all as! Object, update: true)
                                }
                        }
</code>```

答:
I would sugget to use this:</p>

```<code>for all in PracticeTestValues as? NSArray
 {
    realm.add(all as! Object, update: true)
  }
</code>```

Body:
I need to store alamofire JSON response to realm storage directly. Here is the response tat I get from alamofire JSON.

{
  "all": [
    {
      "date": "2017-03-30T00:00:00.000Z",
      "subject": "loe",
      "desc": "",
      "id": 13,
      "number": "19/312/2012",
      "title": "loe",
      "name": "Supreme",
      "type": "Event",
      "practice": 20,
      "contact": "",
      "object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
    },
    {
      "date": "2017-03-30T00:30:00.000Z",
      "subject": "user",
      "desc": "Loe",
      "id": 138,
      "number": "19/312/2012",
      "title": "loe user",
      "name": "Supreme India",
      "type": "Appointment",
      "practice": 6,
      "contact": 91,
      "object": "{\"id\":20,\"id\":13,\"name\":\"loe\",\"time\":\"2017-03-30T00:00:00.000Z\",\"end\":\"2017-03-31T00:00:00.000Z\",\"creator\":\"user\",\"created_by\":132,\"des\":\"\",\"created_at\":\"2017-03-30T08:22:31.150Z\",\"updated_at\":\"2017-03-30T08:23:04.944Z\",\"judge\":null,\"purpose\":null,\"google_event_id\":null,\"is_completed\":false,\"business\":null,\"last_notified\":\"2017-03-30T08:23:04.926Z\",\"next\":null,\"business_date\":null,\"business\":false}"
    }

And Here is the code that I have used for realm storage

class PracticeArea:Object,Mappable
{
    dynamic var contact = 0
    dynamic var id = ""
    dynamic var number = ""
    dynamic var title = ""
    dynamic var name = ""
    dynamic var date = ""
    dynamic var description2 = ""
    dynamic var object = ""
    dynamic var practice = 0
    dynamic var subject = ""
    dynamic var type = ""

    override static func primaryKey() -> String?
    {
        return "contact"
    }

    //Impl. of Mappable protocol
    required convenience init?(map: Map)
    {
        self.init()
    }

    func mapping(map: Map)
    {
        contact    <- map["contact"]
        id <- map["id"]
        number <- map["number"]
        title <- map["title"]
        name <- map["name"]
        date <- map["date"]
        description2 <- map["description"]
        object <- map["object"]
        practice <- map["practice"]
        subject <- map["subject"]
        type <- map["type"]
    }
}

Code Used for Storing Values:

let PracticeTestValues = response.result.value!
let realm:Realm = try! Realm()
                        try! realm.write
                        {
                                for all in PracticeTestValues as! [Any]
                                {
                                    realm.add(all as! Object, update: true)
                                }
                        }

Body:
I would sugget to use this:

for all in PracticeTestValues as? NSArray
 {
    realm.add(all as! Object, update: true)
  }


问:
RadRichTextBox ContextMenu Click Event WPF
In a scenario i need to handle the click event of a menu inside the default ContextMenu of RadRichTextBox. Is there anyway that i can get click event of the "Edit Hyperlink" in the ContextMenu?

Or do i have any alternate solution?

答:
You could handle the RadMenuItem.Click event:

```<code><telerik:RadRichTextBox x:Name="rtb" telerik:RadMenuItem.Click="rtb_Click" />
</code>```

```<code>private void rtb_Click(object sender, RoutedEventArgs e)
{
    Telerik.Windows.Controls.RadMenuItem item = e.OriginalSource as Telerik.Windows.Controls.RadMenuItem;
    if (item != null && item.Header != null && item.Header.ToString() == "Edit Hyperlink...")
    {
        //...
    }
}
</code>```

Body:
You could handle the RadMenuItem.Click event:

<telerik:RadRichTextBox x:Name="rtb" telerik:RadMenuItem.Click="rtb_Click" />

private void rtb_Click(object sender, RoutedEventArgs e)
{
    Telerik.Windows.Controls.RadMenuItem item = e.OriginalSource as Telerik.Windows.Controls.RadMenuItem;
    if (item != null && item.Header != null && item.Header.ToString() == "Edit Hyperlink...")
    {
        //...
    }
}