问:
How to filter DataGridView to keep only a given set of rows
In C# I have DataGridView populated via DataSource. With some custom made filter I determine a subset of rows (by looping through the rows and checking the conditions on columns, to be precise) and need to keep/show only these rows in the DatGridView.

One option I understand is to loop through the grid and hide the rows which are outside my index set. This, however, is painfully slow for larger set of rows.
My question is:

given a datagridview which is bind to a datasource, and a subset of its rows, is there an efficient way to keep only those rows in datagridview?

答:
Slow speed probably comes only from the GUI updates. You may want to

Suspend/ResumeLayout the DGV and/or

DoubleBuffer the DGV.

The latter will speed up all display operations including scrolling.

If you'd rather go for a real filter you will need an extra column to hold the filter value and a BindingSource.

(You won't need the extra colum, if you can put your logic into the filter..)

Assuming a DataTable DT as your DataSource first add a filter column:

```<code>DT.Columns.Add("Filter", typeof(int));
</code>```

Next create a  BindingSource BS = new BindingSource();

Now bind the original datasource to the bindingsource and use it as the new datasource:

```<code>BS.DataSource = DT;
yourDGV.DataSource  = BS;
</code>```

Now you can use your code to set a value for the filter column and finally set or unset the filter:

```<code>BS.Filter = "Filter = 23";  // use your indicator logic!
BS.Filter = "";              // unset filter
</code>```

For the Filter you can use the DataColumn.Expression Property syntax.

If you want to see the filter column you need to add it to the DGV columns as well and set the connection to the datasource.

Example:

```<code>yourDGV.Columns.Add("Filter", "filter");
yourDGV.Columns["Filter"].DataPropertyName = "Filter";
</code>```

Body:
Slow speed probably comes only from the GUI updates. You may want to

Suspend/ResumeLayout the DGV and/or

DoubleBuffer the DGV.

The latter will speed up all display operations including scrolling.

If you'd rather go for a real filter you will need an extra column to hold the filter value and a BindingSource.

(You won't need the extra colum, if you can put your logic into the filter..)

Assuming a DataTable DT as your DataSource first add a filter column:

DT.Columns.Add("Filter", typeof(int));

Next create a  BindingSource BS = new BindingSource();

Now bind the original datasource to the bindingsource and use it as the new datasource:

BS.DataSource = DT;
yourDGV.DataSource  = BS;

Now you can use your code to set a value for the filter column and finally set or unset the filter:

BS.Filter = "Filter = 23";  // use your indicator logic!
BS.Filter = "";              // unset filter

For the Filter you can use the DataColumn.Expression Property syntax.

If you want to see the filter column you need to add it to the DGV columns as well and set the connection to the datasource.

Example:

yourDGV.Columns.Add("Filter", "filter");
yourDGV.Columns["Filter"].DataPropertyName = "Filter";


来源: stackexchange

问:
How to render a vnode (slot of a vue component) and mount it on an element?
For example, here we have a dialog component.

```<code>...

<dialog>
  <div>
   {{data}}
  </div>
</dialog>

...
</code>```

As we known, due to the stack context, it's hard to make the dialog always be the topmost element.

So we need to mount the dialog element as a body's child.

I tried this in dialog's mounted hook.

```<code>var slot=this.$slots.default
var vm = new Vue({
        render: ()=>slot
}
var div=document.createElement('div')
document.body.append(div)
vm.mount(div)
</code>```

The result is: it mounted successfully.

However, when I changed the data, the mounted vm didn't change.

I wonder how to make it reactive or is there any other way to achieve this.

答:
Now that I can't find any methods to solve this.
I have to read some open source ui framework's source code because I know they do put the dialog in the body's child level.

And I found that they do render the <slot>, but I can't find any code rendered in the corresponding position and I can't find any code they use to 'remove' it.

...

Then, I found a line of code, document.body.append(this.$el). I am stupid. I didn't realize that append will just remove the element from it's original position and append  it to the new position util I re-read the whole code once again.

I did think about this way, just append $el to somewhere. But I am afraid that it'll break the component down.

So, the solution is:

just define a normal vue component

ship the $el or child element to anywhere you want using element.append etc. after the component mounted

no need to remove the element manually when component is destroyed if you just ship the $el, vue will take care of it.

ContentLicense: CC BY-SA 4.0

Body:
For example, here we have a dialog component.

...

<dialog>

   {{data}}

</dialog>

...

As we known, due to the stack context, it's hard to make the dialog always be the topmost element.

So we need to mount the dialog element as a body's child.

I tried this in dialog's mounted hook.

var slot=this.$slots.default
var vm = new Vue({
        render: ()=>slot
}
var div=document.createElement('div')
document.body.append(div)
vm.mount(div)

The result is: it mounted successfully.

However, when I changed the data, the mounted vm didn't change.

I wonder how to make it reactive or is there any other way to achieve this.


问:
OpenCV warpAffine and inverse warpAffine inconsistence
I'm using the OpenCV warpAffine function to do some image processing. The weird thing is that I found after applying a warpAffine and then an inverse warpAffine. The processed image is inconsistent with the original image, where there is one-pixel border padding at the bottom.

img_path = '140028_199844.jpg'
img = cv2.imread(img_path,cv2.IMREAD_COLOR)
plt.imshow(img[:,:,::-1])
h,w,_=img.shape # h=220 w=173
```

<p><img src="https://i.stack.imgur.com/gn1br.jpg" alt="enter image description here"></p>

<pre class="lang-py prettyprint-override"><code>src = np.array([[ 86., 109.5], [ 86. , 0. ], [-23.5, 0. ]])
dst = np.array([[192., 192.], [192. , 0.], [  0. , 0.]])
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
inv_trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
</code>```

input = cv2.warpAffine(
    img,
    trans,
    (384, 384),
    flags=cv2.INTER_LINEAR,
    borderMode=cv2.BORDER_CONSTANT,
    borderValue=(0, 0, 0))
plt.imshow(input[:,:,::-1])
```

<p><img src="https://i.stack.imgur.com/BLNhZ.png" alt="enter image description here"></p>

<pre class="lang-py prettyprint-override"><code>output = cv2.warpAffine(
        input,
        inv_trans,
        (w, h),
        flags=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_CONSTANT,
        borderValue=(0,0,0))
plt.imshow(output[:,:,::-1])
</code>```

So what is the possible reseason for such problem?

答:
It is probably a numerical issue, since the warped coordinates get mapped back to integer indices (i.e. in range w and h).

You will likely see a worse effect if you do this multiple times, i.e. warp, invert, warp, invert, etc.

Body:
I'm using the OpenCV warpAffine function to do some image processing. The weird thing is that I found after applying a warpAffine and then an inverse warpAffine. The processed image is inconsistent with the original image, where there is one-pixel border padding at the bottom.

img_path = '140028_199844.jpg'
img = cv2.imread(img_path,cv2.IMREAD_COLOR)
plt.imshow(img[:,:,::-1])
h,w,_=img.shape # h=220 w=173

src = np.array([[ 86., 109.5], [ 86. , 0. ], [-23.5, 0. ]])
dst = np.array([[192., 192.], [192. , 0.], [  0. , 0.]])
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
inv_trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))

input = cv2.warpAffine(
    img,
    trans,
    (384, 384),
    flags=cv2.INTER_LINEAR,
    borderMode=cv2.BORDER_CONSTANT,
    borderValue=(0, 0, 0))
plt.imshow(input[:,:,::-1])

output = cv2.warpAffine(
        input,
        inv_trans,
        (w, h),
        flags=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_CONSTANT,
        borderValue=(0,0,0))
plt.imshow(output[:,:,::-1])

So what is the possible reseason for such problem?


问:
How to set root view controller in Today extension programmatically
I have a project without storyboard. I've set root view controller in AppDelegate. Now I've added a today extension. I got a new storyboard MainInterface.storyboard with root view controller TodayViewController. How can I delete MainInterface.storyboard and set root view controller programmatically?

答:
Using the URL Scheme to achieve your goal, See this code.

Write the following code in TodayViewController (Today extension swift file)

```<code>@IBAction func buttonTapped(_ sender: UIButton) {
        let url = URL(string: "MyAppTodayExtension://")!
        self.extensionContext?.open(url, completionHandler: { (success) in
            if (!success) {
                print("error: failed to open app from Today Extension")
            }
        })
    }
</code>```

Add URL Scheme in your info.plist file

```<code><key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>MyAppTodayExtension</string>
            </array>
        </dict>
    </array>
</code>```

When you tap in today extension then get call following method in AppDelegate.swift file.

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        //Write code here for navigating to a specific controller OR set root view controller
        return true
    }
</code>```

Body:
Using the URL Scheme to achieve your goal, See this code.

Write the following code in TodayViewController (Today extension swift file)

@IBAction func buttonTapped(_ sender: UIButton) {
        let url = URL(string: "MyAppTodayExtension://")!
        self.extensionContext?.open(url, completionHandler: { (success) in
            if (!success) {
                print("error: failed to open app from Today Extension")
            }
        })
    }

Add URL Scheme in your info.plist file

<key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>MyAppTodayExtension</string>
            </array>
        </dict>
    </array>

When you tap in today extension then get call following method in AppDelegate.swift file.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        //Write code here for navigating to a specific controller OR set root view controller
        return true
    }


问:
How many wiki instances to install?
I've been asked to install Mediawiki to house documentation for a company intranet. Furthermore, I've been asked to install several instances - one per contributing group: non-technical users get one, developers one, management one, etc. The idea is to provide separate web spaces for each group. Is there a way to achieve separation within one instance?

答:
I am working with trac, that based on wiki.

(With small assumption, that your wiki is something like wiki that i am worked with.)

I think that you can install even more wiki's, because they are easy to maintain.

Of course you can to suggest to your boss, to start with one wiki with many categories.

Suggestions:

one wiki is a project that more flexible for backup and restore

preventing from documentation duplicate

start from one (lets say, for developers), and then add other wiki. (when developers is start to work on wiki, you can try again with "categories version" and you will know exactly what the cost of a lot of wikis)

did he shure about the Mediawiki? wizard of wiki choising

ContentLicense: CC BY-SA 2.5

Title: How many wiki instances to install?

LastEditorDisplayName: nzpcmad

OwnerDisplayName: Avram


问:
Can I force delete an AWS CloudFormation stack that is In Progress of Rollback
An AWS CloudFormation rollback (e.g., UPDATE_ROLLBACK_IN_PROGRESS) has been in progress forever, like over an hour and a half. I want to delete the stack altogether or force stop any activity. Is this possible?

Thanks!

答: You can try to delete the resources and then the update rollback will complete successfully.</p>

ContentLicense: CC BY-SA 3.0


问:
jQuery.Deferred exception: Cannot set property '_DT_CellIndex' of undefined TypeError: Cannot set property '_DT_CellIndex' of undefined
I got this error in datatable. I have included all header files corrrectly but don't know why this error occurs.

jQuery.Deferred exception: Cannot set property '_DT_CellIndex' of
  undefined TypeError: Cannot set property '_DT_CellIndex' of undefined

I tried some solutions like no empty rows, equal number of headings and columns etc. but nothing worked here. Please help.

```<code><div class="row">
   <div class="col-md-12">
      <table class="table table-striped table-hover datatable">
         <thead>
            <tr>
               <th>Target</th>
               <th>Goal</th>
               <th>Target Status</th>
               <th>Date</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Demo Target</td>
               <td>Some Goal</td>
               <td>Some Status</td>
               <td>Some Date</td>
            </tr>
         </tbody>
      </table>
   </div>
</div>
</code>```

Here is my js code-

```<code>   $(document).ready(function(){
   $.extend( $.fn.dataTable.defaults, {
       autoWidth: false,
       dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
       language: {
           search: '<span>Filter:</span> _INPUT_',
           searchPlaceholder: 'Search...',
           lengthMenu: '<span>Show:</span> _MENU_',
           paginate: { 'first': 'First', 'last': 'Last', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' }
       }
   });

   var table = $('.datatable').DataTable({
       buttons: {
           buttons: [
               {
                   extend: 'copyHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'excelHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'pdfHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'colvis',
                   text: '<i class="icon-three-bars"></i>',
                   className: 'btn bg-blue btn-icon dropdown-toggle'
               }
           ]
       },
       "aaSorting": []
   });
</code>```

答: I see no issue with your code, it works just fine on my end. I would check your html for duplicates i.e. using .datatable class in another spot and would use an id to initiate it.

Body:
I got this error in datatable. I have included all header files corrrectly but don't know why this error occurs.

jQuery.Deferred exception: Cannot set property '_DT_CellIndex' of
  undefined TypeError: Cannot set property '_DT_CellIndex' of undefined

I tried some solutions like no empty rows, equal number of headings and columns etc. but nothing worked here. Please help.

               Target
               Goal
               Target Status
               Date

               Demo Target
               Some Goal
               Some Status
               Some Date

Here is my js code-

   $(document).ready(function(){
   $.extend( $.fn.dataTable.defaults, {
       autoWidth: false,
       dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
       language: {
           search: 'Filter: _INPUT_',
           searchPlaceholder: 'Search...',
           lengthMenu: 'Show: _MENU_',
           paginate: { 'first': 'First', 'last': 'Last', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' }
       }
   });

   var table = $('.datatable').DataTable({
       buttons: {
           buttons: [
               {
                   extend: 'copyHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'excelHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'pdfHtml5',
                   className: 'btn btn-light',
                   exportOptions: {
                       columns: [ 0, ":visible" ]
                   }
               },
               {
                   extend: 'colvis',
                   text: '',
                   className: 'btn bg-blue btn-icon dropdown-toggle'
               }
           ]
       },
       "aaSorting": []
   });


问:
C++ : const reference to local object
```<code>const std::string s1 = "abc";
const std::string & s2 = "abc";
</code>```

Is the definition of s2 legal? If so, what is the difference between between s1 and s2?

Thanks.

答:
Both are legal.

S1 is a variable of the type std::String with a const Qualifier.

S2 is const Reference to a temporary of the type std::string.

Title: C++ : const reference to local object

Body:
const std::string s1 = "abc";
const std::string & s2 = "abc";

Is the definition of s2 legal? If so, what is the difference between between s1 and s2?

Thanks.


问:
Is it good practice to use "using" on a new empty DataTable?
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

```<code>using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}
</code>```

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

```<code>DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();
</code>```

Changing this to use using, I have:

```<code>using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}
</code>```

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

答:
Just another approach but similar to that what John said. You can use a func<> to set your get method and use this in the using()

```<code>Func<DataTable> func = null;
switch (foo)
{
    case bar:
        func = () => BLL.GetDataTable(bar);
        break;
    default:
        func = () => BLL.GetDataTable();
        break;
 }

 using (var dt = func())
 {
     // iteration logic here
 }
</code>```

Personally i would prefer Johns approach, its a bit more readable. But all do the same, so it's up to you to use what you like most.

Body:
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();

Changing this to use using, I have:

using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

Body:
Just another approach but similar to that what John said. You can use a func<> to set your get method and use this in the using()

Func<DataTable> func = null;
switch (foo)
{
    case bar:
        func = () => BLL.GetDataTable(bar);
        break;
    default:
        func = () => BLL.GetDataTable();
        break;
 }

 using (var dt = func())
 {
     // iteration logic here
 }

Personally i would prefer Johns approach, its a bit more readable. But all do the same, so it's up to you to use what you like most.


问:
EF - Save Changes - How to fix VIOLATION OF PRIMARY KEY constraint
I am using Entity Framework to add data into a table in sql.
I have the below class and method to add the new records.
But I am getting the below error.

SqlException: Violation of PRIMARY KEY constraint
  'PK__Users__3214EC27E90BFE7E'. Cannot insert duplicate key in object
  'dbo.Users'. The duplicate key value is (0). The statement has been
  terminated.

```<code>public partial class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public string Surname { get; set; }

}

    public void InsertUser(MyEvent e)
    {
        using (var db = CreateInstance())
        {
            var users = db.Set<User>();
            users.Add(new User
            {
                Name= e.Name,
                Surname= e.Surname
            });
            db.SaveChanges();
         }
      }
</code>```

How can EF auto-increment the ID in the table?

答:
It should be the SQL server itself incrementing the PK, not the EF. If you have multiple EF clients inserting data into the DB at the same time, it would be difficult to ensure the PK is incremented correctly. With SQL it is much easier, all you need to do is set the PK column as identity with auto-increments.

If the PK column is row_id, you can define it like this via scripting:

```<code>[row_id] [int] IDENTITY(1,1) NOT NULL
</code>```

Or, if you create the table using SSMS designer, then in the column properties set Identity Specification as:

```<code>Is Identity = Yes
Identity Increment = 1
Identity Seed = 1
</code>```

Body:
I am using Entity Framework to add data into a table in sql.
I have the below class and method to add the new records.
But I am getting the below error.

SqlException: Violation of PRIMARY KEY constraint
  'PK__Users__3214EC27E90BFE7E'. Cannot insert duplicate key in object
  'dbo.Users'. The duplicate key value is (0). The statement has been
  terminated.

public partial class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public string Surname { get; set; }

}

    public void InsertUser(MyEvent e)
    {
        using (var db = CreateInstance())
        {
            var users = db.Set<User>();
            users.Add(new User
            {
                Name= e.Name,
                Surname= e.Surname
            });
            db.SaveChanges();
         }
      }

How can EF auto-increment the ID in the table?

Body:
It should be the SQL server itself incrementing the PK, not the EF. If you have multiple EF clients inserting data into the DB at the same time, it would be difficult to ensure the PK is incremented correctly. With SQL it is much easier, all you need to do is set the PK column as identity with auto-increments.

If the PK column is row_id, you can define it like this via scripting:

[row_id] [int] IDENTITY(1,1) NOT NULL

Or, if you create the table using SSMS designer, then in the column properties set Identity Specification as:

Is Identity = Yes
Identity Increment = 1
Identity Seed = 1


答:
I'm currently working on a switch dataset that I polled from an sql database where each port on the respective switch has a data frame which has a time series. So to access this time series information for each specific port I represented the switches by their IP addresses and the various number of ports on the switch, and to make sure I don't re-query what I already queried before I used the .unique() method to get unique queries of each.

I set my index to be the IP and Port indices and accessed the port information like so:

```<code>def yield_df(df):
for ip in df.index.get_level_values('ip').unique():
    for port in df.loc[ip].index.get_level_values('port').unique():
        yield df.loc[ip].loc[port]
</code>```

Then I cycled the port data frames with a for loop like so:

```<code>for port_df in yield_df(adb_df):
</code>```

I'm sure there are faster ways to carry out these procedures in pandas but I hope this helps you start solving your problem

Title: How to cycle a Pandas dataframe grouping by hierarchical multiindex from top to bottom and store results

Body:
I'm trying to create a forecasting process using hierarchical time series. My problem is that I can't find a way to create a for loop that hierarchically extracts daily time series from a pandas dataframe grouping the sum of quantities by date. The resulting daily time series should be passed to a function inside the loop, and the results stored in some other object.

Dataset

The initial dataset is a table that represents the daily sales data of 3 hierarchical levels: city, shop, product. The initial table has this structure:

+============+============+============+============+==========+
| Id_Level_1 | Id_Level_2 | Id_Level_3 |    Date    | Quantity |
+============+============+============+============+==========+
| Rome       | Shop1      | Prod1      | 01/01/2015 |       50 |
+------------+------------+------------+------------+----------+
| Rome       | Shop1      | Prod1      | 02/01/2015 |       25 |
+------------+------------+------------+------------+----------+
| Rome       | Shop1      | Prod1      | 03/01/2015 |       73 |
+------------+------------+------------+------------+----------+
| Rome       | Shop1      | Prod1      | 04/01/2015 |       62 |
+------------+------------+------------+------------+----------+
| ...        | ...        | ...        | ...        |      ... |
+------------+------------+------------+------------+----------+
| Milan      | Shop3      | Prod9      | 31/12/2018 |      185 |
+------------+------------+------------+------------+----------+
| Milan      | Shop3      | Prod9      | 31/12/2018 |      147 |
+------------+------------+------------+------------+----------+
| Milan      | Shop3      | Prod9      | 31/12/2018 |      206 |
+------------+------------+------------+------------+----------+

Each City (Id_Level_1) has many Shops (Id_Level_2), and each one has some Products (Id_Level_3). Each shop has a different mix of products (maybe shop1 and shop3 have product7, which is not available in other shops). All data are daily and the measure of interest is the quantity.

Hierarchical Index (MultiIndex)

I need to create a tree structure (hierarchical structure) to extract a time series for each "node" of the structure. I call a "node" a cobination of the hierarchical keys, i.e. "Rome" and "Milan" are nodes of Level 1, while "Rome|Shop1" and "Milan|Shop9" are nodes of level 2. In particulare, I need this on level 3, because each product (Id_Level_3) has different sales in each shop of each city. Here is the strict hierarchy.
Nodes of level 3 are "Rome, Shop1, Prod1", "Rome, Shop1, Prod2", "Rome, Shop2, Prod1", and so on. The key of the nodes is logically the concatenation of the ids.

For each node, the time series is composed by two columns: Date and Quantity.

# MultiIndex dataframe
Liv_Labels = ['Id_Level_1', 'Id_Level_2', 'Id_Level_3', 'Date']
df.set_index(Liv_Labels, drop=False, inplace=True)

The I need to extract the aggregated time series in order but keeping the hierarchical nodes.

Level 0:

Level_0 = df.groupby(level=['Data'])['Qta'].sum()

Level 1:

# Node Level 1 "Rome"
Level_1['Rome'] = df.loc[idx[['Rome'],:,:]].groupby(level=['Data']).sum()

# Node Level 1 "Milan"
Level_1['Milan'] = df.loc[idx[['Milan'],:,:]].groupby(level=['Data']).sum()

Level 2:

# Node Level 2 "Rome, Shop1"
Level_2['Rome',] = df.loc[idx[['Rome'],['Shop1'],:]].groupby(level=['Data']).sum()

... repeat for each level 2 node ...

# Node Level 2 "Milan, Shop9"
Level_2['Milan'] = df.loc[idx[['Milan'],['Shop9'],:]].groupby(level=['Data']).sum()

Attempts

I already tried creating dictionaries and multiindex, but my problem is that I can't get a proper "node" use inside the loop. I can't even extract the unique level nodes keys, so I can't collect a specific node time series.

# Get level labels
Level_Labels = ['Id_Liv'+str(n) for n in range(1, Liv_Num+1)]+['Data']

# Initialize dictionary
TimeSeries = {}

# Get Level 0 time series
TimeSeries["Level_0"] = df.groupby(level=['Data'])['Qta'].sum()

# Get othe levels time series from 1 to Level_Num
for i in range(1, Liv_Num+1):
    TimeSeries["Level_"+str(i)] = df.groupby(level=Level_Labels[0:i]+['Data'])['Qta'].sum()

Desired result

I would like a loop the cycles my dataset with these actions:

Creates a structure of all the unique node keys

Extracts the node time series grouped by Date and Quantity

Store the time series in a structure for later use

Thanks in advance for any suggestion! Best regards.
FR

Body:
I'm currently working on a switch dataset that I polled from an sql database where each port on the respective switch has a data frame which has a time series. So to access this time series information for each specific port I represented the switches by their IP addresses and the various number of ports on the switch, and to make sure I don't re-query what I already queried before I used the .unique() method to get unique queries of each.

I set my index to be the IP and Port indices and accessed the port information like so:

def yield_df(df):
for ip in df.index.get_level_values('ip').unique():
    for port in df.loc[ip].index.get_level_values('port').unique():
        yield df.loc[ip].loc[port]

Then I cycled the port data frames with a for loop like so:

for port_df in yield_df(adb_df):

I'm sure there are faster ways to carry out these procedures in pandas but I hope this helps you start solving your problem


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
You should just use pd.to_datetime to convert your string values:

```<code>df["time_diff"] = (pd.to_datetime(df.end_date) - pd.to_datetime(df.start_date))
</code>```

The resul will automatically be a timedelta64

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
You should just use pd.to_datetime to convert your string values:

df["time_diff"] = (pd.to_datetime(df.end_date) - pd.to_datetime(df.start_date))

The resul will automatically be a timedelta64


问:
Javascript: promise.resolve() statement valid?
As I understand, Promise is a function of window object.

Console View (Chrome)

```<code>window.hasOwnProperty('Promise') // true

window.Promise // ƒ Promise() { [native code] }
</code>```

But what I don't understand is how can a Promise.resolve() be a valid statement since it Promise is a function, not an object. Nor am I calling the promise function, like this window.promise() so that it then returns an object which has a resolve method.

Kindly clear this.

Thanks

答:
Functions can have properties on them as well:

class MyClass {
  static fn() {
    console.log('fn running');
  }
}

const m = new MyClass();
MyClass.fn();```
</div>
</div>
</p>

<p>The actual source code of <code>window.Promise</code> may be hidden, but just like <code>MyClass</code> above, that doesn't stop the function itself from being able to have properties.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(Object.getOwnPropertyNames(Promise));</code>```

Body:
As I understand, Promise is a function of window object.

Console View (Chrome)

window.hasOwnProperty('Promise') // true

window.Promise // ƒ Promise() { [native code] }

But what I don't understand is how can a Promise.resolve() be a valid statement since it Promise is a function, not an object. Nor am I calling the promise function, like this window.promise() so that it then returns an object which has a resolve method.

Kindly clear this.

Thanks

Body:
Functions can have properties on them as well:

class MyClass {
  static fn() {
    console.log('fn running');
  }
}

const m = new MyClass();
MyClass.fn();

The actual source code of window.Promise may be hidden, but just like MyClass above, that doesn't stop the function itself from being able to have properties.

console.log(Object.getOwnPropertyNames(Promise));


问:
Short way to replace values in a Series based on values in another Series?
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

```<code>    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)
</code>```

答:
how about the use of numpy where clause to check values in a and b and replace? see a mockup below. I have used column 'c' to illustrate

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })
#replace b value if the corresponding value in column a is 1 and column b is NaN
df['c'] = np.where(((df['a'] == 1) & (df['b'].isna())), df['a'], df['b'])
df
</code>```

original dataframe

```<code>     a  b
0   1.0 1.0
1   NaN 5.0
2   3.0 6.0
</code>```

result:

```<code>      a b   c
0   1.0 NaN 1.0
1   NaN 5.0 5.0
2   3.0 6.0 6.0
</code>```

Body:
I the below code, I am replacing all NaN values from column b with blank string if the corresponding value in column a is 1.

The code works, but I have to type df.loc[df.a == 1, 'b'] twice.

Is there a shorter/better way to do it?

    import pandas as pd

    df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })

    filtered = df.loc[df.a == 1, 'b']
    filtered.fillna('', inplace=True)
    df.loc[df.a == 1, 'b'] = filtered
    print(df)

Body:
how about the use of numpy where clause to check values in a and b and replace? see a mockup below. I have used column 'c' to illustrate

import pandas as pd
import numpy as np
df = pd.DataFrame({
        'a': [1, None, 3],
        'b': [None, 5, 6],
    })
#replace b value if the corresponding value in column a is 1 and column b is NaN
df['c'] = np.where(((df['a'] == 1) & (df['b'].isna())), df['a'], df['b'])
df

original dataframe

     a  b
0   1.0 1.0
1   NaN 5.0
2   3.0 6.0

result:

      a b   c
0   1.0 NaN 1.0
1   NaN 5.0 5.0
2   3.0 6.0 6.0


问:
JS alert not happening before php header/location change
This is an interesting one...
I am trying to test for something, then show an alert then once the OK is clicked relocate the page to somewhere else, using header
However if I have the code below it just goes straight to the URL.
If I comment out the header then the alert works....

```<code>elseif ($user['archived']=="1"){
    echo "<script type='text/javascript'>alert('Sorry you are no longer an owner');</script>";
    sleep(10);
    header('location: https://some URL');
}
</code>```

答:
You could use a meta redirect instead. I'm not sure if this is good or bad practice but it will do the trick for you.</p>

```<code>if (...) {
    // ...
} elseif ($user['archived']=="1") {
    echo '<meta http-equiv="refresh" content="10; URL=someurl">';'
    echo "<script type='text/javascript'>alert('Sorry you are no longer an owner');</script>";
    exit;
}
</code>```

Body:
This is an interesting one...
I am trying to test for something, then show an alert then once the OK is clicked relocate the page to somewhere else, using header
However if I have the code below it just goes straight to the URL.
If I comment out the header then the alert works....

elseif ($user['archived']=="1"){
    echo "";
    sleep(10);
    header('location: https://some URL');
}

Body:
You could use a meta redirect instead. I'm not sure if this is good or bad practice but it will do the trick for you.

if (...) {
    // ...
} elseif ($user['archived']=="1") {
    echo '<meta http-equiv="refresh" content="10; URL=someurl">';'
    echo "<script type='text/javascript'>alert('Sorry you are no longer an owner');</script>";
    exit;
}


问:
HighCharts Create gradiance decress color to blur for each value on bar chart
I'm trying to create some high carts bar with gradient decrees for each bar
bar decrees color become blurry for each range, for rank 1 bar the color is solid

this is my sample picture

anyone can help me

答:
You can use colorAxis from heatmap series by wrapping colum's prototype:

```<code>var columnProto = Highcharts.seriesTypes.column.prototype;

columnProto.axisTypes = ['xAxis', 'yAxis', 'colorAxis'];
columnProto.optionalAxis = 'colorAxis';
columnProto.colorKey = 'y';

Highcharts.wrap(columnProto, 'translate', function(proceed) {
    proceed.apply(this, Array.prototype.slice.call(arguments, 1));

    Highcharts.seriesTypes.heatmap.prototype.translateColors.call(this);
});

Highcharts.chart('container', {
    series: [{
        type: 'bar',
        data: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    }],
    colorAxis: {
        minColor: '#c6e48b',
        maxColor: '#196127',
        min: 1,
        max: 9
    }
});
</code>```

Live demo: http://jsfiddle.net/BlackLabel/u8wgh0dk/

API Reference: https://api.highcharts.com/highcharts/colorAxis

Body:
You can use colorAxis from heatmap series by wrapping colum's prototype:

var columnProto = Highcharts.seriesTypes.column.prototype;

columnProto.axisTypes = ['xAxis', 'yAxis', 'colorAxis'];
columnProto.optionalAxis = 'colorAxis';
columnProto.colorKey = 'y';

Highcharts.wrap(columnProto, 'translate', function(proceed) {
    proceed.apply(this, Array.prototype.slice.call(arguments, 1));

    Highcharts.seriesTypes.heatmap.prototype.translateColors.call(this);
});

Highcharts.chart('container', {
    series: [{
        type: 'bar',
        data: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    }],
    colorAxis: {
        minColor: '#c6e48b',
        maxColor: '#196127',
        min: 1,
        max: 9
    }
});

Live demo: http://jsfiddle.net/BlackLabel/u8wgh0dk/

API Reference: https://api.highcharts.com/highcharts/colorAxis


问:
Ruby: How to replace elements in an Array?
I'm building a simple tic-tac-toe game and I've totally hit a wall with my grid.

I'd like to "puts @grid" including player input every time players have made their choice. How can I achieve this? I'm almost a total beginner with Ruby and have never build any games before. Any help is greatly appreciated, thanks in advance!

I tried making two different grids (grid and grid_with_markers) but couldn't figure out where to go from there. Looking back, having two grids also just seemed like a bad idea. I also tried having a Hash (marker_positions), but that seemed overly complicated compared to an Array.

Here is the grid

```<code>def initialize
    @possible_choice = [1,2,3,4,5,6,7,8,9]
    @marker_positions = [1,2,3,4,5,6,7,8,9]
    @grid = "
                |----|----|----|
                |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
                |----|----|----|
                |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
                |----|----|----|
                |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
                |----|----|----|
                "
end
</code>```

I'd like to use a method add_markers to show the grid with user input. So when a player selects number 1 @marker_positions[0] would be replaced as "X" (or "O"). Number 4 would replace @marker_positions[3] etc.

Edit: I realised the title of this post was misleading since I actually want to replace elements of @marker_positions Array with Strings ("X" or "O"). But the replaced element is selected based on user input, in other words, player_one and player_two Arrays.

```<code>def add_markers
  puts @grid
end
</code>```

Here's the player_one_turn method

```<code>def player_one_turn()
    puts "Player One, make your choice:"
    p @possible_choice
    add_markers
    @@player_one << @possible_choice.delete(gets.chomp.to_i)
    p "Player One has chosen: #{@@player_one}"
end
</code>```

And here's my entire tictactoe.rb file.

```<code>
class Grid
    WINNING_COMBOS = [
        [1,2,3],[4,5,6],[7,8,9],
        [1,4,7],[2,5,8],[3,6,9],
        [1,5,9],[3,5,7]
    ]
    attr_accessor :possible_choice
    attr_accessor :marker_positions
    attr_accessor :grid

    def initialize
        @possible_choice = [1,2,3,4,5,6,7,8,9]
        @marker_positions = [1,2,3,4,5,6,7,8,9]
        @grid = "
                |----|----|----|
                |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
                |----|----|----|
                |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
                |----|----|----|
                |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
                |----|----|----|
                "
    end

    def add_markers

        puts @grid
    end
end

class Game < Grid
    @@player_one = Array.new
    @@player_two = Array.new

    def game
        puts
        puts "*** This is a tic-tac-toe game for two human players. ***"
        puts
        loop do
            player_one_turn()
            puts
                if has_won?(@@player_one)
                    puts "The game has ended. Player One has won!"
                    puts
                    return
                end
            break if @@player_one.length == 5 || @@player_one.include?(nil)
            player_two_turn()
            puts
                if has_won?(@@player_two)
                    puts "The game has ended. Player Two has won!"
                    puts
                    return
                end
        end
    end

    def player_one_turn()
        puts "Player One, make your choice:"
        p @possible_choice
        add_markers
        @@player_one << @possible_choice.delete(gets.chomp.to_i)
        p "Player One has chosen: #{@@player_one}"
    end

    def player_two_turn()
        puts "Player Two, make your choice:"
        p @possible_choice
        add_markers
        @@player_two << @possible_choice.delete(gets.chomp.to_i)
        p "Player Two has chosen: #{@@player_two}"
    end

    def has_won?(player)
        WINNING_COMBOS.any? { |combo| (player & combo).size == combo.size}
    end
end

new_game = Game.new
new_game.game

</code>```

(I know it isn't very clean. Thank you for taking time to read all the way down here.)

答:
So when a player selects number 1 @marker_positions[0] would be replaced as "X"

You just have to read the user input: (example shows result for player entering 1)

```<code>input = gets.to_i
#=> 1
</code>```

and replace the corresponding array element: (we have to subtract 1 because array is zero-based)

```<code>@marker_positions[input - 1] = 'X'
</code>```

Using the array values within the grid string is another issue. The interpolations via #{...} happens when creating the string, just before it is assigned to @grid in initialize. This means the string is not being updated when the interpolated value changes afterwards – it just stays the same unless you interpolate it again:

```<code>x = 'foo'
@grid = "hello #{x}"
#=> "Hello foo"

x = 'bar'
@grid
#=> "Hello foo"  <- doesn't change

@grid = "hello #{x}"
#=> "Hello bar"
</code>```

To get a "fresh" grid every time you call add_markers you could simply move the string interpolation code from initialize into that method: (instead of "...", I'm using <<~EOD ... EOD, a "squiggly" heredoc which ignores leading whitespace)

class Grid
  attr_accessor :marker_positions

  def initialize
    @marker_positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  end

  def add_markers
    puts <<~EOD
      |----|----|----|
      |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
      |----|----|----|
      |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
      |----|----|----|
      |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
      |----|----|----|
    EOD
  end
end
```

<p>This would result in: (the <code>#</code> are not part of the actual output)</p>

<pre class="lang-rb prettyprint-override"><code>grid = Grid.new
grid.add_markers
#|----|----|----|
#|  1 |  2 |  3 |
#|----|----|----|
#|  4 |  5 |  6 |
#|----|----|----|
#|  7 |  8 |  9 |
#|----|----|----|

grid.marker_positions[0] = 'X'
grid.marker_positions[4] = 'X'
grid.marker_positions[8] = 'X'
grid.add_markers
#|----|----|----|
#|  X |  2 |  3 |
#|----|----|----|
#|  4 |  X |  6 |
#|----|----|----|
#|  7 |  8 |  X |
#|----|----|----|
</code>```

Another – maybe cleaner – option is to define a template with placeholders that are replaced by their actual (or current) values when rendering the template:

class Grid
  TEMPLATE = <<~EOD.freeze
    ┌───┬───┬───┐
    │ 1 │ 2 │ 3 │
    ├───┼───┼───┤
    │ 4 │ 5 │ 6 │
    ├───┼───┼───┤
    │ 7 │ 8 │ 9 │
    └───┴───┴───┘
  EOD

  attr_accessor :marker_positions

  def initialize
    @marker_positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  end

  def render
    puts TEMPLATE.gsub(/[1-9]/) { |d| @marker_positions[d.to_i - 1] }
  end
end
```

<p><code>gsub</code> scans the template string for digits <code>1</code> to <code>9</code> and replaces each occurrence <code>d</code> with the block's result, which simply picks the corresponding value from our array.</p>

<p>Usage:</p>

<pre class="lang-rb prettyprint-override"><code>grid = Grid.new
grid.render
#┌───┬───┬───┐
#│ 1 │ 2 │ 3 │
#├───┼───┼───┤
#│ 4 │ 5 │ 6 │
#├───┼───┼───┤
#│ 7 │ 8 │ 9 │
#└───┴───┴───┘

grid.marker_positions[0] = 'X'
grid.marker_positions[4] = 'X'
grid.marker_positions[8] = 'X'
grid.render
#┌───┬───┬───┐
#│ X │ 2 │ 3 │
#├───┼───┼───┤
#│ 4 │ X │ 6 │
#├───┼───┼───┤
#│ 7 │ 8 │ X │
#└───┴───┴───┘
</code>```

The Unicode box-drawing characters are just for demonstration purposes, it will work just fine with ASCII characters.

Based on the above, a very basic game loop could look like this:

grid = Grid.new

%w[X O].cycle do |marker|
  grid.render
  print "Player #{marker}: "
  input = gets.to_i
  grid.marker_positions[input - 1] = marker
  # TODO: break if player wins
end
```

The code cycles between "X" and "O" and for each iteration:

renders the grid

ask the player with that marker for their input

updates the marker_positions

What's missing is an additional step to break the loop if a player wins. And probably some logic to validate the input (prevent a player from overwriting a spot already taken, check that input is within 1-9 etc).

Hope this helps.

A last note: assuming that users enter their input via a computer keyboard, you might want to flip the grid vertically to match the layout of a numeric keypad.

Body:
I'm building a simple tic-tac-toe game and I've totally hit a wall with my grid.

I'd like to "puts @grid" including player input every time players have made their choice. How can I achieve this? I'm almost a total beginner with Ruby and have never build any games before. Any help is greatly appreciated, thanks in advance!

I tried making two different grids (grid and grid_with_markers) but couldn't figure out where to go from there. Looking back, having two grids also just seemed like a bad idea. I also tried having a Hash (marker_positions), but that seemed overly complicated compared to an Array.

Here is the grid

def initialize
    @possible_choice = [1,2,3,4,5,6,7,8,9]
    @marker_positions = [1,2,3,4,5,6,7,8,9]
    @grid = "
                |----|----|----|
                |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
                |----|----|----|
                |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
                |----|----|----|
                |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
                |----|----|----|
                "
end

I'd like to use a method add_markers to show the grid with user input. So when a player selects number 1 @marker_positions[0] would be replaced as "X" (or "O"). Number 4 would replace @marker_positions[3] etc.

Edit: I realised the title of this post was misleading since I actually want to replace elements of @marker_positions Array with Strings ("X" or "O"). But the replaced element is selected based on user input, in other words, player_one and player_two Arrays.

def add_markers
  puts @grid
end

Here's the player_one_turn method

def player_one_turn()
    puts "Player One, make your choice:"
    p @possible_choice
    add_markers
    @@player_one << @possible_choice.delete(gets.chomp.to_i)
    p "Player One has chosen: #{@@player_one}"
end

And here's my entire tictactoe.rb file.

class Grid
    WINNING_COMBOS = [
        [1,2,3],[4,5,6],[7,8,9],
        [1,4,7],[2,5,8],[3,6,9],
        [1,5,9],[3,5,7]
    ]
    attr_accessor :possible_choice
    attr_accessor :marker_positions
    attr_accessor :grid

    def initialize
        @possible_choice = [1,2,3,4,5,6,7,8,9]
        @marker_positions = [1,2,3,4,5,6,7,8,9]
        @grid = "
                |----|----|----|
                |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
                |----|----|----|
                |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
                |----|----|----|
                |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
                |----|----|----|
                "
    end

    def add_markers

        puts @grid
    end
end

class Game < Grid
    @@player_one = Array.new
    @@player_two = Array.new

    def game
        puts
        puts "*** This is a tic-tac-toe game for two human players. ***"
        puts
        loop do
            player_one_turn()
            puts
                if has_won?(@@player_one)
                    puts "The game has ended. Player One has won!"
                    puts
                    return
                end
            break if @@player_one.length == 5 || @@player_one.include?(nil)
            player_two_turn()
            puts
                if has_won?(@@player_two)
                    puts "The game has ended. Player Two has won!"
                    puts
                    return
                end
        end
    end

    def player_one_turn()
        puts "Player One, make your choice:"
        p @possible_choice
        add_markers
        @@player_one << @possible_choice.delete(gets.chomp.to_i)
        p "Player One has chosen: #{@@player_one}"
    end

    def player_two_turn()
        puts "Player Two, make your choice:"
        p @possible_choice
        add_markers
        @@player_two << @possible_choice.delete(gets.chomp.to_i)
        p "Player Two has chosen: #{@@player_two}"
    end

    def has_won?(player)
        WINNING_COMBOS.any? { |combo| (player & combo).size == combo.size}
    end
end

new_game = Game.new
new_game.game

(I know it isn't very clean. Thank you for taking time to read all the way down here.)

Body:
So when a player selects number 1 @marker_positions[0] would be replaced as "X"

You just have to read the user input: (example shows result for player entering 1)

input = gets.to_i
#=> 1

and replace the corresponding array element: (we have to subtract 1 because array is zero-based)

@marker_positions[input - 1] = 'X'

Using the array values within the grid string is another issue. The interpolations via #{...} happens when creating the string, just before it is assigned to @grid in initialize. This means the string is not being updated when the interpolated value changes afterwards – it just stays the same unless you interpolate it again:

x = 'foo'
@grid = "hello #{x}"
#=> "Hello foo"

x = 'bar'
@grid
#=> "Hello foo"  <- doesn't change

@grid = "hello #{x}"
#=> "Hello bar"

To get a "fresh" grid every time you call add_markers you could simply move the string interpolation code from initialize into that method: (instead of "...", I'm using <<~EOD ... EOD, a "squiggly" heredoc which ignores leading whitespace)

class Grid
  attr_accessor :marker_positions

  def initialize
    @marker_positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  end

  def add_markers
    puts <<~EOD
      |----|----|----|
      |  #{@marker_positions[0]} |  #{@marker_positions[1]} |  #{@marker_positions[2]} |
      |----|----|----|
      |  #{@marker_positions[3]} |  #{@marker_positions[4]} |  #{@marker_positions[5]} |
      |----|----|----|
      |  #{@marker_positions[6]} |  #{@marker_positions[7]} |  #{@marker_positions[8]} |
      |----|----|----|
    EOD
  end
end

This would result in: (the # are not part of the actual output)

grid = Grid.new
grid.add_markers
#|----|----|----|
#|  1 |  2 |  3 |
#|----|----|----|
#|  4 |  5 |  6 |
#|----|----|----|
#|  7 |  8 |  9 |
#|----|----|----|

grid.marker_positions[0] = 'X'
grid.marker_positions[4] = 'X'
grid.marker_positions[8] = 'X'
grid.add_markers
#|----|----|----|
#|  X |  2 |  3 |
#|----|----|----|
#|  4 |  X |  6 |
#|----|----|----|
#|  7 |  8 |  X |
#|----|----|----|

Another – maybe cleaner – option is to define a template with placeholders that are replaced by their actual (or current) values when rendering the template:

class Grid
  TEMPLATE = <<~EOD.freeze
    ┌───┬───┬───┐
    │ 1 │ 2 │ 3 │
    ├───┼───┼───┤
    │ 4 │ 5 │ 6 │
    ├───┼───┼───┤
    │ 7 │ 8 │ 9 │
    └───┴───┴───┘
  EOD

  attr_accessor :marker_positions

  def initialize
    @marker_positions = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  end

  def render
    puts TEMPLATE.gsub(/[1-9]/) { |d| @marker_positions[d.to_i - 1] }
  end
end

gsub scans the template string for digits 1 to 9 and replaces each occurrence d with the block's result, which simply picks the corresponding value from our array.

Usage:

grid = Grid.new
grid.render
#┌───┬───┬───┐
#│ 1 │ 2 │ 3 │
#├───┼───┼───┤
#│ 4 │ 5 │ 6 │
#├───┼───┼───┤
#│ 7 │ 8 │ 9 │
#└───┴───┴───┘

grid.marker_positions[0] = 'X'
grid.marker_positions[4] = 'X'
grid.marker_positions[8] = 'X'
grid.render
#┌───┬───┬───┐
#│ X │ 2 │ 3 │
#├───┼───┼───┤
#│ 4 │ X │ 6 │
#├───┼───┼───┤
#│ 7 │ 8 │ X │
#└───┴───┴───┘

The Unicode box-drawing characters are just for demonstration purposes, it will work just fine with ASCII characters.

Based on the above, a very basic game loop could look like this:

grid = Grid.new

%w[X O].cycle do |marker|
  grid.render
  print "Player #{marker}: "
  input = gets.to_i
  grid.marker_positions[input - 1] = marker
  # TODO: break if player wins
end

The code cycles between "X" and "O" and for each iteration:

renders the grid

ask the player with that marker for their input

updates the marker_positions

What's missing is an additional step to break the loop if a player wins. And probably some logic to validate the input (prevent a player from overwriting a spot already taken, check that input is within 1-9 etc).

Hope this helps.

A last note: assuming that users enter their input via a computer keyboard, you might want to flip the grid vertically to match the layout of a numeric keypad.


问:
Simple software testing tool - VB.NET
ok, please do no laugh at this :x

i'm trying to create a simple software testing tool in VB.NET

i created a simple C program PROG.EXE which scans a number and prints the OUTPUT, and started building my tester, it should execute PROG.EXE  output.txt, so PROG.EXE takes input from input.txt and prints the output to output.txt

but i failed, at first i tried Process.start then shell but nothing worked !

so i did this trick, the VB.NET codes generate a batch file with this codes PROG.EXE  output.txt, but again i failed, though the VB.NET created the batch file and executes too, but nothing happened ! but when i manually run the batch file i got success !

i tried executing the batchfile then sendkey the VBCR/LF/CRLF still nothing happens !

whats wrong ?

My VB.NET Code, i am using Visual Studio 2010 Professional

```<code>Option Explicit On
Option Strict On
Public Class Form1
 Dim strFileName As String

 Private Sub btnRun_Click() Handles btnRun.Click
  Dim strOutput As String
  Using P As New Process()
   P.StartInfo.FileName = strFileName
   P.StartInfo.Arguments = txtInput.Text
   P.StartInfo.RedirectStandardOutput = True
   P.StartInfo.UseShellExecute = False
  P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden  ' will this hide the console ?
   P.Start()
   Using SR = P.StandardOutput
    strOutput = SR.ReadToEnd()
   End Using
  End Using
  txtOutput.Text = strOutput
 End Sub

 Private Sub btnTarget_Click() Handles btnTarget.Click
  dlgFile.ShowDialog()
  strFileName = dlgFile.FileName
  lblFileName.Text = strFileName
 End Sub
End Class
</code>```

And this is my C code

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

void main()
{
 int x;
 scanf("%d",&x);
 printf("%d",(x*x));
}
</code>```

my program runs perfectly when i run prog.exe <input.txt> output.txt in console

答:
Below is a fully working example. You want to use the Process class as you tried but you need to RedirectStandardOutput on the process's StartInfo. Then you can just read the process's StandardOutput. The sample below is written using VB 2010 but works pretty much the same for older versions.

```<code>Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "ping.exe"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            P.StartInfo.Arguments = "127.0.0.1"

            ''//Tell the process that we want to handle the commands output stream
            ''//NOTE: Some programs also write to StandardError so you might want to watch that, too
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Start the process
            P.Start()

            ''//Wrap a StreamReader around the standard output
            Using SR = P.StandardOutput
                ''//Read everything from the stream
                T = SR.ReadToEnd()
            End Using
        End Using

        ''//At this point T will hold whatever the process with the given arguments kicked out
        ''//Here we are just dumping it to the screen
        MessageBox.Show(T)
    End Sub
End Class
</code>```

EDIT

Here is an updated version that reads from both StandardOutput and StandardError. This time it reads asynchronously. The code calls the CHOICE exe and passes an invalid command line switch which will trigger writing to StandardError instead of StandardOutput. For your program you should probably monitor both. Also, if you're passing a file into the program make sure that you are specifying the absolute path to the file and make sure that if you have spaces in the file path that you are wrapping the path in quotes.

```<code>Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "choice"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            ''//NOTE: I am passing an invalid parameter to show off standard error
            P.StartInfo.Arguments = "/G"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardOutput = True
            P.StartInfo.RedirectStandardError = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//Start the process
            P.Start()

            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()

            ''//Signal that we want to pause until the program is done running
            P.WaitForExit()

            Me.Close()
        End Using
    End Sub

    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class
</code>```

Its important that you put your entire file path in quotes if it has spaces in it (in fact, you should always enclose it in quotes just in case.) For instance, this won't work:

```<code>P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = "C:\Program Files\Windows NT\Accessories\wordpad.exe"
</code>```

But this will:

```<code>P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = """C:\Program Files\Windows NT\Accessories\wordpad.exe"""
</code>```

EDIT 2

Okay, I'm an idiot. I thought you were just wrapping a filename in angled brackets like <input.txt> or [input.txt], I didn't realize that you were using actual stream redirectors! (A space before and after input.txt would have helped.) Sorry for the confusion.

There are two ways to handle stream redirection with the Process object. The first is to manually read input.txt and write it to StandardInput and then read StandardOutput and write that to output.txt but you don't want to do that. The second way is to use the Windows command interpreter, cmd.exe which has a special argument /C. When passed it executes any string after it for you. All stream redirections work as if you typed them at the command line. Its important that whatever command you pass gets wrapped in quotes so along with the file paths you'll see some double-quoting. So here's a version that does all that:

```<code>Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\input.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        ''//""C:\PROG.exe" < "C:\input.txt" > "C:\output.txt""
        Dim FullCommand = String.Format("""""{0}"" < ""{1}"" > ""{2}""""", FullExePath, FullInputPath, FullOutputPath)
        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()

            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
End Class
</code>```

EDIT 3

The entire command argument that you pass to cmd /C needs to be wrapped in a set of quotes. So if you concat it it would be:

```<code>Dim FullCommand as String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
</code>```

Here's what the actual command that you pass should look like:

```<code>cmd /C ""C:\PROG.exe" < "C:\INPUT.txt" > "C:\output.txt""
</code>```

Here's a full code block. I've added back the error and output readers just in case you're getting a permission error or something. So look at the Immediate Window to see if any errors are kicked out. If this doesn't work I don't know what to tell you.

```<code>Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\INPUT.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        Dim FullCommand As String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
        Trace.WriteLine("cmd /C " & FullCommand)

        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardError = True
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()

            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()

            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class
</code>```

Title: Simple software testing tool - VB.NET

Body:
ok, please do no laugh at this :x

i'm trying to create a simple software testing tool in VB.NET

i created a simple C program PROG.EXE which scans a number and prints the OUTPUT, and started building my tester, it should execute PROG.EXE  output.txt, so PROG.EXE takes input from input.txt and prints the output to output.txt

but i failed, at first i tried Process.start then shell but nothing worked !

so i did this trick, the VB.NET codes generate a batch file with this codes PROG.EXE  output.txt, but again i failed, though the VB.NET created the batch file and executes too, but nothing happened ! but when i manually run the batch file i got success !

i tried executing the batchfile then sendkey the VBCR/LF/CRLF still nothing happens !

whats wrong ?

My VB.NET Code, i am using Visual Studio 2010 Professional

Option Explicit On
Option Strict On
Public Class Form1
 Dim strFileName As String

 Private Sub btnRun_Click() Handles btnRun.Click
  Dim strOutput As String
  Using P As New Process()
   P.StartInfo.FileName = strFileName
   P.StartInfo.Arguments = txtInput.Text
   P.StartInfo.RedirectStandardOutput = True
   P.StartInfo.UseShellExecute = False
  P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden  ' will this hide the console ?
   P.Start()
   Using SR = P.StandardOutput
    strOutput = SR.ReadToEnd()
   End Using
  End Using
  txtOutput.Text = strOutput
 End Sub

 Private Sub btnTarget_Click() Handles btnTarget.Click
  dlgFile.ShowDialog()
  strFileName = dlgFile.FileName
  lblFileName.Text = strFileName
 End Sub
End Class

And this is my C code

#include<stdio.h>
#include<conio.h>

void main()
{
 int x;
 scanf("%d",&x);
 printf("%d",(x*x));
}

my program runs perfectly when i run prog.exe <input.txt> output.txt in console

Body:
Below is a fully working example. You want to use the Process class as you tried but you need to RedirectStandardOutput on the process's StartInfo. Then you can just read the process's StandardOutput. The sample below is written using VB 2010 but works pretty much the same for older versions.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "ping.exe"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            P.StartInfo.Arguments = "127.0.0.1"

            ''//Tell the process that we want to handle the commands output stream
            ''//NOTE: Some programs also write to StandardError so you might want to watch that, too
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Start the process
            P.Start()

            ''//Wrap a StreamReader around the standard output
            Using SR = P.StandardOutput
                ''//Read everything from the stream
                T = SR.ReadToEnd()
            End Using
        End Using

        ''//At this point T will hold whatever the process with the given arguments kicked out
        ''//Here we are just dumping it to the screen
        MessageBox.Show(T)
    End Sub
End Class

EDIT

Here is an updated version that reads from both StandardOutput and StandardError. This time it reads asynchronously. The code calls the CHOICE exe and passes an invalid command line switch which will trigger writing to StandardError instead of StandardOutput. For your program you should probably monitor both. Also, if you're passing a file into the program make sure that you are specifying the absolute path to the file and make sure that if you have spaces in the file path that you are wrapping the path in quotes.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//This will hold the entire output of the command that we are running
        Dim T As String

        ''//Create our process object
        Using P As New Process()
            ''//Pass it the EXE that we want to execute
            ''//NOTE: you might have to use an absolute path here
            P.StartInfo.FileName = "choice"

            ''//Pass it any arguments needed
            ''//NOTE: if you pass a file name as an argument you might have to use an absolute path
            ''//NOTE: I am passing an invalid parameter to show off standard error
            P.StartInfo.Arguments = "/G"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardOutput = True
            P.StartInfo.RedirectStandardError = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//Start the process
            P.Start()

            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()

            ''//Signal that we want to pause until the program is done running
            P.WaitForExit()

            Me.Close()
        End Using
    End Sub

    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class

Its important that you put your entire file path in quotes if it has spaces in it (in fact, you should always enclose it in quotes just in case.) For instance, this won't work:

P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = "C:\Program Files\Windows NT\Accessories\wordpad.exe"

But this will:

P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = """C:\Program Files\Windows NT\Accessories\wordpad.exe"""

EDIT 2

Okay, I'm an idiot. I thought you were just wrapping a filename in angled brackets like <input.txt> or [input.txt], I didn't realize that you were using actual stream redirectors! (A space before and after input.txt would have helped.) Sorry for the confusion.

There are two ways to handle stream redirection with the Process object. The first is to manually read input.txt and write it to StandardInput and then read StandardOutput and write that to output.txt but you don't want to do that. The second way is to use the Windows command interpreter, cmd.exe which has a special argument /C. When passed it executes any string after it for you. All stream redirections work as if you typed them at the command line. Its important that whatever command you pass gets wrapped in quotes so along with the file paths you'll see some double-quoting. So here's a version that does all that:

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\input.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        ''//""C:\PROG.exe" < "C:\input.txt" > "C:\output.txt""
        Dim FullCommand = String.Format("""""{0}"" < ""{1}"" > ""{2}""""", FullExePath, FullInputPath, FullOutputPath)
        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()

            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
End Class

EDIT 3

The entire command argument that you pass to cmd /C needs to be wrapped in a set of quotes. So if you concat it it would be:

Dim FullCommand as String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""

Here's what the actual command that you pass should look like:

cmd /C ""C:\PROG.exe" < "C:\INPUT.txt" > "C:\output.txt""

Here's a full code block. I've added back the error and output readers just in case you're getting a permission error or something. So look at the Immediate Window to see if any errors are kicked out. If this doesn't work I don't know what to tell you.

Option Explicit On
Option Strict On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ''//Full path to our various files
        Dim FullExePath As String = "C:\PROG.exe"
        Dim FullInputPath As String = "C:\INPUT.txt"
        Dim FullOutputPath As String = "C:\output.txt"

        ''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
        Dim FullCommand As String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
        Trace.WriteLine("cmd /C " & FullCommand)

        ''//Create our process object
        Using P As New Process()
            ''//We are going to use the command shell and tell it to process our command for us
            P.StartInfo.FileName = "cmd"

            ''//Tell the process that we want to handle the command output AND error streams
            P.StartInfo.RedirectStandardError = True
            P.StartInfo.RedirectStandardOutput = True

            ''//This is needed for the previous line to work
            P.StartInfo.UseShellExecute = False

            ''//Add handlers for both of the data received events
            AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
            AddHandler P.OutputDataReceived, AddressOf OutputDataReceived

            ''//The /C (capitalized) means "execute whatever else is passed"
            P.StartInfo.Arguments = "/C " & FullCommand

            ''//Start the process
            P.Start()

            ''//Start reading from both error and output
            P.BeginErrorReadLine()
            P.BeginOutputReadLine()

            ''//Signal to wait until the process is done running
            P.WaitForExit()
        End Using

        Me.Close()
    End Sub
    Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Error  : {0}", e.Data))
    End Sub
    Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
        Trace.WriteLine(String.Format("From Output : {0}", e.Data))
    End Sub
End Class


问:
Making my function general as possible for checking a state
I want to create a function that can be general as possible but It doesn't work now.

I have two case :

Check if the state of a state is not empty or true and if my item is equal to him, I want to reset him by calling resetState() and set to false and empty string

Check if the state of a state is not empty and if my item is equal to him, I want to reset him by calling resetState()and the empty string

My problem is : I try to replace stateItem.checkedA by something like stateItem.item to avoid repetitions but doesn't work for me, is it possible in react to do that ?

This is what I have :

```<code>const [stateBoolean, setStateBoolean] = React.useState({
    checkedA: false,
    checkedB: false
  });

const [stateItem, setStateItem] = React.useState({
    checkedA: "",
    checkedB: "toto",
    checkedC: "onlyHere not in Boolean"
  });

  const check = (listState) => {
    listState.map(item => {
      (stateBoolean.checkedA === true || stateItem.checkedA !== "") &&
      item === "checkedA"
        ? (resetChange("checkedA", "stateItem"),
          resetChange("checkedA", "stateBoolean"))
        : null;
      (stateBoolean.checkedB === true || stateItem.checkedB !== "") &&
      item === "checkedB"
        ? (resetChange("checkedB", "stateItem"), resetChange("checkedB", "stateBoolean"))
        : null;
      stateItem.checkedC !== "" && item === "checkedC"
        ? resetChange("checkedC", "stateItem")
        : null;
    });
  };
</code>```

What I expected, but not working:

```<code>const checkWanted = (listState) => {
    listState.map(item => {
      (stateBoolean.item === true || stateItem.item !== "") &&
      (item === "checkedB" || item === "checkedA")
        ? (resetChange(item, "stateItem"), resetChange(item, "stateBoolean"))
        : null;
      stateItem.checkedEOther !== "" && item === "checkedEOther"
        ? resetChange(item, "stateItem")
        : null;
    });
  };
</code>```

Any idea?

答:
Use stateBoolean[item] instead, you can access properties of an object like an array

The function map return a new Array mdn description
If you want to iterate on a array and do something you should use forEach or a for loop.

Body:
I want to create a function that can be general as possible but It doesn't work now.

I have two case :

Check if the state of a state is not empty or true and if my item is equal to him, I want to reset him by calling resetState() and set to false and empty string

Check if the state of a state is not empty and if my item is equal to him, I want to reset him by calling resetState()and the empty string

My problem is : I try to replace stateItem.checkedA by something like stateItem.item to avoid repetitions but doesn't work for me, is it possible in react to do that ?

This is what I have :

const [stateBoolean, setStateBoolean] = React.useState({
    checkedA: false,
    checkedB: false
  });

const [stateItem, setStateItem] = React.useState({
    checkedA: "",
    checkedB: "toto",
    checkedC: "onlyHere not in Boolean"
  });

  const check = (listState) => {
    listState.map(item => {
      (stateBoolean.checkedA === true || stateItem.checkedA !== "") &&
      item === "checkedA"
        ? (resetChange("checkedA", "stateItem"),
          resetChange("checkedA", "stateBoolean"))
        : null;
      (stateBoolean.checkedB === true || stateItem.checkedB !== "") &&
      item === "checkedB"
        ? (resetChange("checkedB", "stateItem"), resetChange("checkedB", "stateBoolean"))
        : null;
      stateItem.checkedC !== "" && item === "checkedC"
        ? resetChange("checkedC", "stateItem")
        : null;
    });
  };

What I expected, but not working:

const checkWanted = (listState) => {
    listState.map(item => {
      (stateBoolean.item === true || stateItem.item !== "") &&
      (item === "checkedB" || item === "checkedA")
        ? (resetChange(item, "stateItem"), resetChange(item, "stateBoolean"))
        : null;
      stateItem.checkedEOther !== "" && item === "checkedEOther"
        ? resetChange(item, "stateItem")
        : null;
    });
  };

Any idea?


答:
But what I don't understand is how can a Promise.resolve() be a valid statement since it Promise is a function, not an object.

In JavaScript, functions are a type of object.

alert("This is an alert. You see it because a function was called.");

alert.foo = 1;

alert(`There is a property on this function with the value: ${alert.foo}`);

console.log(`Alert is an instance of Function: ${alert instanceof Function}`);
console.log(`Alert is an instance of Number: ${alert instanceof Number}`);
console.log(`Alert is an instance of Object: ${alert instanceof Object}`);```

Title: Javascript: promise.resolve() statement valid?


问:
I don't know opencv Error about code checking footsize
I want to make program checking my foot-size

I don't know this error about opencv

url: http://cocoding94.blogspot.com/2017/05/blog-post_7.html .

```<code>import numpy as np

import matplotlib.pyplot as plt

import cv2

img = cv2.imread("foot.jpeg")

blur = cv2.blur(img,(5,10))

rows,cols,ch = img.shape

pts1 = np.float32([170,270],[480,220],[240, 710],[540,650])
pts2 = np.float32([0,0],[210,0],[0,297],[210,297])

M = cv2.getPerspectiveTransform(pts1,pts2)

dst = cv2.warpPerspective(img,M,(210,297))

plt.subplot(121),plt.imshow(img),plt.title('Input')

plt.plot(*zip(*point), marker='.', color='r', ls='')

plt.subplot(122),plt.imshow(dst),plt.title('Output')

plt.show()
</code>```

In raspberry pi error printing:

Traceback (most recent call last):  File "foot.py",line 7,in
  blur = cv2. blur (img,(5,10)) cv2.error:OpenCV(3.4.3)
  /home/pi/opencv/opencv-3.4.3/modules/core/src/matrix.cpp:756: error:
  (-215:Assertion failed) dims <=2 && step[0] > 0 in function
  'locateROI'

答:
but please next time add more information to make this community greater than another, I fixed some errors in your code, i don´t your original image, but the code now works well, try to change your point to get a good perspective:

```<code>import numpy as np
import matplotlib.pyplot as plt
import cv2

img = cv2.imread("machupichu.jpg")
#blur = cv2.blur(img,(5,5))
#rows,cols,ch = img.shape

point=[[170,270],[480,220],[240, 710],[540,650]]

pts1 = np.float32([[170,270],[480,220],[240, 710],[540,650]])
pts2 = np.float32([[0,0],[210,0],[0,297],[210,297]])

M = cv2.getPerspectiveTransform(pts1,pts2)

dst = cv2.warpPerspective(img,M,(210,297))

plt.subplot(121)
plt.imshow(img)
plt.title('Input')

plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122)
plt.imshow(dst)
plt.title('Output')
plt.show()
</code>```

Here is the image which I used:
Machu Pichu
This is the result:

Best Regards.

Body:
I want to make program checking my foot-size

I don't know this error about opencv

url: http://cocoding94.blogspot.com/2017/05/blog-post_7.html .

import numpy as np

import matplotlib.pyplot as plt

import cv2

img = cv2.imread("foot.jpeg")

blur = cv2.blur(img,(5,10))

rows,cols,ch = img.shape

pts1 = np.float32([170,270],[480,220],[240, 710],[540,650])
pts2 = np.float32([0,0],[210,0],[0,297],[210,297])

M = cv2.getPerspectiveTransform(pts1,pts2)

dst = cv2.warpPerspective(img,M,(210,297))

plt.subplot(121),plt.imshow(img),plt.title('Input')

plt.plot(*zip(*point), marker='.', color='r', ls='')

plt.subplot(122),plt.imshow(dst),plt.title('Output')

plt.show()

In raspberry pi error printing:

Traceback (most recent call last):  File "foot.py",line 7,in
  blur = cv2. blur (img,(5,10)) cv2.error:OpenCV(3.4.3)
  /home/pi/opencv/opencv-3.4.3/modules/core/src/matrix.cpp:756: error:
  (-215:Assertion failed) dims <=2 && step[0] > 0 in function
  'locateROI'

Body:
but please next time add more information to make this community greater than another, I fixed some errors in your code, i don´t your original image, but the code now works well, try to change your point to get a good perspective:

import numpy as np
import matplotlib.pyplot as plt
import cv2

img = cv2.imread("machupichu.jpg")
#blur = cv2.blur(img,(5,5))
#rows,cols,ch = img.shape

point=[[170,270],[480,220],[240, 710],[540,650]]

pts1 = np.float32([[170,270],[480,220],[240, 710],[540,650]])
pts2 = np.float32([[0,0],[210,0],[0,297],[210,297]])

M = cv2.getPerspectiveTransform(pts1,pts2)

dst = cv2.warpPerspective(img,M,(210,297))

plt.subplot(121)
plt.imshow(img)
plt.title('Input')

plt.plot(*zip(*point), marker='.', color='r', ls='')
plt.subplot(122)
plt.imshow(dst)
plt.title('Output')
plt.show()

Here is the image which I used:
Machu Pichu
This is the result:

Best Regards.


问:
Smooth Progress Bar Animation
I'm trying to implement a smooth animation for my ProgressBar, but when I increase the time (30 seconds), the animation is no longer smooth.

Example with 5 seconds:

Example with 30 seconds:

My progress background:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#10444444" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#20444444" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#30444444" />
        </shape>
    </item>
    <item android:id="@android:id/background">
        <shape>
            <solid android:color="@color/black_thirty" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#3500D0" />
            </shape>
        </clip>
    </item>
</layer-list>
</code>```

My progress layout:

```<code><ProgressBar
    android:id="@+id/pb_loading"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:indeterminate="false"
    android:layout_centerInParent="true"
    android:progress="100"
    android:progressDrawable="@drawable/my_progress_bar" />
</code>```

My animation method:

```<code>private void startAnimation(){
    ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.pb_loading);
    ObjectAnimator progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 100, 0);
    progressAnimator.setDuration(30000);
    progressAnimator.setInterpolator(new LinearInterpolator());
    progressAnimator.start();
}
</code>```

答:
If you have Android N and above, you can use :

```<code>progressBar.setProgress(newProgress, true)
</code>```

Docs:

Sets the current progress to the specified value, optionally animating
  the visual position between the current and target values.

Animation does not affect the result of getProgress(), which will
  return the target value immediately after this method is called.

https://developer.android.com/reference/android/widget/ProgressBar.html#setProgress(int,%20boolean)

Title: Smooth Progress Bar Animation

Body:
I'm trying to implement a smooth animation for my ProgressBar, but when I increase the time (30 seconds), the animation is no longer smooth.

Example with 5 seconds:

Example with 30 seconds:

My progress background:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#10444444" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#20444444" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" />
            <solid android:color="#30444444" />
        </shape>
    </item>
    <item android:id="@android:id/background">
        <shape>
            <solid android:color="@color/black_thirty" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#3500D0" />
            </shape>
        </clip>
    </item>
</layer-list>

My progress layout:

<ProgressBar
    android:id="@+id/pb_loading"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:indeterminate="false"
    android:layout_centerInParent="true"
    android:progress="100"
    android:progressDrawable="@drawable/my_progress_bar" />

My animation method:

private void startAnimation(){
    ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.pb_loading);
    ObjectAnimator progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 100, 0);
    progressAnimator.setDuration(30000);
    progressAnimator.setInterpolator(new LinearInterpolator());
    progressAnimator.start();
}

Body:
If you have Android N and above, you can use :

progressBar.setProgress(newProgress, true)

Docs:

Sets the current progress to the specified value, optionally animating
  the visual position between the current and target values.

Animation does not affect the result of getProgress(), which will
  return the target value immediately after this method is called.

https://developer.android.com/reference/android/widget/ProgressBar.html#setProgress(int,%20boolean)


问:
Make a custom taxonomy child of another custom taxonomy
For a Wordpress plugin that I am currently developing (support ticket system) I have to map the following.
Each ticket is assigned to a project (1: 1 relationship).
Each project is in turn assigned to a customer (1: 1 relationship).
Thus, a customer can be assigned any number of projects (1: n relationship).
Also a Ticket could have multiple answers (like this question) which I think should also be a cpt.

I have already created the ticket as a custom post type.
Customers and project should be in my opinion taxonomies of the ticket.
The project should be assigned to the customer as parent taxonomy.
Therefore, I have set hierarchical = true for project.
But actually projects will be shown instead of customers in the parent dropdown(see screenshot below).
As far as I've read in Codex, I can customize the dropdown using the "taxonomy_parent_dropdown_args"-hook.

But I am not sure if there might be problems due to the different slugs.
Is this correct or is there a better way to archieve this?

答:
Try it</p>

```<code>                $taxonomyName = "com_category";
                $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));

                foreach ($parent_terms as $pterm) {
                    $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
                    foreach ($terms as $term) {
                        echo '<div class="single_cat col-md-3">';
                        echo '<h3>'.$pterm->name.'</h3>';
                        echo "<ul>";
                        echo '<li><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></li>';
                        echo "</ul>";
                        echo '</div>';
                    }
                }
</code>```

Body:
Try it

                $taxonomyName = "com_category";
                $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));

                foreach ($parent_terms as $pterm) {
                    $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
                    foreach ($terms as $term) {
                        echo '<div class="single_cat col-md-3">';
                        echo '<h3>'.$pterm->name.'</h3>';
                        echo "<ul>";
                        echo '<li><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></li>';
                        echo "</ul>";
                        echo '</div>';
                    }
                }


问:
Which COM smart pointer classes to use?
I'm confused by the choices for COM smart pointers classes for C++ programming:

There's three four I'm aware of:

CCOMPtr from ATL

_com_ptr_t from the MS Com Support Classes

TComInterface (because I'm using C++Builder 2009)

CCOMQIPtr, (which I'd previously forgotten)

I've read about the error vs. exception handling differences of the first two, but TComInterface seems totally undocumented. Both the first two seem to have gotchas or 'unexpected' behaviour, from what I can find.

Ideally, I'd like something that's clean and modern C++, but boost::com doesn't exist as far as I know...

I need to control an application from another vendor. They provide a COM interface via a TLB file.

答:
As kenny mentioned you can use CComPtr to manage pointers to the COM Interfaces. This class is well documented (see msdn) and uses automatic reference counting, what, I suppose, you are wanting.

OTOH, Rob question is important: do you really uses COM Interfaces? For just pointers you can use smart pointers from STL or boost libraries which anyway better (in general) than CComPtr.

Title: Which COM smart pointer classes to use?