问:
LINQ in Business Layer paging / sorting gridview in User layer
I have a gridview in my user layer that uses a business layer method as its datasource, and I want the gridview to support paging and sorting. When I returned an Ienumerable from the method, it will bring back all of the data. If I use Take/Skip to bring back only a page's worth, the gridview doesn't realize that there are many pages of data.

When I change the Ienumerable to an IQueryable, the DataBind() fails because the data has already been disposed of. I think this problem has something to do with when the query actually executes and it may have to do with the filters I am applying to the query (see below).

User Layer Code:

```<code>grdSelectedQuestionaires.DataSource = assessment.FilteredAssessmentList(filter);
grdSelectedQuestionaires.DataBind(); <-- Fails - "Cannot access a disposed object"
</code>```

Business Layer Code:

```<code>public IQueryable<Assessment> FilteredAssessmentList(AssessmentSearchFilter filter)
    {
        using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
        {
            var rows = (
                    from a in dc.vPAQSummaries
                    select new Assessment()
                    {
                        PAQNumber = a.PAQNumber.Trim(),
                        CustomerID = (int)a.CustomerID,
                        Department = a.Department.Trim(),
                        CustomerName = a.CustomerName.Trim(),
                        DOTNumber = a.DOTNumber.Trim(),
                        OrgName = a.OrgName.Trim(),
                        DateEntered = a.DateEntered,
                        GroupNumber = a.GroupNumber.Trim(),
                        JobTitle = a.JobTitle.Trim(),
                        FileNames = a.FileNames.Trim(),
                        AnalystType = a.AnalystType.ToString(),
                        Incumbents = a.Incumbents,
                    });

            //  Filter by Customer ID
            if (filter.CustomerID > 0)
            {
                rows = rows.Where(r => r.CustomerID == filter.CustomerID);
            }
            else
            {
                rows = rows.Where(r => r.CustomerID != null);
            }

            //  Filter by DOT Number
            if (!string.IsNullOrEmpty(filter.DOTNumberFrom))
            {
                if (string.IsNullOrEmpty(filter.DOTNumberTo))
                {
                    rows = rows.Where(r => r.DOTNumber == filter.DOTNumberFrom);
                }
                else
                {
                    rows = rows.Where(r => r.DOTNumber.CompareTo(filter.DOTNumberFrom) >= 0
                        && r.DOTNumber.CompareTo(filter.DOTNumberTo) <= 0);
                }
            }

            //  Filter by OrgName
            if (!string.IsNullOrEmpty(filter.OrgName))
            {
                rows = rows.Where(r => r.OrgName.StartsWith(filter.OrgName));
            }

            //  Filter by Group
            if (!string.IsNullOrEmpty(filter.GroupNumberFrom))
            {
                if (!string.IsNullOrEmpty(filter.GroupNumberTo))
                {
                    rows = rows.Where(r => r.GroupNumber == filter.GroupNumberFrom);
                }
                else
                {
                    rows = rows.Where(r => r.GroupNumber.CompareTo(filter.GroupNumberFrom) >= 0
                        && r.GroupNumber.CompareTo(filter.GroupNumberTo) <= 0);
                }
            }

            if (filter.Skip > 0)
            {
                rows = rows.Skip(filter.Skip);
            }
            if (filter.Take > 0)
            {
                rows = rows.Take(filter.Take);
            }
            else
            {
                rows = rows.Take(100);
            }

            return rows.Distinct();
        }
    }
}
</code>```

答:
The paging problem was caused by the Using statement. Changing this:

```<code>using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
...
}
</code>```

to this:

```<code>PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext();
</code>```

Made paging work. Now I have to figure out how sorting works.

Body:
I have a gridview in my user layer that uses a business layer method as its datasource, and I want the gridview to support paging and sorting. When I returned an Ienumerable from the method, it will bring back all of the data. If I use Take/Skip to bring back only a page's worth, the gridview doesn't realize that there are many pages of data.

When I change the Ienumerable to an IQueryable, the DataBind() fails because the data has already been disposed of. I think this problem has something to do with when the query actually executes and it may have to do with the filters I am applying to the query (see below).

User Layer Code:

grdSelectedQuestionaires.DataSource = assessment.FilteredAssessmentList(filter);
grdSelectedQuestionaires.DataBind(); <-- Fails - "Cannot access a disposed object"

Business Layer Code:

public IQueryable<Assessment> FilteredAssessmentList(AssessmentSearchFilter filter)
    {
        using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
        {
            var rows = (
                    from a in dc.vPAQSummaries
                    select new Assessment()
                    {
                        PAQNumber = a.PAQNumber.Trim(),
                        CustomerID = (int)a.CustomerID,
                        Department = a.Department.Trim(),
                        CustomerName = a.CustomerName.Trim(),
                        DOTNumber = a.DOTNumber.Trim(),
                        OrgName = a.OrgName.Trim(),
                        DateEntered = a.DateEntered,
                        GroupNumber = a.GroupNumber.Trim(),
                        JobTitle = a.JobTitle.Trim(),
                        FileNames = a.FileNames.Trim(),
                        AnalystType = a.AnalystType.ToString(),
                        Incumbents = a.Incumbents,
                    });

            //  Filter by Customer ID
            if (filter.CustomerID > 0)
            {
                rows = rows.Where(r => r.CustomerID == filter.CustomerID);
            }
            else
            {
                rows = rows.Where(r => r.CustomerID != null);
            }

            //  Filter by DOT Number
            if (!string.IsNullOrEmpty(filter.DOTNumberFrom))
            {
                if (string.IsNullOrEmpty(filter.DOTNumberTo))
                {
                    rows = rows.Where(r => r.DOTNumber == filter.DOTNumberFrom);
                }
                else
                {
                    rows = rows.Where(r => r.DOTNumber.CompareTo(filter.DOTNumberFrom) >= 0
                        && r.DOTNumber.CompareTo(filter.DOTNumberTo) <= 0);
                }
            }

            //  Filter by OrgName
            if (!string.IsNullOrEmpty(filter.OrgName))
            {
                rows = rows.Where(r => r.OrgName.StartsWith(filter.OrgName));
            }

            //  Filter by Group
            if (!string.IsNullOrEmpty(filter.GroupNumberFrom))
            {
                if (!string.IsNullOrEmpty(filter.GroupNumberTo))
                {
                    rows = rows.Where(r => r.GroupNumber == filter.GroupNumberFrom);
                }
                else
                {
                    rows = rows.Where(r => r.GroupNumber.CompareTo(filter.GroupNumberFrom) >= 0
                        && r.GroupNumber.CompareTo(filter.GroupNumberTo) <= 0);
                }
            }

            if (filter.Skip > 0)
            {
                rows = rows.Skip(filter.Skip);
            }
            if (filter.Take > 0)
            {
                rows = rows.Take(filter.Take);
            }
            else
            {
                rows = rows.Take(100);
            }

            return rows.Distinct();
        }
    }
}

Body:
The paging problem was caused by the Using statement. Changing this:

using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
...
}

to this:

PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext();

Made paging work. Now I have to figure out how sorting works.


来源: stackexchange

答:
I finally found a solution i found in this link. https://data.stackexchange.com/stackoverflow/query/61772/new</p>
```<code>select  min(ServerDateTime) as DateTime
,       max(cBid) as Highest
,       min(cBid) as Lowest
,       min(case when rn_asc = 1 then [cBid] end) as first
,       min(case when rn_desc = 1 then [cBid] end) as Last
from    (
        select  row_number() over (
                    partition by cast(cast(ServerDateTime as float) * 60 * 24 as int)
                    order by ServerDateTime) as rn_asc
        ,       row_number() over (
                    partition by cast(cast(ServerDateTime as float) * 60 * 24 as int)
                    order by ServerDateTime desc) as rn_desc
        ,       *
        from    dbo.MT4TICK
        ) as SubQueryAlias

group by
        cast(cast(ServerDateTime as float) * 60 * 24 as int)
order by DateTime
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL Server : tick-by-tick data to OHLC

Body:
Can anyone please help with a SQL query to convert tick-by-tick data to OHLC (Open\High\Low\Close) one in 1 minute intervals? I was able to get High and Low data, but having difficulties with Open and Close.

My sample data looks like this:

  idc   ServerDateTime          iDateTime   sSymbol cAsk    cBid    Spread
---------------------------------------------------------------------------
2539581 2017-11-13 00:14:56.357 1510539296  EURUSD  1.16473 1.16460 0.00013
2539582 2017-11-13 00:14:56.373 1510539296  EURUSD  1.16475 1.16461 0.00014
2539583 2017-11-13 00:14:56.423 1510539296  EURUSD  1.16476 1.16462 0.00014
2539584 2017-11-13 00:14:56.520 1510539296  EURUSD  1.16477 1.16463 0.00014
2539585 2017-11-13 00:14:56.643 1510539296  EURUSD  1.16478 1.16463 0.00015
2539586 2017-11-13 00:14:58.207 1510539298  EURUSD  1.16478 1.16464 0.00014
2539587 2017-11-13 00:14:59.477 1510539299  EURUSD  1.16477 1.16464 0.00013
2539588 2017-11-13 00:15:00.337 1510539300  EURUSD  1.16477 1.16463 0.00014
2539589 2017-11-13 00:15:00.747 1510539300  EURUSD  1.16478 1.16463 0.00015
2539590 2017-11-13 00:15:00.873 1510539300  EURUSD  1.16477 1.16463 0.00014
2539591 2017-11-13 00:15:01.510 1510539301  EURUSD  1.16477 1.16464 0.00013

There are some similar question with answers, but those are for python and MySQL.

Body:
I finally found a solution i found in this link. https://data.stackexchange.com/stackoverflow/query/61772/new

select  min(ServerDateTime) as DateTime
,       max(cBid) as Highest
,       min(cBid) as Lowest
,       min(case when rn_asc = 1 then [cBid] end) as first
,       min(case when rn_desc = 1 then [cBid] end) as Last
from    (
        select  row_number() over (
                    partition by cast(cast(ServerDateTime as float) * 60 * 24 as int)
                    order by ServerDateTime) as rn_asc
        ,       row_number() over (
                    partition by cast(cast(ServerDateTime as float) * 60 * 24 as int)
                    order by ServerDateTime desc) as rn_desc
        ,       *
        from    dbo.MT4TICK
        ) as SubQueryAlias

group by
        cast(cast(ServerDateTime as float) * 60 * 24 as int)
order by DateTime

ContentLicense: CC BY-SA 4.0


问:
Trying to remove a RecycleView item(Loaded from webservices) by swiping left or right
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

```<code>    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}
</code>```

and my Adapter class is

MyRecyclerAdapter.java

```<code>    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}
</code>```

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

```<code>        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());
</code>```

答:
Remove Data from ArrayList inside onMove(). The use notifyDataSetChanged()

```<code>ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
       // rView.removeViewAt(viewHolder.getAdapterPosition());
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition()); //Optional .Since we uses notifyDataSetChanged()
        data.remove(viewHolder.getAdapterPosition());

       // adapter.notifyDataSetChanged();
     //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

        return false;
    }
</code>```

use adapter.notifyDataSetChanged(); after itemTouchHelper.attachToRecyclerView(rView)

please try this. Happy Coding

Body:
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}

and my Adapter class is

MyRecyclerAdapter.java

    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

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

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());

Body:
Remove Data from ArrayList inside onMove(). The use notifyDataSetChanged()

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
       // rView.removeViewAt(viewHolder.getAdapterPosition());
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition()); //Optional .Since we uses notifyDataSetChanged()
        data.remove(viewHolder.getAdapterPosition());

       // adapter.notifyDataSetChanged();
     //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

        return false;
    }

use adapter.notifyDataSetChanged(); after itemTouchHelper.attachToRecyclerView(rView)

please try this. Happy Coding


问:
How to show ajax response into bootstrap modal
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

```<code> <a href="#." data-toggle="modal" data-target="#myModal" data-id="{{$user->id}}"  class="chooseSchoolBtn">Choose School</a>
</code>```

Ajax :

```<code>$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});
</code>```

Modal:

```<code><div class="modal-body">
    // This section will come dynamically
    <div class="col-md-2 col-sm-4 col-xs-12">
        <div class="single_school">
            <div class="selection_area">
                <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>
            <div class="school_img_area" style="background-image: url(school/images/school/school1.jpg);">
            </div>
            <div class="school_info">
                <p class="school_name">School Name</p>
                <p class="school_description">Good School...</p>
                <p class="school_price">12$</p>
            </div>
        </div>
    </div>
    // dynamic section ends
</div>
</code>```

json response :

```<code>{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}
</code>```

答:
Just change the ajax response data

```<code>info.done(function(data){
    $.each(data,function(index,value){
        $(".school_img_area").attr("style","background-image: url(school/images/school/"+value.display_image+");");
        $(".school_name").html(value.name);
        $(".school_price").html(value.price);
    });
});
</code>```

Happy Coding :-)

Body:
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

 id}}"  class="chooseSchoolBtn">Choose School

Ajax :

$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});

Modal:

    // This section will come dynamically

School Name

Good School...

12$

    // dynamic section ends

json response :

{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}

Body:
Just change the ajax response data

info.done(function(data){
    $.each(data,function(index,value){
        $(".school_img_area").attr("style","background-image: url(school/images/school/"+value.display_image+");");
        $(".school_name").html(value.name);
        $(".school_price").html(value.price);
    });
});

Happy Coding :-)


问:
Type safe version of lodash _.get - deconstruct array type conditionally
For a long time we've been having a problem that the only way to access a nested property safely and easily is to use _.get. Ex:

```<code>_.get(obj, "Some.Nested[2].Property", defaultValue);
</code>```

This works great, but doesn't stand up to property renames as frequently happens. Theoretically, it should be possible to transform the above into the following and allow TypeScript to implicitly type check it:

```<code>safeGet(obj, "Some", "Nested", 2, "Property", defaultValue);
</code>```

I've been successful in creating such a typing for everything except for array types:

```<code>function getSafe<TObject, P1 extends keyof TObject>(obj: TObject, p1: P1): TObject[P1];

function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1]>(obj: TObject, p1: P1, p2: P2): TObject[P1][P2];
</code>```

This properly checks for items at depth (I will auto generate these statements to 10 levels or so). It fails with array properties because the type passed into the next parameter is T[] and not T.

The complexity or verbosity of any solution is of no consideration as the code will be auto generated, the problem is that I can't seem to find any combination of type declarations which will allow me to accept an integer parameter and deconstruct the array type moving forward.

You can deconstruct an array (where T is an array) using T[number]. The problem is that I have no way to constrain where T is an array on a nested property.

```<code>function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1][number]>(obj: TObject, p1: P1, index: number, p2: P2): TObject[P1][number][P2];
                                                                                ^^^^^^                                                             ^^^^^^
const test2 = getSafe(obj, "Employment", 0, "Id"); // example usage
</code>```

That actually works at the call-site (no errors there, correctly gives us param and return types), but gives us an error in the declaration itself because you can't index TObject[P1] with [number] as we can't guarantee TObject[P1] is an array.

(Note: TType[number] is a viable way to get the element type from an array type, but we need to convince the compiler that we're doing this to an array)

The question is really, would there be away to add a array constraint to TObject[P1] or is there another way to do this that I'm missing.

答:
I've since figured this out and published an npm package here: ts-get-safe

The key point was figuring out how to conditionally restructure the array into it's element type. In order to do that, you first have to assert that all the properties are either an array or never. The type that solved the equation was:

```<code>type GSArrEl<TKeys extends keyof TObj, TObj> = { [P in TKeys]: undefined[] & TObj[P] }[TKeys][number];
</code>```

The magic is in { [P in TKeys]: undefined[] & TObj[P] } where we essentially union each property of TObj to undefined[]. Because we are then sure that each property is either an array or never (it will be never on each property which is not an array), we can then do the destructuring expression [number] to get the element type.

Here is an example of two array destructuring happening at the same time:

```<code>function getSafe<TObject, P0 extends keyof TObject, A1 extends GSArrEl<P0, TObject>, P2 extends keyof A1, P3 extends keyof A1[P2], A4 extends GSArrEl<P3, A1[P2]>>(obj: TObject, p0: P0, a1: number, p2: P2, p3: P3, a4: number): A4;
</code>```

Hundreds of combinations of arrays and object properties have been generated in my ts-get-safe library and are ready to use, however I'm still open to ways to improve this in a generic way such that we can use a dynamic number of parameters in the same declaration. Even a way to combine Array and Property navigation into the same type constraint so we don't have to generate every variation of array and property access.

Body:
For a long time we've been having a problem that the only way to access a nested property safely and easily is to use _.get. Ex:

_.get(obj, "Some.Nested[2].Property", defaultValue);

This works great, but doesn't stand up to property renames as frequently happens. Theoretically, it should be possible to transform the above into the following and allow TypeScript to implicitly type check it:

safeGet(obj, "Some", "Nested", 2, "Property", defaultValue);

I've been successful in creating such a typing for everything except for array types:

function getSafe<TObject, P1 extends keyof TObject>(obj: TObject, p1: P1): TObject[P1];

function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1]>(obj: TObject, p1: P1, p2: P2): TObject[P1][P2];

This properly checks for items at depth (I will auto generate these statements to 10 levels or so). It fails with array properties because the type passed into the next parameter is T[] and not T.

The complexity or verbosity of any solution is of no consideration as the code will be auto generated, the problem is that I can't seem to find any combination of type declarations which will allow me to accept an integer parameter and deconstruct the array type moving forward.

You can deconstruct an array (where T is an array) using T[number]. The problem is that I have no way to constrain where T is an array on a nested property.

function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1][number]>(obj: TObject, p1: P1, index: number, p2: P2): TObject[P1][number][P2];
                                                                                ^^^^^^                                                             ^^^^^^
const test2 = getSafe(obj, "Employment", 0, "Id"); // example usage

That actually works at the call-site (no errors there, correctly gives us param and return types), but gives us an error in the declaration itself because you can't index TObject[P1] with [number] as we can't guarantee TObject[P1] is an array.

(Note: TType[number] is a viable way to get the element type from an array type, but we need to convince the compiler that we're doing this to an array)

The question is really, would there be away to add a array constraint to TObject[P1] or is there another way to do this that I'm missing.

Body:
I've since figured this out and published an npm package here: ts-get-safe

The key point was figuring out how to conditionally restructure the array into it's element type. In order to do that, you first have to assert that all the properties are either an array or never. The type that solved the equation was:

type GSArrEl<TKeys extends keyof TObj, TObj> = { [P in TKeys]: undefined[] & TObj[P] }[TKeys][number];

The magic is in { [P in TKeys]: undefined[] & TObj[P] } where we essentially union each property of TObj to undefined[]. Because we are then sure that each property is either an array or never (it will be never on each property which is not an array), we can then do the destructuring expression [number] to get the element type.

Here is an example of two array destructuring happening at the same time:

function getSafe<TObject, P0 extends keyof TObject, A1 extends GSArrEl<P0, TObject>, P2 extends keyof A1, P3 extends keyof A1[P2], A4 extends GSArrEl<P3, A1[P2]>>(obj: TObject, p0: P0, a1: number, p2: P2, p3: P3, a4: number): A4;

Hundreds of combinations of arrays and object properties have been generated in my ts-get-safe library and are ready to use, however I'm still open to ways to improve this in a generic way such that we can use a dynamic number of parameters in the same declaration. Even a way to combine Array and Property navigation into the same type constraint so we don't have to generate every variation of array and property access.


问:
Share button not working in my app
I have created a simple website app using webview in android studio and given it internet access permission also enabled java script on app

When I have added a WhatsApp share button using this code

```<code> <button>
<a href="whatsapp://send?text=HERE GOES THE URL ENCODED TEXT YOU WANT TO SHARE" data-action="share/whatsapp/share">Share via Whatsapp</a>
</button>
</code>```

This is working well in all mobile browsers but when I try to use this on my app I am getting an error screen saying

Web page not available

The web page
  at whatsapp://send?text=I'm%20interested%20in%20your%20car%20for%20salecould
  not be loaded because:

net::ERR_UNKNOWN_URL_SCHEME

This is my code in mainactivity.java

```<code>package com.a4extras.ukzz.whatsappdaily;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView = (WebView)findViewById(R.id.WebView);
        WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mywebView.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");
        mywebView.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (mywebView.canGoBack()) {
            mywebView.goBack();
        } else {
            super.onBackPressed();
        }
    }}
</code>```

This is because my app is taking whatsapp:// as a URL
So how can prevent this so that the Share button will work properly

Please help me with necessary script
Thanks

答:
The simple workaround is to use javascript in href:

```<code><a href="javascript:go('whatsapp://send?text=HERE')">Share</a>
</code>```

or, if using Chrome based webview:

```<code><a href="intent://send?text=HERE#Intent;scheme=whatsapp;package=com.whatsapp;end">Share</a>
</code>```

More complex, but more powerful solution is to control whatsapp scheme by yourself:

In your WebViewClient:

```<code>@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    Uri uri = request.getUrl();
    if (Objects.equals(uri.getScheme(), "whatsapp")) {
        try {
            Intent intent = Intent.parseUri(request.getUrl().toString(), Intent.URI_INTENT_SCHEME);
            if(intent.resolveActivity(getPackageManager()) != null)
                startActivity(intent);
            return true;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    return super.shouldOverrideUrlLoading(view, request);
}
</code>```

Title: Share button not working in my app

Body:
I have created a simple website app using webview in android studio and given it internet access permission also enabled java script on app

When I have added a WhatsApp share button using this code

 <button>
Share via Whatsapp
</button>

This is working well in all mobile browsers but when I try to use this on my app I am getting an error screen saying

Web page not available

The web page
  at whatsapp://send?text=I'm%20interested%20in%20your%20car%20for%20salecould
  not be loaded because:

net::ERR_UNKNOWN_URL_SCHEME

This is my code in mainactivity.java

package com.a4extras.ukzz.whatsappdaily;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView = (WebView)findViewById(R.id.WebView);
        WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mywebView.loadUrl("http://ukzz4u.blogspot.com/2017/11/whatsapp-share-01.html");
        mywebView.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (mywebView.canGoBack()) {
            mywebView.goBack();
        } else {
            super.onBackPressed();
        }
    }}

This is because my app is taking whatsapp:// as a URL
So how can prevent this so that the Share button will work properly

Please help me with necessary script
Thanks

Body:
The simple workaround is to use javascript in href:

<a href="javascript:go('whatsapp://send?text=HERE')">Share</a>

or, if using Chrome based webview:

<a href="intent://send?text=HERE#Intent;scheme=whatsapp;package=com.whatsapp;end">Share</a>

More complex, but more powerful solution is to control whatsapp scheme by yourself:

In your WebViewClient:

@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    Uri uri = request.getUrl();
    if (Objects.equals(uri.getScheme(), "whatsapp")) {
        try {
            Intent intent = Intent.parseUri(request.getUrl().toString(), Intent.URI_INTENT_SCHEME);
            if(intent.resolveActivity(getPackageManager()) != null)
                startActivity(intent);
            return true;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    return super.shouldOverrideUrlLoading(view, request);
}


问:
SQL Server selecting a string from table using in clause
I'm having a strange SQL Server issue.

Using the following query:

```<code>SELECT id FROM table WHERE id IN ('id1', 'id2', .......)
</code>```

when id is nchar(30) and 'id1','id2' are values, I get a result which isn't in the values I entered.

Is it possible that SQL Server is searching for a string contained in the values?

Added

query:

```<code>SELECT Word FROM WordDictionary WHERE Word IN ('DESPERADO', 'WWW.MYSAVINGS.COM', 'RELIED', 'GALS/GUYS....U', 'MISSOULA', 'STARING...WHY', 'OHIO,,,WHAT', 'ALEYO"MEANS', 'EXCRETE', 'POETERS', 'REMOVAL?IF', 'MOTOT', 'VIEW/SOUND', 'SCHOLD', 'FLINGS', '300000', 'BIGBANG', 'INVOKE', 'COMPLIER', 'UPNISHAD', 'FLUFF/LINT', 'DONATED?..PLEASE', 'EPHEDRINE', 'AGAIN-', 'WHUNT', 'LEVE', 'ARIEL', 'SEIZURES,AND', 'ANYON', 'WELL~AS', 'GGGGGGGGOOOOOOOOOOOOOOOOODDDDD', 'ALGERIA', 'LONDON...CAN', 'TWAIN''S', 'BUTIFUL', 'CIRRHIOSIS', 'PHP-NUKE', 'SCREWD', 'RECONNECT', 'BAND...''SIGUR', 'ROS''', 'DEFLEPOARD', 'FIHGT', 'DRE''S', 'ACQUAINTED', '77067', 'INCREASE/DECREASE', 'AWHILE..SHOULD', 'BABY???..MORE', 'CHRISTEN', 'SUNSLIFE', 'HYANCINTHS', 'NOVEMEBER', 'IEEE', 'IRENE', '5"4', 'BAYSIDE', 'DOJO', 'PEOPLES::DO', 'INFORMATION/ANSWER', 'BLACKWORM', 'MYWIFE.D', '42D', 'COLONEL', 'ESCAPES', 'KW', 'WASH/CLENSE', 'ENCOURAGES', 'HOLINESS', '4710', 'MONOATOMIC', 'FORM-', 'NAVIGATIONS', 'ASHLIEY(TWINS', 'ALIAS....WHAT', 'MARIOKART', 'HORNYNESS', 'CONVERSIONS', 'NUIT', 'PARISTEL:0660442290PL06', 'PUSSY', 'WILLOWS', 'BOYFRIEND/BABYDADDY', 'PARASITES', 'TABOILD', 'J.T', 'TERESEA', '---FREE---', 'KAMORA', 'SIMONS', 'FORSYTHIA', 'RAZORTHOUGHT', 'ABSINTHE', '9-3', 'BAIT-CASTING', 'CUMULATIVE', 'HELP>>>', 'MATZO', 'LIMOSINE', 'SCD353', 'BANGARAM', 'BRUNEL', 'KWTV878', 'NEAPOLITAN', 'OFYOUR', '2SIN', '²', '3SINX', 'IMPERFECTION', 'NONBELIEF', 'FLEM', 'NON-ADJACENT', 'WASHINGTION', 'WHERE/IF', 'BRONTE''S', 'WUTHERING', 'SOMEONE/A', 'TEAM.WHAT', 'PRESIDENT,WHEN', 'DIRICHLET', 'X-AND', 'Y-INTERCEPTS', 'STAMPED', 'PROCRDURE', 'AK32', '*67', 'HANUKKAH', 'MONIE', 'TAGAYTAY', 'NATURES', 'HASS', 'TORMENTS', 'PROPOTIONAL', 'SUDERLAND', 'CONROL', 'CONSEQUENCE', 'SAW?YOU', 'WITHDREW', 'PMT', 'JAIL?WAT', 'DEFFEND', '-12>8X', '4X>6', 'MX-C550', '6-DISC', 'SVQ3', 'BULLSHITING', 'PWEAZE', '23SECONDS', 'VISHWANATHAN''S', 'INTERNALIZING', 'MCCAFFERTY''S', 'TODAY...AND', 'CHANCE....WOULD', 'DEC.''41', '''45', 'HAILLE', 'SELASSIE', 'OF...GREENDAY', 'DEAD/ARMY', 'EX-NFL', 'JACKSONVILLE,FL', 'ATLANTA,HOUSTON,OR', 'ECCENTRICITY', 'CONIC', 'XXX@YAHOO.CO.UK', 'XXX@YAHOO.COM', 'DISCRET', '_______', 'ROMACE', 'SUBCATEGORY', 'REDUDUCE', 'EXERCISER', 'MUNITE', 'MESSENGER.SO', 'NIGEL', 'PLANER', 'QUESTION?31576*66496139', 'KODJOE', '919', '1847', 'D.WADE', 'HUMAN''S', 'MULTI-NATIONAL', 'GOGGLE', 'GAAP', 'CONFUSED.IONT', 'ST8', 'ROOM/HOME', 'BOLB', 'GRANDMA-', 'PARSON', 'BELIZE', 'UNITY', 'AWARDS''', 'TOGHTHER', 'LONDON+GREATER', 'JERSEY...IE', 'NETGAR', 'NBC,ABC', 'CONON', 'RECIDENT', 'CANCERS', 'PITTSBURGH/INDY', 'CREATETH', 'MUSICAL''S', 'HEELLLLPPPP', 'MASRER', 'NAME,AND', 'ANAEROBIC', 'SPACIAL', 'SPOUSE/SIGNIFICANT', 'TRIGNOCEPHALY', 'RAW''S', 'BLOGGIN', '9.2', 'FLATTENING', 'FLOWER,ANIMALAND', 'EXPRESSES', 'FRDS', 'NOT?PLS', 'CLEARIFY', 'CLEARFIELD/JEFFERSON', 'HACE', 'FELICIANO', 'MEDICINE--THEY', 'DASCHUND', 'PLINTER', 'SKETCHY', 'I..WHAT', 'JUVENTINA', 'SOMUCH', 'SHEEN', 'HALEX', '11-IN-1', 'URBANIZATION', 'WILWOOD', 'CALIPER', 'NERVE-RACKING', 'OBSESESSION', 'EZRA', 'TALBOT', 'SHOCKWAVE', 'PASCO', '300$-600$', '108,000', '*BOYZ', 'ONLY*PLZ', 'INTERNET)CAN', 'CONCISE', 'TOP40', 'HICUPPS', '4:00', 'OPOSITE', 'NETWORKER?=', 'Q-LINK', 'HSG', 'AMINE', 'RIGHTS,,HOW', 'EMILIANO', 'PEDREGON', 'DILEMA', 'GROUPTHINK', 'MONTEAL', '17...&', '13:04', 'NASHIK', 'NOBIA', 'LINEWIRE', 'ISOCKS', 'DAY........WAIT', 'KATY', 'BODERLINE', 'CONNORS', 'WHWRE', 'CROMWELL', 'COE', '1+1=', 'UMMM.....WHATS', 'BOND''S', 'VIEWLOADER', 'MAXIS', 'MAT_LOVE83@YAHOO.COM', 'SCISSORS', 'UNSANITARY', 'KANSANS', 'SALINA', '''ARENA''', '''CAROLINA''', 'BIOMAGNIFICATION', 'BIOASSIMILATION', 'WOMBATS', 'POOS', 'ARSES', 'SOCIALIZATION', 'GROUPS,RACES', 'FULL-BLOOD', 'TASMANIAN', 'INCLINE', 'PICA', 'FIGGERED', '9.HE', 'RETINOBLASTOMA,IS', 'COAT''S', '2MOWRO', 'DOTHAN', 'DIFRNT', 'DEPICTS', 'WHAK', 'NETHERLAND', 'FORTHE', 'OFMICROSOFT', 'INDIGO', 'I-MAC', 'SHANGHAINESE', 'DINOSAOUR', 'SUBCAMPS', 'CARDINAL', 'NEBRASKA''S', 'KOMO', 'PIRATE/SAILING', 'ZOPICLONE', 'CRYPTIC', 'CLUE"COULD', 'WHEELCHAIR,NO', 'OVERWIEGHT.DOES', 'ALL..MY', 'BOYFRIIEND', 'MAGTECH', 'TROUBLES...ANY', 'BACK,REDUCED', 'JEWELY', 'CRAFTSMEN''S', 'HAUNTER', 'GENGAR', 'CRYSTAL.WHERE', 'LAHORE', 'SANDLER''S', 'ACCENT...WHAT', 'WOOOOOAAAAAAAAH', 'W''T', 'RAJASEKARAN_NIKIL@YAHOO.COM', 'SPEICES', 'MCFLY', 'BIOCONVERSION', 'GUERRERO', 'CATHOLICS......WHAT', 'NOV.1--', 'ECONOLINE', 'AMOVIE', 'COUNSELLING', 'HANDSPAN', 'ATTIUTE', 'HAIR??HELP', 'PLASTIC?CERAMIC', 'TITLEIST', 'REISDENTS', '7''S', 'FERMATS', 'JBW&CWW', 'RB''S', 'KENYON', 'BAPTIST''S', 'THUMPERS', 'THOZ', 'HATZ', 'MSNISMS', 'POLL/SURVEY', 'INFUSION', 'FUNDRAISER', 'PROTECTS', 'ANTOINO', 'SYALLBUS', 'GCSES', 'SPIDER,SNAKE,DOG,CAT', 'KNOW.PLEASE', 'CHACH', 'DISSAPIONTED', 'TODGER', 'SH*TTING', 'LODESTONE', 'SARBANES', 'OXLEY', 'ANOTHR', 'RELATIONSHIP????HOW', 'T9', 'JIGGLY', 'GOOD?IS', 'HARDEN', 'DESERT?I', 'SIGNIFANT', 'WEDO', 'SCHAT', 'LQ', 'TENCHI', 'ME...WHAT''S', 'ERUPTED', '£40', '£150', 'UPGRATE', 'I500', '2003SE', 'PROMOT', 'SALUTES', 'GRAEME', 'SOUNESS', 'SERRONE', 'AHAVE', 'BUSTSA', 'IMPARTIAL', 'SUGARCULT', 'RFID', 'SWIPE', '30X', 'HOUSE''S', 'BI-WAY', 'BLYTHE,CA', 'REDDER', 'PLUMPER', 'LEFTWINGERS', 'WHINGE', 'ANNOYING..!!1', 'SENSORY', 'ADHD/ODD', 'ZYBAN', 'RAMP', 'SUB-WOOFER''S', 'TATTOOIST', '477', 'SOFISTCATED', 'B/J', 'ALLURE', 'THIS?(SEE', 'PAKISTANIS:DO', 'PLEASE?I', 'CLASHING', 'KNOW(DOCS', 'WHITESMOKE', 'SCREEN''S', 'SPINK', 'YOUI', 'DELICATE', 'MISDIAGNOSED', 'DIPERNO', 'HIM.PLEASE', '45CM', '35CM', 'ENOUGHT', 'DECIMETERS?PUT', 'RDMB', 'HOMELOANS', 'HAA', 'ORIGIANL', 'RESTON', 'ZINNIAS', 'PERENNIAL', 'WHOOPIE', 'CUSHIONS', 'POOFS', 'CAT,ITS', 'TIME,ITS', 'TUXEDOS', 'CHICKAN', 'WHISLE', 'RUMBLING', '7LEVELS', 'YOUFROM', 'CEMO', 'RECURRENT', 'LARYNGEAL', 'W/NO', 'SOUCRE', 'COMMA', 'WORDCUB', 'WOMEN:HAVE', 'PIGGYBACK', 'ANOLE', 'CHRISTIANSEN', 'SWEEPSTAKES,GETTING', 'WON.HOW', 'EUDORA5.1', 'EXPRESS,NETSCAPE4.X', '6.X', '''COURT', 'WISK''', '4/13', '50-70', 'DAUGHTER,CAN', 'UVULA', '''AYURVEDA''', 'ACUPUNTURE', 'BAJA', 'REASONIBLE', 'PUZZY', 'SORCERER', 'DISEASES/SICKNESS', 'ANUS/RECTUM?CAN', 'HOME?WHAT', 'COCETH', 'KELLOGGS', 'DAISUKE')
</code>```

result:

```<code>2
</code>```

Added

```<code>CREATE TABLE [dbo].[WordDictionary](
[Word] [nchar](30) NOT NULL,
[Count] [int] NOT NULL,
    CONSTRAINT [PK_WordDictionary] PRIMARY KEY CLUSTERED
    (
      [Word] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
</code>```

答:
```<code>select * from test
where data IN ('Aa' COLLATE SQL_Latin1_General_CP1_CS_AS, 'Ab' COLLATE SQL_Latin1_General_CP1_CS_AS)
</code>```

Body:
I'm having a strange SQL Server issue.

Using the following query:

SELECT id FROM table WHERE id IN ('id1', 'id2', .......)

when id is nchar(30) and 'id1','id2' are values, I get a result which isn't in the values I entered.

Is it possible that SQL Server is searching for a string contained in the values?

Added

query:

SELECT Word FROM WordDictionary WHERE Word IN ('DESPERADO', 'WWW.MYSAVINGS.COM', 'RELIED', 'GALS/GUYS....U', 'MISSOULA', 'STARING...WHY', 'OHIO,,,WHAT', 'ALEYO"MEANS', 'EXCRETE', 'POETERS', 'REMOVAL?IF', 'MOTOT', 'VIEW/SOUND', 'SCHOLD', 'FLINGS', '300000', 'BIGBANG', 'INVOKE', 'COMPLIER', 'UPNISHAD', 'FLUFF/LINT', 'DONATED?..PLEASE', 'EPHEDRINE', 'AGAIN-', 'WHUNT', 'LEVE', 'ARIEL', 'SEIZURES,AND', 'ANYON', 'WELL~AS', 'GGGGGGGGOOOOOOOOOOOOOOOOODDDDD', 'ALGERIA', 'LONDON...CAN', 'TWAIN''S', 'BUTIFUL', 'CIRRHIOSIS', 'PHP-NUKE', 'SCREWD', 'RECONNECT', 'BAND...''SIGUR', 'ROS''', 'DEFLEPOARD', 'FIHGT', 'DRE''S', 'ACQUAINTED', '77067', 'INCREASE/DECREASE', 'AWHILE..SHOULD', 'BABY???..MORE', 'CHRISTEN', 'SUNSLIFE', 'HYANCINTHS', 'NOVEMEBER', 'IEEE', 'IRENE', '5"4', 'BAYSIDE', 'DOJO', 'PEOPLES::DO', 'INFORMATION/ANSWER', 'BLACKWORM', 'MYWIFE.D', '42D', 'COLONEL', 'ESCAPES', 'KW', 'WASH/CLENSE', 'ENCOURAGES', 'HOLINESS', '4710', 'MONOATOMIC', 'FORM-', 'NAVIGATIONS', 'ASHLIEY(TWINS', 'ALIAS....WHAT', 'MARIOKART', 'HORNYNESS', 'CONVERSIONS', 'NUIT', 'PARISTEL:0660442290PL06', 'PUSSY', 'WILLOWS', 'BOYFRIEND/BABYDADDY', 'PARASITES', 'TABOILD', 'J.T', 'TERESEA', '---FREE---', 'KAMORA', 'SIMONS', 'FORSYTHIA', 'RAZORTHOUGHT', 'ABSINTHE', '9-3', 'BAIT-CASTING', 'CUMULATIVE', 'HELP>>>', 'MATZO', 'LIMOSINE', 'SCD353', 'BANGARAM', 'BRUNEL', 'KWTV878', 'NEAPOLITAN', 'OFYOUR', '2SIN', '²', '3SINX', 'IMPERFECTION', 'NONBELIEF', 'FLEM', 'NON-ADJACENT', 'WASHINGTION', 'WHERE/IF', 'BRONTE''S', 'WUTHERING', 'SOMEONE/A', 'TEAM.WHAT', 'PRESIDENT,WHEN', 'DIRICHLET', 'X-AND', 'Y-INTERCEPTS', 'STAMPED', 'PROCRDURE', 'AK32', '*67', 'HANUKKAH', 'MONIE', 'TAGAYTAY', 'NATURES', 'HASS', 'TORMENTS', 'PROPOTIONAL', 'SUDERLAND', 'CONROL', 'CONSEQUENCE', 'SAW?YOU', 'WITHDREW', 'PMT', 'JAIL?WAT', 'DEFFEND', '-12>8X', '4X>6', 'MX-C550', '6-DISC', 'SVQ3', 'BULLSHITING', 'PWEAZE', '23SECONDS', 'VISHWANATHAN''S', 'INTERNALIZING', 'MCCAFFERTY''S', 'TODAY...AND', 'CHANCE....WOULD', 'DEC.''41', '''45', 'HAILLE', 'SELASSIE', 'OF...GREENDAY', 'DEAD/ARMY', 'EX-NFL', 'JACKSONVILLE,FL', 'ATLANTA,HOUSTON,OR', 'ECCENTRICITY', 'CONIC', 'XXX@YAHOO.CO.UK', 'XXX@YAHOO.COM', 'DISCRET', '_______', 'ROMACE', 'SUBCATEGORY', 'REDUDUCE', 'EXERCISER', 'MUNITE', 'MESSENGER.SO', 'NIGEL', 'PLANER', 'QUESTION?31576*66496139', 'KODJOE', '919', '1847', 'D.WADE', 'HUMAN''S', 'MULTI-NATIONAL', 'GOGGLE', 'GAAP', 'CONFUSED.IONT', 'ST8', 'ROOM/HOME', 'BOLB', 'GRANDMA-', 'PARSON', 'BELIZE', 'UNITY', 'AWARDS''', 'TOGHTHER', 'LONDON+GREATER', 'JERSEY...IE', 'NETGAR', 'NBC,ABC', 'CONON', 'RECIDENT', 'CANCERS', 'PITTSBURGH/INDY', 'CREATETH', 'MUSICAL''S', 'HEELLLLPPPP', 'MASRER', 'NAME,AND', 'ANAEROBIC', 'SPACIAL', 'SPOUSE/SIGNIFICANT', 'TRIGNOCEPHALY', 'RAW''S', 'BLOGGIN', '9.2', 'FLATTENING', 'FLOWER,ANIMALAND', 'EXPRESSES', 'FRDS', 'NOT?PLS', 'CLEARIFY', 'CLEARFIELD/JEFFERSON', 'HACE', 'FELICIANO', 'MEDICINE--THEY', 'DASCHUND', 'PLINTER', 'SKETCHY', 'I..WHAT', 'JUVENTINA', 'SOMUCH', 'SHEEN', 'HALEX', '11-IN-1', 'URBANIZATION', 'WILWOOD', 'CALIPER', 'NERVE-RACKING', 'OBSESESSION', 'EZRA', 'TALBOT', 'SHOCKWAVE', 'PASCO', '300$-600$', '108,000', '*BOYZ', 'ONLY*PLZ', 'INTERNET)CAN', 'CONCISE', 'TOP40', 'HICUPPS', '4:00', 'OPOSITE', 'NETWORKER?=', 'Q-LINK', 'HSG', 'AMINE', 'RIGHTS,,HOW', 'EMILIANO', 'PEDREGON', 'DILEMA', 'GROUPTHINK', 'MONTEAL', '17...&', '13:04', 'NASHIK', 'NOBIA', 'LINEWIRE', 'ISOCKS', 'DAY........WAIT', 'KATY', 'BODERLINE', 'CONNORS', 'WHWRE', 'CROMWELL', 'COE', '1+1=', 'UMMM.....WHATS', 'BOND''S', 'VIEWLOADER', 'MAXIS', 'MAT_LOVE83@YAHOO.COM', 'SCISSORS', 'UNSANITARY', 'KANSANS', 'SALINA', '''ARENA''', '''CAROLINA''', 'BIOMAGNIFICATION', 'BIOASSIMILATION', 'WOMBATS', 'POOS', 'ARSES', 'SOCIALIZATION', 'GROUPS,RACES', 'FULL-BLOOD', 'TASMANIAN', 'INCLINE', 'PICA', 'FIGGERED', '9.HE', 'RETINOBLASTOMA,IS', 'COAT''S', '2MOWRO', 'DOTHAN', 'DIFRNT', 'DEPICTS', 'WHAK', 'NETHERLAND', 'FORTHE', 'OFMICROSOFT', 'INDIGO', 'I-MAC', 'SHANGHAINESE', 'DINOSAOUR', 'SUBCAMPS', 'CARDINAL', 'NEBRASKA''S', 'KOMO', 'PIRATE/SAILING', 'ZOPICLONE', 'CRYPTIC', 'CLUE"COULD', 'WHEELCHAIR,NO', 'OVERWIEGHT.DOES', 'ALL..MY', 'BOYFRIIEND', 'MAGTECH', 'TROUBLES...ANY', 'BACK,REDUCED', 'JEWELY', 'CRAFTSMEN''S', 'HAUNTER', 'GENGAR', 'CRYSTAL.WHERE', 'LAHORE', 'SANDLER''S', 'ACCENT...WHAT', 'WOOOOOAAAAAAAAH', 'W''T', 'RAJASEKARAN_NIKIL@YAHOO.COM', 'SPEICES', 'MCFLY', 'BIOCONVERSION', 'GUERRERO', 'CATHOLICS......WHAT', 'NOV.1--', 'ECONOLINE', 'AMOVIE', 'COUNSELLING', 'HANDSPAN', 'ATTIUTE', 'HAIR??HELP', 'PLASTIC?CERAMIC', 'TITLEIST', 'REISDENTS', '7''S', 'FERMATS', 'JBW&CWW', 'RB''S', 'KENYON', 'BAPTIST''S', 'THUMPERS', 'THOZ', 'HATZ', 'MSNISMS', 'POLL/SURVEY', 'INFUSION', 'FUNDRAISER', 'PROTECTS', 'ANTOINO', 'SYALLBUS', 'GCSES', 'SPIDER,SNAKE,DOG,CAT', 'KNOW.PLEASE', 'CHACH', 'DISSAPIONTED', 'TODGER', 'SH*TTING', 'LODESTONE', 'SARBANES', 'OXLEY', 'ANOTHR', 'RELATIONSHIP????HOW', 'T9', 'JIGGLY', 'GOOD?IS', 'HARDEN', 'DESERT?I', 'SIGNIFANT', 'WEDO', 'SCHAT', 'LQ', 'TENCHI', 'ME...WHAT''S', 'ERUPTED', '£40', '£150', 'UPGRATE', 'I500', '2003SE', 'PROMOT', 'SALUTES', 'GRAEME', 'SOUNESS', 'SERRONE', 'AHAVE', 'BUSTSA', 'IMPARTIAL', 'SUGARCULT', 'RFID', 'SWIPE', '30X', 'HOUSE''S', 'BI-WAY', 'BLYTHE,CA', 'REDDER', 'PLUMPER', 'LEFTWINGERS', 'WHINGE', 'ANNOYING..!!1', 'SENSORY', 'ADHD/ODD', 'ZYBAN', 'RAMP', 'SUB-WOOFER''S', 'TATTOOIST', '477', 'SOFISTCATED', 'B/J', 'ALLURE', 'THIS?(SEE', 'PAKISTANIS:DO', 'PLEASE?I', 'CLASHING', 'KNOW(DOCS', 'WHITESMOKE', 'SCREEN''S', 'SPINK', 'YOUI', 'DELICATE', 'MISDIAGNOSED', 'DIPERNO', 'HIM.PLEASE', '45CM', '35CM', 'ENOUGHT', 'DECIMETERS?PUT', 'RDMB', 'HOMELOANS', 'HAA', 'ORIGIANL', 'RESTON', 'ZINNIAS', 'PERENNIAL', 'WHOOPIE', 'CUSHIONS', 'POOFS', 'CAT,ITS', 'TIME,ITS', 'TUXEDOS', 'CHICKAN', 'WHISLE', 'RUMBLING', '7LEVELS', 'YOUFROM', 'CEMO', 'RECURRENT', 'LARYNGEAL', 'W/NO', 'SOUCRE', 'COMMA', 'WORDCUB', 'WOMEN:HAVE', 'PIGGYBACK', 'ANOLE', 'CHRISTIANSEN', 'SWEEPSTAKES,GETTING', 'WON.HOW', 'EUDORA5.1', 'EXPRESS,NETSCAPE4.X', '6.X', '''COURT', 'WISK''', '4/13', '50-70', 'DAUGHTER,CAN', 'UVULA', '''AYURVEDA''', 'ACUPUNTURE', 'BAJA', 'REASONIBLE', 'PUZZY', 'SORCERER', 'DISEASES/SICKNESS', 'ANUS/RECTUM?CAN', 'HOME?WHAT', 'COCETH', 'KELLOGGS', 'DAISUKE')

result:

2

Added

CREATE TABLE [dbo].[WordDictionary](
[Word] [nchar](30) NOT NULL,
[Count] [int] NOT NULL,
    CONSTRAINT [PK_WordDictionary] PRIMARY KEY CLUSTERED
    (
      [Word] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]


问:
Waterline - Postgres - DataTypes
I am having difficulties with Waterline models and creating the Postgres tables related to those models.

No matter what I do to create a varchar(n) in the table through a model, it converts the attribute to text. And bigint also is being converted to integer!

Should I change the ORM?

Is there a way to do that?

答:
Sails supported datatype:

String, text, integer, float, date, datetime, boolean, binary, array, json, mediumtext, longtext, objectid

If you need to specify exact length -> varchar(n), you need to use supported data type as shown above, or sails provide option called query.

Model.query() method which you can use to perform any kind of query you want.

```<code>var queryString='CREATE TABLE if not exists sailsusers.test (id INT NOT NULL,name VARCHAR(45) NULL,PRIMARY KEY (id))'
 Test.query(queryString,function(err,a){
    if(err)
      return console.log(err);
    console.log(a,'\n',b);
    res.ok();
 });
</code>```

Title: Waterline - Postgres - DataTypes

Body:
Sails supported datatype:

String, text, integer, float, date, datetime, boolean, binary, array, json, mediumtext, longtext, objectid

If you need to specify exact length -> varchar(n), you need to use supported data type as shown above, or sails provide option called query.

Model.query() method which you can use to perform any kind of query you want.

var queryString='CREATE TABLE if not exists sailsusers.test (id INT NOT NULL,name VARCHAR(45) NULL,PRIMARY KEY (id))'
 Test.query(queryString,function(err,a){
    if(err)
      return console.log(err);
    console.log(a,'\n',b);
    res.ok();
 });


问:
xcode 9 - How to take screenshot for itunesconnect using Simulator
In xcode 8 simulator when I used to take screenshots they were of the right size for itunesconnect if there is no scaling in the simulator.

With the Xcode 9 the simulators scaling is different when it is at 100% the screenshots are not accepted at the iTunesConnect.

Maybe my LED (1080p) resolution is less than thats why I am having this problem. So on my current display how can I take screenshots with right size for itunesconnet?

答:
In the debug menu uncheck Optimize Rendering for Window Size. Then screenshots will be at the device native resolution.

I recommend turning this back on afterwards because it improves performance.


问:
Docker: Clone git repo in current directory
I am using docker to clone a public repository. It's cloned successfully. But I don't know where its cloned? Also how can I clone the repo in my current working directory using docker?

Dockerfile

```<code>FROM debian:stretch

RUN apt-get update
RUN apt-get install -y git
RUN git clone https://github.com/ishpreet-singh/Sudoku.git
</code>```

Terminal

```<code>root@ubuntu:/home/hp1/Desktop/src/sample# docker build -t img2 .
Sending build context to Docker daemon  2.048kB
Step 1/4 : FROM debian:stretch
 ---> 6d83de432e98
Step 2/4 : RUN apt-get update
 ---> Using cache
 ---> 5ad3bd342683
Step 3/4 : RUN apt-get install -y git
 ---> Using cache
 ---> 29bdeb15539f
Step 4/4 : RUN git clone https://github.com/ishpreet-singh/Sudoku.git
 ---> Running in 613bdd58bc99
Cloning into 'Sudoku'...
 ---> ba9f61f10baf
Removing intermediate container 613bdd58bc99
Successfully built ba9f61f10baf
Successfully tagged img2:latest
</code>```

答:
The repository will be cloned to the WORKDIR directory which defaults to /.

So after logging into container you'll find the cloned repository under /Sudoku.

Cloning a git repo using docker seems to be a strange scenario? Why would one do that?

Body:
I am using docker to clone a public repository. It's cloned successfully. But I don't know where its cloned? Also how can I clone the repo in my current working directory using docker?

Dockerfile

FROM debian:stretch

RUN apt-get update
RUN apt-get install -y git
RUN git clone https://github.com/ishpreet-singh/Sudoku.git

Terminal

root@ubuntu:/home/hp1/Desktop/src/sample# docker build -t img2 .
Sending build context to Docker daemon  2.048kB
Step 1/4 : FROM debian:stretch
 ---> 6d83de432e98
Step 2/4 : RUN apt-get update
 ---> Using cache
 ---> 5ad3bd342683
Step 3/4 : RUN apt-get install -y git
 ---> Using cache
 ---> 29bdeb15539f
Step 4/4 : RUN git clone https://github.com/ishpreet-singh/Sudoku.git
 ---> Running in 613bdd58bc99
Cloning into 'Sudoku'...
 ---> ba9f61f10baf
Removing intermediate container 613bdd58bc99
Successfully built ba9f61f10baf
Successfully tagged img2:latest


问:
How do I automatically update the value of a variable when a data is changed in ionic 3?
I am trying to get total price of the orders made that I have stored in an array. The code looks something like this.

```<code>import { Component } from '@angular/core';
import { Config } from '../config';
var ordersArray = [

];
@Component({
  selector: 'orders-page',
  templateUrl : 'orders.html'
})

export class Orders{
  public orders = ordersArray;
  public config = new Config;
  public addOrder(item){
    ordersArray.push(item);
  }
  public clearOrders(){
    var length = this.orders.length;
    for(let i = 0; i < length; i++){
      ordersArray.pop();
    }
  }
  public total = this.getPrice();
  public getPrice(){
    let price = 0;
    for(let order of ordersArray){
      price = (parseInt(order.item.price) * parseInt(order.quantity) ) + price;
    }
    return price;
  }
  public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
  }
}
</code>```

And the template, I have {{total}}.
Now, when I remove an element from the ordersArray, I want the {{total}} to automatically update. How do I do that ?

答:
Call getPrice() after updating the ordersArray, So call getPrice() inside the clearOrder()

Try this

```<code>public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
    this.total = this.getPrice();
  }
</code>```

Body:
I am trying to get total price of the orders made that I have stored in an array. The code looks something like this.

import { Component } from '@angular/core';
import { Config } from '../config';
var ordersArray = [

];
@Component({
  selector: 'orders-page',
  templateUrl : 'orders.html'
})

export class Orders{
  public orders = ordersArray;
  public config = new Config;
  public addOrder(item){
    ordersArray.push(item);
  }
  public clearOrders(){
    var length = this.orders.length;
    for(let i = 0; i < length; i++){
      ordersArray.pop();
    }
  }
  public total = this.getPrice();
  public getPrice(){
    let price = 0;
    for(let order of ordersArray){
      price = (parseInt(order.item.price) * parseInt(order.quantity) ) + price;
    }
    return price;
  }
  public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
  }
}

And the template, I have {{total}}.
Now, when I remove an element from the ordersArray, I want the {{total}} to automatically update. How do I do that ?

Body:
Call getPrice() after updating the ordersArray, So call getPrice() inside the clearOrder()

Try this

public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
    this.total = this.getPrice();
  }


问:
How to access complete object from a select field in react js
I'm working on a form in which we have a customer field which is a drop down and currency field which is again a drop down field. I have to set the values of the other fields based on the selected customer. But i'm not getting how to do it.

I tried to use the customerObj and set the value for the currency option also, but it didn't work.

This is my complete component code:

```<code>import React from 'react';
import Links from './Links.jsx';
import style from './app.css';

import axios from 'axios';

class AddNewProject extends React.Component {

    constructor(props) {
        super(props);

        this.state = {clients: [],
                      project : {
                          client : '',
                          currency : ''
                      }
                     };
        this.getClients = this.getClients.bind(this);
        this.handleUserInput = this.handleUserInput.bind(this);
    }
  // on load od component this method will be called.
    componentDidMount() {
        this.getClients();
    }

    // Api call for fetching the customers
    getClients(){
        axios({
            method: 'get',
            url: 'http://localhost:6060/account/getAll',
        }).then(response => {
                console.log('response:',response.data.data);
                this.setState({
                    clients: response.data.data
                })
            this.state.clients = response.data.data;
            })
            .catch(error => {
                console.log('Error fetching and parsing data', error);
                this.setState({
                    clients: []
                })
            });
        console.log(this.state.clients);
    }

    // on change handler
    handleUserInput(e){
        const value = e.target.value;
        const name = e.target.name;
        let {project} = this.state;
        // here i want to set the value for the currency drop down also
        project.client = value;
        this.setState({
            project
        })
    }

    render() {

        // creating options for customer/client
        var customerOptions = this.state.clients.map(function(customerObj ,index) {
            return (
                <option key={index+1} value={customerObj} >{customerObj.name}</option>
            );
        }.bind(this));

        // creating currency options
        var currencies = [{value: "USD"}, {value: "INR"}]

        var currencyOptions = currencies.map(function(currencyObj ,index) {
            return (
                <option key={index+1} value={currencyObj.value} >{currencyObj.value}</option>
            );
        }.bind(this));

      return (
        <div>
            <Links activeTabName="tab3"></Links>
            <div className="container">
                <div className = "row col-md-4">
                    <h1>Add New Project...</h1>
                </div>
                <div className = "row col-md-4">
                </div>
                <div className = "row col-md-4">
                </div>
                <hr style = {{'clear':'both'}}>
                </hr>
                <form id = "addEmployeeForm" className = {style.fontClass} >
                    <div className = "form-group row col-md-6">
                        <div className = "col-sm-4">
                            <label className="col-form-label">Customer
                                <sup className = {style.redSup}>*</sup>:
                            </label>
                        </div>
                        <div className = "col-sm-6">
                            <select name="client" value = {this.state.project.client} onChange={this.handleUserInput}>
                                <option value="">Select Customer</option>
                                {customerOptions}
                                </select>
                        </div>
                    </div>
                    <div className = "form-group row col-md-6">
                        <div className = "col-sm-4">
                            <label className="col-form-label">Currency
                                <sup className = {style.redSup}>*</sup>:
                            </label>
                        </div>
                        <div className = "col-sm-6">
                            <select name="currency" value = {this.state.project.currency} onChange={this.handleUserInput}>
                                <option value="">Select Currency</option>
                                {currencyOptions}
                                </select>
                        </div>
                    </div>
                </form>
            </div>
        </div>
      )
    }
}

export default AddNewProject;
</code>```

答:
For value in the options use index for customerOptions

```<code>var customerOptions = this.state.clients.map(function(customerObj ,index) {
            return (
                <option key={index+1} value={index} >{customerObj.name}</option>
            );
        }.bind(this));
</code>```

JS :

```<code> handleUserInput(e){
        // will give selected customer
        let selectedCustomer = this.state.clients[event.target.value];

        //script to get the currency
        let selectedCurrency = ..
        this.setState({project.currency:selectedCurrency});
    }
</code>```

DEMO : https://codesandbox.io/s/z081rpqj4

Body:
I'm working on a form in which we have a customer field which is a drop down and currency field which is again a drop down field. I have to set the values of the other fields based on the selected customer. But i'm not getting how to do it.

I tried to use the customerObj and set the value for the currency option also, but it didn't work.

This is my complete component code:

import React from 'react';
import Links from './Links.jsx';
import style from './app.css';

import axios from 'axios';

class AddNewProject extends React.Component {

    constructor(props) {
        super(props);

        this.state = {clients: [],
                      project : {
                          client : '',
                          currency : ''
                      }
                     };
        this.getClients = this.getClients.bind(this);
        this.handleUserInput = this.handleUserInput.bind(this);
    }
  // on load od component this method will be called.
    componentDidMount() {
        this.getClients();
    }

    // Api call for fetching the customers
    getClients(){
        axios({
            method: 'get',
            url: 'http://localhost:6060/account/getAll',
        }).then(response => {
                console.log('response:',response.data.data);
                this.setState({
                    clients: response.data.data
                })
            this.state.clients = response.data.data;
            })
            .catch(error => {
                console.log('Error fetching and parsing data', error);
                this.setState({
                    clients: []
                })
            });
        console.log(this.state.clients);
    }

    // on change handler
    handleUserInput(e){
        const value = e.target.value;
        const name = e.target.name;
        let {project} = this.state;
        // here i want to set the value for the currency drop down also
        project.client = value;
        this.setState({
            project
        })
    }

    render() {

        // creating options for customer/client
        var customerOptions = this.state.clients.map(function(customerObj ,index) {
            return (
                <option key={index+1} value={customerObj} >{customerObj.name}</option>
            );
        }.bind(this));

        // creating currency options
        var currencies = [{value: "USD"}, {value: "INR"}]

        var currencyOptions = currencies.map(function(currencyObj ,index) {
            return (
                <option key={index+1} value={currencyObj.value} >{currencyObj.value}</option>
            );
        }.bind(this));

      return (

            <Links activeTabName="tab3"></Links>

Add New Project...

                <form id = "addEmployeeForm" className = {style.fontClass} >

                            Customer
                                *:

                            <select name="client" value = {this.state.project.client} onChange={this.handleUserInput}>
                                <option value="">Select Customer</option>
                                {customerOptions}
                                </select>

                            Currency
                                *:

                            <select name="currency" value = {this.state.project.currency} onChange={this.handleUserInput}>
                                <option value="">Select Currency</option>
                                {currencyOptions}
                                </select>

                </form>

      )
    }
}

export default AddNewProject;

Body:
For value in the options use index for customerOptions

var customerOptions = this.state.clients.map(function(customerObj ,index) {
            return (
                <option key={index+1} value={index} >{customerObj.name}</option>
            );
        }.bind(this));

JS :

 handleUserInput(e){
        // will give selected customer
        let selectedCustomer = this.state.clients[event.target.value];

        //script to get the currency
        let selectedCurrency = ..
        this.setState({project.currency:selectedCurrency});
    }

DEMO : https://codesandbox.io/s/z081rpqj4


问:
How to increase the counter value when clicking the button in java script
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo">
      <span id="box1" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;"></span>
      <span id="box2" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box3" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box4" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box5" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box6" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box7" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box8" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box9" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box10"style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

答:
Something like this ?

var count = 0;

function myFunction(){

  count++;
  console.log(count)

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="myFunction()">click</button></code>```

Body:
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }

      <input type="text" id="value" value="0">

      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">

Body:
Something like this ?

var count = 0;

function myFunction(){

  count++;
  console.log(count)

}

<button onclick="myFunction()">click</button>


问:
Get WinWord version from Python program
in one simple Python program for testing users environment, I should also get version of installed Word (example: WinWord 16, 64-bit).
Any idea how to do that? I'm sure, that different GUIDs should exist, but where can I find them :-)

**** edit

I checked both suggestions, but it isn't enough. I have to get an information if Word is 32- or 64-bit. Until now, I have checked location of "winword.exe". For example: 1. location for 64-bit Office 15 c:\program files\microsoft office\office15\winword.exe 2. location for 32-bit Office 15 c:\program files (x86)\microsoft office\office15\winword.exe

I'm sure that M$ has list of GUIDs (used in registry) for latest versions of Word. But I can't find the list :-) With suggested solutions, I can't check 32- or 64- technology.

答:
Searching shorcuts with architecture detection (32-bit or 64-bit)

I figured the additional information would be useful, but you can reduce it to just 32-bit and 64-bit.

```<code>import subprocess, os, struct

def getWordVersion():
    directory = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"
    wordFile = ""
    wordVersion = ""

    def recursiveSearch(directory):
        for root, dirs, filenames in os.walk(directory):
            for dire in dirs:
                result = recursiveSearch(root + "\\" + dire)
                if result:
                    return result
            for filename in filenames:
                if filename.endswith(".lnk") and filename.startswith("Word "):
                    wordFile = root + "\\" + filename
                    wordVersion = filename[:-4]
                    return wordFile, wordVersion
        return False

    wordFile, wordVersion = recursiveSearch(directory)

    lnkTarget = subprocess.check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",
                      "(New-Object -ComObject WScript.Shell).CreateShortcut('" + wordFile + "').TargetPath"],shell=True)
    locationOfLnk = lnkTarget.strip()

    IMAGE_FILE_MACHINE_I386=332
    IMAGE_FILE_MACHINE_IA64=512
    IMAGE_FILE_MACHINE_AMD64=34404
    f=open(locationOfLnk, "rb")

    f.seek(60)
    s=f.read(4)
    header_offset=struct.unpack("<L", s)[0]
    f.seek(header_offset+4)
    s=f.read(2)
    machine=struct.unpack("<H", s)[0]
    architecture = ""

    if machine==IMAGE_FILE_MACHINE_I386:
        architecture = "IA-32 (32-bit x86)"
    elif machine==IMAGE_FILE_MACHINE_IA64:
        architecture = "IA-64 (Itanium)"
    elif machine==IMAGE_FILE_MACHINE_AMD64:
        architecture = "AMD64 (64-bit x86)"
    else:
        architecture = "Unknown architecture"

    f.close()
    return wordVersion + " "  + architecture

print(getWordVersion())
</code>```

Registry Method

A method is to loop through all registry keys under Office and find the most recent one.  Unfortunately, Microsoft decided it was a great idea to change the install directory in nearly every version. So, if you want to compile a complete list of all install locations, that'd work to (unless they installed it at a custom location).

Note: This is Python 3 code, if you need Python 2, then change winreg to _winreg.

```<code>import winreg

def getMicrosoftWordVersion():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Office", 0, winreg.KEY_READ)
    versionNum = 0
    i = 0
    while True:
        try:
            subkey = winreg.EnumKey(key, i)
            i+=1
            if versionNum < float(subkey):
                versionNum = float(subkey)
        except: #relies on error handling WindowsError as e as well as type conversion when we run out of numbers
            break
    return versionNum

print(getMicrosoftWordVersion())
</code>```

Title: Get WinWord version from Python program

Body:
Searching shorcuts with architecture detection (32-bit or 64-bit)

I figured the additional information would be useful, but you can reduce it to just 32-bit and 64-bit.

import subprocess, os, struct

def getWordVersion():
    directory = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"
    wordFile = ""
    wordVersion = ""

    def recursiveSearch(directory):
        for root, dirs, filenames in os.walk(directory):
            for dire in dirs:
                result = recursiveSearch(root + "\\" + dire)
                if result:
                    return result
            for filename in filenames:
                if filename.endswith(".lnk") and filename.startswith("Word "):
                    wordFile = root + "\\" + filename
                    wordVersion = filename[:-4]
                    return wordFile, wordVersion
        return False

    wordFile, wordVersion = recursiveSearch(directory)

    lnkTarget = subprocess.check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",
                      "(New-Object -ComObject WScript.Shell).CreateShortcut('" + wordFile + "').TargetPath"],shell=True)
    locationOfLnk = lnkTarget.strip()

    IMAGE_FILE_MACHINE_I386=332
    IMAGE_FILE_MACHINE_IA64=512
    IMAGE_FILE_MACHINE_AMD64=34404
    f=open(locationOfLnk, "rb")

    f.seek(60)
    s=f.read(4)
    header_offset=struct.unpack("<L", s)[0]
    f.seek(header_offset+4)
    s=f.read(2)
    machine=struct.unpack("<H", s)[0]
    architecture = ""

    if machine==IMAGE_FILE_MACHINE_I386:
        architecture = "IA-32 (32-bit x86)"
    elif machine==IMAGE_FILE_MACHINE_IA64:
        architecture = "IA-64 (Itanium)"
    elif machine==IMAGE_FILE_MACHINE_AMD64:
        architecture = "AMD64 (64-bit x86)"
    else:
        architecture = "Unknown architecture"

    f.close()
    return wordVersion + " "  + architecture

print(getWordVersion())

Registry Method

A method is to loop through all registry keys under Office and find the most recent one.  Unfortunately, Microsoft decided it was a great idea to change the install directory in nearly every version. So, if you want to compile a complete list of all install locations, that'd work to (unless they installed it at a custom location).

Note: This is Python 3 code, if you need Python 2, then change winreg to _winreg.

import winreg

def getMicrosoftWordVersion():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Office", 0, winreg.KEY_READ)
    versionNum = 0
    i = 0
    while True:
        try:
            subkey = winreg.EnumKey(key, i)
            i+=1
            if versionNum < float(subkey):
                versionNum = float(subkey)
        except: #relies on error handling WindowsError as e as well as type conversion when we run out of numbers
            break
    return versionNum

print(getMicrosoftWordVersion())


问:
GNU autotools: Debug/Release targets?
I've been looking for this for a while: I'm currently converting a medium-size program to autotools, coming from an Eclipse-based method (with makefiles)

I'm always used to having a "debug" build, with all debug symbols and no optimizations, and a "release" build, without debug symbols and best optimizations.

Now I'm trying to replicate this in some way with autotools, so I can (perhaps) do something like:

```<code>./configure
make debug
</code>```

Which would have all debug symbols and no optimizations, and where:

```<code>./configure
make
</code>```

Would result in the "release" version (default)

PS: I've read about the --enable-debug flag/feature, but in my current (simple) setup, using that is unrecognized by configure

答:
Another example to configure CFLAGS/CXXFLAGS without editing Makefile.in or Makefile.am. Add this code to your configure.in or configure.ac file:

```<code>test -z "$SED" && SED=sed

AC_ARG_ENABLE([debug],
  [AS_HELP_STRING([--enable-debug],
                  [whether to include debug symbols (default is no)])],
  [enable_debug=$enableval],
  [enable_debug=no]
)

if test "x$enable_debug" = xyes; then
  dnl Remove all optimization flags from CFLAGS
  changequote({,})
  CFLAGS=`echo "$CFLAGS" | $SED -e 's/-O[0-9s]*//g'`
  CXXFLAGS=`echo "$CXXFLAGS" | $SED -e 's/-O[0-9s]*//g'`

  CFLAGS=`echo "$CFLAGS" | $SED -e 's/-g[0-9]*//g'`
  CXXFLAGS=`echo "$CXXFLAGS" | $SED -e 's/-g[0-9]*//g'`
  changequote([,])

  CFLAGS="$CFLAGS -g -O0"
  CXXFLAGS="$CXXFLAGS -g -O0"
fi

echo "CFLAGS=$CFLAGS"
</code>```

Test it:

```<code>$ ./configure --enable-debug | grep CFLAGS
</code>```

Title: GNU autotools: Debug/Release targets?

Body:
I've been looking for this for a while: I'm currently converting a medium-size program to autotools, coming from an Eclipse-based method (with makefiles)

I'm always used to having a "debug" build, with all debug symbols and no optimizations, and a "release" build, without debug symbols and best optimizations.

Now I'm trying to replicate this in some way with autotools, so I can (perhaps) do something like:

./configure
make debug

Which would have all debug symbols and no optimizations, and where:

./configure
make

Would result in the "release" version (default)

PS: I've read about the --enable-debug flag/feature, but in my current (simple) setup, using that is unrecognized by configure

Body:
Another example to configure CFLAGS/CXXFLAGS without editing Makefile.in or Makefile.am. Add this code to your configure.in or configure.ac file:

test -z "$SED" && SED=sed

AC_ARG_ENABLE([debug],
  [AS_HELP_STRING([--enable-debug],
                  [whether to include debug symbols (default is no)])],
  [enable_debug=$enableval],
  [enable_debug=no]
)

if test "x$enable_debug" = xyes; then
  dnl Remove all optimization flags from CFLAGS
  changequote({,})
  CFLAGS=`echo "$CFLAGS" | $SED -e 's/-O[0-9s]*//g'`
  CXXFLAGS=`echo "$CXXFLAGS" | $SED -e 's/-O[0-9s]*//g'`

  CFLAGS=`echo "$CFLAGS" | $SED -e 's/-g[0-9]*//g'`
  CXXFLAGS=`echo "$CXXFLAGS" | $SED -e 's/-g[0-9]*//g'`
  changequote([,])

  CFLAGS="$CFLAGS -g -O0"
  CXXFLAGS="$CXXFLAGS -g -O0"
fi

echo "CFLAGS=$CFLAGS"

Test it:

$ ./configure --enable-debug | grep CFLAGS


问:
link speed vs throughput
I am new to networking. while doing an experiment on file transfer protocol(wired connection), I have to calculate the time taken to transfer 1 file from source to destination.
For calculating the file transfer time, i require the file size as well as the link speed.

Can anyone please explain what is this link speed and how to calculate it?
is it same as PHY rate?

Does PHY rates exist for wired connections or it exists in wireless connections only?

And also,please explain the difference between PHY rate,link speed and throughput.

Thanks in advance.

答:
You will need to consider the whole protocol stack for the exercise:

FTP

TCP

IP

Ethernet

PHY

Each of these layers reduces the raw PHY rate.

On the Ethernet and IP layers, it's quite simple. Each frame on these protocols has a maximum size (MTU) and a fixed size which needs to be allocated for the header of each frame.

After subtracting the overhead for the headers, you have the throughput via IP.

For TCP, we can ignore the data overhead for now, as the main factor is the additional round-trips added. In this case let's only deal with the handshake and ignore the other details for now. This means for the SYN-ACK-ACK sequence, we will to have account for twice the delay before the link is established from the client side.

For FTP, let's also assume the most simple case, anonymous login, active transfer, no encoding. That adds one more roundtrip before the actual data transfer starts.

Why did we choose to ignore the data size in the FTP and TCP protocol? Because for all modern link speeds, this is completely masked by the delay.

So in total your effective throughput is now PHY rate * Ethernet overhead * IP overhead + file size / (4 * Delay)

Choosing a different transfer encoding in FTP would add another factor to the left side. Accounting for TCP window scaling, retransmissions, login via FTP etc. would add more round-trips.

There could also be additional protocols in that stack, introducing further overhead. E.g. network tunnels.

Title: link speed vs throughput


问:
Determine current host location e.g. Europe/London
I'm developing a client application that will run on our user's servers. I'd like to make a guess at the current location e.g. America/New_York or Europe/London to relay to the service so it can compute current time on the client with respect to UTC offset and daylight saving rules. </p>

<p>Any thoughts on how the app could best guess at current location? I know I can get the current timezone like "PST" but that doesn't tell me what I need to know. </p>

答:
On Ubuntu (and probably other Linux distros), /etc/timezone contains a description of the location (e.g. Australia/Sydney), if one was set when the server was setup. As has been mentioned in the comments, there is no guarantee this is going to be correct.

If you have internet access you could do a GET request to https://freegeoip.net/json/ or something similar which will return a json object containing geolocation data for your ip. Again, there are many things that could affect the accuracy of this.

The code below does both these things, note for brevity there is no error checking (which is bad).

```<code>package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type LocationData struct {
    IP          string  `json:"ip"`
    CountryCode string  `json:"country_code"`
    CountryName string  `json:"country_name"`
    RegionCode  string  `json:"region_code"`
    RegionName  string  `json:"region_name"`
    City        string  `json:"city"`
    ZipCode     string  `json:"zip_code"`
    TimeZone    string  `json:"time_zone"`
    Latitude    float64 `json:"latitude"`
    Longitude   float64 `json:"longitude"`
    MetroCode   int     `json:"metro_code"`
}

func main() {
    // Using /etc/timezone
    buf, _ := ioutil.ReadFile("/etc/timezone")
    fmt.Printf("%s", buf)

    // Using freegeoip
    var locationData LocationData

    resp, _ := http.Get("https://freegeoip.net/json/")
    defer resp.Body.Close()

    decoder := json.NewDecoder(resp.Body)
    decoder.Decode(&locationData)

    fmt.Println(locationData.TimeZone)
}
</code>```

Body:
I'm developing a client application that will run on our user's servers. I'd like to make a guess at the current location e.g. America/New_York or Europe/London to relay to the service so it can compute current time on the client with respect to UTC offset and daylight saving rules.

Any thoughts on how the app could best guess at current location? I know I can get the current timezone like "PST" but that doesn't tell me what I need to know.

Body:
On Ubuntu (and probably other Linux distros), /etc/timezone contains a description of the location (e.g. Australia/Sydney), if one was set when the server was setup. As has been mentioned in the comments, there is no guarantee this is going to be correct.

If you have internet access you could do a GET request to https://freegeoip.net/json/ or something similar which will return a json object containing geolocation data for your ip. Again, there are many things that could affect the accuracy of this.

The code below does both these things, note for brevity there is no error checking (which is bad).

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type LocationData struct {
    IP          string  `json:"ip"`
    CountryCode string  `json:"country_code"`
    CountryName string  `json:"country_name"`
    RegionCode  string  `json:"region_code"`
    RegionName  string  `json:"region_name"`
    City        string  `json:"city"`
    ZipCode     string  `json:"zip_code"`
    TimeZone    string  `json:"time_zone"`
    Latitude    float64 `json:"latitude"`
    Longitude   float64 `json:"longitude"`
    MetroCode   int     `json:"metro_code"`
}

func main() {
    // Using /etc/timezone
    buf, _ := ioutil.ReadFile("/etc/timezone")
    fmt.Printf("%s", buf)

    // Using freegeoip
    var locationData LocationData

    resp, _ := http.Get("https://freegeoip.net/json/")
    defer resp.Body.Close()

    decoder := json.NewDecoder(resp.Body)
    decoder.Decode(&locationData)

    fmt.Println(locationData.TimeZone)
}


问:
JQuery how to pass data to click without onclick?
I have problem to pass data to function from blade template to click. I don;t want to use onclik. I have a global variable passed to my blade tempate like : oreder and after blick on button I need to pass this data. HEre is my code:

```<code> <button class="btn" id="someButton">Some text</button>
</code>```

And here jQuery :

```<code>$(document).ready(function () {

$('#someButton').on('click', function (here I need to pass global data from blade like : order->id etc) {});
})
</code>```

Is there a possibility to do this?

答:
HTML:

```<code><button class="btn" id="someButton" data-order-id="{{$order->id}}">Some text</button>
</code>```

JQuery:

```<code>$('#someButton').on('click', function() {
    var order_id = $(this).data('order-id');
});
</code>```

Body:
I have problem to pass data to function from blade template to click. I don;t want to use onclik. I have a global variable passed to my blade tempate like : oreder and after blick on button I need to pass this data. HEre is my code:

 <button class="btn" id="someButton">Some text</button>

And here jQuery :

$(document).ready(function () {

$('#someButton').on('click', function (here I need to pass global data from blade like : order->id etc) {});
})

Is there a possibility to do this?

Body:
HTML:

<button class="btn" id="someButton" data-order-id="{{$order->id}}">Some text</button>

JQuery:

$('#someButton').on('click', function() {
    var order_id = $(this).data('order-id');
});


答:
If you want to pass global data in your jQuery function, then you can take that gloabal variable in hidden field like

```<code><input type="hidden" id="gloabalVariable" value="{{$order->id }}">
</code>```

And in your jQuery, you can get it by following line:

```<code>var orderId = $('#gloabalVariable').val();
</code>```

Also you have mentioned that you dont want to use onClick event.
In this case, you can bind either .click() or .mousedown() event on your button.

Please let us know if you need further help regarding this.

Thanks

Title: JQuery how to pass data to click without onclick?

Body:
If you want to pass global data in your jQuery function, then you can take that gloabal variable in hidden field like

<input type="hidden" id="gloabalVariable" value="{{$order->id }}">

And in your jQuery, you can get it by following line:

var orderId = $('#gloabalVariable').val();

Also you have mentioned that you dont want to use onClick event.
In this case, you can bind either .click() or .mousedown() event on your button.

Please let us know if you need further help regarding this.

Thanks


问:
WPF Changing Button Properties after clicked
My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amount of time and I want to reflect the restarting status inside of the control. This is roughly what I have for the restart button click handler

```<code>private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    Controller.Stop();
    Controller.WaitForStatus(ServiceControllerStatus.Stopped);
    Controller.Start();
    Controller.WaitForStatus(ServiceControllerStatus.Running);

    startStopButton.Visibility = Visibility.Visible;
    restartButton.Visibility   = Visibility.Visible;

    statusTextBlock.Text = Controller.Status.ToString();
}
</code>```

Even when I step through the debugger I don't see these changes reflected in the application. Must be something that I'm missing. Also, I've tried disabling the buttons instead of hiding them and that does not work either.

答:
You're doing everything on the UI thread, so the UI isn't updated until this code completes. You should do the heavy lifting on a background thread. The BackgroundWorker component makes this easy:

```<code>private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    var backgroundWorker = new BackgroundWorker();

    // this delegate will run on a background thread
    backgroundWorker.DoWork += delegate
    {
        Controller.Stop();
        Controller.WaitForStatus(ServiceControllerStatus.Stopped);
        Controller.Start();
        Controller.WaitForStatus(ServiceControllerStatus.Running);
    };

    // this delegate will run on the UI thread once the work is complete
    backgroundWorker.RunWorkerCompleted += delegate
    {
        startStopButton.Visibility = Visibility.Visible;
        restartButton.Visibility   = Visibility.Visible;

        statusTextBlock.Text = Controller.Status.ToString();
    };

    backgroundWorker.RunWorkerAsync();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amount of time and I want to reflect the restarting status inside of the control. This is roughly what I have for the restart button click handler

private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    Controller.Stop();
    Controller.WaitForStatus(ServiceControllerStatus.Stopped);
    Controller.Start();
    Controller.WaitForStatus(ServiceControllerStatus.Running);

    startStopButton.Visibility = Visibility.Visible;
    restartButton.Visibility   = Visibility.Visible;

    statusTextBlock.Text = Controller.Status.ToString();
}

Even when I step through the debugger I don't see these changes reflected in the application. Must be something that I'm missing. Also, I've tried disabling the buttons instead of hiding them and that does not work either.

Body:
You're doing everything on the UI thread, so the UI isn't updated until this code completes. You should do the heavy lifting on a background thread. The BackgroundWorker component makes this easy:

private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    var backgroundWorker = new BackgroundWorker();

    // this delegate will run on a background thread
    backgroundWorker.DoWork += delegate
    {
        Controller.Stop();
        Controller.WaitForStatus(ServiceControllerStatus.Stopped);
        Controller.Start();
        Controller.WaitForStatus(ServiceControllerStatus.Running);
    };

    // this delegate will run on the UI thread once the work is complete
    backgroundWorker.RunWorkerCompleted += delegate
    {
        startStopButton.Visibility = Visibility.Visible;
        restartButton.Visibility   = Visibility.Visible;

        statusTextBlock.Text = Controller.Status.ToString();
    };

    backgroundWorker.RunWorkerAsync();
}