问:
Pivot table in SAS
The data looks as following:

```<code>YEAR    MONTH   ID1 ID2 FIELD   FIELD_DESC
2017    4   123 2222    FFF red1
2017    4   123 2222    FFG red2
2017    4   224 2221    XYZ green1
2017    4   225 1234    TYU blue5
</code>```

and desired output is

```<code>YEAR    MONTH   ID1 ID2 blue5   green1  red1    red2
2017    4   123 2222    0   0   1   1
2017    4   224 2221    0   1   0   0
2017    4   225 1234    1   0   0   0
</code>```

On SQL server I used to run the following:

```<code>select year, month, id1, id2, [field1], [field2] .... [fieldn]
from (select year, month, id1, id2, field, field_desc from source_table) P
Pivot (count(field) for field_desc in ([field1], [field2] .... [fieldn])) Pvt
</code>```

The above would give me counts of field of each possible description by year, month, id1, id2.

I'm trying to translate this to SAS.

One approach would be conditional sums

```<code>proc sql;
create table aggr_table as
select year, month, id1, id2,
sum(case when field_desc = 'field1' then 1 else 0 end) as field1
...
sum(case when field_desc = 'fieldn' then 1 else 0 end) as fiendn
from source_table
group by year, month, id1, id2;
quit;
</code>```

Second way I tried to do it was by

```<code>proc sort data = source_table
 by year descending month descending id1 descending id2;
run;

data table_aggr (keep year month id1 id2 field1 .... fieldn);
set source_table
retain field1
....
fieldn 0);

if field_desc = 'field1' then do;
field1 = field1 +1;
end;
....
if field_desc = 'fieldn' then do;
fieldn = fieldn + 1;
end;

if last.id2 then
output;
by year month id1 id2;
run;
</code>```

But the second way does not seem to work

ERROR: BY variables are not properly sorted on data set
  WORK.SOURCE_TABLE

My questions:
1) My googling so far seems to indicate preference for doing this kind of data manipulation in the data step rather than proc sql step, is there a particular advantage ?

2) What did I do wrong in the data step ?

3) Is there a better way to replicate the SQL code at the top of the post ? Both SAS options I'm looking at look rather unwieldy compared to SQL original.

Thank you
Ben

答:
You can use PROC SUMMARY to count for you and then use PROC TRANSPOSE to turn the counts into variables instead of observations. If you just do it directly then you will get missing values instead of zero for the combinations that do not appear. You could post-process the file to replace the missing counts with zeros.  Or use the method below to build a CLASSDATA table to feed to PROC SUMMARY to insure that all of zeros are included before the transpose.

```<code>proc sql noprint ;
 create table classdata as
 select *
 from (select distinct year,month,id1,id2 from have) a
    , (select distinct field_desc from have) b
 ;
quit;
proc summary data=have nway classdata=classdata exclusive ;
  class year month id1 id2 field_desc ;
  output out=counts ;
run;
proc transpose data=counts out=want(drop=_name_);
  by year month id1 id2 ;
  id field_desc ;
  var _freq_;
run;
</code>```

You could have PROC SQL generate the full rank counts directly with a little bit of tricky SQL.  Combine the data with the full list of the id variable values and count how many times the two id variables match.

```<code>proc sql noprint ;
 create table counts as
 select year,month,id1,id2
      , b.field_desc
      , sum(a.field_desc=b.field_desc) as count
 from have a
    , (select distinct field_desc from have) b
 group by year,month,id1,id2,b.field_desc
 order by year,month,id1,id2,b.field_desc
 ;
quit;
</code>```

Generating the SQL is easy.  If the number of derived variables is small then just generate the code into a macro variable. (If the list is large then generate the code using a data step using either call execute() or by writing it to a file and using %include to run it.)

```<code>proc sql noprint ;
 select distinct
 catx(' '
     ,'sum(field_desc ='
     ,quote(trim(field_desc))
     ,') as'
     ,nliteral(field_desc)
     )
   into :code separated by ','
   from have
 ;
 create table want as
   select year, month, id1, id2
        , &code
   from have
   group by year, month, id1, id2
  ;
quit;
</code>```

If you want to do it in a data step then look into using HASH object to gather that data.  Then use PROC TRANSPOSE or a code generation technique (like in the SQL above) to transform from observations to variables.

Title: Pivot table in SAS

Body:
The data looks as following:

YEAR    MONTH   ID1 ID2 FIELD   FIELD_DESC
2017    4   123 2222    FFF red1
2017    4   123 2222    FFG red2
2017    4   224 2221    XYZ green1
2017    4   225 1234    TYU blue5

and desired output is

YEAR    MONTH   ID1 ID2 blue5   green1  red1    red2
2017    4   123 2222    0   0   1   1
2017    4   224 2221    0   1   0   0
2017    4   225 1234    1   0   0   0

On SQL server I used to run the following:

select year, month, id1, id2, [field1], [field2] .... [fieldn]
from (select year, month, id1, id2, field, field_desc from source_table) P
Pivot (count(field) for field_desc in ([field1], [field2] .... [fieldn])) Pvt

The above would give me counts of field of each possible description by year, month, id1, id2.

I'm trying to translate this to SAS.

One approach would be conditional sums

proc sql;
create table aggr_table as
select year, month, id1, id2,
sum(case when field_desc = 'field1' then 1 else 0 end) as field1
...
sum(case when field_desc = 'fieldn' then 1 else 0 end) as fiendn
from source_table
group by year, month, id1, id2;
quit;

Second way I tried to do it was by

proc sort data = source_table
 by year descending month descending id1 descending id2;
run;

data table_aggr (keep year month id1 id2 field1 .... fieldn);
set source_table
retain field1
....
fieldn 0);

if field_desc = 'field1' then do;
field1 = field1 +1;
end;
....
if field_desc = 'fieldn' then do;
fieldn = fieldn + 1;
end;

if last.id2 then
output;
by year month id1 id2;
run;

But the second way does not seem to work

ERROR: BY variables are not properly sorted on data set
  WORK.SOURCE_TABLE

My questions:
1) My googling so far seems to indicate preference for doing this kind of data manipulation in the data step rather than proc sql step, is there a particular advantage ?

2) What did I do wrong in the data step ?

3) Is there a better way to replicate the SQL code at the top of the post ? Both SAS options I'm looking at look rather unwieldy compared to SQL original.

Thank you
Ben

Body:
You can use PROC SUMMARY to count for you and then use PROC TRANSPOSE to turn the counts into variables instead of observations. If you just do it directly then you will get missing values instead of zero for the combinations that do not appear. You could post-process the file to replace the missing counts with zeros.  Or use the method below to build a CLASSDATA table to feed to PROC SUMMARY to insure that all of zeros are included before the transpose.

proc sql noprint ;
 create table classdata as
 select *
 from (select distinct year,month,id1,id2 from have) a
    , (select distinct field_desc from have) b
 ;
quit;
proc summary data=have nway classdata=classdata exclusive ;
  class year month id1 id2 field_desc ;
  output out=counts ;
run;
proc transpose data=counts out=want(drop=_name_);
  by year month id1 id2 ;
  id field_desc ;
  var _freq_;
run;

You could have PROC SQL generate the full rank counts directly with a little bit of tricky SQL.  Combine the data with the full list of the id variable values and count how many times the two id variables match.

proc sql noprint ;
 create table counts as
 select year,month,id1,id2
      , b.field_desc
      , sum(a.field_desc=b.field_desc) as count
 from have a
    , (select distinct field_desc from have) b
 group by year,month,id1,id2,b.field_desc
 order by year,month,id1,id2,b.field_desc
 ;
quit;

Generating the SQL is easy.  If the number of derived variables is small then just generate the code into a macro variable. (If the list is large then generate the code using a data step using either call execute() or by writing it to a file and using %include to run it.)

proc sql noprint ;
 select distinct
 catx(' '
     ,'sum(field_desc ='
     ,quote(trim(field_desc))
     ,') as'
     ,nliteral(field_desc)
     )
   into :code separated by ','
   from have
 ;
 create table want as
   select year, month, id1, id2
        , &code
   from have
   group by year, month, id1, id2
  ;
quit;

If you want to do it in a data step then look into using HASH object to gather that data.  Then use PROC TRANSPOSE or a code generation technique (like in the SQL above) to transform from observations to variables.


来源: stackexchange

问:
Without using for each loop container in ssis , I have to dump one folder that contains several files in it
There is one folder that contains 4 csv files , I have to dump it to sql server without using foreach loop container. How to do that?</p>

答:
Solution

the simplest way is to import these files to sql using an Execute sql Task, but first you should build the whole sql command using a Script Task

Just follow this article to learn more on import csv to SQL:

SQL SERVER – Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server

Example

Assuming that we have the following 4 flat files in the Directory C:\New\ with the following structure:

```<code>Col1,Col2,Col3
bla,bla,bla
bla,bla,bla
</code>```

First of all we have to add an Execute Sql Task to create the Sql Table

```<code>CREATE TABLE TBLTEMP(COL1 VARCHAR(50),
                 COL2 VARCHAR(50),
                 COL3 VARCHAR(50))
</code>```

Second we have to add Variable @[User::strQuery] of type string

Add a Script Task and select @[User::strQuery] as ReadWrite Variable

In The Script Task Write The Following Code:

```<code>Public Sub Main()

    Dim strQuery As String = ""

    For Each strFile As String In IO.Directory.GetFiles("C:\New", "*.csv", IO.SearchOption.TopDirectoryOnly)

        strQuery &= vbNewLine &
            "BULK INSERT [TBLTEMP] " & vbNewLine &
            " FROM '" & strFile & "' WITH" & vbNewLine &
            "(FIELDTERMINATOR = ','," & vbNewLine &
            "ROWTERMINATOR = '\n' ) " & vbNewLine &
            "GO" & vbNewLine

    Next

    Dts.Variables.Item("User::strQuery").Value = strQuery

    Dts.TaskResult = ScriptResults.Success
End Sub
</code>```

Add an Execute Sql Task and use @[User::strQuery] as SqlCommand (Select Source Type = Variable)

ScreenShots

First Execute Sql Task

Script Task

Second Execute Sql Task

Whole Package

ContentLicense: CC BY-SA 3.0

Body:
Solution

the simplest way is to import these files to sql using an Execute sql Task, but first you should build the whole sql command using a Script Task

Just follow this article to learn more on import csv to SQL:

SQL SERVER – Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server

Example

Assuming that we have the following 4 flat files in the Directory C:\New\ with the following structure:

Col1,Col2,Col3
bla,bla,bla
bla,bla,bla

First of all we have to add an Execute Sql Task to create the Sql Table

CREATE TABLE TBLTEMP(COL1 VARCHAR(50),
                 COL2 VARCHAR(50),
                 COL3 VARCHAR(50))

Second we have to add Variable @[User::strQuery] of type string

Add a Script Task and select @[User::strQuery] as ReadWrite Variable

In The Script Task Write The Following Code:

Public Sub Main()

    Dim strQuery As String = ""

    For Each strFile As String In IO.Directory.GetFiles("C:\New", "*.csv", IO.SearchOption.TopDirectoryOnly)

        strQuery &= vbNewLine &
            "BULK INSERT [TBLTEMP] " & vbNewLine &
            " FROM '" & strFile & "' WITH" & vbNewLine &
            "(FIELDTERMINATOR = ','," & vbNewLine &
            "ROWTERMINATOR = '\n' ) " & vbNewLine &
            "GO" & vbNewLine

    Next

    Dts.Variables.Item("User::strQuery").Value = strQuery

    Dts.TaskResult = ScriptResults.Success
End Sub

Add an Execute Sql Task and use @[User::strQuery] as SqlCommand (Select Source Type = Variable)

ScreenShots

First Execute Sql Task

Script Task

Second Execute Sql Task

Whole Package


问:
Simplest CSS equivalent for two-column one-row table?
What is the simplest CSS equivalent for this HTML code:

```<code><table><tr><td>
One<br>
Two
</td><td>
Three<br>
Four
</td></tr></table>
</code>```

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

答:
This is the "simplest" I could get. Using flexbox's flex-direction and flex-wrap properties, you can make the single "column" of an unordered list bridge two columns. You'll need to adjust the max-height of the ul and the width of the lis to ensure the values wrap the way you want them to.

.table-list {
  margin: 0;
  padding: 0;
  text-indent: 0;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  max-height: 3rem;
}

.table-list li {
  list-style-type: none;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="table-list">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul></code>```

Body:
What is the simplest CSS equivalent for this HTML code:

One

Two

Three

Four

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

Body:
This is the "simplest" I could get. Using flexbox's flex-direction and flex-wrap properties, you can make the single "column" of an unordered list bridge two columns. You'll need to adjust the max-height of the ul and the width of the lis to ensure the values wrap the way you want them to.

.table-list {
  margin: 0;
  padding: 0;
  text-indent: 0;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  max-height: 3rem;
}

.table-list li {
  list-style-type: none;
  width: 50%;
}

<ul class="table-list">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>


问:
Application crashed when trying to load Json using retrofit to a recyclerView in a fragment in a tablayout
so to be more specific i have an activity which contains a tablayout each tab should basically load a standalone fragment containing a recycler view an i want the data retrieved from the api using retrofit to be loaded in the recyclerView bases on user action

so this is the activity :

```<code>public class RestaurantLogoView extends AppCompatActivity implements LiteFragment.OnFragmentInteractionListener, RegularFragment.OnFragmentInteractionListener, View.OnClickListener {
    private static final String TAG = "RestaurantLogoView";
        public static ProgressDialog progressDialog;
    //TODO
    public static View.OnClickListener myOnClickListener;

    private String chosenArea;
    TextView locationTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),getApplicationContext());
        //remove this if you still didnt get data in the fragment
        mViewPager.setAdapter(pagerAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());

        locationTv = (TextView) findViewById(R.id.location_tv);
        chosenArea = (String) getIntent().getSerializableExtra("Object");
        locationTv.setText(chosenArea);
        locationTv.setOnClickListener(this);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        //TODO i added this lately not sure what its supposed to do but consider removing it
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */

//
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_restaurant_main_view, menu);
//        return true;
//    }
    @Override
    public void onClick(View v) {
        if (v == locationTv) {
            Intent o = new Intent(getApplicationContext(), AreaList.class);
            startActivity(o);
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "What do you want to eat today?", Toast.LENGTH_LONG).show();
        }
    }

    private class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        String tabTitles[] = {getString(R.string.regular), getString(R.string.lite)};
        Context context;

        SectionsPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    new RegularFragment();
                    return RegularFragment.newInstance(TAG, position);
                case 1:
                    new LiteFragment();
                    return LiteFragment.newInstance(TAG, position);

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }

    }

}
`
</code>```

This is the first fragment which should be shown in my first tab

```<code>public class RegularFragment extends Fragment {

    OnFragmentInteractionListener mListener;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String REGULAR_PARAM1 = "lite";
    View RootView;
    List<RestaurantModel> regularRestaurants;
    private RecyclerView recyclerView;
    RecyclerViewAdapter adapter;
    private Call<RestaurantElKbeer> callbackCall;
    private String TAG = "RegularFragment";
    //new
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public RegularFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static Fragment newInstance(String param, int position) {

        //TODO it might be important i didnt know why i created it
        Fragment fragment = new RegularFragment();
        Bundle args = new Bundle();
        args.putInt(param, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        regularRestaurants = requestRegularList();
        mPage = getArguments().getInt(ARG_PAGE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //new
        RootView = inflater.inflate(R.layout.fragment_regular, container, false);
        recyclerView = (RecyclerView) RootView.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        initializeAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(llm);
        return RootView;
    }

    private void initializeAdapter() {
        adapter = new RecyclerViewAdapter(getActivity(), regularRestaurants);
        recyclerView.setAdapter(adapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private List<RestaurantModel> requestRegularList() {
        List<RestaurantModel> myRestaurantsList = new ArrayList<>();
        RestAdapter restAdapter = new RestAdapter();
        API api = restAdapter.getApi();
        // URL: https://betaweb.jeebley.com/services_new/services.php?action=search&langId=1&countryId=21&cuisineType=1&cuisineId=all&areaId=1&delvType=1

        Call<RestaurantElKbeer> call = api.getRestaurants("search", "1", "21", "all", "1", "1");
        call.enqueue(new Callback<RestaurantElKbeer>() {
            @Override
            public void onResponse(@NonNull Call<RestaurantElKbeer> call, @NonNull Response<RestaurantElKbeer> response) {
                if (response.isSuccessful()) {
                    ArrayList<String> names = new ArrayList<String>();
                    RestaurantElKbeer restaurantResponse = response.body();
                   List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
                if(list != null && !list.isEmpty()){
                    for (int i = 0; i < list.size(); i++) {
                        String name;
                        name = list.get(i).getRName();
                        names.add(name);
                        Log.i(TAG, "onResponse: " + names.get(i));
                    }

                }
                else
                    {
                        Log.i(TAG, "onResponse(regular): RestaurantModelList is null");
                    }
                    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), list);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setOnClickListener(v -> {
                        Intent i = new Intent(getContext(), ChooseYourLanguage.class);
                        i.putExtra("Object", getId());
                        startActivityForResult(i, 0);
                    });
                }
            }

            @Override
            public void onFailure(@NonNull Call<RestaurantElKbeer> call, Throwable t) {
                Log.i(TAG, "onFailure: failed RegularFragmentCall");
            }
        });
        return myRestaurantsList;
    }

    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    /**
     * Initialize the contents of the Fragment host's standard options menu.  You
     * should place your menu items in to <var>menu</var>.  For this method
     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
     * {@link RestaurantLogoView#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
     * for more information.
     *
     * @param menu     The options menu in which you place your items.
     * @param inflater
     * @see #setHasOptionsMenu
     * @see #onPrepareOptionsMenu
     * @see #onOptionsItemSelected
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setHasOptionsMenu(boolean hasMenu) {
        super.setHasOptionsMenu(hasMenu);
    }
}
</code>```

And this is my RecyclerViewAdapter

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private List<RestaurantModel> items;
    private Context ctx;

    public RecyclerViewAdapter(Context context, List<RestaurantModel> items) {
        this.ctx = context;
        this.items=items;
    }

    private OnItemClickListener mOnItemClickListener;
    private SharedPref sharedPref;

    public interface OnItemClickListener {
        void onItemClick(View view, RestaurantModel obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView title;
        TextView description;
        ImageView imageView;

        ViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.restaurant_card_view);
            title = (TextView) itemView.findViewById(R.id.restaurantName_section_label);
            description = (TextView) itemView.findViewById(R.id.section_label2);
            imageView = (ImageView) itemView.findViewById(R.id.restaurantImageView);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.restaurant_card_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        RestaurantModel p = (RestaurantModel) payloads.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());
            holder.imageView.setImageResource(R.mipmap.ic_launcher);
        }
       holder.cv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Log.i("RecyclerViewAdapter", "onClick: replace with intent to send Restaurant data");
           }
       });
    }

    @Override
    public void onBindViewHolder(ViewHolder holder,int position) {

        final RestaurantModel p = items.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());

        }
        holder.cv.setOnClickListener(view -> {
                mOnItemClickListener.onItemClick(view, p, position);

        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public interface OnLoadMoreListener {
        void onLoadMore(int current_page);
    }
}
</code>```

This is the exception i'm getting

**

06-06 00:11:05.215 10571-10571/com.jeebley.jeebley E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.jeebley.jeebley, PID: 10571
                                                                       java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.jeebley.jeebley.adapters.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:109)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3310)
                                                                           at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                           at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                           at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at com.android.internal.policy.DecorView.onLayout(DecorView.java:774)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2511)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1364)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6763)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:923)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:909)
                                                                           at android.os.Handler.handleCallback(Handler.java:761)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:156)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6524)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
  06-06 00:11:05.238 10571-10571/com.jeebley.jeebley I/Process: Sending signal. PID: 10571 SIG: 9

**

答:
first, check if restaurantResponse.getRestaurantModel() return null.</p>

```<code>List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
if(list == null){
    enter code here
}
</code>```

Body:
so to be more specific i have an activity which contains a tablayout each tab should basically load a standalone fragment containing a recycler view an i want the data retrieved from the api using retrofit to be loaded in the recyclerView bases on user action

so this is the activity :

public class RestaurantLogoView extends AppCompatActivity implements LiteFragment.OnFragmentInteractionListener, RegularFragment.OnFragmentInteractionListener, View.OnClickListener {
    private static final String TAG = "RestaurantLogoView";
        public static ProgressDialog progressDialog;
    //TODO
    public static View.OnClickListener myOnClickListener;

    private String chosenArea;
    TextView locationTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),getApplicationContext());
        //remove this if you still didnt get data in the fragment
        mViewPager.setAdapter(pagerAdapter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show());

        locationTv = (TextView) findViewById(R.id.location_tv);
        chosenArea = (String) getIntent().getSerializableExtra("Object");
        locationTv.setText(chosenArea);
        locationTv.setOnClickListener(this);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        //TODO i added this lately not sure what its supposed to do but consider removing it
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */

//
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_restaurant_main_view, menu);
//        return true;
//    }
    @Override
    public void onClick(View v) {
        if (v == locationTv) {
            Intent o = new Intent(getApplicationContext(), AreaList.class);
            startActivity(o);
            finish();
        } else {
            Toast.makeText(getApplicationContext(), "What do you want to eat today?", Toast.LENGTH_LONG).show();
        }
    }

    private class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        String tabTitles[] = {getString(R.string.regular), getString(R.string.lite)};
        Context context;

        SectionsPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    new RegularFragment();
                    return RegularFragment.newInstance(TAG, position);
                case 1:
                    new LiteFragment();
                    return LiteFragment.newInstance(TAG, position);

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }

    }

}
`

This is the first fragment which should be shown in my first tab

public class RegularFragment extends Fragment {

    OnFragmentInteractionListener mListener;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String REGULAR_PARAM1 = "lite";
    View RootView;
    List<RestaurantModel> regularRestaurants;
    private RecyclerView recyclerView;
    RecyclerViewAdapter adapter;
    private Call<RestaurantElKbeer> callbackCall;
    private String TAG = "RegularFragment";
    //new
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public RegularFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static Fragment newInstance(String param, int position) {

        //TODO it might be important i didnt know why i created it
        Fragment fragment = new RegularFragment();
        Bundle args = new Bundle();
        args.putInt(param, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        regularRestaurants = requestRegularList();
        mPage = getArguments().getInt(ARG_PAGE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //new
        RootView = inflater.inflate(R.layout.fragment_regular, container, false);
        recyclerView = (RecyclerView) RootView.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        initializeAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(llm);
        return RootView;
    }

    private void initializeAdapter() {
        adapter = new RecyclerViewAdapter(getActivity(), regularRestaurants);
        recyclerView.setAdapter(adapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private List<RestaurantModel> requestRegularList() {
        List<RestaurantModel> myRestaurantsList = new ArrayList<>();
        RestAdapter restAdapter = new RestAdapter();
        API api = restAdapter.getApi();
        // URL: https://betaweb.jeebley.com/services_new/services.php?action=search&langId=1&countryId=21&cuisineType=1&cuisineId=all&areaId=1&delvType=1

        Call<RestaurantElKbeer> call = api.getRestaurants("search", "1", "21", "all", "1", "1");
        call.enqueue(new Callback<RestaurantElKbeer>() {
            @Override
            public void onResponse(@NonNull Call<RestaurantElKbeer> call, @NonNull Response<RestaurantElKbeer> response) {
                if (response.isSuccessful()) {
                    ArrayList<String> names = new ArrayList<String>();
                    RestaurantElKbeer restaurantResponse = response.body();
                   List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
                if(list != null && !list.isEmpty()){
                    for (int i = 0; i < list.size(); i++) {
                        String name;
                        name = list.get(i).getRName();
                        names.add(name);
                        Log.i(TAG, "onResponse: " + names.get(i));
                    }

                }
                else
                    {
                        Log.i(TAG, "onResponse(regular): RestaurantModelList is null");
                    }
                    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), list);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setOnClickListener(v -> {
                        Intent i = new Intent(getContext(), ChooseYourLanguage.class);
                        i.putExtra("Object", getId());
                        startActivityForResult(i, 0);
                    });
                }
            }

            @Override
            public void onFailure(@NonNull Call<RestaurantElKbeer> call, Throwable t) {
                Log.i(TAG, "onFailure: failed RegularFragmentCall");
            }
        });
        return myRestaurantsList;
    }

    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    /**
     * Initialize the contents of the Fragment host's standard options menu.  You
     * should place your menu items in to <var>menu</var>.  For this method
     * to be called, you must have first called {@link #setHasOptionsMenu}.  See
     * {@link RestaurantLogoView#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu}
     * for more information.
     *
     * @param menu     The options menu in which you place your items.
     * @param inflater
     * @see #setHasOptionsMenu
     * @see #onPrepareOptionsMenu
     * @see #onOptionsItemSelected
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void setHasOptionsMenu(boolean hasMenu) {
        super.setHasOptionsMenu(hasMenu);
    }
}

And this is my RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private List<RestaurantModel> items;
    private Context ctx;

    public RecyclerViewAdapter(Context context, List<RestaurantModel> items) {
        this.ctx = context;
        this.items=items;
    }

    private OnItemClickListener mOnItemClickListener;
    private SharedPref sharedPref;

    public interface OnItemClickListener {
        void onItemClick(View view, RestaurantModel obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        CardView cv;
        TextView title;
        TextView description;
        ImageView imageView;

        ViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.restaurant_card_view);
            title = (TextView) itemView.findViewById(R.id.restaurantName_section_label);
            description = (TextView) itemView.findViewById(R.id.section_label2);
            imageView = (ImageView) itemView.findViewById(R.id.restaurantImageView);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.restaurant_card_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        RestaurantModel p = (RestaurantModel) payloads.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());
            holder.imageView.setImageResource(R.mipmap.ic_launcher);
        }
       holder.cv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Log.i("RecyclerViewAdapter", "onClick: replace with intent to send Restaurant data");
           }
       });
    }

    @Override
    public void onBindViewHolder(ViewHolder holder,int position) {

        final RestaurantModel p = items.get(position);
        holder.title.setText(p.getRName());
        if (!p.getDelvType().equals("1")) {
            holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge());
        } else {
            holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge());

        }
        holder.cv.setOnClickListener(view -> {
                mOnItemClickListener.onItemClick(view, p, position);

        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public interface OnLoadMoreListener {
        void onLoadMore(int current_page);
    }
}

This is the exception i'm getting

**

06-06 00:11:05.215 10571-10571/com.jeebley.jeebley E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.jeebley.jeebley, PID: 10571
                                                                       java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                           at com.jeebley.jeebley.adapters.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:109)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)
                                                                           at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3310)
                                                                           at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
                                                                           at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
                                                                           at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391)
                                                                           at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1515)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                           at com.android.internal.policy.DecorView.onLayout(DecorView.java:774)
                                                                           at android.view.View.layout(View.java:17687)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5631)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2511)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1364)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6763)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:923)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:735)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:909)
                                                                           at android.os.Handler.handleCallback(Handler.java:761)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:156)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6524)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
  06-06 00:11:05.238 10571-10571/com.jeebley.jeebley I/Process: Sending signal. PID: 10571 SIG: 9

**

Body:
first, check if restaurantResponse.getRestaurantModel() return null.

List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
if(list == null){
    enter code here
}


问:
How to remove lines from File A that are in File B in Windows command shell?
This other question is excellent for joining two files.  I need to do sort of the opposite.  I need to remove lines from File A that are in File B.

This question is similar to this other question, except that question is for unix and this is for the windows command shell (cmd.exe).

I would like to use tools that are native to Windows 7 Pro.

Update:

The files are hosts files.  Each one has lines consisting of:

127.0.0.1   host.domain.com

or

0.0.0.0   host.domain.com

or

# this is a comment

Files may have up to 200,000 lines.  Spaces and tabs may be present.

Although I prefer it to be preserved, order does not affect function.

Here are some examples of hosts files:

https://adaway.org/hosts.txt

https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext

https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts

https://hosts-file.net/ad_servers.txt

http://winhelp2002.mvps.org/hosts.txt

http://someonewhocares.org/hosts/hosts

(Don't worry about 0.0.0.0 vs '127.0.0.1` for this question.)

答:
As dbenham pointed out in a comment, there is a bug of findstr with multiple literal search strings -- reference this thread: Why doesn't this FINDSTR example with multiple literal search strings find a match?. To work around this, you could do the following in command prompt:

copy "fileB" "fileC" & (for /F usebackq^ delims^= eol^= %L in ("fileA") do findstr /V /X /C:"%L" "fileC" > "fileC") & move /Y "fileC" "fileB"
```

<p>Or in a batch file:</p>

<pre class="lang-cmd prettyprint-override"><code>copy "fileB" "fileC"
for /F usebackq^ delims^= eol^= %%L in ("fileA") do (
    findstr /V /X /C:"%%L" "fileC" > "fileC"
)
move /Y "fileC" "fileB"
</code>```

This first copies fileB as fileC, then removes lines from fileC matching those of fileA one after another, then replacing the original fileB by the modified fileC.

Body:
As dbenham pointed out in a comment, there is a bug of findstr with multiple literal search strings -- reference this thread: Why doesn't this FINDSTR example with multiple literal search strings find a match?. To work around this, you could do the following in command prompt:

copy "fileB" "fileC" & (for /F usebackq^ delims^= eol^= %L in ("fileA") do findstr /V /X /C:"%L" "fileC" > "fileC") & move /Y "fileC" "fileB"

Or in a batch file:

copy "fileB" "fileC"
for /F usebackq^ delims^= eol^= %%L in ("fileA") do (
    findstr /V /X /C:"%%L" "fileC" > "fileC"
)
move /Y "fileC" "fileB"

This first copies fileB as fileC, then removes lines from fileC matching those of fileA one after another, then replacing the original fileB by the modified fileC.


问:
Dependency Properties on Controls
In WPF some properties of controls are dependency properties, others are normal properties.

Eg TextBox.SelectedText is a normal property and not a dependency property. I use MVVM and it happens often to me that I want to bind to some property, but I cant, because it is a normal property.

Can someone explain to me, what logic stands behind the decision whether a property is normal or a dependency property.

Also, can I work around this and somehow bind to the normal properties as if they were dependency properties?

答: You can bind to normal properties, but if your property changes, your binding will not get notified. However, you can implement INotifyPropertyChanged in your classes and the binding will update your control automatically.</p>

ContentLicense: CC BY-SA 2.5

Title: Dependency Properties on Controls


问:
Illegal type 'void' in Android Java Class
I have the error Illegal type 'void' in an Android Java Application.

The error comes on the private void createFolder() and public void onRequestPermissionsResult code block.

I dont know if there is missing some imports or there is an error with the public class Berechtigungen extends AppCompatActivity code-line.

If anyone knows an answer to this, please write it, thanks.

My code:

```<code>package barsoftware.suedtirolpointer;

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;

public class Berechtigungen extends AppCompatActivity {

    final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

    public void GPS() {
        if(ActivityCompat.checkSelfPermission(Berechtigungen.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            // Anweisung
        } else {
            ActivityCompat.requestPermissions(Berechtigungen.this,new  String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
        }
    }
};

private void createFolder(){
    File ordner = new File(Environment.getExternalStorageDirectory(), "TestOrdner");
    ordner.mkdirs();
    Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
        createFolder();
    }
}
}
</code>```

答:
It's a syntax error, it should be like this:</p>

```<code>package barsoftware.suedtirolpointer;

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;

public class Berechtigungen extends AppCompatActivity {

    final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

    public void GPS() {

        if (ActivityCompat.checkSelfPermission(Berechtigungen.this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //

        } else {

            ActivityCompat.requestPermissions(Berechtigungen.this,
            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
            REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
        }
    }

    private void createFolder() {

        File ordner = new File(Environment.getExternalStorageDirectory(), "TestOrdner");
        ordner.mkdirs();
        Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION
        && grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            createFolder();
        }
    }
}
</code>```

Body:
I have the error Illegal type 'void' in an Android Java Application.

The error comes on the private void createFolder() and public void onRequestPermissionsResult code block.

I dont know if there is missing some imports or there is an error with the public class Berechtigungen extends AppCompatActivity code-line.

If anyone knows an answer to this, please write it, thanks.

My code:

package barsoftware.suedtirolpointer;

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;

public class Berechtigungen extends AppCompatActivity {

    final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

    public void GPS() {
        if(ActivityCompat.checkSelfPermission(Berechtigungen.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            // Anweisung
        } else {
            ActivityCompat.requestPermissions(Berechtigungen.this,new  String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
        }
    }
};

private void createFolder(){
    File ordner = new File(Environment.getExternalStorageDirectory(), "TestOrdner");
    ordner.mkdirs();
    Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
        createFolder();
    }
}
}

Body:
It's a syntax error, it should be like this:

package barsoftware.suedtirolpointer;

import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;

public class Berechtigungen extends AppCompatActivity {

    final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

    public void GPS() {

        if (ActivityCompat.checkSelfPermission(Berechtigungen.this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //

        } else {

            ActivityCompat.requestPermissions(Berechtigungen.this,
            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
            REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
        }
    }

    private void createFolder() {

        File ordner = new File(Environment.getExternalStorageDirectory(), "TestOrdner");
        ordner.mkdirs();
        Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION
        && grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            createFolder();
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
I want to make a navbar stick to the top but when I scroll the bar comes down but behind the content
Here is my code:

#nav {
  color: #ffffff;
  display: -moz-flex;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -moz-transition: -moz-transform 1s ease, opacity 1s ease;
  -webkit-transition: -webkit-transform 1s ease, opacity 1s ease;
  -ms-transition: -ms-transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease;
  background: rgba(255, 255, 255, 0.175);
  height: 4rem;
  line-height: 4rem;
  margin: -4rem auto 0 auto;
  overflow: hidden;
  padding: 0 2rem 0 0;
  position: relative;
  width: calc(100% - 4rem);
  max-width: 72rem;
  z-index: 2;
}

#nav ul.links {
  display: -moz-flex;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -moz-flex-grow: 1;
  -webkit-flex-grow: 1;
  -ms-flex-grow: 1;
  flex-grow: 1;
  -moz-flex-shrink: 1;
  -webkit-flex-shrink: 1;
  -ms-flex-shrink: 1;
  flex-shrink: 1;
  font-family: "Source Sans Pro", Helvetica, sans-serif;
  font-weight: 900;
  letter-spacing: 0.075em;
  list-style: none;
  margin-bottom: 0;
  padding-left: 0;
  text-transform: uppercase;
}

#nav ul.links li {
  display: block;
  padding-left: 0;
}

#nav ul.icons {
  -moz-flex-grow: 0;
  -webkit-flex-grow: 0;
  -ms-flex-grow: 0;
  flex-grow: 0;
  -moz-flex-shrink: 0;
  -webkit-flex-shrink: 0;
  -ms-flex-shrink: 0;
  flex-shrink: 0;
  margin-bottom: 0;
}

@media screen and (max-width: 980px) {
  #nav {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Nav -->
<nav id="nav_bar">
  <ul class="nav_links">
    <li class="active">Fried Potato</li>
    <li>Generic Page</li>
    <li>Elements Reference</li>
  </ul>
  <ul class="icons">
    <li><span class="label">Twitter</span></li>
  </ul>
</nav></code>```

Basically what happened first is that the navbar was not in the center of the page after I figured out that the bar is behind the content.

答:
Have you tried changing:

```<code> position: fixed;
</code>```

in #nav?

Body:
Here is my code:

#nav {
  color: #ffffff;
  display: -moz-flex;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -moz-transition: -moz-transform 1s ease, opacity 1s ease;
  -webkit-transition: -webkit-transform 1s ease, opacity 1s ease;
  -ms-transition: -ms-transform 1s ease, opacity 1s ease;
  transition: transform 1s ease, opacity 1s ease;
  background: rgba(255, 255, 255, 0.175);
  height: 4rem;
  line-height: 4rem;
  margin: -4rem auto 0 auto;
  overflow: hidden;
  padding: 0 2rem 0 0;
  position: relative;
  width: calc(100% - 4rem);
  max-width: 72rem;
  z-index: 2;
}

#nav ul.links {
  display: -moz-flex;
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -moz-flex-grow: 1;
  -webkit-flex-grow: 1;
  -ms-flex-grow: 1;
  flex-grow: 1;
  -moz-flex-shrink: 1;
  -webkit-flex-shrink: 1;
  -ms-flex-shrink: 1;
  flex-shrink: 1;
  font-family: "Source Sans Pro", Helvetica, sans-serif;
  font-weight: 900;
  letter-spacing: 0.075em;
  list-style: none;
  margin-bottom: 0;
  padding-left: 0;
  text-transform: uppercase;
}

#nav ul.links li {
  display: block;
  padding-left: 0;
}

#nav ul.icons {
  -moz-flex-grow: 0;
  -webkit-flex-grow: 0;
  -ms-flex-grow: 0;
  flex-grow: 0;
  -moz-flex-shrink: 0;
  -webkit-flex-shrink: 0;
  -ms-flex-shrink: 0;
  flex-shrink: 0;
  margin-bottom: 0;
}

@media screen and (max-width: 980px) {
  #nav {
    display: none;
  }
}

Fried Potato

Generic Page

Elements Reference

Twitter

Basically what happened first is that the navbar was not in the center of the page after I figured out that the bar is behind the content.

Body:
Have you tried changing:

 position: fixed;

in #nav?


问:
Making a client's website live with a customized domain name
I'm trying to make a website for a client right now, and I'm using Sublime Text to build it from Scratch using JQuery, JavaScript, HTML5, and CSS3.

However, I don't know how to make it live with a custom domain name when it's built from scratch. Furthermore, I need to make sure the client is paying for any monthly fees that may occur.

Finally, should I switch to only building websites with customizing site building tools like WordPress or SquareSpace? I haven't seen many tutorials on how to host a website after bulding it from scratch for a client.
Thanks!

答:
Google : How to publish a website tutorial. There are many tutorials out there to walk you through the process.

That said, the basic process is as follows.

Register a domain name using a registrar of choice.

Purchase a hosting plan from a host of choice.

Bind your domain to the new hosting account (your host will have a help section for this)

Follow the help section for that host to get your FTP client configured. You will use this to push the files from your computer to the server.

Your website is now live.


问:
Wordpress Custom Meta Box Update Template
So I have created a custom plugin to add another meta box of which will control the page template. The code functions perfectly fine if you only have 1 page with the set value.

Example:
1 Page has radio button 2 selected (works fine)
2 Pages have radio button 2 selected (The first page will work fine the 2nd page will default to the page.php default file.)

Any Ideas as to why it will select the different template value for one page but then for all others defaults back to the page.php template?

```<code><?php
/**
* Plugin Name: Wireframe Templates For Pages V3.7
* Description: Adds a wireframe selection section for the page template
* Version: 1.0
* Author: Daniel Vickers
*/

// Dont call me direct!
if ( ! defined( 'ABSPATH' ) ) exit;

// Create content
function custom_meta_box_markup($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");

    ?>

<style>
label > input{ /* HIDE RADIO */
  visibility: hidden; /* Makes input not-clickable */
  position: absolute; /* Remove input from document flow */
}
label > input + img{ /* IMAGE STYLES */
  cursor:pointer;
  border:2px solid transparent;
}
label > input:checked + img{ /* (RADIO CHECKED) IMAGE STYLES */
  border:2px solid #f00;
}
</style>

        <div>

            <h4>Radio options</h4>
            <?php
                // U need to use this to set the checked="checked"
                $checkbox_value = get_post_meta($object->ID, "page-template-radio", true);
            ?>
                       <label>
                       <input type="radio" name="page-template-radio" value="default"<?php if($checkbox_value == 'default'){echo 'checked =\"checked\"';} ?> /><img src="http://via.placeholder.com/150x220"></label>
                       <label>
                       <input type="radio" name="page-template-radio" value="2col" <?php if($checkbox_value == '2col'){echo 'checked =\"checked\"';} ?>/><img src="http://via.placeholder.com/150x220"></label>
                       <label>
                       <input type="radio" name="page-template-radio" value="1col" <?php if($checkbox_value == '1col'){echo 'checked =\"checked\"';} ?>/>
                       <img src="http://via.placeholder.com/150x220">
                       </label>

        </div>
<?php
}

// Saving data
function save_custom_meta_box($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
        return $post_id;

    if(!current_user_can("edit_post", $post_id))
        return $post_id;

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;

    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;

    if(isset($_POST["meta-box-radio"]))
    {
        $meta_box_value = $_POST["meta-box-radio"];
    }
    update_post_meta($post_id, "meta-box-radio", $meta_box_value);

}

add_action("save_post", "save_custom_meta_box", 10, 3);

function add_custom_meta_box()
{
    add_meta_box("demo-meta-box", "Page Template", "custom_meta_box_markup", "page", "normal", "high", null);
}

add_action("add_meta_boxes", "add_custom_meta_box");

// Get our option for post ID from the options meta box change "$field_name" to your option name you use in the meta box
$post_option = get_post_meta(get_the_ID(),"page-template-radio",true);

// Check our option and change the display to what option is set

    if($post_option == "default")
    {
        update_post_meta( $page_id, '_wp_page_template', 'page.php' );
   }
    elseif($post_option == "2col") {
        update_post_meta( $page_id, '_wp_page_template', 'page-2col.php' );
    }
    elseif ($post_option == "1col") {
        update_post_meta( $page_id, '_wp_page_template', 'page-1col.php' );
    }
    else{
     // Added for when an option is not set
    }?>
</code>```

答:
Your code looks a bit like a mess, but I think I see the problem.
You're saving the value in a different meta property than you're getting the value from.

In the edit screen you can also open the 'extra fields' item. That would show you all the meta data for a post and is a great help for diagnosing problems with saving meta.

You can also have a look at https://github.com/svrooij/wp-geocoded-posts/blob/master/geocoded-posts/includes/class-geocoded-posts-editor.php this is the class of my plugin, for adding some meta fields to a post. It's getting loaded by the plugin file a folder higher.

Body:
So I have created a custom plugin to add another meta box of which will control the page template. The code functions perfectly fine if you only have 1 page with the set value.

Example:
1 Page has radio button 2 selected (works fine)
2 Pages have radio button 2 selected (The first page will work fine the 2nd page will default to the page.php default file.)

Any Ideas as to why it will select the different template value for one page but then for all others defaults back to the page.php template?

<?php
/**
* Plugin Name: Wireframe Templates For Pages V3.7
* Description: Adds a wireframe selection section for the page template
* Version: 1.0
* Author: Daniel Vickers
*/

// Dont call me direct!
if ( ! defined( 'ABSPATH' ) ) exit;

// Create content
function custom_meta_box_markup($object)
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");

    ?>

Radio options

            <?php
                // U need to use this to set the checked="checked"
                $checkbox_value = get_post_meta($object->ID, "page-template-radio", true);
            ?>

                       <input type="radio" name="page-template-radio" value="default"<?php if($checkbox_value == 'default'){echo 'checked =\"checked\"';} ?> />

                       <input type="radio" name="page-template-radio" value="2col" <?php if($checkbox_value == '2col'){echo 'checked =\"checked\"';} ?>/>

                       <input type="radio" name="page-template-radio" value="1col" <?php if($checkbox_value == '1col'){echo 'checked =\"checked\"';} ?>/>

<?php
}

// Saving data
function save_custom_meta_box($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
        return $post_id;

    if(!current_user_can("edit_post", $post_id))
        return $post_id;

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;

    $slug = "post";
    if($slug != $post->post_type)
        return $post_id;

    if(isset($_POST["meta-box-radio"]))
    {
        $meta_box_value = $_POST["meta-box-radio"];
    }
    update_post_meta($post_id, "meta-box-radio", $meta_box_value);

}

add_action("save_post", "save_custom_meta_box", 10, 3);

function add_custom_meta_box()
{
    add_meta_box("demo-meta-box", "Page Template", "custom_meta_box_markup", "page", "normal", "high", null);
}

add_action("add_meta_boxes", "add_custom_meta_box");

// Get our option for post ID from the options meta box change "$field_name" to your option name you use in the meta box
$post_option = get_post_meta(get_the_ID(),"page-template-radio",true);

// Check our option and change the display to what option is set

    if($post_option == "default")
    {
        update_post_meta( $page_id, '_wp_page_template', 'page.php' );
   }
    elseif($post_option == "2col") {
        update_post_meta( $page_id, '_wp_page_template', 'page-2col.php' );
    }
    elseif ($post_option == "1col") {
        update_post_meta( $page_id, '_wp_page_template', 'page-1col.php' );
    }
    else{
     // Added for when an option is not set
    }?>


问:
Grunt wiredep:app Cannot find Bower packages
After running

yo ionic

from https://github.com/diegonetto/generator-ionic

Then lauching grunt serve i've got this :

Running "wiredep:app" (wiredep) task

Cannot find where you keep your Bower packages.

I'm stuck and I can't get a preview of the app.

答:
@arnaudlrx 's answer is correct but check if you instal git in your machine , because if you run </p>

```<code>bower install jquery --save
</code>```

<p>but you don't have git installed there nothing will work </p>

Body:
@arnaudlrx 's answer is correct but check if you instal git in your machine , because if you run

bower install jquery --save

but you don't have git installed there nothing will work


问:
How can I set the timestamps in a Git repository to those of an otherwise-identical repository?
I just cloned my git files from a repository onto a new computer. Now they all say that they were modified/created today, rather than the actual dates from the old computer.

How can I "restore" these timestamps in bulk?

Here's what I did:

On my Old Workstation:

I had a repository at ~/MyWork.git that I used as a centralized repository: any clones of that repository pulled/pushed from/to that repository.

I had a local clone of that repository at ~/MyWork. This was my "working repository".

On my New Workstation:

I mounted the old hard drive to `/Volumes/OldComputer'

I copied the centralized repository from my old hard drive to the new:
cp /Volumes/OldComputer/Users/Me/MyWork.git ~/MyWorkNew.git. (It would now be my centralized repository.)

I created a new folder mkdir ~/MyWorkNew on the new computer to be my new "working repository".

I cloned the new centralized repository to the new working repository: git clone ~/MyWorkNew.git ~/MyWorkNew/

I feel like there should be a good way using git to do this without just copying everything directly, e.g. cp -rp /Volumes/OldComputer/Users/Me/MyWork ~/MyWorkNew...but perhaps I'm wrong?

Alternative Solution

Short of simply copying all files over, is there a way to copy all timestamps from one repository to another programmatically (#ScriptFu)? The whole directory structure and file names should be the same between the two repositories. It seems it could be done via recursion: "for each File, recursively, in OldDir and NewDir, set the timestamp of NewDir/File to that of OldDir/File".

答:
Filesystem timestamps record the last time anything wrote to a file.  In your case, that would be when you copied into them.

If you want the last-committed timestamp for a file, do e.g. git log -1 --pretty=%cd -- $thefile or git blame @ $thefile to get the last-committed timestamp for each line in it.

Using filesystem timestamps the way you're after is an easy-to-make rookie mistake.  Any system relying on filesystem timestamps to sync other content with your current source will fail. The breakage will generally be of the very worst kind: the results of whatever sort of compilation you do will not reflect the source they were, to all appearances, generated from, because the tools that check those dates will see that the results were generated after the file last changed.  Which, if you do what you're asking for here, will be a lie.

Doing what you're asking for even if only sometimes, only when that's what you'll be using most often, is a recipe for failure.  Keep semantics simple: filesystem timestamp = time-filesystem-written, commit timestamp = time-commit-written, and everything works.

Trust Us: You Really Really Don't Want Surprise Semantics.


问:
Redshift Alternative for Correlated Sub-Query
I am using Redshift and need an alternative for a correlated subquery.  I am getting the correlated subquery not supported error. However, for this particular exercise of trying to identify all sales transactions made by the same customer within a given hour from the originating transaction, I am not sure a traditional left join would work either.  I.e., the query is dependent on the context or current value from the parent select.  I have also tried something similar using row_number() window function but again, need a way to window / partition on a date range - not just customer_id.

The overall goal is to find the first sales transaction for a given customer id, then find all subsequent transactions made within 60 minutes of the first transaction.  This logic will continue on for the remainder of the transactions for the same customer (and ultimately all customers in the database).  That is, once the initial 60 minute window has been established from the time of the first transaction, a second 60 minute window would begin at the end of the first 60 minute window, and all transactions within the second window would also be identified and combined and then repeat for the remainder of transactions.

The output would list the first transaction id that started the 60 minute window, then the other subsequent transaction ids that were made within the 60 minute window.  The 2nd row would display the first transaction id made by the same customer in the next 60 minute window (again, the first transaction post the first 60 minute window would be the start of the second 60 minute window) and then the subsequent transactions also made within the second 60 minute window.

The query example in its most basic form looks like the query below:

```<code>select
s1.customer_id,
s1.transaction_id,
s1.order_time,
(
    select
        s2.transaction_id
    from
        sales s2
    where
        s2.order_time > s1.order_time and
        s2.order_time <= dateadd(m,60,s1.order_time) and
        s2.customer_id = s1.customer_id
    order by
        s2.order_time asc
    limit 1
) as sales_transaction_id_1,
(
    select
        s3.transaction_id
    from
        sales s3
    where
        s3.order_time > s1.order_time and
        s3.order_time <= dateadd(m,60,s1.order_time) and
        s3.customer_id = s1.customer_id
    order by
        s3.order_time asc
    limit 1 offset 1
) as sales_transaction_id_2,
(
    select
        s3.transaction_id
    from
        sales s4
    where
        s4.order_time > s1.order_time and
        s4.order_time <= dateadd(m,60,s1.order_time) and
        s4.customer_id = s1.customer_id
    order by
        s4.order_time asc
    limit 1 offset 1
) as sales_transaction_id_3
from
    (
        select
            sales.customer_id,
            sales.transaction_id,
            sales.order_time
        from
            sales
        order by
            sales.order_time desc
    ) s1;
</code>```

For example, if a customer made the following transactions:

```<code>customer_id     transaction_id      order_time
1234                33453           2017-06-05 13:30
1234                88472           2017-06-05 13:45
1234                88477           2017-06-05 14:10

1234                99321           2017-06-07 8:30
1234                99345           2017-06-07 8:45
</code>```

The expected output would be as:

```<code>customer_id     transaction_id  sales_transaction_id_1 sales_transaction_id_2   sales_transaction_id_3
1234                33453           88472                   88477                   NULL
1234                99321           99345                   NULL                    NULL
</code>```

Also, it appears Redshift does not support lateral joins which seems to further restrict the options at my disposal.  Any help would be greatly appreciated.

答:
From your description, you just want group by and some sort of date difference.  I'm not sure how you want to combine the rows, but here is the basic idea:

```<code>select s.customer_id,
       min(order_time) as first_order_in_hour,
       max(order_time) as last_order_in_hour,
       count(*) as num_orders
from (select s.*,
             min(order_time) over (partition by customer_id) as min_ot
      from sales s
     ) s
group by customer_id, floor(datediff(second, min_ot, order_time) / (60 * 60));
</code>```

This formulation (or something similar because Postgres does not have datediff()) would also be much faster in Postgres.

Body:
I am using Redshift and need an alternative for a correlated subquery.  I am getting the correlated subquery not supported error. However, for this particular exercise of trying to identify all sales transactions made by the same customer within a given hour from the originating transaction, I am not sure a traditional left join would work either.  I.e., the query is dependent on the context or current value from the parent select.  I have also tried something similar using row_number() window function but again, need a way to window / partition on a date range - not just customer_id.

The overall goal is to find the first sales transaction for a given customer id, then find all subsequent transactions made within 60 minutes of the first transaction.  This logic will continue on for the remainder of the transactions for the same customer (and ultimately all customers in the database).  That is, once the initial 60 minute window has been established from the time of the first transaction, a second 60 minute window would begin at the end of the first 60 minute window, and all transactions within the second window would also be identified and combined and then repeat for the remainder of transactions.

The output would list the first transaction id that started the 60 minute window, then the other subsequent transaction ids that were made within the 60 minute window.  The 2nd row would display the first transaction id made by the same customer in the next 60 minute window (again, the first transaction post the first 60 minute window would be the start of the second 60 minute window) and then the subsequent transactions also made within the second 60 minute window.

The query example in its most basic form looks like the query below:

select
s1.customer_id,
s1.transaction_id,
s1.order_time,
(
    select
        s2.transaction_id
    from
        sales s2
    where
        s2.order_time > s1.order_time and
        s2.order_time <= dateadd(m,60,s1.order_time) and
        s2.customer_id = s1.customer_id
    order by
        s2.order_time asc
    limit 1
) as sales_transaction_id_1,
(
    select
        s3.transaction_id
    from
        sales s3
    where
        s3.order_time > s1.order_time and
        s3.order_time <= dateadd(m,60,s1.order_time) and
        s3.customer_id = s1.customer_id
    order by
        s3.order_time asc
    limit 1 offset 1
) as sales_transaction_id_2,
(
    select
        s3.transaction_id
    from
        sales s4
    where
        s4.order_time > s1.order_time and
        s4.order_time <= dateadd(m,60,s1.order_time) and
        s4.customer_id = s1.customer_id
    order by
        s4.order_time asc
    limit 1 offset 1
) as sales_transaction_id_3
from
    (
        select
            sales.customer_id,
            sales.transaction_id,
            sales.order_time
        from
            sales
        order by
            sales.order_time desc
    ) s1;

For example, if a customer made the following transactions:

customer_id     transaction_id      order_time
1234                33453           2017-06-05 13:30
1234                88472           2017-06-05 13:45
1234                88477           2017-06-05 14:10

1234                99321           2017-06-07 8:30
1234                99345           2017-06-07 8:45

The expected output would be as:

customer_id     transaction_id  sales_transaction_id_1 sales_transaction_id_2   sales_transaction_id_3
1234                33453           88472                   88477                   NULL
1234                99321           99345                   NULL                    NULL

Also, it appears Redshift does not support lateral joins which seems to further restrict the options at my disposal.  Any help would be greatly appreciated.

Body:
From your description, you just want group by and some sort of date difference.  I'm not sure how you want to combine the rows, but here is the basic idea:

select s.customer_id,
       min(order_time) as first_order_in_hour,
       max(order_time) as last_order_in_hour,
       count(*) as num_orders
from (select s.*,
             min(order_time) over (partition by customer_id) as min_ot
      from sales s
     ) s
group by customer_id, floor(datediff(second, min_ot, order_time) / (60 * 60));

This formulation (or something similar because Postgres does not have datediff()) would also be much faster in Postgres.


问:
Can not render value with Vuejs, but console log work fine
I getting started with VueJS and must say it works amazing, though trying the Vue-Resource implementation, does only work half the time.

When pulling data from my server, it seems like it wont finalize the data.

An example is the following code, where in I have loaded a request from my server, but it will only load half the data.

The response I am trying to insert into the parser, looks like this.

[{ city: "New York", amount: 8 }, { city: "San Francisco", amount: 18 }]

The issue is when I am logging it to the console it works fine, but rendering removes the amount. Never the city, only the amount from each location.

Can anybody tell me how this happens. I can only find solutions from Vue.js 0.9, but I am using Vue.js 2.3.3 and Vue-resource 1.3.3.

```<code>vm = new Vue({
el: '#devApp',
data: {
    citiesCount: [],
},
mounted: function()
{
    this.getLocationsCityCount();
    this.getLatestLocations();
},
methods: {
    getLocationsCityCount: function(cb)
    {
        var test = this.$http.get('/api/v1/locations/count/cities').then(
            success => {
                console.log(success.body.response);
                this.citiesCount = success.body.response;
            },
            error => {
                console.log('error');
                console.log(error);
            }
        );
    },
}
</code>```

});

答:
It is not the template, but here you go, I have tried with static data.

Here is the template:

```<code><div id="devApp" class="panel panel-default">
<div class="panel-heading">
    <h4 class="panel-title">Location amount per city</h4>
</div>

<ul class="list-group location-list">
    <li class="list-group-item" v-for="item in citiesCount">@{{item.city}}<span class="badge">@{{item.amount}}</span></li>
</ul>
</code>```

Body:
I getting started with VueJS and must say it works amazing, though trying the Vue-Resource implementation, does only work half the time.

When pulling data from my server, it seems like it wont finalize the data.

An example is the following code, where in I have loaded a request from my server, but it will only load half the data.

The response I am trying to insert into the parser, looks like this.

[{ city: "New York", amount: 8 }, { city: "San Francisco", amount: 18 }]

The issue is when I am logging it to the console it works fine, but rendering removes the amount. Never the city, only the amount from each location.

Can anybody tell me how this happens. I can only find solutions from Vue.js 0.9, but I am using Vue.js 2.3.3 and Vue-resource 1.3.3.

vm = new Vue({
el: '#devApp',
data: {
    citiesCount: [],
},
mounted: function()
{
    this.getLocationsCityCount();
    this.getLatestLocations();
},
methods: {
    getLocationsCityCount: function(cb)
    {
        var test = this.$http.get('/api/v1/locations/count/cities').then(
            success => {
                console.log(success.body.response);
                this.citiesCount = success.body.response;
            },
            error => {
                console.log('error');
                console.log(error);
            }
        );
    },
}

});

Body:
It is not the template, but here you go, I have tried with static data.

Here is the template:

<div id="devApp" class="panel panel-default">
<div class="panel-heading">
    <h4 class="panel-title">Location amount per city</h4>
</div>

<ul class="list-group location-list">
    <li class="list-group-item" v-for="item in citiesCount">@{{item.city}}<span class="badge">@{{item.amount}}</span></li>
</ul>


问:
Why AngularJS data binding is not working
Playing with some AngularJS and a very simple example is not working - like Angular isn't loading. In the example I have a simple data binding test where I'm just using {{}} to print out a hardcoded string. But all I get are the braces and the string inside of it.

```<code><!DOCTYPE html >
<html lang="en" ng-app>
<head >
    <title >Data Binding</title >
    <meta charset="UTF-8">
    <link href="../libs/bootstrap/dist/css/bootstrap.min.css"
      rel="stylesheet" >
    <link href="main.css"
      rel="stylesheet" >
</head >

<body >

<div class="container" >
    {{ 'dummy text' }}    <<== Uninterpreted Angular
</div >

<script src="../libs/angular/angular.min.js" ></script >
</body >
</html >
</code>```

The HTML validates, but I can't see why it won't execute properly. It's probably one of those "everyone knows that" type of thing!

答:
I  just replaced your angular reference with CDN and it works fine. Here is the code snippet. May be your include directory is wrong for angular or your angular file is corrupted.

<!DOCTYPE html >

    <title >Data Binding</title >
    <meta charset="UTF-8">
    <link href="../libs/bootstrap/dist/css/bootstrap.min.css"
      rel="stylesheet" >
    <link href="main.css"
      rel="stylesheet" >

    {{ 1+1 }}

```

Body:
Playing with some AngularJS and a very simple example is not working - like Angular isn't loading. In the example I have a simple data binding test where I'm just using {{}} to print out a hardcoded string. But all I get are the braces and the string inside of it.

<!DOCTYPE html >

    <title >Data Binding</title >
    <meta charset="UTF-8">
    <link href="../libs/bootstrap/dist/css/bootstrap.min.css"
      rel="stylesheet" >
    <link href="main.css"
      rel="stylesheet" >

    {{ 'dummy text' }}    <<== Uninterpreted Angular

The HTML validates, but I can't see why it won't execute properly. It's probably one of those "everyone knows that" type of thing!

Body:
I  just replaced your angular reference with CDN and it works fine. Here is the code snippet. May be your include directory is wrong for angular or your angular file is corrupted.

<!DOCTYPE html >
<html lang="en" ng-app>
<head >
    <title >Data Binding</title >
    <meta charset="UTF-8">
    <link href="../libs/bootstrap/dist/css/bootstrap.min.css"
      rel="stylesheet" >
    <link href="main.css"
      rel="stylesheet" >
</head >

<body >

<div class="container" >
    {{ 1+1 }}
</div >

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js" ></script >
</body >
</html >