问:
A problem in Updation of the record c#
i don't know why every time i perform update of my record, the query from which i update do not increments the ID from 0 to 1 and always it takes 0.. i don't know how do i increment my id to 1 and so far.. please explain.. :/ .. my code is :</p>

```<code>private void btnUpdate_Click(object sender, EventArgs e)
            {
                int CustomerID =0;
                SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;
                Initial Catalog=Gym;Integrated Security=True");
                SqlCommand cmd  = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                BindGridView();
            }

private void BindGridView()
        {
            SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=Gym;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select * from Customer", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgView_CustomerInfo.DataSource = dt.DefaultView;
        }
</code>```

答:
Your really need to read a book about .net programming. Your code is full of glitches...

To get you started...

```<code>        // put the connection string into the app.config
        using (SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS; Initial Catalog=Gym;Integrated Security=True"))
        {
            int result = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn).ExecuteNonQuery();
            // eval result to see wether there was realy an updated record...
        }
</code>```

On a SqlConnection use the using() statement. That way the dispose of the object is taken care of. In fact use it on all objects that are disposable.

Try to use app.config / web.config for the connection string.

Escape all the user input that goes to the sql server to prevent sql-injection. http://de.wikipedia.org/wiki/SQL-Injection

Title: A problem in Updation of the record c#

Body:
i don't know why every time i perform update of my record, the query from which i update do not increments the ID from 0 to 1 and always it takes 0.. i don't know how do i increment my id to 1 and so far.. please explain.. :/ .. my code is :

private void btnUpdate_Click(object sender, EventArgs e)
            {
                int CustomerID =0;
                SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;
                Initial Catalog=Gym;Integrated Security=True");
                SqlCommand cmd  = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                BindGridView();
            }

private void BindGridView()
        {
            SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=Gym;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("Select * from Customer", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dgView_CustomerInfo.DataSource = dt.DefaultView;
        }

Body:
Your really need to read a book about .net programming. Your code is full of glitches...

To get you started...

        // put the connection string into the app.config
        using (SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS; Initial Catalog=Gym;Integrated Security=True"))
        {
            int result = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn).ExecuteNonQuery();
            // eval result to see wether there was realy an updated record...
        }

On a SqlConnection use the using() statement. That way the dispose of the object is taken care of. In fact use it on all objects that are disposable.

Try to use app.config / web.config for the connection string.

Escape all the user input that goes to the sql server to prevent sql-injection. http://de.wikipedia.org/wiki/SQL-Injection


来源: stackexchange

问:
Angular material 1 / md-virtual-repeat select scroll
What is the right way to change md-virtual-repeat's scroll to watch events from an other scroll ?

I have tried some manual triggering

And i readed this question but it is not exactly i want.

So is there a way to select a scrool to virtual-repeat container ?

EDIT 2

I need to change scrollbar of virtual repeat with scrollbar of Body

 Live example

(function() {
  'use strict';

  var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);

  app.filter('to_trusted', ['$sce', function($sce) {
    return function(text) {
      return $sce.trustAsHtml(text);
    };
  }]);

  app.controller('AppCtrl', function($timeout) {
    this.itemSize = 529.39;

    var DynamicItems = function() {
      this.loadedPages = {};
      this.numItems = 0;
      this.PAGE_SIZE = 50;
      this.fetchNumItems_();
    };

    DynamicItems.prototype.getItemAtIndex = function(index) {
      var pageNumber = Math.floor(index / this.PAGE_SIZE);
      var page = this.loadedPages[pageNumber];

      if (page) {
        return page[index % this.PAGE_SIZE];
      } else if (page !== null) {
        this.fetchPage_(pageNumber);
      }
    };

    DynamicItems.prototype.getLength = function() {
      return this.numItems;
    };

    DynamicItems.prototype.fetchPage_ = function(pageNumber) {
      this.loadedPages[pageNumber] = null;

      $timeout(angular.noop, 300).then(angular.bind(this, function() {
        this.loadedPages[pageNumber] = [];
        var pageOffset = pageNumber * this.PAGE_SIZE;
        //console.log(pageNumber);

        for (var i = pageOffset; i < pageOffset + this.PAGE_SIZE; i++) {
          var obj = {};
          obj.name = 'Ad ' + i;
          obj.surname = 'Soyad ' + i;
          obj.age = i;
          obj.image = 'http://lorempixel.com/75/75/cats?' + i;
          obj.list = [];
          obj.clicked = false;
          obj.status = "asd";
          obj.html = '' + i + '---Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500 lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960 larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur.' + i;
          for (var j = 0; j < 1000; j++) {
            obj.list.push('http://lorempixel.com/75/75/city/?' + j);
          }

          this.loadedPages[pageNumber].push(obj);
        }

        //this.setItemNum(this.numItems + this.PAGE_SIZE);
      }));
    };

    DynamicItems.prototype.fetchNumItems_ = function() {
      $timeout(angular.noop, 300).then(angular.bind(this, function() {
        //console.log("fetchNumItems_");
        this.numItems = 10000;
      }));
    };

    DynamicItems.prototype.setItemNum = function(number) {
      this.numItems = number;
    };

    this.dynamicItems = new DynamicItems();
    //console.log(this.dynamicItems);
  });
}());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.virtualRepeatdemoDeferredLoading #vertical-container {
  width: 100%;
}
.virtualRepeatdemoDeferredLoading .repeated-item {
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  padding-top: 10px;
}
.virtualRepeatdemoDeferredLoading md-content {
  margin: 16px;
}
.virtualRepeatdemoDeferredLoading md-virtual-repeat-container {
  border: solid 1px grey;
}
.virtualRepeatdemoDeferredLoading .md-virtual-repeat-container .md-virtual-repeat-offsetter div {
  padding-left: 16px;
}
.virtualRepeatdemoHorizontalUsage #horizontal-container {
  height: 100px;
  width: 100%;
}
.virtualRepeatdemoHorizontalUsage .repeated-item {
  border-right: 1px solid #ddd;
  box-sizing: border-box;
  display: inline-block;
  height: 84px;
  padding-top: 10px;
  text-align: center;
  width: 100px;
}
.virtualRepeatdemoHorizontalUsage md-content {
  margin: 16px;
}
.virtualRepeatdemoHorizontalUsage md-virtual-repeat-container {
  border: solid 1px grey;
}</code>```

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta name="robots" content="noindex">
  <link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" />
  <link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" />
  <link rel="canonical" href="http://codepen.io/anon/pen/OWXMXW" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
  <link rel='stylesheet prefetch' href='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.1/angular-material.css'>
  <link rel='stylesheet prefetch' href='https://material.angularjs.org/1.1.1/docs.css'>

 Virtual Repeat Test

    <md-content layout="column" flex layout-fill>

      <md-virtual-repeat-container flex layout-fill md-auto-shrink="false" layout id="vertical-container">

 Adı : {{item.name}}
 Soyadı : {{item.surname}}
 Yaşı : {{item.age}}
 is Clicked : {{ item.clicked }}
 status : {{ item.status }}

 List Items

          <md-content ng-if="item.clicked == true" class="virtualRepeatdemoHorizontalUsage" layout="column">

            <md-virtual-repeat-container id="horizontal-container" md-orient-horizontal="">

            </md-virtual-repeat-container>
          </md-content>

      </md-virtual-repeat-container>
    </md-content>

```

答:
If I understand your question correctly, you just want to scroll the virtual repeater div using a scrollbar somewhere else on your page? One way to do that would be to create a directive that listens to scroll event of the div you want to use as the visible scrollbar and then just scroll the other div the same percentage.

Here is one such directive. Add it to the md-virtual-repeat-container and point it to the div you want to scroll it. The divs can even be different heights.

Update
I changed the directive to fall back to the body tag if an element wasn't specified.

app = angular.module('myApp', ['ngMaterial']);

app.controller("myController", function($scope) {
  $scope.items = [];
  for (var i = 0; i < 5000000; i++) {
    $scope.items.push(i);
  }
});

app.directive("scrollFrom", function($window, $document) {
  return {
    scope: {
      elTarget: '@scrollFrom'
    },
    link: function(scope, element, attrs) {
      var body = $document[0].body;
      angular.element(scope.elTarget || $window).bind("scroll", function() {
        var percentScrolled = scope.elTarget ?
          this.scrollHeight > 0 ? this.scrollTop / (this.scrollHeight - element.height()) : 0 :
          body.scrollHeight > 0 ? body.scrollTop / (body.scrollHeight - element.height()) : 0;
        var trgt = angular.element(element).find('.md-virtual-repeat-scroller')[0];
        trgt.scrollTop = trgt.scrollHeight * percentScrolled;
      });
    }
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#vertical-container {
  height: 292px;
  width: 100%;
  max-width: 400px;
  position: fixed;
  top: 10px;
}

#vertical-container .md-virtual-repeat-scroller {
  overflow: hidden;
}

.repeated-item {
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  height: 40px;
  padding-top: 10px;
}

md-virtual-repeat-container {
  border: solid 4px grey;
}</code>```

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.4/angular-material.min.css" />

    <md-virtual-repeat-container id="vertical-container" scroll-from>

        {{item}}

    </md-virtual-repeat-container>

```

ContentLicense: CC BY-SA 3.0

Body:
What is the right way to change md-virtual-repeat's scroll to watch events from an other scroll ?

I have tried some manual triggering

And i readed this question but it is not exactly i want.

So is there a way to select a scrool to virtual-repeat container ?

EDIT 2

I need to change scrollbar of virtual repeat with scrollbar of Body

 Live example

(function() {
  'use strict';

  var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);

  app.filter('to_trusted', ['$sce', function($sce) {
    return function(text) {
      return $sce.trustAsHtml(text);
    };
  }]);

  app.controller('AppCtrl', function($timeout) {
    this.itemSize = 529.39;

    var DynamicItems = function() {
      this.loadedPages = {};
      this.numItems = 0;
      this.PAGE_SIZE = 50;
      this.fetchNumItems_();
    };

    DynamicItems.prototype.getItemAtIndex = function(index) {
      var pageNumber = Math.floor(index / this.PAGE_SIZE);
      var page = this.loadedPages[pageNumber];

      if (page) {
        return page[index % this.PAGE_SIZE];
      } else if (page !== null) {
        this.fetchPage_(pageNumber);
      }
    };

    DynamicItems.prototype.getLength = function() {
      return this.numItems;
    };

    DynamicItems.prototype.fetchPage_ = function(pageNumber) {
      this.loadedPages[pageNumber] = null;

      $timeout(angular.noop, 300).then(angular.bind(this, function() {
        this.loadedPages[pageNumber] = [];
        var pageOffset = pageNumber * this.PAGE_SIZE;
        //console.log(pageNumber);

        for (var i = pageOffset; i < pageOffset + this.PAGE_SIZE; i++) {
          var obj = {};
          obj.name = 'Ad ' + i;
          obj.surname = 'Soyad ' + i;
          obj.age = i;
          obj.image = 'http://lorempixel.com/75/75/cats?' + i;
          obj.list = [];
          obj.clicked = false;
          obj.status = "asd";
          obj.html = '' + i + '---Lorem Ipsum, dizgi ve baskı endüstrisinde kullanılan mıgır metinlerdir. Lorem Ipsum, adı bilinmeyen bir matbaacının bir hurufat numune kitabı oluşturmak üzere bir yazı galerisini alarak karıştırdığı 1500 lerden beri endüstri standardı sahte metinler olarak kullanılmıştır. Beşyüz yıl boyunca varlığını sürdürmekle kalmamış, aynı zamanda pek değişmeden elektronik dizgiye de sıçramıştır. 1960 larda Lorem Ipsum pasajları da içeren Letraset yapraklarının yayınlanması ile ve yakın zamanda Aldus PageMaker gibi Lorem Ipsum sürümleri içeren masaüstü yayıncılık yazılımları ile popüler olmuştur.' + i;
          for (var j = 0; j < 1000; j++) {
            obj.list.push('http://lorempixel.com/75/75/city/?' + j);
          }

          this.loadedPages[pageNumber].push(obj);
        }

        //this.setItemNum(this.numItems + this.PAGE_SIZE);
      }));
    };

    DynamicItems.prototype.fetchNumItems_ = function() {
      $timeout(angular.noop, 300).then(angular.bind(this, function() {
        //console.log("fetchNumItems_");
        this.numItems = 10000;
      }));
    };

    DynamicItems.prototype.setItemNum = function(number) {
      this.numItems = number;
    };

    this.dynamicItems = new DynamicItems();
    //console.log(this.dynamicItems);
  });
}());

.virtualRepeatdemoDeferredLoading #vertical-container {
  width: 100%;
}
.virtualRepeatdemoDeferredLoading .repeated-item {
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  padding-top: 10px;
}
.virtualRepeatdemoDeferredLoading md-content {
  margin: 16px;
}
.virtualRepeatdemoDeferredLoading md-virtual-repeat-container {
  border: solid 1px grey;
}
.virtualRepeatdemoDeferredLoading .md-virtual-repeat-container .md-virtual-repeat-offsetter div {
  padding-left: 16px;
}
.virtualRepeatdemoHorizontalUsage #horizontal-container {
  height: 100px;
  width: 100%;
}
.virtualRepeatdemoHorizontalUsage .repeated-item {
  border-right: 1px solid #ddd;
  box-sizing: border-box;
  display: inline-block;
  height: 84px;
  padding-top: 10px;
  text-align: center;
  width: 100px;
}
.virtualRepeatdemoHorizontalUsage md-content {
  margin: 16px;
}
.virtualRepeatdemoHorizontalUsage md-virtual-repeat-container {
  border: solid 1px grey;
}

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta name="robots" content="noindex">
  <link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" />
  <link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" />
  <link rel="canonical" href="http://codepen.io/anon/pen/OWXMXW" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
  <link rel='stylesheet prefetch' href='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.1/angular-material.css'>
  <link rel='stylesheet prefetch' href='https://material.angularjs.org/1.1.1/docs.css'>

 Virtual Repeat Test

    <md-content layout="column" flex layout-fill>

      <md-virtual-repeat-container flex layout-fill md-auto-shrink="false" layout id="vertical-container">

 Adı : {{item.name}}
 Soyadı : {{item.surname}}
 Yaşı : {{item.age}}
 is Clicked : {{ item.clicked }}
 status : {{ item.status }}

 List Items

          <md-content ng-if="item.clicked == true" class="virtualRepeatdemoHorizontalUsage" layout="column">

            <md-virtual-repeat-container id="horizontal-container" md-orient-horizontal="">

            </md-virtual-repeat-container>
          </md-content>

      </md-virtual-repeat-container>
    </md-content>

Body:
If I understand your question correctly, you just want to scroll the virtual repeater div using a scrollbar somewhere else on your page? One way to do that would be to create a directive that listens to scroll event of the div you want to use as the visible scrollbar and then just scroll the other div the same percentage.

Here is one such directive. Add it to the md-virtual-repeat-container and point it to the div you want to scroll it. The divs can even be different heights.

Update
I changed the directive to fall back to the body tag if an element wasn't specified.

app = angular.module('myApp', ['ngMaterial']);

app.controller("myController", function($scope) {
  $scope.items = [];
  for (var i = 0; i < 5000000; i++) {
    $scope.items.push(i);
  }
});

app.directive("scrollFrom", function($window, $document) {
  return {
    scope: {
      elTarget: '@scrollFrom'
    },
    link: function(scope, element, attrs) {
      var body = $document[0].body;
      angular.element(scope.elTarget || $window).bind("scroll", function() {
        var percentScrolled = scope.elTarget ?
          this.scrollHeight > 0 ? this.scrollTop / (this.scrollHeight - element.height()) : 0 :
          body.scrollHeight > 0 ? body.scrollTop / (body.scrollHeight - element.height()) : 0;
        var trgt = angular.element(element).find('.md-virtual-repeat-scroller')[0];
        trgt.scrollTop = trgt.scrollHeight * percentScrolled;
      });
    }
  };
});

#vertical-container {
  height: 292px;
  width: 100%;
  max-width: 400px;
  position: fixed;
  top: 10px;
}

#vertical-container .md-virtual-repeat-scroller {
  overflow: hidden;
}

.repeated-item {
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  height: 40px;
  padding-top: 10px;
}

md-virtual-repeat-container {
  border: solid 4px grey;
}

<html ng-app="myApp">

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.4/angular-material.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-aria.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.4/angular-material.min.js"></script>
</head>

<body style="height: 5000000px">
  <div ng-controller="myController">
    <md-virtual-repeat-container id="vertical-container" scroll-from>
      <div md-virtual-repeat="item in items" class="repeated-item" flex>
        {{item}}
      </div>
    </md-virtual-repeat-container>
  </div>
</body>

</html>


问:
Continuously updated slider can't be dragged
I'm using React wrapped with cljs+reagent to make a small app. One of the things I need is a slider that updates ~every second, and that can be adjusted by the user. Right now I'm using this:

```<code> [:div.scrubber [:input
                 {:type  "range"
                  :min   "0"
                  :max   "100"
                  :value (str percent-through)}]]
</code>```

I'm adjusting the value property of the range slider every second. However, this seems to prevent user interaction with it. Here's a gif showing this: (captured on chrome)

What is the best way to allow the user to control the slider? Stopping the update timer does not have any effect, and it appears that the value is locked.

答: Yeah if you have control over the timer I would cancel it once the user starts to interact with the slider, and then after updating state with their changes, create a new timer.</p>

Body:
I'm using React wrapped with cljs+reagent to make a small app. One of the things I need is a slider that updates ~every second, and that can be adjusted by the user. Right now I'm using this:

 [:div.scrubber [:input
                 {:type  "range"
                  :min   "0"
                  :max   "100"
                  :value (str percent-through)}]]

I'm adjusting the value property of the range slider every second. However, this seems to prevent user interaction with it. Here's a gif showing this: (captured on chrome)

What is the best way to allow the user to control the slider? Stopping the update timer does not have any effect, and it appears that the value is locked.


问:
CheckBox Checked property not updating while form is running
I have a simple function that returns whether a checkbox is checked or not, and another method from another class uses this info.

Whenever I change the "Checked" property to false before running the form, my code works as expected and treats the boolean variable for the checked property as false. However, if i try to change the checkbox while the form is actually running, my code always treats the checked property as true regardless of whether the box is checked or not.

My code is not a Form1_Load one time thing, it is a function that is called every time a button is clicked. (Of course this button was clicked after the checkbox was untoggled, and it still treats the checkbox checked variable as true even though it should be false.)

Literally my code:

(I understand this looks like a weird way to check it, but it's needed because of class to class referencing issues)

```<code>    public bool Check1()
    {
        check1 = this.checkBox1.Checked;
        return check1;
    }
</code>```

Check1(); always returns true regardless of whether checkBox1 is checked or not. But again, if I uncheck the checkbox prior to running the form, it returns false as it should.

Any suggestions to get it to update properly?

EDIT:

```<code>                Block_Map_Array.Form1 f = new Block_Map_Array.Form1();
</code>```

It is called in the new instance.

答:
Assuming you have something like this in your form class:

```<code>public partial class Form1 : Form
{
    private bool check1;

    public bool Check1()
    {
        check1 = this.checkBox1.Checked;
        return check1;
    }

    // rest of class omitted
}
</code>```

And you want some other class to have access to this instance method of the UI form, you will need to provide a way for the form to pass itself to your other class, for example:

```<code>class Block_Map_Array
{
    private Form1 f;

    public Block_Map_Array(Form1 uiInstance)
    {
        this.f = uiInstance;
    }

    public void SomeMethod()
    {
        if (f.Check1())
        {
            // do something...
        }
    }

    // rest of class omitted...
}
</code>```

Then, when you instantiate this class from form1, you could do something like:

```<code>private void Form1_Load(object sender, EventArgs e)
{
    Block_Map_Array foo = new Block_Map_Array(this);

    foo.SomeMethod();
}
</code>```

Of course, this is not really the best design. Normally you would pass some data directly to the method from the form, rather than the whole form instance.

Body:
I have a simple function that returns whether a checkbox is checked or not, and another method from another class uses this info.

Whenever I change the "Checked" property to false before running the form, my code works as expected and treats the boolean variable for the checked property as false. However, if i try to change the checkbox while the form is actually running, my code always treats the checked property as true regardless of whether the box is checked or not.

My code is not a Form1_Load one time thing, it is a function that is called every time a button is clicked. (Of course this button was clicked after the checkbox was untoggled, and it still treats the checkbox checked variable as true even though it should be false.)

Literally my code:

(I understand this looks like a weird way to check it, but it's needed because of class to class referencing issues)

    public bool Check1()
    {
        check1 = this.checkBox1.Checked;
        return check1;
    }

Check1(); always returns true regardless of whether checkBox1 is checked or not. But again, if I uncheck the checkbox prior to running the form, it returns false as it should.

Any suggestions to get it to update properly?

EDIT:

                Block_Map_Array.Form1 f = new Block_Map_Array.Form1();

It is called in the new instance.

Body:
Assuming you have something like this in your form class:

public partial class Form1 : Form
{
    private bool check1;

    public bool Check1()
    {
        check1 = this.checkBox1.Checked;
        return check1;
    }

    // rest of class omitted
}

And you want some other class to have access to this instance method of the UI form, you will need to provide a way for the form to pass itself to your other class, for example:

class Block_Map_Array
{
    private Form1 f;

    public Block_Map_Array(Form1 uiInstance)
    {
        this.f = uiInstance;
    }

    public void SomeMethod()
    {
        if (f.Check1())
        {
            // do something...
        }
    }

    // rest of class omitted...
}

Then, when you instantiate this class from form1, you could do something like:

private void Form1_Load(object sender, EventArgs e)
{
    Block_Map_Array foo = new Block_Map_Array(this);

    foo.SomeMethod();
}

Of course, this is not really the best design. Normally you would pass some data directly to the method from the form, rather than the whole form instance.


问:
adding items to array during emit overrides the previous element in angular 4
I am working on a project , where i have a use case to add a new list item on click of add button and the added data must be rendered as a new list item.

add content component

import { Component,Output,EventEmitter} from '@angular/core';
@Component({
  selector: 'add-content',
  template:`<input type='text' [(ngModel)] = 'content'/>
            <button (click) = 'addNewContent(content)'>`
})
export class AddContentComponent {
  @Output() newContent: EventEmitter < any > = new EventEmitter();
  content: any;
  constructor() {
    this.content = {};
  }
  addNewContent(content) {
    if (content) {
      this.content.body = content;
      this.newContent.emit(this.content);
    }
  }
}```
</div>
</div>
</p>

<blockquote>
  <p>contentlistcomponent</p>
</blockquote>

<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>import {Component} from '@angular/core';

@Component({
   selector:'content-list',
   template:`<ul>
              <li *ngFor="let content of contentList">{{content.body}}</li>
              <add-content (newContent)=getContent($event)></add-content>
              </ul>`

});
export class ContentListComponent {
contentList:Array<any>;
constructor(){
 this.contentList = [];
}
getContent(content){
if(content){
  this.contentList.push(content);
}
}</code>```

when first content is added the list renders the typed content correctly however when second content is added the previous content is also replaced by the new content and two list items with last item's content is displayed.As I am newbie , I couldn't figure out where I am going wrong.Could anyone help me with this issue?

EDIT
I have created a plunker showing the issue,

https://plnkr.co/edit/Wgj4I9yAQjSxi1C91vnb?p=preview

答:
The problem is that object reference is maintained for content variable in getContent function. You need to do following to push to contentList without maintaining reference of previous values.

```<code>getContent(content){
 if(content){
  var copy = Object.assign({}, content);
  this.contentList.push(copy);
  }
}
</code>```

Hope it helps !!

Body:
I am working on a project , where i have a use case to add a new list item on click of add button and the added data must be rendered as a new list item.

add content component

import { Component,Output,EventEmitter} from '@angular/core';
@Component({
  selector: 'add-content',
  template:`<input type='text' [(ngModel)] = 'content'/>
            <button (click) = 'addNewContent(content)'>`
})
export class AddContentComponent {
  @Output() newContent: EventEmitter < any > = new EventEmitter();
  content: any;
  constructor() {
    this.content = {};
  }
  addNewContent(content) {
    if (content) {
      this.content.body = content;
      this.newContent.emit(this.content);
    }
  }
}

contentlistcomponent

import {Component} from '@angular/core';

@Component({
   selector:'content-list',
   template:`

{{content.body}}

              <add-content (newContent)=getContent($event)></add-content>

`

});
export class ContentListComponent {
contentList:Array<any>;
constructor(){
 this.contentList = [];
}
getContent(content){
if(content){
  this.contentList.push(content);
}
}

when first content is added the list renders the typed content correctly however when second content is added the previous content is also replaced by the new content and two list items with last item's content is displayed.As I am newbie , I couldn't figure out where I am going wrong.Could anyone help me with this issue?

EDIT
I have created a plunker showing the issue,

https://plnkr.co/edit/Wgj4I9yAQjSxi1C91vnb?p=preview

Body:
The problem is that object reference is maintained for content variable in getContent function. You need to do following to push to contentList without maintaining reference of previous values.

getContent(content){
 if(content){
  var copy = Object.assign({}, content);
  this.contentList.push(copy);
  }
}

Hope it helps !!


问:
How to hide mouse cursor with jquery
How to hide mouse cursor with jquery in entire webpage.
 I tried this

```<code>$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});
</code>```

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.

答:
I bet it has nothing to do with the jQuery method, but in fact the CSS for your page.

Make sure (using firebug) that the body element is actually visible on the page, the contents might because the overflow is set to auto by default, but you'll also need to set the body height and width to 100% to ensure that when you're mouse moves across the screen it actually invokes body.mouseover()

Here's a working example » http://jsfiddle.net/Ilmv/XQmqe/

ContentLicense: CC BY-SA 2.5

Title: How to hide mouse cursor with jquery

Body:
How to hide mouse cursor with jquery in entire webpage.
 I tried this

$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.


问:
How to wait for Function to finish before continuing
In my current project I want to be able to display the users current position on a map.
I have implemented this functionality via the requestLocation method provided by Apple, but the problem is that my code continues without waiting for the requestLocation Function to finish.

The flow is this: First I call the positionController.setPositionViaLocationData() function, which handles the setup and execution of the requestLocation method. In the end this receives the coordinates and stores them in the userPosition member of the PositionController.
In the next line of code I want to access the userPosition via the PositionController but here comes my problem:

The line ...

```<code>var userPosition = positionController.getPosition()
</code>```

... is executed before positionController.setPositionViaLocationData() is finished, thus it takes the default values stored in userPosition.

How can I make my code wait for positionController.setPositionViaLocationData() before executing
var userPosition = positionController.getPosition()?
I already read stuff about Closures and CompletionManagers but I don't get that stuff to work for me.

Heres the code of both classes, first the ViewController who calls the functions:

```<code>import UIKit
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()

        positionController.setPositionViaLocationData()
        var userPosition = positionController.getPosition()
        setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)

    }

    func setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: Double, userPositionLongitude: Double){
        let camera = GMSCameraPosition.camera(withLatitude: userPositionLatitude,
                                              longitude: userPositionLongitude, zoom:3)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        self.view = mapView
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView
    }

}
</code>```

And now my PositionController class:

```<code>import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate {

    let locationManager: CLLocationManager
    var userPosition = Position(longitude: 0,latitude: 0)

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func setPositionViaLocationData(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func setPosition(longitude: Double, latitude: Double){
        userPosition.longitude = longitude
        userPosition.latitude = latitude
    }

    func getPosition() -> (userLongitude: Double, userLatitude: Double){
        return (userPosition.longitude, userPosition.latitude)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        userPosition.latitude = locValue.latitude
        userPosition.longitude = locValue.longitude
    }
}
</code>```

答:
As Rob commented, one cannot wait for the locationRequest method to end.

Looking at the code the MapViewController.setUserPositionMarkerOnMapAndShowMap method should be called from the PositionController .locationManager(didUpdateLocations) method.

The problem doing so is that the PositionController doesn't know about MapViewController.

Some options:

Pass an instance of the MapViewController to the PositionController.

Leave out the PositionController controller altogether and implement the functionality ('didUpdateLocations') in the MapViewController.

PS: Not related to your question directly but maybe indicating some confusion, both MapViewController and PositionController declare the CLLocationManagerDelegate protocol but only the PositionController is implementing it.

Body:
In my current project I want to be able to display the users current position on a map.
I have implemented this functionality via the requestLocation method provided by Apple, but the problem is that my code continues without waiting for the requestLocation Function to finish.

The flow is this: First I call the positionController.setPositionViaLocationData() function, which handles the setup and execution of the requestLocation method. In the end this receives the coordinates and stores them in the userPosition member of the PositionController.
In the next line of code I want to access the userPosition via the PositionController but here comes my problem:

The line ...

var userPosition = positionController.getPosition()

... is executed before positionController.setPositionViaLocationData() is finished, thus it takes the default values stored in userPosition.

How can I make my code wait for positionController.setPositionViaLocationData() before executing
var userPosition = positionController.getPosition()?
I already read stuff about Closures and CompletionManagers but I don't get that stuff to work for me.

Heres the code of both classes, first the ViewController who calls the functions:

import UIKit
import GoogleMaps
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let positionController = PositionController()

    override func viewDidLoad() {
        super.viewDidLoad()

        positionController.setPositionViaLocationData()
        var userPosition = positionController.getPosition()
        setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: userPosition.userLatitude, userPositionLongitude: userPosition.userLongitude)

    }

    func setUserPositionMarkerOnMapAndShowMap(userPositionLatitude: Double, userPositionLongitude: Double){
        let camera = GMSCameraPosition.camera(withLatitude: userPositionLatitude,
                                              longitude: userPositionLongitude, zoom:3)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera)
        let marker = GMSMarker()

        self.view = mapView
        marker.snippet = "Munich"
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = mapView

        self.view = mapView
    }

}

And now my PositionController class:

import Foundation
import CoreLocation

class PositionController: CLLocationManager, CLLocationManagerDelegate {

    let locationManager: CLLocationManager
    var userPosition = Position(longitude: 0,latitude: 0)

    override init() {
        self.locationManager = CLLocationManager()
        print("---------------Init---------------------------")
    }

    func setPositionViaLocationData(){

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.requestLocation()
    }

    func setPosition(longitude: Double, latitude: Double){
        userPosition.longitude = longitude
        userPosition.latitude = latitude
    }

    func getPosition() -> (userLongitude: Double, userLatitude: Double){
        return (userPosition.longitude, userPosition.latitude)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        userPosition.latitude = locValue.latitude
        userPosition.longitude = locValue.longitude
    }
}


问:
Subsetting data table by using NA's (or some other value) as endpoints for the subsets
I am attempting to subset a data table by using some NA values in a column as the end points for the subsetting.  Here is some fake data to show what I mean:

```<code>require(data.table)
set.seed(34)
somestuff <- c(NA,'sdr','utyrd','ytrd','fc',NA,NA,'09h','87h',NA,NA,NA,'0ij','5fdg','g7','h8o7hy')
someotherstuff <- sample(LETTERS,length(somestuff))

dat <- data.table(somestuff,someotherstuff)
</code>```

I would like to subset 'dat' to the following 3 subsets (dat1, dat2, dat3 below).  Basically to remove the rows with NA but to also leverage some of those NA values in the first column as the non-inclusive endpoints for the subsetting. In other words, the groups for subsetting are separated by single or multiple cells of NAs in a column.

```<code>dat1 <- dat[2:5]
dat2 <- dat[8:9]
dat3 <- dat[13:16]
</code>```

The actual data I will be using will have several subsets and usually multiple consecutive NA values in a column and when I pull this data each week it will have these NA's in different places.  I wanted to see if anyone knew of an efficient way to subset based on using a common element (like NA) or string within a column to specify the subsetting endpoints.  I'm not wed to a data.table solution though I tend to use these most.  I've been trying split() such as this:

```<code>split(dat,by=is.na(dat$somestuff))
</code>```

as well as appending a counter to rows without the NA but it doesn't seem to be coming together.  Any thoughts?

答:
We can create a grouping variable with rleid and then split into a list of data.tables

```<code>dt <- dat[,  grp := rleid(is.na(somestuff))][!is.na(somestuff), .SD]
unname(split(dt, by = "grp", keep.by = FALSE))
#[[1]]
#   somestuff someotherstuff
#1:       sdr              Y
#2:     utyrd              V
#3:      ytrd              F
#4:        fc              W

#[[2]]
#   somestuff someotherstuff
#1:       09h              N
#2:       87h              H

#[[3]]
#   somestuff someotherstuff
#1:       0ij              K
#2:      5fdg              A
#3:        g7              C
#4:    h8o7hy              I
</code>```

Or this can be done with base R

```<code>i1 <- is.na(dat$somestuff)
split(dat[!i1], cumsum(i1)[!i1])
</code>```

Body:
I am attempting to subset a data table by using some NA values in a column as the end points for the subsetting.  Here is some fake data to show what I mean:

require(data.table)
set.seed(34)
somestuff <- c(NA,'sdr','utyrd','ytrd','fc',NA,NA,'09h','87h',NA,NA,NA,'0ij','5fdg','g7','h8o7hy')
someotherstuff <- sample(LETTERS,length(somestuff))

dat <- data.table(somestuff,someotherstuff)

I would like to subset 'dat' to the following 3 subsets (dat1, dat2, dat3 below).  Basically to remove the rows with NA but to also leverage some of those NA values in the first column as the non-inclusive endpoints for the subsetting. In other words, the groups for subsetting are separated by single or multiple cells of NAs in a column.

dat1 <- dat[2:5]
dat2 <- dat[8:9]
dat3 <- dat[13:16]

The actual data I will be using will have several subsets and usually multiple consecutive NA values in a column and when I pull this data each week it will have these NA's in different places.  I wanted to see if anyone knew of an efficient way to subset based on using a common element (like NA) or string within a column to specify the subsetting endpoints.  I'm not wed to a data.table solution though I tend to use these most.  I've been trying split() such as this:

split(dat,by=is.na(dat$somestuff))

as well as appending a counter to rows without the NA but it doesn't seem to be coming together.  Any thoughts?

Body:
We can create a grouping variable with rleid and then split into a list of data.tables

dt <- dat[,  grp := rleid(is.na(somestuff))][!is.na(somestuff), .SD]
unname(split(dt, by = "grp", keep.by = FALSE))
#[[1]]
#   somestuff someotherstuff
#1:       sdr              Y
#2:     utyrd              V
#3:      ytrd              F
#4:        fc              W

#[[2]]
#   somestuff someotherstuff
#1:       09h              N
#2:       87h              H

#[[3]]
#   somestuff someotherstuff
#1:       0ij              K
#2:      5fdg              A
#3:        g7              C
#4:    h8o7hy              I

Or this can be done with base R

i1 <- is.na(dat$somestuff)
split(dat[!i1], cumsum(i1)[!i1])


问:
Cannot enable migrations in VS.2017 with ASP.NET Core web application
I started to build my ASP.NET web application with the ASP.NET Core template. I noticed it has already two files in the ~\Data\Migrations folder one naemd *_CreateIdentitySchema.cs and the other ApplicationDbContextModelSnapshot.

At first it was complaining that i had Powershell 2 so I installed v3.
Then I installed the package EntityFramework (v6.1.3) from the package manager because somehow that was not installed from the template as it was the case in VS.2015.

Now it gives me an error like "Exception calling "SetData" with "2" argument(s): " and then  a bunch of things.

```<code> $domain.SetData('contextProject', $contextProject)
 CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  FullyQualifiedErrorId : SerializationException
 Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
</code>```

Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
At C:\Users\Devel.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:720 char:5
+     $domain.SetData('startUpProject', $startUpProject)

I am using VS.2017 Update 1, I get the impression this "core" thing is complicating life more than making it simpler.

答:
Not sure if any of this helps: I had the same issue after placing my enties in a project targetting .NET 4.6.2, but using the "new" MSBuild-Syntax (I think that's what it is called).

Projectname.csproj (the one containing the code from the entity framework) looked like this:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net462</TargetFramework>
</code>```

I now recreated the project using VS 2017's "Windows Classic Desktop - Class Library (.NET Framework)" template (basically: Copy all the code and setup all dependencies again).

Now, the Projectname.csproj looks like this (legacy MSBuild? Not sure how to call it):

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
</code>```

I still could add the "new" project as a reference to the project containing the ASP.NET Core stuff. And, more importantly, using "Add-Migration" on the project containing the EF types now works (EDIT: I still need to follow the advise given by Damian Drygiel: Startup project has to be a different project with a valid app.config).

Honestly speaking, I am still not sure whether using this workaround is a good idea or not as it leads to mixing the two types of projects / MSBuild versions. Not sure what the implications are. So far, it seems to work.

My take-away so far: Don't try to use .NET 4.6 with the "new" project format. This does not seem to work well at the moment.

Body:
I started to build my ASP.NET web application with the ASP.NET Core template. I noticed it has already two files in the ~\Data\Migrations folder one naemd *_CreateIdentitySchema.cs and the other ApplicationDbContextModelSnapshot.

At first it was complaining that i had Powershell 2 so I installed v3.
Then I installed the package EntityFramework (v6.1.3) from the package manager because somehow that was not installed from the template as it was the case in VS.2015.

Now it gives me an error like "Exception calling "SetData" with "2" argument(s): " and then  a bunch of things.

 $domain.SetData('contextProject', $contextProject)
 CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  FullyQualifiedErrorId : SerializationException
 Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,

Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
At C:\Users\Devel.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:720 char:5
+     $domain.SetData('startUpProject', $startUpProject)

I am using VS.2017 Update 1, I get the impression this "core" thing is complicating life more than making it simpler.

Body:
Not sure if any of this helps: I had the same issue after placing my enties in a project targetting .NET 4.6.2, but using the "new" MSBuild-Syntax (I think that's what it is called).

Projectname.csproj (the one containing the code from the entity framework) looked like this:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net462</TargetFramework>

I now recreated the project using VS 2017's "Windows Classic Desktop - Class Library (.NET Framework)" template (basically: Copy all the code and setup all dependencies again).

Now, the Projectname.csproj looks like this (legacy MSBuild? Not sure how to call it):

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>

I still could add the "new" project as a reference to the project containing the ASP.NET Core stuff. And, more importantly, using "Add-Migration" on the project containing the EF types now works (EDIT: I still need to follow the advise given by Damian Drygiel: Startup project has to be a different project with a valid app.config).

Honestly speaking, I am still not sure whether using this workaround is a good idea or not as it leads to mixing the two types of projects / MSBuild versions. Not sure what the implications are. So far, it seems to work.

My take-away so far: Don't try to use .NET 4.6 with the "new" project format. This does not seem to work well at the moment.


问:
How can I track the add ons(products) associated with the transaction data layer- GTM?
I have following data layer deployed on confirmation page which captures the transactional data all correct.
    enter code here

```<code><!-- Enhanced Ecommerce Data Layer through Google Tag Manager -->
<script>
dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': rtCONFIRMATIONNUMBER_0,
        'revenue': rtTOTALCOST,
        'tax':rtTAX_0,
      },
      'products': [{
        'name': rtPROPERTYNAME+'-'+rtROOMTYPE_0,
        'id': rtCONFIRMATIONNUMBER_0,
        'price': rtTOTALCOST,
        'quantity': 1
       }]
    }
  }
},{
    'event': 'purchase'
});
</script>
<!-- END Enhanced Ecommerce Data Layer through Google Tag Manager -->
</code>```

But this is not enough when user is adding some other add ons available at the time of checkout which I want to capture under the same transaction ID.
How can I modify this to capture the added Items data?

答:
First of all, there looks to be an error with your dataLayer.push. Your event key should be defined in the same object as your ecommerce object if you are planning on firing tags with the purchase event:

```<code>dataLayer.push({
   'ecommerce': {
      // ecommerce stuff
   },
   'event': 'purchase'
})
</code>```

Back to your main question now, one option would be to add the other add-ons as separate products:

```<code> dataLayer.push({
   'ecommerce': {
      'purchase': {
         'actionField': {
            'id': rtCONFIRMATIONNUMBER_0,
            'revenue': rtTOTALCOST,
            'tax': rtTAX_0,
         },
         'products': [{
               'name': rtPROPERTYNAME + '-' + rtROOMTYPE_0,
               'id': rtCONFIRMATIONNUMBER_0,
               'price': rtTOTALCOST,
               'quantity': 1
            },
            {
               'name': rtPROPERTYNAME2 + '-' + rtROOMTYPE2_0,
               'id': rtCONFIRMATIONNUMBER2_0,
               'price': rtTOTALCOST2,
               'quantity': 1,
               'category': 'add-on'
            },
            // other product objects like add-ons
         ]
      }
   }
</code>```

Body:
I have following data layer deployed on confirmation page which captures the transactional data all correct.
    enter code here

But this is not enough when user is adding some other add ons available at the time of checkout which I want to capture under the same transaction ID.
How can I modify this to capture the added Items data?

Body:
First of all, there looks to be an error with your dataLayer.push. Your event key should be defined in the same object as your ecommerce object if you are planning on firing tags with the purchase event:

dataLayer.push({
   'ecommerce': {
      // ecommerce stuff
   },
   'event': 'purchase'
})

Back to your main question now, one option would be to add the other add-ons as separate products:

 dataLayer.push({
   'ecommerce': {
      'purchase': {
         'actionField': {
            'id': rtCONFIRMATIONNUMBER_0,
            'revenue': rtTOTALCOST,
            'tax': rtTAX_0,
         },
         'products': [{
               'name': rtPROPERTYNAME + '-' + rtROOMTYPE_0,
               'id': rtCONFIRMATIONNUMBER_0,
               'price': rtTOTALCOST,
               'quantity': 1
            },
            {
               'name': rtPROPERTYNAME2 + '-' + rtROOMTYPE2_0,
               'id': rtCONFIRMATIONNUMBER2_0,
               'price': rtTOTALCOST2,
               'quantity': 1,
               'category': 'add-on'
            },
            // other product objects like add-ons
         ]
      }
   }


问:
I have an array containing different div IDs how do i target specific IDs from within the aray javascript/jquery
So I have an array in my script.js file. The array contains around 12 different things. I use the array to store divs IDs'. Because I want to load those divs dynamically. I've done that I loaded the divs dynamically but now I want to use that array for loading things inside the first div(a title a picture and so on).

```<code>let donorFeatureNames = [
    'SpawnVehicle',
    'RepairVehicle',
    'RocketVoltic',
    'MoreVehicle',
    'ChatColors',
    'Deagle',
    'M4',
    'Sniper',
    'CopFeature',
    'CrimFeature',
    'Changeskin',
    'Cash'
]

function loadFeatures () {
    for (i = 0; i < 12; i++) {
        $('#featureMenu').append('<div id=' + '"' + donorFeatureNames[i] + '"' + 'class="item notLoaded"></div>')

        $("'#" + donorFeatureNames[i] + "'").append(span class="title">' + $(this).data('donorfeature') + '</span>)
    }
</code>```

I hope you understand what I'm asking. Cause I'm not that good at explaining things.

答:
Instead of an array, just use jquery:

```<code>@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index1001</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        //credit to https://stackoverflow.com/questions/941206/jquery-add-image-inside-of-div-tag
        $(function () {
            $("#test1").append("Text");
            $('#test2').prepend("<img src='../../Images/w.JPG' />")
        })
    </script>
</head>
<body>
    <div id="test1" class="anArray"></div>
    <br/>
    <div id="test2" class="anArray"></div>
</body>
</html>
</code>```

You can even do this to make an array:  $(".anArray").addClass("aColor");

Body:
So I have an array in my script.js file. The array contains around 12 different things. I use the array to store divs IDs'. Because I want to load those divs dynamically. I've done that I loaded the divs dynamically but now I want to use that array for loading things inside the first div(a title a picture and so on).

let donorFeatureNames = [
    'SpawnVehicle',
    'RepairVehicle',
    'RocketVoltic',
    'MoreVehicle',
    'ChatColors',
    'Deagle',
    'M4',
    'Sniper',
    'CopFeature',
    'CrimFeature',
    'Changeskin',
    'Cash'
]

function loadFeatures () {
    for (i = 0; i < 12; i++) {
        $('#featureMenu').append('

')

        $("'#" + donorFeatureNames[i] + "'").append(span class="title">' + $(this).data('donorfeature') + ')
    }

I hope you understand what I'm asking. Cause I'm not that good at explaining things.

Body:
Instead of an array, just use jquery:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index1001</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        //credit to https://stackoverflow.com/questions/941206/jquery-add-image-inside-of-div-tag
        $(function () {
            $("#test1").append("Text");
            $('#test2').prepend("<img src='../../Images/w.JPG' />")
        })
    </script>
</head>
<body>
    <div id="test1" class="anArray"></div>
    <br/>
    <div id="test2" class="anArray"></div>
</body>
</html>

You can even do this to make an array:  $(".anArray").addClass("aColor");


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
When using SELECT * it can have a performance hit. Applications which use the SELECT * syntax when they actually only need a handful of columns are transferring more data across the network than they need to consume, which is wasteful.

Also, in Microsoft SQL Server at least, there's a strange problem when you use SELECT * in a view and then add a column to the underlying table. The column headings and data returned by the view don't match each other following certain changes! See my blog post for further details of this particular problem.


问:
Is Solr available for .Net?
I want to learn Solr. May I know some good tutorial/links for it?

Also, is Solr available for .NET?

答:
I would like to introduce my open-source library called LinqToSolr, which provides the functionality of building linq-queries to Solr.
Here is a nuget page or browse github project</p>

Title: Is Solr available for .Net?


问:
How to create n strings of random lengths the sum of which is equal to a given amount?
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

```<code>total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];
</code>```

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

```<code>gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}
</code>```

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

```<code>var gapLength = getRandomInt(1, total / 4);
</code>```

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.

答:
This is a similar problem to "find a random collection of k numbers whose sum is N". The original version of this answer used a simple solution which is unbiased if the numbers are continuous (i.e. floating point): generate k-1 numbers in the range [0, N], sort them, put 0 at the beginning and N at the end, and then find the differences between successive elements. But since there are no fractional characters, we need the numbers to be integers and the above algorithm is biased against collections which include 0 (there is an infinitesimal probability of getting 0 in the continuous case, but it is significant in the discrete case).

An unbiased solution for generating non-empty integer solutions is to find a random (k-1)-combination of the integers in the inclusive range [1, N-1]. To find the random combination use the first k-1 elements of a random shuffle of the range (using the Fisher-Yates shuffle). The combination is then sorted (if necessary) and a 0 prepended; these values are the starting positions of each string (so that the next value is the ending position.)

That will not produce empty substrings, since each substring has a unique starting point. To include empty substrings, use the above  with N+k instead of N, and then shrink every range by 1: if the indices are sorted, you can do that by subtracting i from the ith index.

In Python:

```<code>from random import sample
def random_split(str, k):
    v = [0] + sorted(sample(range(1, len(str)), k-1)) + [len(str)]
    return [str[v[i]:v[i+1]] for i in range(k)]

def random_split_allow_empty(str, k):
    v = [0] + sorted(sample(range(1, len(str)+k), k-1)) + [len(str)+k]
        return [str[v[i]-i:v[i+1]-i-1] for i in range(k)]
</code>```

In Javascript:

```<code>function shuffle(vec, k) {
  for (let i = 0; i < k; ++i) {
    let r = i + Math.floor(Math.random() * (vec.length - i));
    let t = vec[r];
    vec[r] = vec[i];
    vec[i] = t;
  }
  return vec;
}

function random_partition(N, k) {
  let v = [];
  for (let i = 1; i < N; ++i) v[i-1] = i;
  shuffle(v, k - 1);
  v[k-1] = 0;
  return v.slice(0, k).sort((a,b)=>a-b);
}

function random_split(s, k) {
  return random_partition(s.length, k).map(
    (v, i, a) => s.slice(v, a[i+1]));
}

function random_split_allow_empty(s, k) {
  return random_partition(s.length + k, k).map((v,i)=>v-i).map(
    (v, i, a) => s.slice(v, a[i+1]));
}
</code>```

Body:
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

var gapLength = getRandomInt(1, total / 4);

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.

Body:
This is a similar problem to "find a random collection of k numbers whose sum is N". The original version of this answer used a simple solution which is unbiased if the numbers are continuous (i.e. floating point): generate k-1 numbers in the range [0, N], sort them, put 0 at the beginning and N at the end, and then find the differences between successive elements. But since there are no fractional characters, we need the numbers to be integers and the above algorithm is biased against collections which include 0 (there is an infinitesimal probability of getting 0 in the continuous case, but it is significant in the discrete case).

An unbiased solution for generating non-empty integer solutions is to find a random (k-1)-combination of the integers in the inclusive range [1, N-1]. To find the random combination use the first k-1 elements of a random shuffle of the range (using the Fisher-Yates shuffle). The combination is then sorted (if necessary) and a 0 prepended; these values are the starting positions of each string (so that the next value is the ending position.)

That will not produce empty substrings, since each substring has a unique starting point. To include empty substrings, use the above  with N+k instead of N, and then shrink every range by 1: if the indices are sorted, you can do that by subtracting i from the ith index.

In Python:

from random import sample
def random_split(str, k):
    v = [0] + sorted(sample(range(1, len(str)), k-1)) + [len(str)]
    return [str[v[i]:v[i+1]] for i in range(k)]

def random_split_allow_empty(str, k):
    v = [0] + sorted(sample(range(1, len(str)+k), k-1)) + [len(str)+k]
        return [str[v[i]-i:v[i+1]-i-1] for i in range(k)]

In Javascript:

function shuffle(vec, k) {
  for (let i = 0; i < k; ++i) {
    let r = i + Math.floor(Math.random() * (vec.length - i));
    let t = vec[r];
    vec[r] = vec[i];
    vec[i] = t;
  }
  return vec;
}

function random_partition(N, k) {
  let v = [];
  for (let i = 1; i < N; ++i) v[i-1] = i;
  shuffle(v, k - 1);
  v[k-1] = 0;
  return v.slice(0, k).sort((a,b)=>a-b);
}

function random_split(s, k) {
  return random_partition(s.length, k).map(
    (v, i, a) => s.slice(v, a[i+1]));
}

function random_split_allow_empty(s, k) {
  return random_partition(s.length + k, k).map((v,i)=>v-i).map(
    (v, i, a) => s.slice(v, a[i+1]));
}


问:
Concurrent Modification Exception in Processing Sketch
I'm working on modifying the Attraction2D example from the Toxiclibs library to be controlled by gestures from a Leap Motion sensor, as opposed to the mouse in the example.

I'm doing all my gesture recognition in an Open Frameworks app, and sending that over OSC.

When a Gesture 0 event occurs, I call the method below to remove the gestureAttractor from the physics object:

```<code>void resetAttraction() {
  if (gestureAttractor != null){
      physics.removeBehavior(gestureAttractor);
      println("ATTRACTOR NULL");
     } else {
        println("not null");
     }
}
</code>```

If a Gesture 1 event occurs, I call this method to create a new gestureAttractor, and add it back to the physics object:

```<code>void addAttraction(){
   if (gestureAttractor == null) {
       println("ATTRACTOR NULL");
       position1.set(340, 191);
       gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
       physics.addBehavior(gestureAttractor);
   } else {
       println("not null");
   }
}
</code>```

What seems to happen consistently is whenever the gesture state changes, I'll get a ConcurrentModificationException crash at physics.update(); in the draw method.

I'm sure it has something to do with the way the lifecycle of these objects are handled, but I haven't been able to determine anything yet - anyone have any ideas?

Below is the entirety of the sketch:

```<code>import toxi.geom.*;
import toxi.physics2d.*;
import toxi.physics2d.behaviors.*;

import oscP5.*;
import netP5.*;

OscP5 oscP5;

int NUM_PARTICLES = 750;

VerletPhysics2D physics;
//AttractionBehavior2D mouseAttractor;
AttractionBehavior2D gestureAttractor;

//Vec2D mousePos;
Vec2D position1;

boolean isGestureAttractorAdded;

void setup() {
  size(680, 382,P3D);
  // setup physics with 10% drag
  physics = new VerletPhysics2D();
  physics.setDrag(0.05f);
  physics.setWorldBounds(new Rect(0, 0, width, height));
  // the NEW way to add gravity to the simulation, using behaviors
  physics.addBehavior(new GravityBehavior2D(new Vec2D(0, 0.15f)));

  // start oscP5, listening for incoming messages at port 12000
  oscP5 = new OscP5(this, 6000);

  position1 = new Vec2D(340, 191);

  addAttraction();

  //gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
  //physics.addBehavior(gestureAttractor);
}

void addParticle() {
  VerletParticle2D p = new VerletParticle2D(Vec2D.randomVector().scale(5).addSelf(width / 2, 0));
  physics.addParticle(p);
  // add a negative attraction force field around the new particle
  physics.addBehavior(new AttractionBehavior2D(p, 20, -1.2f, 0.01f));
}

void draw() {
  background(255,0,0);
  noStroke();
  fill(255);
  if (physics.particles.size() < NUM_PARTICLES) {
    addParticle();
  }
  physics.update();
  for (VerletParticle2D p : physics.particles) {
    ellipse(p.x, p.y, 5, 5);
  }
}

void mousePressed() {
  //position1 = new Vec2D(mouseX, mouseY);
   //create a new positive attraction force field around the mouse position (radius=250px)
  //gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
  //physics.addBehavior(gestureAttractor);

  //println(physics.behaviors);
}

void mouseDragged() {
  // update mouse attraction focal point
  //position1.set(mouseX, mouseY);
}

void mouseReleased() {
  // remove the mouse attraction when button has been released
  //physics.removeBehavior(gestureAttractor);
}

///// OSC RECEIVING

void oscEvent(OscMessage theOscMessage) {
  /* check if theOscMessage has the address pattern we are looking for. */

  if (theOscMessage.checkAddrPattern("/gesture_classification") == true)  {
    /* check if the typetag is the right one. */
    if(theOscMessage.checkTypetag("i")) {
      /* parse theOscMessage and extract the values from the osc message arguments. */
      int gestureClassLabel = theOscMessage.get(0).intValue();
      println(" Gesture is: ", gestureClassLabel);

      if (gestureClassLabel == 0){
        resetAttraction();
      } else if (gestureClassLabel == 1) {
        addAttraction();
      } else if (gestureClassLabel == 2) {
          //physics.removeBehavior(gestureAttractor);
      }
    }
  }

}

//////METHODS FOR SETTING POSITION / REMOVAL OF ATTRACTORS...

void resetAttraction() {
  if (gestureAttractor != null){
      physics.removeBehavior(gestureAttractor);
      println("ATTRACTOR NULL");
     } else {
        println("not null");
     }
 }

void addAttraction(){
     if (gestureAttractor == null) {
         println("ATTRACTOR NULL");
         position1.set(340, 191);
         gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
         physics.addBehavior(gestureAttractor);
     } else {
       println("not null");
     }
}
</code>```

答:
tl;dr: You shouldn't modify a data structure with one thread while you're iterating over it from another thread.

The draw() function is happening on one thread, and it's accessing and modifying data structures inside the physics library.

The oscEvent() function is happening on another thread, and it's also accessing and modifying those same data structures. That's what's causing your error. And please note that wrapping it in a try block is not fixing anything. It's just printing out more information when the error does happen.

To really fix the problem, you need to read up on synchornizing data access between threads. For example, you could use synchronized blocks to prevent different threads from accessing the same data structure. You'll find a ton of results if you google your error.

Body:
I'm working on modifying the Attraction2D example from the Toxiclibs library to be controlled by gestures from a Leap Motion sensor, as opposed to the mouse in the example.

I'm doing all my gesture recognition in an Open Frameworks app, and sending that over OSC.

When a Gesture 0 event occurs, I call the method below to remove the gestureAttractor from the physics object:

void resetAttraction() {
  if (gestureAttractor != null){
      physics.removeBehavior(gestureAttractor);
      println("ATTRACTOR NULL");
     } else {
        println("not null");
     }
}

If a Gesture 1 event occurs, I call this method to create a new gestureAttractor, and add it back to the physics object:

void addAttraction(){
   if (gestureAttractor == null) {
       println("ATTRACTOR NULL");
       position1.set(340, 191);
       gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
       physics.addBehavior(gestureAttractor);
   } else {
       println("not null");
   }
}

What seems to happen consistently is whenever the gesture state changes, I'll get a ConcurrentModificationException crash at physics.update(); in the draw method.

I'm sure it has something to do with the way the lifecycle of these objects are handled, but I haven't been able to determine anything yet - anyone have any ideas?

Below is the entirety of the sketch:

import toxi.geom.*;
import toxi.physics2d.*;
import toxi.physics2d.behaviors.*;

import oscP5.*;
import netP5.*;

OscP5 oscP5;

int NUM_PARTICLES = 750;

VerletPhysics2D physics;
//AttractionBehavior2D mouseAttractor;
AttractionBehavior2D gestureAttractor;

//Vec2D mousePos;
Vec2D position1;

boolean isGestureAttractorAdded;

void setup() {
  size(680, 382,P3D);
  // setup physics with 10% drag
  physics = new VerletPhysics2D();
  physics.setDrag(0.05f);
  physics.setWorldBounds(new Rect(0, 0, width, height));
  // the NEW way to add gravity to the simulation, using behaviors
  physics.addBehavior(new GravityBehavior2D(new Vec2D(0, 0.15f)));

  // start oscP5, listening for incoming messages at port 12000
  oscP5 = new OscP5(this, 6000);

  position1 = new Vec2D(340, 191);

  addAttraction();

  //gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
  //physics.addBehavior(gestureAttractor);
}

void addParticle() {
  VerletParticle2D p = new VerletParticle2D(Vec2D.randomVector().scale(5).addSelf(width / 2, 0));
  physics.addParticle(p);
  // add a negative attraction force field around the new particle
  physics.addBehavior(new AttractionBehavior2D(p, 20, -1.2f, 0.01f));
}

void draw() {
  background(255,0,0);
  noStroke();
  fill(255);
  if (physics.particles.size() < NUM_PARTICLES) {
    addParticle();
  }
  physics.update();
  for (VerletParticle2D p : physics.particles) {
    ellipse(p.x, p.y, 5, 5);
  }
}

void mousePressed() {
  //position1 = new Vec2D(mouseX, mouseY);
   //create a new positive attraction force field around the mouse position (radius=250px)
  //gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
  //physics.addBehavior(gestureAttractor);

  //println(physics.behaviors);
}

void mouseDragged() {
  // update mouse attraction focal point
  //position1.set(mouseX, mouseY);
}

void mouseReleased() {
  // remove the mouse attraction when button has been released
  //physics.removeBehavior(gestureAttractor);
}

///// OSC RECEIVING

void oscEvent(OscMessage theOscMessage) {
  /* check if theOscMessage has the address pattern we are looking for. */

  if (theOscMessage.checkAddrPattern("/gesture_classification") == true)  {
    /* check if the typetag is the right one. */
    if(theOscMessage.checkTypetag("i")) {
      /* parse theOscMessage and extract the values from the osc message arguments. */
      int gestureClassLabel = theOscMessage.get(0).intValue();
      println(" Gesture is: ", gestureClassLabel);

      if (gestureClassLabel == 0){
        resetAttraction();
      } else if (gestureClassLabel == 1) {
        addAttraction();
      } else if (gestureClassLabel == 2) {
          //physics.removeBehavior(gestureAttractor);
      }
    }
  }

}

//////METHODS FOR SETTING POSITION / REMOVAL OF ATTRACTORS...

void resetAttraction() {
  if (gestureAttractor != null){
      physics.removeBehavior(gestureAttractor);
      println("ATTRACTOR NULL");
     } else {
        println("not null");
     }
 }

void addAttraction(){
     if (gestureAttractor == null) {
         println("ATTRACTOR NULL");
         position1.set(340, 191);
         gestureAttractor = new AttractionBehavior2D(position1, 250, 0.9f);
         physics.addBehavior(gestureAttractor);
     } else {
       println("not null");
     }
}


问:
Replace all occurrences of a string (given their starting and ending index ) with a unique ID in Python
I am working on a dataset that I have to preprocess. I want to replace all occurrences (given by starting and ending index) with their unique IDs.

Given a string of text like:

s = "The hypotensive effect of 100 mg/kg alpha-methyldopa was also partially reversed by naloxone. Naloxone alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously hypertensive rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of [3H]-naloxone (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM)."

and a list of dictionaries like:

[

'D006973': [{'length': '12',
            'offset': '199',
            'text': ['hypertensive'],
            'type': 'Disease'}],

'D008750': [{'length': '16',
            'offset': '36',
            'text': ['alpha-methyldopa'],
            'type': 'Chemical'}],

'D007022': [{'length': '11',
            'offset': '4',
            'text': ['hypotensive'],
            'type': 'Disease'}],

'D009270': [{'length': '8',
            'offset': '84',
            'text': ['naloxone'],
            'type': 'Chemical'},
           {'length': '8',
            'offset': '94',
            'text': ['Naloxone'],
            'type': 'Chemical'},
           {'length': '13',
            'offset': '293',
            'text': ["[3H]-naloxone"],
            'type': 'Chemical'}]

]

I want to replace all occurrences given by offsets with their respective IDs. So for last dictionary I want all the values in the list to be replaced by 'D009270'.

Example 1: for first dictionary with key 'D006973', I want to replace 'hypertensive', which is present at index 199 and is of length 12, with 'D006973'.

Example 2: for last dictionary with key 'D009270', I want to replace substrings from indices (given by tuples)

```<code>[(84, 92), (94, 102), (293, 306)]
</code>```

In last sentence, naloxone is present with "naloxone-suppressible", but I don't want to replace it. So I cannot simply use str.replace().

I replaced string from starting index to end index (ex: 199 to 211 for 'hypertensive') with its unique ID. But this disturbs offsets of other 'yet to be replaced' entities.
I could use padding for when the text to be replaced ('D006973') is smaller than the string ('hypertensive'). But it will fail when the text to be repaced is greater in size.

答:
You can use string formatters with a placeholder character:

```<code>from operator import itemgetter

s = "The hypotensive effect of 100 mg/kg alpha-methyldopa was also partially reversed by naloxone. Naloxone alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously hypertensive rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of [3H]-naloxone (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM)."

dictionary={
'D006973': [{'length': '12', 'offset': '199', 'text': ['hypertensive'], 'type': 'Disease'}],
'D008750': [{'length': '16', 'offset': '36', 'text': ['alpha-methyldopa'], 'type': 'Chemical'}],
'D007022': [{'length': '11', 'offset': '4', 'text': ['hypotensive'], 'type': 'Disease'}],
'D009270': [{'length': '8', 'offset': '84', 'text': ['naloxone'], 'type': 'Chemical'}, {'length': '8', 'offset': '94', 'text': ['Naloxone'], 'type': 'Chemical'}, {'length': '13', 'offset': '293', 'text': ["[3H]-naloxone"], 'type': 'Chemical'}]
}

index_list=[]
for key in dictionary:
    for dic in dictionary[key]:
        o=int(dic['offset'])
        index_tuple=o , o+int(dic['length']),key
        index_list.append(index_tuple)

index_list.sort(key=itemgetter(0))
format_list=[]
lt=list(s)
for i,j in enumerate(index_list):
    si=j[0]
    ei=j[1]
    lt[si:ei]=list("{}") + ["@"]*((ei-si)-2)
    format_list.append(j[2])

text = "".join(lt)
text = text.replace("@","")
text = text.format(*format_list)
</code>```

Result : 'The D007022 effect of 100 mg/kg D008750 was also partially reversed by D009270. D009270 alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously D006973 rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of D009270 (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM).'

Body:
I am working on a dataset that I have to preprocess. I want to replace all occurrences (given by starting and ending index) with their unique IDs.

Given a string of text like:

s = "The hypotensive effect of 100 mg/kg alpha-methyldopa was also partially reversed by naloxone. Naloxone alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously hypertensive rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of [3H]-naloxone (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM)."

and a list of dictionaries like:

[

'D006973': [{'length': '12',
            'offset': '199',
            'text': ['hypertensive'],
            'type': 'Disease'}],

'D008750': [{'length': '16',
            'offset': '36',
            'text': ['alpha-methyldopa'],
            'type': 'Chemical'}],

'D007022': [{'length': '11',
            'offset': '4',
            'text': ['hypotensive'],
            'type': 'Disease'}],

'D009270': [{'length': '8',
            'offset': '84',
            'text': ['naloxone'],
            'type': 'Chemical'},
           {'length': '8',
            'offset': '94',
            'text': ['Naloxone'],
            'type': 'Chemical'},
           {'length': '13',
            'offset': '293',
            'text': ["[3H]-naloxone"],
            'type': 'Chemical'}]

]

I want to replace all occurrences given by offsets with their respective IDs. So for last dictionary I want all the values in the list to be replaced by 'D009270'.

Example 1: for first dictionary with key 'D006973', I want to replace 'hypertensive', which is present at index 199 and is of length 12, with 'D006973'.

Example 2: for last dictionary with key 'D009270', I want to replace substrings from indices (given by tuples)

[(84, 92), (94, 102), (293, 306)]

In last sentence, naloxone is present with "naloxone-suppressible", but I don't want to replace it. So I cannot simply use str.replace().

I replaced string from starting index to end index (ex: 199 to 211 for 'hypertensive') with its unique ID. But this disturbs offsets of other 'yet to be replaced' entities.
I could use padding for when the text to be replaced ('D006973') is smaller than the string ('hypertensive'). But it will fail when the text to be repaced is greater in size.

Body:
You can use string formatters with a placeholder character:

from operator import itemgetter

s = "The hypotensive effect of 100 mg/kg alpha-methyldopa was also partially reversed by naloxone. Naloxone alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously hypertensive rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of [3H]-naloxone (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM)."

dictionary={
'D006973': [{'length': '12', 'offset': '199', 'text': ['hypertensive'], 'type': 'Disease'}],
'D008750': [{'length': '16', 'offset': '36', 'text': ['alpha-methyldopa'], 'type': 'Chemical'}],
'D007022': [{'length': '11', 'offset': '4', 'text': ['hypotensive'], 'type': 'Disease'}],
'D009270': [{'length': '8', 'offset': '84', 'text': ['naloxone'], 'type': 'Chemical'}, {'length': '8', 'offset': '94', 'text': ['Naloxone'], 'type': 'Chemical'}, {'length': '13', 'offset': '293', 'text': ["[3H]-naloxone"], 'type': 'Chemical'}]
}

index_list=[]
for key in dictionary:
    for dic in dictionary[key]:
        o=int(dic['offset'])
        index_tuple=o , o+int(dic['length']),key
        index_list.append(index_tuple)

index_list.sort(key=itemgetter(0))
format_list=[]
lt=list(s)
for i,j in enumerate(index_list):
    si=j[0]
    ei=j[1]
    lt[si:ei]=list("{}") + ["@"]*((ei-si)-2)
    format_list.append(j[2])

text = "".join(lt)
text = text.replace("@","")
text = text.format(*format_list)

Result : 'The D007022 effect of 100 mg/kg D008750 was also partially reversed by D009270. D009270 alone did not affect either blood pressure or heart rate. In brain membranes from spontaneously D006973 rats clonidine, 10(-8) to 10(-5) M, did not influence stereoselective binding of D009270 (8 nM), and naloxone, 10(-8) to 10(-4) M, did not influence naloxone-suppressible binding of [3H]-dihydroergocryptine (1 nM).'


问:
Apply VBA Macro To Filtered Cells Only
Got a bit of a problem. Auditors have requested an entire Excel-dump of our whole ledger, which is massive (why? Why do they want this?). I.T. have eventually managed to export it for me over several workbooks, but it appears that some lines are duplicated. There appears to be no pattern as to which ones. I've got some code to delete wholly duplicated lines, but each spreadsheets are so massive I wouldn't be able to run it on the whole dataset.

I've identified the subledgers that are affected, and though I could filter and then apply the code just to these ones. It will still take ages, but not quite as ages as going through and searching for them all 'by eye' would.

Is there a way, please, of applying the code just to the cells I have filtered? I've tried SpecialCells(xlCellTypeVisible), but I think I was adding it in the wrong place as my macro is still searching through the whole workbook.

Original code before I added SpecialCells is as follows:

```<code>Dim ColN As Long
Dim MyS As Worksheet: Set MyS = ActiveSheet
Dim MyR As Range: Set MyR = MyS.Cells(1, 1).CurrentRegion
Dim NumCol As Long: NumCol = MyR.Columns.Count
Dim MyArray As Variant: ReDim MyArray(0 To NumCol - 1)

For ColN = 1 To NumCol
    MyArray(ColN - 1) = ColN
Next
MyR.RemoveDuplicates Columns:=(MyArray), Header:=xlYes
Dim rowcount As Long, i As Long, j As Long, k As Boolean
rowcount = MyR.Rows.Count
For i = rowcount To 1 Step -1
    k = 0
    For j = 1 To NumCol
        If MyR.Value2(i, j) <> "" Then
            k = 1
            Exit For
        End If
    Next j
    If k = 0 Then
        MyR.Rows(i).Delete Shift:=xlUp
    End If
Next I
Application.ScreenUpdating = True
</code>```

Many thanks.

答:
```<code>For i = rowcount To 1 Step -1
    k = 0
      For j = 1 To NumCol
        If MyR.Value2(i, j) <> ""  and Rows(I, j).Hidden = false Then
</code>```

<p>I'm on my phone, so I can't test.  </p>

Title: Apply VBA Macro To Filtered Cells Only

Body:
Got a bit of a problem. Auditors have requested an entire Excel-dump of our whole ledger, which is massive (why? Why do they want this?). I.T. have eventually managed to export it for me over several workbooks, but it appears that some lines are duplicated. There appears to be no pattern as to which ones. I've got some code to delete wholly duplicated lines, but each spreadsheets are so massive I wouldn't be able to run it on the whole dataset.

I've identified the subledgers that are affected, and though I could filter and then apply the code just to these ones. It will still take ages, but not quite as ages as going through and searching for them all 'by eye' would.

Is there a way, please, of applying the code just to the cells I have filtered? I've tried SpecialCells(xlCellTypeVisible), but I think I was adding it in the wrong place as my macro is still searching through the whole workbook.

Original code before I added SpecialCells is as follows:

Dim ColN As Long
Dim MyS As Worksheet: Set MyS = ActiveSheet
Dim MyR As Range: Set MyR = MyS.Cells(1, 1).CurrentRegion
Dim NumCol As Long: NumCol = MyR.Columns.Count
Dim MyArray As Variant: ReDim MyArray(0 To NumCol - 1)

For ColN = 1 To NumCol
    MyArray(ColN - 1) = ColN
Next
MyR.RemoveDuplicates Columns:=(MyArray), Header:=xlYes
Dim rowcount As Long, i As Long, j As Long, k As Boolean
rowcount = MyR.Rows.Count
For i = rowcount To 1 Step -1
    k = 0
    For j = 1 To NumCol
        If MyR.Value2(i, j) <> "" Then
            k = 1
            Exit For
        End If
    Next j
    If k = 0 Then
        MyR.Rows(i).Delete Shift:=xlUp
    End If
Next I
Application.ScreenUpdating = True

Many thanks.

Body:
For i = rowcount To 1 Step -1
    k = 0
      For j = 1 To NumCol
        If MyR.Value2(i, j) <> ""  and Rows(I, j).Hidden = false Then

I'm on my phone, so I can't test.


问:
Sort List with two parameters but in different lines of code
I have a method which sorts a List of Clients.

There are two parameters I want to sort by.
I am well aware of the

```<code>List.OrderBy(x => x. [...]).ThenBy...
</code>```

Method but my situation is a bit different:

```<code>switch(mySortType)
{
     case SortType.mostVisits:
         clients = clients.OrderBy(x => x. and so on...)
     break;
     More cases with different sortTypes
}
</code>```

And after that I would like to sort after a Boolean parameter, but only if the settings tell the method to do so via another bool.
Ist there a way to say something like

```<code>clients = clients.OrderBy(Current).ThenBy(x => x.param).ToList()?
</code>```

I could of course have an if() in every case

```<code>case SortType.MostVisits:
  if(settingsTellsMeToDoSo)
     clients = clients.OrderBy(x=>x.numberOfVisits).ThenBy(x => x.param).ToList();
  else clients = clients.OrderBy(x => x.numberOfVisits).ToList();
</code>```

and then use the simple ThenBy Method but I thaught that there has to be an easier way to do it.

I hope you got my question right. I am not sure whether or not I was able to explain well enough...

regards,
Eric

答:
I am not sure what you are trying to simplify, you can't remove the decision making from your code, but you could order the sort statements better:

```<code>IOrderedEnumerable<Client> orderedClients;

case SortType.MostVisits:
  orderedClients = clients.OrderBy(x => x.numberOfVisits);
  if(settingsTellsMeToDoSo)
      orderedClients = orderedClients.ThenBy(x => x.param);
break;
</code>```

then after the switch is ended:

```<code>clients = orderedClients.ToList();
</code>```

Body:
I have a method which sorts a List of Clients.

There are two parameters I want to sort by.
I am well aware of the

List.OrderBy(x => x. [...]).ThenBy...

Method but my situation is a bit different:

switch(mySortType)
{
     case SortType.mostVisits:
         clients = clients.OrderBy(x => x. and so on...)
     break;
     More cases with different sortTypes
}

And after that I would like to sort after a Boolean parameter, but only if the settings tell the method to do so via another bool.
Ist there a way to say something like

clients = clients.OrderBy(Current).ThenBy(x => x.param).ToList()?

I could of course have an if() in every case

case SortType.MostVisits:
  if(settingsTellsMeToDoSo)
     clients = clients.OrderBy(x=>x.numberOfVisits).ThenBy(x => x.param).ToList();
  else clients = clients.OrderBy(x => x.numberOfVisits).ToList();

and then use the simple ThenBy Method but I thaught that there has to be an easier way to do it.

I hope you got my question right. I am not sure whether or not I was able to explain well enough...

regards,
Eric

Body:
I am not sure what you are trying to simplify, you can't remove the decision making from your code, but you could order the sort statements better:

IOrderedEnumerable<Client> orderedClients;

case SortType.MostVisits:
  orderedClients = clients.OrderBy(x => x.numberOfVisits);
  if(settingsTellsMeToDoSo)
      orderedClients = orderedClients.ThenBy(x => x.param);
break;

then after the switch is ended:

clients = orderedClients.ToList();


问:
Slow down iOS animation to debug?
On OS X, one can hold the shift key to cause animation to slow down. Is there some way to apply this to iOS via a remote debugger or in Instruments?

(Alternatively, I could record in QuickTime and replay frame by frame, but I would rather not have to do that.)

EDIT: I'm looking for a way to do this on the device.

答:
Temporarily set layer.speed on the view you are animating to a value less than one. For example in my UIViewController subclass, I have a UIView subclass which is animating some changes to it's subviews. If I want to slow down those animations (and only those, not other transitions):

```<code>class MyViewController: UIViewController {
    private let myView = MyView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // slow down animation speed for only this view
        myView.layer.speed = 0.1
    }
}
</code>```

If you want to slow down all animations in your app, set window?.layer.speed, for example in your AppDelegate.

Don't forget to remove this code once you're done perfecting your animation!

Title: Slow down iOS animation to debug?

Body:
Temporarily set layer.speed on the view you are animating to a value less than one. For example in my UIViewController subclass, I have a UIView subclass which is animating some changes to it's subviews. If I want to slow down those animations (and only those, not other transitions):

class MyViewController: UIViewController {
    private let myView = MyView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // slow down animation speed for only this view
        myView.layer.speed = 0.1
    }
}

If you want to slow down all animations in your app, set window?.layer.speed, for example in your AppDelegate.

Don't forget to remove this code once you're done perfecting your animation!


问:
How can I create N variables in for?
I need some way to create N variables(number greater than 1) by for?

for example, something like that:

```<code> int N=1000;
 for(int i=0; i < N; i++){
    char* var_i = malloc(sizeof(1));
    }
</code>```

NOTE: I know that the code above is not working, I wrote it just for explain my intent.

答:
You can use array. Here is two examples:

```<code>#include <stdio.h>
#define N 10000

int main(void)
{
    char array[N];
    for (size_t i = 0; i < N; i++) {
         /* Do what you want. */
    }
    return 0;
}
</code>```

Or if you want in heap:

```<code>#include <stdio.h>
#include <stdlib.h>
#define N 10000

int main(void)
{
    char *array = malloc(sizeof *array * N);
    if (array == NULL) {
        perror("Malloc");
        exit(EXIT_FAILURE);
    }
    for (size_t i = 0; i < N; i++) {
         /* Do what you want. */
    }
    free(array);
    return 0;
}
</code>```

Title: How can I create N variables in for?

Body:
I need some way to create N variables(number greater than 1) by for?

for example, something like that:

 int N=1000;
 for(int i=0; i < N; i++){
    char* var_i = malloc(sizeof(1));
    }

NOTE: I know that the code above is not working, I wrote it just for explain my intent.

Body:
You can use array. Here is two examples:

#include <stdio.h>
#define N 10000

int main(void)
{
    char array[N];
    for (size_t i = 0; i < N; i++) {
         /* Do what you want. */
    }
    return 0;
}

Or if you want in heap:

#include <stdio.h>
#include <stdlib.h>
#define N 10000

int main(void)
{
    char *array = malloc(sizeof *array * N);
    if (array == NULL) {
        perror("Malloc");
        exit(EXIT_FAILURE);
    }
    for (size_t i = 0; i < N; i++) {
         /* Do what you want. */
    }
    free(array);
    return 0;
}