问:
Creating several windows around a date
I am working with a dataset which has several stocks and I merged a data set with events onto it (for the stocks, several events in the period per stock).

Now, for an event study, I want to create several variables that act as dummies and create windows: -60 to -11 days, -5 to -1 day and announcement day plus day +1.
Important are two things:

It has to be by Stock (the windows should not be carried over between stocks)

one announcement/event day (ann_day) should not spoil another event's window.

I tried the following but it is just giving me a window and does not account for different stocks and spoiled windows:

```<code>proc sql;
   create view event_study as
   select distinct b.ann_date,a.date,a.dayid-b.dayid as event_time, a.stock,a.return
   from Dataset_full as a,Announcements as b
   where a.dayid-b.dayid between -60 and 11 and a.secid=b.secid
   order by a.stockb.ann_date,event_time;
quit;
</code>```

Some info: announcement days are the events
dataset_full has the stock, date, return, volume.  One row per calendar/trading day.
Announcement has stock, announcement date and announcement info (one row per announcement)
Data should look like this:

```<code>Stock   Date    Ann_date    flag_minus60_minus11    flag_minus5_minus1  flag_day0_day1
A   1/01/2016           1
A   2/01/2016           1
A   3/01/2016
A   4/01/2016   4/01/2016           1
A   5/01/2016               1
A   6/01/2016
A   7/01/2016
A   8/01/2016
A   9/01/2016
A   10/01/2016
A   11/01/2016
A   12/01/2016
A   13/01/2016
A   14/01/2016
A   15/01/2016
B   1/01/2016       1
B   2/01/2016       1
B   3/01/2016       1
B   4/01/2016       1
B   5/01/2016       1
B   6/01/2016       1
B   7/01/2016
B   8/01/2016
B   9/01/2016
B   10/01/2016
B   11/01/2016          1
B   12/01/2016          1
B   13/01/2016          1
B   14/01/2016          1
B   15/01/2016          1
B   16/01/2016  16/01/2016          1
B   17/01/2016              1
B   18/01/2016          1
B   19/01/2016          1
B   20/01/2016  20/01/2016          1
B   21/01/2016              1
B   22/01/2016
B   23/01/2016
B   24/01/2016
B   25/01/2016
</code>```

答:
MaBo:

Here is some sample data and SQL.  When you examine the output, I presume you will see 'spoiled' information -- that being a date with more than one future announcement in the flagging time frame.

The issue of flagging trading dates with respect to an event date is inner join.  The inner join has to be performed for each flag being computed, and that inner join needs to be left joined to the trading data to get your 'want'.

```<code>data trading;
  do group = 1 to 4;
    do date = today()-1000 to today(); format date yymmdd10.;
      output;
    end;
  end;
run;

data announcement;
  do group = 1 to 4;
    do date = today()-1000 to today(); format date yymmdd10.;
      if ranuni(123) < 0.01 then output;
    end;
  end;
run;

proc sql;
  create table trading_pre_announce_flagged as
  select
    trading.*
  , announcement.date as annouce_date
  , case when P0.date is not null then 1 else . end as P0_flag label="Announcement was today or yesterday"
  , case when P1.date is not null then 1 else . end as P1_flag label="Announcement in 1 to 5 days"
  , case when P2.date is not null then 1 else . end as P2_flag label="Announcement in 11 to 60 days"
  , case when P2.date is not null then P2.adate else . end as P2_date label="Date of Announcement in 11 to 60 days" format=yymmdd10.

  from
    trading
  left join
    announcement
    on announcement.date = trading.date and announcement.group = trading.group
  left join
    ( select trading.group, trading.date
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
        and announcement.date - trading.date between -1 and 0
    ) as P0
    on P0.date = trading.date and P0.group = trading.group
  left join
    ( select trading.group, trading.date
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
        and announcement.date - trading.date between 1 and 5
    ) as P1
    on P1.date = trading.date and P1.group = trading.group
  left join
    ( select trading.group, trading.date, announcement.date as adate
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
      where announcement.date - trading.date between 11 and 60
    ) as P2
    on P2.date = trading.date and P2.group = trading.group
  order
    by trading.group, trading.date
  ;
quit;
</code>```

At some point (can't find it though) the OP mentioned processing ~750 companies and 500 overall events, and that the SQL solution seemed to be long running.

An alternative would be DATA Step.

The 500 events is a small enough cardinality where arrays of group and date could be used to store the events for lookup. Smart index tracking of the sorted events can be used for doing a minimum scan for evaluating the rules and applying the condition flags.

For example:

```<code>data trading;
  do group = 1 to 700;
    do date = today()-1000 to today(); format date yymmdd10.;
      output;
    end;
  end;
run;

data announcement;
  do eventid = 1 to 500;
    group = ceil(700*ranuni(123));
    date = (today()-1000) + ceil(1000*ranuni(123)); format date yymmdd10.;
    if mod(eventid,20) = 1 then do;
      output;
      eventid+1;
      date = date + 30 + floor(100*ranuni(123));
      output;
      eventid+1;
      date = date + 30 + floor(100*ranuni(123));
    end;
    output;
  end;
run;

proc sort data=announcement;
  by group date;
run;

data _null_;
  if 0 then set announcement nobs=nobs;
  call symputx ('top', nobs+1);
run;

data marked_trading;
  array e_group(0:&TOP) _temporary_;
  array e_date (0:&TOP) _temporary_;

  * load event array;
  do _n_ = 1 by 1 until (last_announcement);
    set announcement end=last_announcement;
    e_group(_n_) = group;
    e_date(_n_) = date;

    eix0 = 1;
    eix1 = 1;
  end;

  e_group(0) = 0; * sentinel;
  e_group(_n_) = 1e9; *sentinel;

  * evaluate flagging criteria for each trade group date;
  do _n_ = 1 by 1 until (last_trading);
    set trading end=last_trading;
    by group;
    if first.group then do;
      * discover indices of events associated with the group;
      do eix0 = eix0 by 1 while (e_group(eix0) < group); end;
      do eix1 = eix0 by 1 while (e_group(eix1) = group); end; eix1 = eix1 - 1;
      eix_group = e_group(eix0);
    end;

    p3_flag = .; p2_flag = .; p1_flag = .;
    if group = eix_group then do;
      * NOTE: bounds are evaluated only at loop initialization;
      * evaluate events for flagging a trade;
      do ix = eix0 to eix1;
        days_to_event = e_date(ix) - date;

        if not p3_flag then if 11 <= days_to_event <= 60 then p3_flag = 1;
        if not p2_flag then if  1 <= days_to_event <= 5  then p2_flag = 1;
        if not p1_flag then if -1 <= days_to_event <= 0  then p1_flag = 1;

        if days_to_event <= -1 then eix0 = ix+1; * update when applicability exhausted;
      end;
    end;

    output;
  end;

  keep group date p:;

  stop;
run;
</code>```

Title: Creating several windows around a date

Body:
I am working with a dataset which has several stocks and I merged a data set with events onto it (for the stocks, several events in the period per stock).

Now, for an event study, I want to create several variables that act as dummies and create windows: -60 to -11 days, -5 to -1 day and announcement day plus day +1.
Important are two things:

It has to be by Stock (the windows should not be carried over between stocks)

one announcement/event day (ann_day) should not spoil another event's window.

I tried the following but it is just giving me a window and does not account for different stocks and spoiled windows:

proc sql;
   create view event_study as
   select distinct b.ann_date,a.date,a.dayid-b.dayid as event_time, a.stock,a.return
   from Dataset_full as a,Announcements as b
   where a.dayid-b.dayid between -60 and 11 and a.secid=b.secid
   order by a.stockb.ann_date,event_time;
quit;

Some info: announcement days are the events
dataset_full has the stock, date, return, volume.  One row per calendar/trading day.
Announcement has stock, announcement date and announcement info (one row per announcement)
Data should look like this:

Stock   Date    Ann_date    flag_minus60_minus11    flag_minus5_minus1  flag_day0_day1
A   1/01/2016           1
A   2/01/2016           1
A   3/01/2016
A   4/01/2016   4/01/2016           1
A   5/01/2016               1
A   6/01/2016
A   7/01/2016
A   8/01/2016
A   9/01/2016
A   10/01/2016
A   11/01/2016
A   12/01/2016
A   13/01/2016
A   14/01/2016
A   15/01/2016
B   1/01/2016       1
B   2/01/2016       1
B   3/01/2016       1
B   4/01/2016       1
B   5/01/2016       1
B   6/01/2016       1
B   7/01/2016
B   8/01/2016
B   9/01/2016
B   10/01/2016
B   11/01/2016          1
B   12/01/2016          1
B   13/01/2016          1
B   14/01/2016          1
B   15/01/2016          1
B   16/01/2016  16/01/2016          1
B   17/01/2016              1
B   18/01/2016          1
B   19/01/2016          1
B   20/01/2016  20/01/2016          1
B   21/01/2016              1
B   22/01/2016
B   23/01/2016
B   24/01/2016
B   25/01/2016

Body:
MaBo:

Here is some sample data and SQL.  When you examine the output, I presume you will see 'spoiled' information -- that being a date with more than one future announcement in the flagging time frame.

The issue of flagging trading dates with respect to an event date is inner join.  The inner join has to be performed for each flag being computed, and that inner join needs to be left joined to the trading data to get your 'want'.

data trading;
  do group = 1 to 4;
    do date = today()-1000 to today(); format date yymmdd10.;
      output;
    end;
  end;
run;

data announcement;
  do group = 1 to 4;
    do date = today()-1000 to today(); format date yymmdd10.;
      if ranuni(123) < 0.01 then output;
    end;
  end;
run;

proc sql;
  create table trading_pre_announce_flagged as
  select
    trading.*
  , announcement.date as annouce_date
  , case when P0.date is not null then 1 else . end as P0_flag label="Announcement was today or yesterday"
  , case when P1.date is not null then 1 else . end as P1_flag label="Announcement in 1 to 5 days"
  , case when P2.date is not null then 1 else . end as P2_flag label="Announcement in 11 to 60 days"
  , case when P2.date is not null then P2.adate else . end as P2_date label="Date of Announcement in 11 to 60 days" format=yymmdd10.

  from
    trading
  left join
    announcement
    on announcement.date = trading.date and announcement.group = trading.group
  left join
    ( select trading.group, trading.date
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
        and announcement.date - trading.date between -1 and 0
    ) as P0
    on P0.date = trading.date and P0.group = trading.group
  left join
    ( select trading.group, trading.date
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
        and announcement.date - trading.date between 1 and 5
    ) as P1
    on P1.date = trading.date and P1.group = trading.group
  left join
    ( select trading.group, trading.date, announcement.date as adate
      from trading
      inner join
      announcement
      on    announcement.group = trading.group
      where announcement.date - trading.date between 11 and 60
    ) as P2
    on P2.date = trading.date and P2.group = trading.group
  order
    by trading.group, trading.date
  ;
quit;

At some point (can't find it though) the OP mentioned processing ~750 companies and 500 overall events, and that the SQL solution seemed to be long running.

An alternative would be DATA Step.

The 500 events is a small enough cardinality where arrays of group and date could be used to store the events for lookup. Smart index tracking of the sorted events can be used for doing a minimum scan for evaluating the rules and applying the condition flags.

For example:

data trading;
  do group = 1 to 700;
    do date = today()-1000 to today(); format date yymmdd10.;
      output;
    end;
  end;
run;

data announcement;
  do eventid = 1 to 500;
    group = ceil(700*ranuni(123));
    date = (today()-1000) + ceil(1000*ranuni(123)); format date yymmdd10.;
    if mod(eventid,20) = 1 then do;
      output;
      eventid+1;
      date = date + 30 + floor(100*ranuni(123));
      output;
      eventid+1;
      date = date + 30 + floor(100*ranuni(123));
    end;
    output;
  end;
run;

proc sort data=announcement;
  by group date;
run;

data _null_;
  if 0 then set announcement nobs=nobs;
  call symputx ('top', nobs+1);
run;

data marked_trading;
  array e_group(0:&TOP) _temporary_;
  array e_date (0:&TOP) _temporary_;

  * load event array;
  do _n_ = 1 by 1 until (last_announcement);
    set announcement end=last_announcement;
    e_group(_n_) = group;
    e_date(_n_) = date;

    eix0 = 1;
    eix1 = 1;
  end;

  e_group(0) = 0; * sentinel;
  e_group(_n_) = 1e9; *sentinel;

  * evaluate flagging criteria for each trade group date;
  do _n_ = 1 by 1 until (last_trading);
    set trading end=last_trading;
    by group;
    if first.group then do;
      * discover indices of events associated with the group;
      do eix0 = eix0 by 1 while (e_group(eix0) < group); end;
      do eix1 = eix0 by 1 while (e_group(eix1) = group); end; eix1 = eix1 - 1;
      eix_group = e_group(eix0);
    end;

    p3_flag = .; p2_flag = .; p1_flag = .;
    if group = eix_group then do;
      * NOTE: bounds are evaluated only at loop initialization;
      * evaluate events for flagging a trade;
      do ix = eix0 to eix1;
        days_to_event = e_date(ix) - date;

        if not p3_flag then if 11 <= days_to_event <= 60 then p3_flag = 1;
        if not p2_flag then if  1 <= days_to_event <= 5  then p2_flag = 1;
        if not p1_flag then if -1 <= days_to_event <= 0  then p1_flag = 1;

        if days_to_event <= -1 then eix0 = ix+1; * update when applicability exhausted;
      end;
    end;

    output;
  end;

  keep group date p:;

  stop;
run;


来源: stackexchange

问:
How to set MessageDigest seed?
The MessageDigest class implements the SHA-1 algorithm (among many others).  The SHA-1 algorithm allows one to use different "seeds" or initial digests.  See SHA-1 Psuedocode

The algorithm initializes variables, or the seed:

```<code>Initialize variables:
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0
</code>```

However the MessageDigest class, as described in the Online Java Manual, provides no API for setting these initial variables.  In fact, it doesn't state the value of the initial variables.

How can I set the initial seed for the SHA-1 algorithm?

Where is an example of SHA-1 in Java, USING AN INITIAL SEED?

(I'm looking for the SHA-1 implementation, unless the example uses MessageDigest with an alternative initial seed.)

答:
I recommend using a salt instead of a seed for MessageDigest family hash functions.  A salt is applied by, for example, prepending the salt bytes to the input.

Prepending a salt is also more powerful than directly setting the seed values, because in addition to changing the internal state of the hash, if the salt is not a multiple of the digest block size then it can also perturb the alignment with which the input is fed into the hash function.

ContentLicense: CC BY-SA 2.5

Title: How to set MessageDigest seed?

Body:
The MessageDigest class implements the SHA-1 algorithm (among many others).  The SHA-1 algorithm allows one to use different "seeds" or initial digests.  See SHA-1 Psuedocode

The algorithm initializes variables, or the seed:

Initialize variables:
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0

However the MessageDigest class, as described in the Online Java Manual, provides no API for setting these initial variables.  In fact, it doesn't state the value of the initial variables.

How can I set the initial seed for the SHA-1 algorithm?

Where is an example of SHA-1 in Java, USING AN INITIAL SEED?

(I'm looking for the SHA-1 implementation, unless the example uses MessageDigest with an alternative initial seed.)


问:
Background applied to the controller not getting applied to table view cells in storyboard swift
I have a storyboard consisting of a background image on top of which rests a table. My issue is that the background image gets applied to the table but not to the cells of the table, they still remain white.

What is it that I am doing wrong?
Please help

答:
in cellForRowAtIndexpath method, use

```<code>cell.backgroundColor = UIColor.clear
</code>```

ContentLicense: CC BY-SA 3.0

Body:
in cellForRowAtIndexpath method, use

cell.backgroundColor = UIColor.clear


问:
Why Same where clause need to write multiple times in a Linq Query for following SQL
What will be the proper linq syntax of below SQL Query ?

```<code>select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2
</code>```

Problem I faced:

I required to filter Where Condition two times 1st at the time within the join & 2nd time during the object.Select expression, please check bellow

```<code>var results = (from a in appointments
                                   join ad in _appointmentDetailRepository.GetAll() on a.ID equals ad.AppointmentID
                                   where ad.ApprovalStatusID == 2
                                   && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   orderby a.ID
                                   select new Appointment
                                   {
                                       ID = a.ID,
                                       CompanyID = a.CompanyID,
                                       LocationID = a.LocationID,
                                       AppointmentDetail = a.AppointmentDetail.Select(ad => new AppointmentDetail
                                       {
                                           ID = ad.ID,
                                           AppDateFrom = ad.AppDateFrom,
                                           AppDateTo = ad.AppDateTo,
                                           AppointmentStatusID = ad.AppointmentStatusID,
}).Where(ad=> ad.ApprovalStatusID == 2
                                        && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                        && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)).ToList()
 }).GroupBy(x => x.ID).Select(x => x.DefaultIfEmpty().FirstOrDefault());
</code>```

Query : Why I required to write Where clause 2 times ?

Required Result

An Appointment Object --> Containing ICollection<AppoinmentDetails> if Details.Where Condition == True

答:
For the given SQL query

```<code>select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2
</code>```

LINQ query can be written as

```<code>var results = (from a in appointments
                       join ad in appointmentDetails on a.ID equals ad.AppointmentID
                       where ad.ApprovalStatusID == 2
                           && a.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                           && a.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t"
                           && ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                           && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                       select new
                       {
                           ID = a.ID,
                           AppointmentStatusID = a.AppointmentStatusID,
                           DetailID = ad.ID
                       }).ToList();
</code>```

You can also write it like

```<code>var results = appointmentDetails
                        .Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                                && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                                && ad.ApprovalStatusID == 2
                                && ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                                && ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
                        .Select(ad =>
                        new
                        {
                            ID = ad.Appointment.ID,
                            AppointmentStatusID = ad.Appointment.AppointmentStatusID,
                            DetailID = ad.ID
                        })
                        .ToList()
</code>```

As per the updated question, to get the the Appointment object with a collection of AppointmentDetails, please try this query

```<code>var results = appointmentDetails
                        .Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                                && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                                && ad.ApprovalStatusID == 2
                                && ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                                && ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
                        .Select(ad =>
                        new
                        {
                            ID = ad.Appointment.ID,
                            AppointmentStatusID = ad.Appointment.AppointmentStatusID,
                            Detail = ad
                        })
                        .AsEnumerable()
                        .GroupBy(a => new { a.ID, a.AppointmentStatusID })
                        .Select(a => new Appointment
                        {
                            ID = a.Key.ID,
                            AppointmentStatusID = a.Key.AppointmentStatusID,
                            AppointmentDetails = a.Select(d => d.Detail).ToList()
                        })
                        .ToList();
</code>```

Body:
What will be the proper linq syntax of below SQL Query ?

select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2

Problem I faced:

I required to filter Where Condition two times 1st at the time within the join & 2nd time during the object.Select expression, please check bellow

var results = (from a in appointments
                                   join ad in _appointmentDetailRepository.GetAll() on a.ID equals ad.AppointmentID
                                   where ad.ApprovalStatusID == 2
                                   && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   orderby a.ID
                                   select new Appointment
                                   {
                                       ID = a.ID,
                                       CompanyID = a.CompanyID,
                                       LocationID = a.LocationID,
                                       AppointmentDetail = a.AppointmentDetail.Select(ad => new AppointmentDetail
                                       {
                                           ID = ad.ID,
                                           AppDateFrom = ad.AppDateFrom,
                                           AppDateTo = ad.AppDateTo,
                                           AppointmentStatusID = ad.AppointmentStatusID,
}).Where(ad=> ad.ApprovalStatusID == 2
                                        && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                        && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)).ToList()
 }).GroupBy(x => x.ID).Select(x => x.DefaultIfEmpty().FirstOrDefault());

Query : Why I required to write Where clause 2 times ?

Required Result

An Appointment Object --> Containing ICollection<AppoinmentDetails> if Details.Where Condition == True

Body:
For the given SQL query

select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2

LINQ query can be written as

var results = (from a in appointments
                       join ad in appointmentDetails on a.ID equals ad.AppointmentID
                       where ad.ApprovalStatusID == 2
                           && a.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                           && a.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t"
                           && ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                           && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                       select new
                       {
                           ID = a.ID,
                           AppointmentStatusID = a.AppointmentStatusID,
                           DetailID = ad.ID
                       }).ToList();

You can also write it like

var results = appointmentDetails
                        .Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                                && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                                && ad.ApprovalStatusID == 2
                                && ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                                && ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
                        .Select(ad =>
                        new
                        {
                            ID = ad.Appointment.ID,
                            AppointmentStatusID = ad.Appointment.AppointmentStatusID,
                            DetailID = ad.ID
                        })
                        .ToList()

As per the updated question, to get the the Appointment object with a collection of AppointmentDetails, please try this query

var results = appointmentDetails
                        .Where(ad => ad.AppDateFrom.Date <= viewmodel.AppointmentDate.Date
                                && ad.AppDateTo.Date >= viewmodel.AppointmentDate.Date
                                && ad.ApprovalStatusID == 2
                                && ad.Appointment.CompanyID == "a3dea87a-804e-4115-98cf-472988cf1678"
                                && ad.Appointment.LocationID == "3165caca-2a48-46f0-bbed-578cff29167t")
                        .Select(ad =>
                        new
                        {
                            ID = ad.Appointment.ID,
                            AppointmentStatusID = ad.Appointment.AppointmentStatusID,
                            Detail = ad
                        })
                        .AsEnumerable()
                        .GroupBy(a => new { a.ID, a.AppointmentStatusID })
                        .Select(a => new Appointment
                        {
                            ID = a.Key.ID,
                            AppointmentStatusID = a.Key.AppointmentStatusID,
                            AppointmentDetails = a.Select(d => d.Detail).ToList()
                        })
                        .ToList();


问:
Kafka console producer not allowing to write message
I am trying to write some message on topic, but console is not allowing me(producer not waiting for stdin input). I cant see any error log too. Topic is created successfully though.
I am using :

```<code>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test.
</code>```

Zookeeper and kafka server are running fine. I am using Mac. What could be the possible issue.
I am following Apache Kafka documentation http://kafka.apache.org/documentation.html#quickstart.

答: kafka-console-producer.sh file is empty. I faced the same issue. The solution is to replace kafka-console-producer.sh with a fresh one. This might be an issue that happens only on Mac OS.

Body:
I am trying to write some message on topic, but console is not allowing me(producer not waiting for stdin input). I cant see any error log too. Topic is created successfully though.
I am using :

bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test.

Zookeeper and kafka server are running fine. I am using Mac. What could be the possible issue.
I am following Apache Kafka documentation http://kafka.apache.org/documentation.html#quickstart.

ContentLicense: CC BY-SA 4.0


问:
Exporting print statements to external file
So I'm trying to teach myself , and Ive been doing online lab exercises to learn it. I wrote a program that goes into pretty good detail of arrays and structures. It uses random numbers to monitor for a spike of 100 psi, and then prints that as a 0 point, and prints the previous 10 seconds of the array and the next 10, as if I was collecting data. The next part of this exercise is to take the program's print statement, and have it write to an external file and have it print there. My thought process is to populate an array in the  printout  function  that  holds  the  values  read  from  the  file  and  then  print from the array to screen. But I'm not sure how this would look, or really how to accomplish it. If anyone could point me in the right direction or give a good explanation it would be greatly appreciated!

My code so far:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define MAX_CHANGE      100
#define ARRAY_SIZE      21

typedef struct data_slice
{
        int t;          // -> Time
        float tp;       // -> Valve pressure
    float tf;       // -> Sodium flow
    float tt;       // -> Sodium temp in Celsius
} data_slice;

// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);

int main()
{
    srand((unsigned int)time(NULL));
    data_slice data[ARRAY_SIZE];
    int index = -1;

    while (1)
    {
        // Initialize the entire array
        initializeArray(data);

                    // If there's a spike.....
        if (spikeValueRecorded(data, index))
        {
            // Set the previous "time" in array to negatives
            int temp = index;
            for (int i = 0; i >= -10; --i)
            {
                data[temp].t = i;
                temp = temp - 1;
                if (temp < 0)
                    temp = temp + ARRAY_SIZE;
            }

                // Record for 10 more seconds
            for (int i = 0; i <= 10; ++i)
            {
                data[index].t = i;
                index = (index + 1) % ARRAY_SIZE; //         Increment the index of the circular array
                get_values(&data[index].tp, &data[index].tf,    &data[index].tt);       // "Record" the values
            }
            break;
        }
    }
    // Print the finished recording
    printIt(data);
}

// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
    *pressure   = (float)(rand() % (700 - 500 + 1) + 500);  //    Range: 500 - 700
    *flow       = (float)(rand() % (20 - 10 + 1) + 10);     //   Range: 10 - 20
    *temp       = (float)(rand() % (200 - 100 + 1) + 100);  //  Range: 100 - 200
}

// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }
}

// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their   times to 0
void initializeArray(data_slice * data)
{
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        data[i].t = 0;
        get_values(&data[i].tp, &data[i].tf, &data[i].tt);
    }
}

// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been   recorded.
//      outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
    float oldValue = data[0].tp;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].tp - oldValue < MAX_CHANGE)
        {
            outputIndex = i;
            return true;
        }
    }
    outputIndex = -1;
    return false;
}
</code>```

答:
You can use the fprintf call exactly like the printf call, with one difference. The first argument will be a pointer to a file handle (FILE*) which you create using a call to fopen("full or relative path","w").

The string format is now the second argument and the variable args list starts at arg 3

Body:
So I'm trying to teach myself , and Ive been doing online lab exercises to learn it. I wrote a program that goes into pretty good detail of arrays and structures. It uses random numbers to monitor for a spike of 100 psi, and then prints that as a 0 point, and prints the previous 10 seconds of the array and the next 10, as if I was collecting data. The next part of this exercise is to take the program's print statement, and have it write to an external file and have it print there. My thought process is to populate an array in the  printout  function  that  holds  the  values  read  from  the  file  and  then  print from the array to screen. But I'm not sure how this would look, or really how to accomplish it. If anyone could point me in the right direction or give a good explanation it would be greatly appreciated!

My code so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define MAX_CHANGE      100
#define ARRAY_SIZE      21

typedef struct data_slice
{
        int t;          // -> Time
        float tp;       // -> Valve pressure
    float tf;       // -> Sodium flow
    float tt;       // -> Sodium temp in Celsius
} data_slice;

// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);

int main()
{
    srand((unsigned int)time(NULL));
    data_slice data[ARRAY_SIZE];
    int index = -1;

    while (1)
    {
        // Initialize the entire array
        initializeArray(data);

                    // If there's a spike.....
        if (spikeValueRecorded(data, index))
        {
            // Set the previous "time" in array to negatives
            int temp = index;
            for (int i = 0; i >= -10; --i)
            {
                data[temp].t = i;
                temp = temp - 1;
                if (temp < 0)
                    temp = temp + ARRAY_SIZE;
            }

                // Record for 10 more seconds
            for (int i = 0; i <= 10; ++i)
            {
                data[index].t = i;
                index = (index + 1) % ARRAY_SIZE; //         Increment the index of the circular array
                get_values(&data[index].tp, &data[index].tf,    &data[index].tt);       // "Record" the values
            }
            break;
        }
    }
    // Print the finished recording
    printIt(data);
}

// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
    *pressure   = (float)(rand() % (700 - 500 + 1) + 500);  //    Range: 500 - 700
    *flow       = (float)(rand() % (20 - 10 + 1) + 10);     //   Range: 10 - 20
    *temp       = (float)(rand() % (200 - 100 + 1) + 100);  //  Range: 100 - 200
}

// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }
}

// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their   times to 0
void initializeArray(data_slice * data)
{
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        data[i].t = 0;
        get_values(&data[i].tp, &data[i].tf, &data[i].tt);
    }
}

// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been   recorded.
//      outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
    float oldValue = data[0].tp;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].tp - oldValue < MAX_CHANGE)
        {
            outputIndex = i;
            return true;
        }
    }
    outputIndex = -1;
    return false;
}


问:
Laravel 5.5 - Pivot tables and hasMany relationship
Let's say I have this following. 4 tables and 3 models (Role, Posts, Users).

A User can be assigned many Roles and Roles can be assigned to many Users.

Posts can created with one Role per entry in the database.

What I need help with

I want to be able to grab a list of all posts of a user from their associated roles. So by calling auth()->user()->getPosts(), I should get all Posts from Roles that are attached to a User. I thought I could use hasManyThrough but I don't see it can help my case as I get: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'field list' (SQL: selectposts.*,roles.user_idfrompostsinner joinrolesonroles.id=posts.role_idwhereroles.user_id= 1)

Here are my models thus far:

User.php

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->hasManyThrough(Posts::class, Role::class);
    }
}
</code>```

Role.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}
</code>```

Posts.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    public function roles()
    {
        return $this->hasMany(Role::class);
    }
}
</code>```

Clone this problem here: https://github.com/naknode/eloquent-help

答:
Forget about hasManyThrough, I was wrong.

Here how you can do it:

```<code>    $user = User::with('roles')->first();

    $userPosts = Posts::whereIn('role_id', $user->roles->pluck('id')->toArray())->get();

    return $userPosts;
</code>```

If you want to get the posts by calling auth()->user()->getPosts() add the following method to your User model:

```<code>public function getPosts()
{
    return Posts::whereIn('role_id', $this->roles->pluck('id')->toArray())->get();
}
</code>```

Body:
Let's say I have this following. 4 tables and 3 models (Role, Posts, Users).

A User can be assigned many Roles and Roles can be assigned to many Users.

Posts can created with one Role per entry in the database.

What I need help with

I want to be able to grab a list of all posts of a user from their associated roles. So by calling auth()->user()->getPosts(), I should get all Posts from Roles that are attached to a User. I thought I could use hasManyThrough but I don't see it can help my case as I get: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'field list' (SQL: selectposts.*,roles.user_idfrompostsinner joinrolesonroles.id=posts.role_idwhereroles.user_id= 1)

Here are my models thus far:

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->hasManyThrough(Posts::class, Role::class);
    }
}

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

Posts.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    public function roles()
    {
        return $this->hasMany(Role::class);
    }
}

Clone this problem here: https://github.com/naknode/eloquent-help

Body:
Forget about hasManyThrough, I was wrong.

Here how you can do it:

    $user = User::with('roles')->first();

    $userPosts = Posts::whereIn('role_id', $user->roles->pluck('id')->toArray())->get();

    return $userPosts;

If you want to get the posts by calling auth()->user()->getPosts() add the following method to your User model:

public function getPosts()
{
    return Posts::whereIn('role_id', $this->roles->pluck('id')->toArray())->get();
}


问:
Library depend on a header file
Let's assume I have a project with a series of libraries. I also need to generate a header file that will be used by all of these projects. So I created a CMake file, like this:

```<code>project(main)

add_subdirectory(sub_1)
add_subdirectory(sub_2)
# ...
add_subdirectory(sub_n)

add_custom_command(
    OUTPUT CustomHeader.h
    COMMENT "Generating custom header for all the libraries"
    COMMAND ...)

add_library(${PROJECT_NAME} STATIC ${OBJECT_LIST})
</code>```

The problem is, that I don't know how to tell CMake to run my custom command (that generates this CustomHeader.h) before it would try to build the libraries in the subfolders.

I tried add_custom_target(TARGET MyPrebuild PRE_BUILD ...) but I'm running on Linux, and this option only works on Windows platform according to the documentation.

add_dependencies only work between targets, and not a target and a single file.

I could, in theory, add the header to be among the source files of the individual libraries (in the sub_1, .., sub_n folders) but it feels wrong, as the header is not required to be part of those libraries.

So I just have no idea how I can make a library depend on an include file, that is not part of it.

Any tips how I can overcome this problem?

答:
I would suggest to add another library target that will both keep track of the generated headers and will help to properly configure other libraries to know where to find them (i.e. target_include_directories).

```<code>cmake_minimum_required(VERSION 3.0)
project(testable)

set(CustomHeaderInPath ${CMAKE_CURRENT_SOURCE_DIR}/CustomHeader.example)
set(CustomHeaderPath ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

add_custom_command(
    OUTPUT ${CustomHeaderPath}
    COMMAND cp ${CustomHeaderInPath} ${CustomHeaderPath}
    COMMENT "Generated file"
    DEPENDS ${CustomHeaderInPath})

add_library(CustomHeaderLibrary ${CustomHeaderPath})
target_include_directories(CustomHeaderLibrary PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
set_target_properties(CustomHeaderLibrary PROPERTIES LINKER_LANGUAGE C)

add_library(LibA a.c)
target_link_libraries(LibA CustomHeaderLibrary)

add_library(LibB b.c)
target_link_libraries(LibB CustomHeaderLibrary)

add_executable(${PROJECT_NAME} main.c)
target_link_libraries(${PROJECT_NAME} PUBLIC LibA LibB)
</code>```

Note that I had to explicitly set the LINKER_LANGUAGE of the new target as cmake won't be able to deduce it properly if no c or cpp files are added to the library.

Title: Library depend on a header file

Body:
Let's assume I have a project with a series of libraries. I also need to generate a header file that will be used by all of these projects. So I created a CMake file, like this:

project(main)

add_subdirectory(sub_1)
add_subdirectory(sub_2)
# ...
add_subdirectory(sub_n)

add_custom_command(
    OUTPUT CustomHeader.h
    COMMENT "Generating custom header for all the libraries"
    COMMAND ...)

add_library(${PROJECT_NAME} STATIC ${OBJECT_LIST})

The problem is, that I don't know how to tell CMake to run my custom command (that generates this CustomHeader.h) before it would try to build the libraries in the subfolders.

I tried add_custom_target(TARGET MyPrebuild PRE_BUILD ...) but I'm running on Linux, and this option only works on Windows platform according to the documentation.

add_dependencies only work between targets, and not a target and a single file.

I could, in theory, add the header to be among the source files of the individual libraries (in the sub_1, .., sub_n folders) but it feels wrong, as the header is not required to be part of those libraries.

So I just have no idea how I can make a library depend on an include file, that is not part of it.

Any tips how I can overcome this problem?

Body:
I would suggest to add another library target that will both keep track of the generated headers and will help to properly configure other libraries to know where to find them (i.e. target_include_directories).

cmake_minimum_required(VERSION 3.0)
project(testable)

set(CustomHeaderInPath ${CMAKE_CURRENT_SOURCE_DIR}/CustomHeader.example)
set(CustomHeaderPath ${CMAKE_CURRENT_BINARY_DIR}/CustomHeader.h)

add_custom_command(
    OUTPUT ${CustomHeaderPath}
    COMMAND cp ${CustomHeaderInPath} ${CustomHeaderPath}
    COMMENT "Generated file"
    DEPENDS ${CustomHeaderInPath})

add_library(CustomHeaderLibrary ${CustomHeaderPath})
target_include_directories(CustomHeaderLibrary PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
set_target_properties(CustomHeaderLibrary PROPERTIES LINKER_LANGUAGE C)

add_library(LibA a.c)
target_link_libraries(LibA CustomHeaderLibrary)

add_library(LibB b.c)
target_link_libraries(LibB CustomHeaderLibrary)

add_executable(${PROJECT_NAME} main.c)
target_link_libraries(${PROJECT_NAME} PUBLIC LibA LibB)

Note that I had to explicitly set the LINKER_LANGUAGE of the new target as cmake won't be able to deduce it properly if no c or cpp files are added to the library.


问:
extract particular columns from matrix and store it as a new matrix in C
I have a matrix stored as a dynamic array i.e. double *inputMat. I know its number of rows and columns through which I can extract any particular column. Now issue is, I have a set of columns to be extracted and stored into another dynamic array. How to do this? I am writing a portion of my code for reference:

```<code>double *extractMatrix(double *inputMat,int rows, int *columnIndex, int columnTotal)
{
   double *outputMat=malloc(sizeof(double)*rows*columnTotal);
   for(int i=0; i<columnTotal; i++)
       memcpy(outputMat, &inputMat[rows*columnIndex[i]],rows*sizeof(double));
   return outputMat;
}
</code>```

The columnIndex contains indices of columns to be extracted from matrix. ColumnTotal is the size of columnIndex array. However this will copy only one particular column of inputMat into outputMat and then probably get overwritten. I want a complete array of all those columns in columnIndex. I am working with lapack and BLAS libraries. If there is an inbuilt way to do this then please share.

答:
Your basic goal is to index your array of double (actually a pointer to double) as if it were a 2D array. You want to do this in a function extracting a certain column columnIndex and dynamically allocating a block of memory to hold the values that make up that column (rows number of values) and return a pointer to the newly allocated block.

Your approach is on the right track, your indexing is just off. It is quite a bit easier to handle the indexing in the for loop itself. The basic approach is:

```<code>int n = 0;
for (int i = colindex; i < rows * cols; i += cols)
    output[n++] = input[i];
</code>```

(that assumes n < INT_MAX values in the column -- adjust as needed)

Putting together a small example that does what it looks like you are trying to do, you could do something like the following:

```<code>#include <stdio.h>
#include <stdlib.h>

int *getcol (const int *a, const int rows, const int col, const int ncols)
{
    int sz = rows * ncols,
        n = 0,   /* output index */
        *out = malloc (rows * sizeof *a);

    if (out)
        for (int i = col; i < sz; i += ncols)  /* index with loop vars */
            out[n++] = a[i];                   /* assign column values */

    return out;
}

int main (void) {

    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        rows = 3,                   /* simulate a 3x3 with 9 values */
        cols = sizeof a / (rows * sizeof *a),
        colidx = 1,                 /* zero based index of wanted column */
        *output = NULL;

    if ((output = getcol (a, rows, colidx, cols))) {
        for (int i = 0; i < rows; i++)
            printf (" %2d\n", output[i]);
        free (output);  /* don't forget to free memory */
    }

    return 0;
}
</code>```

(note: the function parameters are in the order you have listed -- but use shorter names. Preferably you would swap the order so that columnIndex is last, but that's up to you, the column you want need not be passed as a pointer and there is no need for memcpy where simple assignment will work. Also, the column index you want is passed as a zero based index)

Example Use/Output

```<code>$ ./bin/array_idx_1d_as_2d
  2
  5
  8
</code>```

(which is the 2nd column of the simulated 3x3 array from the 9 values)

Look things over and let me know if you have any questions.

Body:
I have a matrix stored as a dynamic array i.e. double *inputMat. I know its number of rows and columns through which I can extract any particular column. Now issue is, I have a set of columns to be extracted and stored into another dynamic array. How to do this? I am writing a portion of my code for reference:

double *extractMatrix(double *inputMat,int rows, int *columnIndex, int columnTotal)
{
   double *outputMat=malloc(sizeof(double)*rows*columnTotal);
   for(int i=0; i<columnTotal; i++)
       memcpy(outputMat, &inputMat[rows*columnIndex[i]],rows*sizeof(double));
   return outputMat;
}

The columnIndex contains indices of columns to be extracted from matrix. ColumnTotal is the size of columnIndex array. However this will copy only one particular column of inputMat into outputMat and then probably get overwritten. I want a complete array of all those columns in columnIndex. I am working with lapack and BLAS libraries. If there is an inbuilt way to do this then please share.

Body:
Your basic goal is to index your array of double (actually a pointer to double) as if it were a 2D array. You want to do this in a function extracting a certain column columnIndex and dynamically allocating a block of memory to hold the values that make up that column (rows number of values) and return a pointer to the newly allocated block.

Your approach is on the right track, your indexing is just off. It is quite a bit easier to handle the indexing in the for loop itself. The basic approach is:

int n = 0;
for (int i = colindex; i < rows * cols; i += cols)
    output[n++] = input[i];

(that assumes n < INT_MAX values in the column -- adjust as needed)

Putting together a small example that does what it looks like you are trying to do, you could do something like the following:

#include <stdio.h>
#include <stdlib.h>

int *getcol (const int *a, const int rows, const int col, const int ncols)
{
    int sz = rows * ncols,
        n = 0,   /* output index */
        *out = malloc (rows * sizeof *a);

    if (out)
        for (int i = col; i < sz; i += ncols)  /* index with loop vars */
            out[n++] = a[i];                   /* assign column values */

    return out;
}

int main (void) {

    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        rows = 3,                   /* simulate a 3x3 with 9 values */
        cols = sizeof a / (rows * sizeof *a),
        colidx = 1,                 /* zero based index of wanted column */
        *output = NULL;

    if ((output = getcol (a, rows, colidx, cols))) {
        for (int i = 0; i < rows; i++)
            printf (" %2d\n", output[i]);
        free (output);  /* don't forget to free memory */
    }

    return 0;
}

(note: the function parameters are in the order you have listed -- but use shorter names. Preferably you would swap the order so that columnIndex is last, but that's up to you, the column you want need not be passed as a pointer and there is no need for memcpy where simple assignment will work. Also, the column index you want is passed as a zero based index)

Example Use/Output

$ ./bin/array_idx_1d_as_2d
  2
  5
  8

(which is the 2nd column of the simulated 3x3 array from the 9 values)

Look things over and let me know if you have any questions.


问:
How to print only specific class value
I have 3 div's in a View. Every div has unique single_value. so when i click on any of that it should alert that data value. For that i used the following script

```<code>  $(document).on('click','.single_school',function(){
      var school = $( ".single_school" ).attr('data-value');
        alert(school)
      });
</code>```

But the problem is i'm only getting the first value whatever div I clicked on. How do i print only the specific div I clicked on.

Here is the View:

```<code><div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="1">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">ABC</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="2">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">XYZ</p>
        </div>
    </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
    <div class="single_school" data-value="3">
        <div class="selection_area choosen_school">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
        <div class="school_info">
            <p class="school_name">PQR</p>
        </div>
    </div>
</div>
</code>```

答:
You should use JQuery data() to fetch the value when clicked on the element. And secondly you should use $(this) to get the current element value and not the classname. In your code, it would always give one result because you are using $( ".single_school" ). This should be replaced with $(this):

$(document).on('click', '.single_school', function() {
  var school = $(this).data('value');
  alert(school)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="1">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">ABC</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="2">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">XYZ</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="3">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">PQR</p>
    </div>
  </div>
</div></code>```

Title: How to print only specific class value

Body:
I have 3 div's in a View. Every div has unique single_value. so when i click on any of that it should alert that data value. For that i used the following script

  $(document).on('click','.single_school',function(){
      var school = $( ".single_school" ).attr('data-value');
        alert(school)
      });

But the problem is i'm only getting the first value whatever div I clicked on. How do i print only the specific div I clicked on.

Here is the View:

ABC

XYZ

PQR

Body:
You should use JQuery data() to fetch the value when clicked on the element. And secondly you should use $(this) to get the current element value and not the classname. In your code, it would always give one result because you are using $( ".single_school" ). This should be replaced with $(this):

$(document).on('click', '.single_school', function() {
  var school = $(this).data('value');
  alert(school)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="1">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">ABC</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="2">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">XYZ</p>
    </div>
  </div>
</div>
<div class="col-md-2 col-sm-4 col-xs-12">
  <div class="single_school" data-value="3">
    <div class="selection_area choosen_school">
      <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
    </div>
    <div class="food_info">
      <p class="school_name">PQR</p>
    </div>
  </div>
</div>


问:
How to block submission until form gets validated using jQuery Validate plugin?
i have a search button on my form, when i hit on it, the onclick attribute activate and jump it into function which i have mentioned on onclick
this is my button,
<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

i want when i hit on search button first form validate then go to that function but i don't know why before validating it directly goes to that function

```<code>$('#myForm').validate({
    onclick:false,
        rules:{
                name:"required",
                dob:"required",
                email:{
                    required: true,
                    email: true
                },
                age:{
                    required: true,
                    number: true,
                    minlength:2,
                    maxlength:2
                }
              },
              messages:{
              name: "Please Enter Name",
              email: "Please Enter valid Email",
              number: "Please Enter Only Digits",
              min_length:"Please Enter Minimum 2 Digit",
              max_length:"Please Enter Maximum 2 Digit"
              }
        });
</code>```

this is my jquery validation code.

```<code><form id="myForm" method="post">
                Name:<p><input id="name_search" class="form-control" type="text" name="name" placeholder="name" required></p>
                Date of Birth:<p><input class="form-control" id="dob_search" type="text" name="dob" placeholder="dd/mm/yy" required></p>
                Sex:<p> <select id="sex_search" name="sex" class="form-control">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                            </select></p>
                Email:<p><input id="mail_search" type="email" class="form-control" name="email" placeholder="Enter your email" required></p>
                Age: <p><input id="age_search" class="form-control" type="text" name="age" placeholder="Age" required></p><br/>
                <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search"></form>
</code>```

this is my form

答:
Your validation plugin might not be loaded. Check the console for errors.

Also getData('search') should be called after validation is passed.

And remove onclick="getData('search')"from

```<code><input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">
</code>```

Try adding

```<code>submitHandler: function(form) {
        getData('search');
      }:
</code>```

in :

```<code>$("#myform").validate({
  submitHandler: function(form) {
    getData('search');
  }
});
</code>```

Body:
i have a search button on my form, when i hit on it, the onclick attribute activate and jump it into function which i have mentioned on onclick
this is my button,
<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

i want when i hit on search button first form validate then go to that function but i don't know why before validating it directly goes to that function

$('#myForm').validate({
    onclick:false,
        rules:{
                name:"required",
                dob:"required",
                email:{
                    required: true,
                    email: true
                },
                age:{
                    required: true,
                    number: true,
                    minlength:2,
                    maxlength:2
                }
              },
              messages:{
              name: "Please Enter Name",
              email: "Please Enter valid Email",
              number: "Please Enter Only Digits",
              min_length:"Please Enter Minimum 2 Digit",
              max_length:"Please Enter Maximum 2 Digit"
              }
        });

this is my jquery validation code.

<form id="myForm" method="post">
                Name:
<input id="name_search" class="form-control" type="text" name="name" placeholder="name" required>

                Date of Birth:
<input class="form-control" id="dob_search" type="text" name="dob" placeholder="dd/mm/yy" required>

                Sex:
 <select id="sex_search" name="sex" class="form-control">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                            </select>

                Email:
<input id="mail_search" type="email" class="form-control" name="email" placeholder="Enter your email" required>

                Age:
<input id="age_search" class="form-control" type="text" name="age" placeholder="Age" required>

                <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search"></form>

this is my form

Body:
Your validation plugin might not be loaded. Check the console for errors.

Also getData('search') should be called after validation is passed.

And remove onclick="getData('search')"from

<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

Try adding

submitHandler: function(form) {
        getData('search');
      }:

in :

$("#myform").validate({
  submitHandler: function(form) {
    getData('search');
  }
});


问:
Moment js default timezone not working when creating date
Please refer to the following code snippets.

Problem 1: I am setting default timezone for moment js. But right after setting it, If I retrieve the timezone from moment it is not what I just set.

```<code>console.log("Currrent timezone: "); console.log(moment.tz());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Currrent timezone after updating: "); console.log(moment.tz());
</code>```

Following log is printed:

```<code>Currrent timezone: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}
Updating timezone: America/Lima
Currrent timezone after updating: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}
</code>```

Problem 2: Also another problem is that, the default timezone which I set is applied to moment.format() function but not applied when creating new date objects from moment.

```<code>console.log(moment(new Date()).toDate()); // this uses user browser timezone
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)
// I want it to give the time in the timezone which i just set above

console.log(moment(new Date()).local().toDate());
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)

console.log(moment(new Date()).format()); // this uses the timezone which I set above in moment default timezone. This is correct intended behavior
// prints: 2017-11-15T03:57:40-05:00
</code>```

答:
1. Solution: Moment timezone setDefault is affecting the instances created after setDefault. If you debug like this:

console.log("Currrent timezone: "); console.log(moment().tz());
console.log("Current time: "); console.log(moment().format());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Current time: "); console.log(moment().format());
console.log("Currrent timezone after updating: "); console.log(moment().tz());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

You can see the setDefault is working.

2. Solution: .local() function sets a flag on the original moment to use local time to display a moment instead of the original moment's time. Even if you use moment.tz.setDefault to alter the timezone, it gets the computer's timezone.

console.log(moment(new Date()).format());
moment.tz.setDefault("America/Lima");
console.log(moment(new Date()).local().format());
console.log(moment(new Date()).format());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
Please refer to the following code snippets.

Problem 1: I am setting default timezone for moment js. But right after setting it, If I retrieve the timezone from moment it is not what I just set.

console.log("Currrent timezone: "); console.log(moment.tz());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Currrent timezone after updating: "); console.log(moment.tz());

Following log is printed:

Currrent timezone: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}
Updating timezone: America/Lima
Currrent timezone after updating: Moment {_isAMomentObject: true, _isUTC: true, _pf: {…}, _locale: Locale, _d: Wed Nov 15 2017 13:39:45 GMT+0500 (Pakistan Standard Time), …}

Problem 2: Also another problem is that, the default timezone which I set is applied to moment.format() function but not applied when creating new date objects from moment.

console.log(moment(new Date()).toDate()); // this uses user browser timezone
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)
// I want it to give the time in the timezone which i just set above

console.log(moment(new Date()).local().toDate());
// prints Wed Nov 15 2017 13:57:40 GMT+0500 (Pakistan Standard Time)

console.log(moment(new Date()).format()); // this uses the timezone which I set above in moment default timezone. This is correct intended behavior
// prints: 2017-11-15T03:57:40-05:00

Body:
1. Solution: Moment timezone setDefault is affecting the instances created after setDefault. If you debug like this:

console.log("Currrent timezone: "); console.log(moment().tz());
console.log("Current time: "); console.log(moment().format());
console.log("Updating timezone: "); console.log("America/Lima");
moment.tz.setDefault("America/Lima");
console.log("Current time: "); console.log(moment().format());
console.log("Currrent timezone after updating: "); console.log(moment().tz());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can see the setDefault is working.

2. Solution: .local() function sets a flag on the original moment to use local time to display a moment instead of the original moment's time. Even if you use moment.tz.setDefault to alter the timezone, it gets the computer's timezone.

console.log(moment(new Date()).format());
moment.tz.setDefault("America/Lima");
console.log(moment(new Date()).local().format());
console.log(moment(new Date()).format());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Calling more than two web services with react js and populate them to a material ui dropdown
I have this piece of code that call a web service and I have some questions.

The first one is, what is the best practice to call a second WS, now I just call one and display the data in a list but what if I have a second WS, should I call it inside the componentDidMout() method?

now I have an array called data but the for example, should I use a second array for a second WS call?

And the second one is, how can I populate the result of the WS in a material ui dropdown, I want to populate them with the data coming with the WS.

I'm new to react so some help would be nice.

```<code>import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';

export default class WebserviceTest extends Component {

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

componentDidMount() {

const url = 'https://randomuser.me/api/?results=4';

 fetch(url).
 then((Response) => Response.json()).
   then((findResponse) => {
     console.log(findResponse);
     this.setState({
       data: findResponse.results
     });
 });

}
 render() {
 const listDesc = this.state.data.map((dt, i) =>
 <div>
   <div>
     <li key={i}>{dt.name.first}</li>
   </div>
 </div>
 );

 return (
    <div>
      <ul>{listDesc}</ul>
    </div>
   );
  }
}
</code>```

The code above is working ok.

Thanks and regards.

答:
Regarding populating the dropdown with data this should do the work.Haven't tested the code.Everything related to material-ui/Dropdown you can check here.

```<code>import React, { Component } from "react";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";

export default class WebserviceTest extends Component {
    constructor() {
        super();
        this.state = {
            data: []
        };
        this.renderOptions = this.renderOptions.bind(this);
    }

    componentDidMount() {
        const url = "https://randomuser.me/api/?results=4";

        fetch(url)
            .then(Response => Response.json())
            .then(findResponse => {
                console.log(findResponse);
                this.setState({
                    data: findResponse.results
                });
            });
    }
    //will set wahtever item the user selects in the dropdown
    handleChange = (event, index, value) => this.setState({ value });
    //we are creating the options to be displayed
    renderOptions() {
        return this.state.data.map((dt, i) => {
            return (
                <div>
                    <MenuItem key={i} value={dt.name.first} primaryText={dt.name.first} />
                </div>
            );
        });
    }

    render() {
        return (
            <div>
                <DropDownMenu value={this.state.value} onChange={this.handleChange}>
                    {this.renderOptions()}
                </DropDownMenu>
            </div>
        );
    }
}
</code>```

What is the best practice to call a second Web Service??

Answer: Calling in componentDidMount is fine.Also it depends on other things.If both the WS calls are independent then you can call them using promise in parallels like:

```<code>Promise
    .all([
        fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
        fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
    ])
    .then((response) => console.log(response)
    )
</code>```

Tip: If you will paste the above snippet in console, you will get the output.You can check the output.It returns an array of responses.

now I have an array called data but the for example, should I use a
  second array for a second WS call?

It depends what you want to do with the data of second WS.If you want to add to the dropdown then you can simply concat with the data array.If want for some other purpose than you should keep the data separate.

And the second one is, how can I populate the result of the WS in a
  material ui dropdown, I want to populate them with the data coming
  with the WS.

The code pasted in the beginning should work.You can simply map over data create options to be displayed in the list

Body:
I have this piece of code that call a web service and I have some questions.

The first one is, what is the best practice to call a second WS, now I just call one and display the data in a list but what if I have a second WS, should I call it inside the componentDidMout() method?

now I have an array called data but the for example, should I use a second array for a second WS call?

And the second one is, how can I populate the result of the WS in a material ui dropdown, I want to populate them with the data coming with the WS.

I'm new to react so some help would be nice.

import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';

export default class WebserviceTest extends Component {

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

componentDidMount() {

const url = 'https://randomuser.me/api/?results=4';

 fetch(url).
 then((Response) => Response.json()).
   then((findResponse) => {
     console.log(findResponse);
     this.setState({
       data: findResponse.results
     });
 });

}
 render() {
 const listDesc = this.state.data.map((dt, i) =>

{dt.name.first}

 );

 return (

{listDesc}

   );
  }
}

The code above is working ok.

Thanks and regards.

Body:
Regarding populating the dropdown with data this should do the work.Haven't tested the code.Everything related to material-ui/Dropdown you can check here.

import React, { Component } from "react";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";

export default class WebserviceTest extends Component {
    constructor() {
        super();
        this.state = {
            data: []
        };
        this.renderOptions = this.renderOptions.bind(this);
    }

    componentDidMount() {
        const url = "https://randomuser.me/api/?results=4";

        fetch(url)
            .then(Response => Response.json())
            .then(findResponse => {
                console.log(findResponse);
                this.setState({
                    data: findResponse.results
                });
            });
    }
    //will set wahtever item the user selects in the dropdown
    handleChange = (event, index, value) => this.setState({ value });
    //we are creating the options to be displayed
    renderOptions() {
        return this.state.data.map((dt, i) => {
            return (
                <div>
                    <MenuItem key={i} value={dt.name.first} primaryText={dt.name.first} />
                </div>
            );
        });
    }

    render() {
        return (
            <div>
                <DropDownMenu value={this.state.value} onChange={this.handleChange}>
                    {this.renderOptions()}
                </DropDownMenu>
            </div>
        );
    }
}

What is the best practice to call a second Web Service??

Answer: Calling in componentDidMount is fine.Also it depends on other things.If both the WS calls are independent then you can call them using promise in parallels like:

Promise
    .all([
        fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
        fetch('https://randomuser.me/api/?results=4').then((res) => res.json()),
    ])
    .then((response) => console.log(response)
    )

Tip: If you will paste the above snippet in console, you will get the output.You can check the output.It returns an array of responses.

now I have an array called data but the for example, should I use a
  second array for a second WS call?

It depends what you want to do with the data of second WS.If you want to add to the dropdown then you can simply concat with the data array.If want for some other purpose than you should keep the data separate.

And the second one is, how can I populate the result of the WS in a
  material ui dropdown, I want to populate them with the data coming
  with the WS.

The code pasted in the beginning should work.You can simply map over data create options to be displayed in the list


问:
FFImageLoading: Unhandled Exception: System.TypeLoadException: Could not load list of method overrides occurred
When trying to init FFImage (in my application):

```<code>CachedImageRenderer.Init();
</code>```

I get the mysterious error:

```<code>Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred
</code>```

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.

答:
I same problem. I updated Xamarin.Form to version 2.5 and removed all bin/obj folders. It solved.

https://github.com/luberda-molinet/FFImageLoading/issues/814#issuecomment-344677274

Body:
When trying to init FFImage (in my application):

CachedImageRenderer.Init();

I get the mysterious error:

Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.


问:
Why do .CSV files downloaded as .TXT in postman?
I was verifying the HTTP content-type header and the file extensions via postman (Using 'Send and Download' button with the HTTP GET request on file URLs).
We have different type of sample files available at http://www.sample-videos.com. and following are some results

content-type image/jpeg   file downloaded as response.jpg

content-type audio/mpeg   file downloaded as response.mpg

content-type application/vnd.ms-excel file downloaded as response.xls

content-type application/vnd.ms-powerpoint file downloaded as sample.ppt

content-type text/plain  file downloaded as response.txt

content-type application/pdf file downloaded as sample.pdf

content-type text/csv file downloaded as response.txt

Can anyone please explain why the text/csv file is downloaded with extension .txt instead of .csv? Also see the screenshot below.

答:
That's the default postman goes to when it doesn't fully understand the content-type.
You need to include 'charset=utf-8' in the content type, as in text/csv; charset=utf-8


问:
Android: How Retrofit/Volley is better than AsyncTask
I saw many answers for comparison between Volley and Retrofit. But I'm unable to find any answer for why both came to front. What were the issues/bugs/problems in AsyncTask or what were the problems in simple HTTP client/server programs.

答:
Actually Volley and Retrofit are libraries where AsyncTask is a way of threading.

SimpleHttpClient is an implementation to do HTTP requests, But you will have to handle everything manually like parsing the response and so many. It runs on whichever thread you are calling it from. To run it in a separate thread you will have to create an AsyncTask.

But, Volley and Retrofit library was created to make the HTTP request very simple by reducing boilerplate code. Using this you have to write only a few lines of codes to make an HTTP request and the HTTP requests will be pushed to separate thread automatically.

If SimpleHttpClient and AsyncTask are written in 30lines of code, you can achieve the same using Retrofit or volley in within 6 to 8 lines of code.


问:
How to filter history based on gitignore?
To be clear on this question, I am not asking about how to remove a single file from history, like this question: Completely remove file from all Git repository commit history. I am also not asking about untracking files from gitignore, like in this question: Ignore files that have already been committed to a Git repository.

I am talking about "updating a .gitignore file, and subsequently removing everything matching the list from history", more or less like this question: Ignore files that have already been committed to a Git repository. However, unfortunately, the answer from that question does not work for this purpose, so I am here to try elaborating the question and hopefully find a good answer that does not involve a human looking through an entire source tree to manually do a filter-branch on each matched file.

Here I provide a test script, currently performing the procedure in the answer of Ignore files that have already been committed to a Git repository. It is going to remove and create a folder root under PWD, so be careful before running it. I will describe my goal after the code.

```<code>#!/bin/bash -e

TESTROOT=${PWD}
GREEN="\e[32m"
RESET="\e[39m"

rm -rf root
mkdir -v root
pushd root

mkdir -v repo
pushd repo
git init

touch a b c x
mkdir -v main
touch main/{a,x,y,z}

# Initial commit
git add .
git commit -m "Initial Commit"
echo -e "${GREEN}Contents of first commit${RESET}"
git ls-files | tee ../00-Initial.txt

# Add another commit just for demo
touch d e f y z main/{b,c}
## Make some other changes
echo "Test" | tee a | tee b | tee c | tee x | tee main/a > main/x
git add .
git commit -m "Some edits"

echo -e "${GREEN}Contents of second commit${RESET}"
git ls-files | tee ../01-Changed.txt

# Now I want to ignore all 'a' and 'b', and all 'main/x', but not 'main/b'
## Checkout the root commit
git checkout -b temp $(git rev-list HEAD | tail -1)
## Add .gitignores
echo "a" >> .gitignore
echo "b" >> .gitignore
echo "x" >> main/.gitignore
echo "!b" >> main/.gitignore
git add .
git commit --amend -m "Initial Commit (2)"
## --v Not sure if it is correct
git rebase --onto temp master
git checkout master
## --v Now, why should I delete this branch?
git branch -D temp
echo -e "${GREEN}Contents after rebase${RESET}"
git ls-files | tee ../02-Rebased.txt

# Supposingly, rewrite history
git filter-branch --tree-filter 'git clean -f -X' -- --all
echo -e "${GREEN}Contents after filter-branch${RESET}"
git ls-files | tee ../03-Rewritten.txt

echo "History of 'a'"
git log -p a

popd # repo

popd # root
</code>```

This code creates a repository, adds some files, do some edit, and perform the cleaning procedure. Also, some log files are generated. Ideally, I would like a, b, and main/x disappear from history, while main/b stays. However, right now nothing is removed from history. What should be modified to perform this goal?

Bonus points if this can be done on multiple branches. But for now, keep it to a single master branch.

答:
On windows this sequence did not work to me:

```<code>cp -R /tmp/ignores-to-add . &&
git rm --cached -qrf . &&
git add . &&
git clean -fqX
</code>```

But following works.

Update every commit with existed .gitignore:

```<code>git filter-branch --index-filter '
  git ls-files -i --exclude-from=.gitignore | xargs git rm --cached -q
' -- --all
</code>```

Update .gitignore in the every commit and filter files:

```<code>cp ../.gitignore /d/tmp-gitignore
git filter-branch --index-filter '
  cp /d/tmp-gitignore ./.gitignore
  git add .gitignore
  git ls-files -i --exclude-from=.gitignore | xargs git rm --cached -q
' -- --all
rm /d/tmp-gitignore
</code>```

Use grep -v if you had special cases, for example file empty to keep empty directory:

```<code>git ls-files -i --exclude-from=.gitignore | grep -vE "empty$" | xargs git rm --cached -q
</code>```

Body:
To be clear on this question, I am not asking about how to remove a single file from history, like this question: Completely remove file from all Git repository commit history. I am also not asking about untracking files from gitignore, like in this question: Ignore files that have already been committed to a Git repository.

I am talking about "updating a .gitignore file, and subsequently removing everything matching the list from history", more or less like this question: Ignore files that have already been committed to a Git repository. However, unfortunately, the answer from that question does not work for this purpose, so I am here to try elaborating the question and hopefully find a good answer that does not involve a human looking through an entire source tree to manually do a filter-branch on each matched file.

Here I provide a test script, currently performing the procedure in the answer of Ignore files that have already been committed to a Git repository. It is going to remove and create a folder root under PWD, so be careful before running it. I will describe my goal after the code.

#!/bin/bash -e

TESTROOT=${PWD}
GREEN="\e[32m"
RESET="\e[39m"

rm -rf root
mkdir -v root
pushd root

mkdir -v repo
pushd repo
git init

touch a b c x
mkdir -v main
touch main/{a,x,y,z}

# Initial commit
git add .
git commit -m "Initial Commit"
echo -e "${GREEN}Contents of first commit${RESET}"
git ls-files | tee ../00-Initial.txt

# Add another commit just for demo
touch d e f y z main/{b,c}
## Make some other changes
echo "Test" | tee a | tee b | tee c | tee x | tee main/a > main/x
git add .
git commit -m "Some edits"

echo -e "${GREEN}Contents of second commit${RESET}"
git ls-files | tee ../01-Changed.txt

# Now I want to ignore all 'a' and 'b', and all 'main/x', but not 'main/b'
## Checkout the root commit
git checkout -b temp $(git rev-list HEAD | tail -1)
## Add .gitignores
echo "a" >> .gitignore
echo "b" >> .gitignore
echo "x" >> main/.gitignore
echo "!b" >> main/.gitignore
git add .
git commit --amend -m "Initial Commit (2)"
## --v Not sure if it is correct
git rebase --onto temp master
git checkout master
## --v Now, why should I delete this branch?
git branch -D temp
echo -e "${GREEN}Contents after rebase${RESET}"
git ls-files | tee ../02-Rebased.txt

# Supposingly, rewrite history
git filter-branch --tree-filter 'git clean -f -X' -- --all
echo -e "${GREEN}Contents after filter-branch${RESET}"
git ls-files | tee ../03-Rewritten.txt

echo "History of 'a'"
git log -p a

popd # repo

popd # root

This code creates a repository, adds some files, do some edit, and perform the cleaning procedure. Also, some log files are generated. Ideally, I would like a, b, and main/x disappear from history, while main/b stays. However, right now nothing is removed from history. What should be modified to perform this goal?

Bonus points if this can be done on multiple branches. But for now, keep it to a single master branch.

Body:
On windows this sequence did not work to me:

cp -R /tmp/ignores-to-add . &&
git rm --cached -qrf . &&
git add . &&
git clean -fqX

But following works.

Update every commit with existed .gitignore:

git filter-branch --index-filter '
  git ls-files -i --exclude-from=.gitignore | xargs git rm --cached -q
' -- --all

Update .gitignore in the every commit and filter files:

cp ../.gitignore /d/tmp-gitignore
git filter-branch --index-filter '
  cp /d/tmp-gitignore ./.gitignore
  git add .gitignore
  git ls-files -i --exclude-from=.gitignore | xargs git rm --cached -q
' -- --all
rm /d/tmp-gitignore

Use grep -v if you had special cases, for example file empty to keep empty directory:

git ls-files -i --exclude-from=.gitignore | grep -vE "empty$" | xargs git rm --cached -q