问:
setInterval code not working
I have this HTML:

```<code><body onclick = 'myMove(event)'>
    <p>
    <button onclick="myMove(event)">Go Right</button>
    </p>
    <div id ="animate"></div>
    <p id='para'>HI</p>
</body>
</code>```

This JavaScript:

```<code>function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  let pos = elem.style.marginLeft;

  function frame() {
    if (pos === event.clientX) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.left = pos + 'px';
    }
  }
</code>```

But every time it runs, the box goes to the start and then moves to my mouse position. Is there a way to make it go to the mouse position from wherever it is and not go back to the start?

答:
    <button onclick="myMove(event)">Go Right</button>

aaa

HI

```

Title: setInterval code not working

Body:
I have this HTML:

    <button onclick="myMove(event)">Go Right</button>

HI

This JavaScript:

function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  let pos = elem.style.marginLeft;

  function frame() {
    if (pos === event.clientX) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.left = pos + 'px';
    }
  }

But every time it runs, the box goes to the start and then moves to my mouse position. Is there a way to make it go to the mouse position from wherever it is and not go back to the start?

Body:
<script>
 let pos = null;
function myMove(event) {
  let elem = document.getElementById("animate");
  document.getElementById('para').innerHTML = event.clientX;
  let id = setInterval(frame, 5);
  if(pos === null){
   pos = elem.style.marginLeft;
  }

  function frame() {
    if (pos === event.clientX ) {
      clearInterval(id);
    } else if(pos < event.clientX){

      pos++;
      elem.style.left = pos + 'px';
    }
    else{
      pos--;
      elem.style.left = pos + 'px';
    }
  }
 }
</script>

<body onclick = 'myMove(event)'>
    <p>
    <button onclick="myMove(event)">Go Right</button>
    </p>
    <div style='position:relative;' id ="animate">aaa</div>
    <p id='para'>HI</p>
</body>


来源: stackexchange

问:
Testing spring-cloud-dataflow stream
I'm looking for a way to easily test any flow. And I thing that spring-cloud-dataflow-acceptance-tests could help me to do that but I can'f find any documentation about that.

How does it work? I launched the application but I don't know how can write and run test.

Does anyone has any suggestion about that?

Thanks

答: The spring-cloud-dataflow-acceptance-tests  is used to deploy and run test scenarios. The readme has an extensive example on how to bootstrap it, is your question about how to write a test for a stream app, or how to test a deployed stream end to end?</p>

ContentLicense: CC BY-SA 3.0

Title: Testing spring-cloud-dataflow stream


问:
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

```<code> (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code>```

settings.py.

```<code>  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }
</code>```

答:
Like raratiru answered, you need DJANGO_SETTINGS_MODULE environment variable defined with the relative pythonic path to your setting file.

OR use your django-admin command with the settings parameter:

```<code>django-admin --settings=mysite.settings dbshell
</code>```

Body:
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

 (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

settings.py.

  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }

Body:
Like raratiru answered, you need DJANGO_SETTINGS_MODULE environment variable defined with the relative pythonic path to your setting file.

OR use your django-admin command with the settings parameter:

django-admin --settings=mysite.settings dbshell


问:
How to force a view to load model values prior to loading controller in AngularJS?
I am trying to auto post a form from a controller without any user interaction on the form. I have a private init() function in the controller that triggers a button click on the form.
But the hidden form fields did not get the values yet. How can I make sure the hidden fields will have values populated before the form submits?

Thank you for any suggestions.

```<code><div>
 <form name="myForm" method="post" action="@Model.Settings["URL"]" ng-controller="MyCtrl">

        <input type="hidden" name="userid" value="{{UserSettings.Settings.UserId}}">
        <input type="hidden" name="amount" value="{{Payment.Amount}}">

        <button id="payButton" type="submit" class="action blue"><span class="label">Pay</span></button>

        <script language="javascript">
            var UserSettings = (function (o) {
                return o;
            })(@Html.Raw(JsonConvert.SerializeObject(@Model)));
        </script>
    </form>
</div>

 myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'dataService',
  function ($scope, $state, $element, service) {

      $scope.Payment = service.GetPayment());
      $scope.UserSettings = UserSettings;

      function init() {

        // How can I force to have values in the hidden form fields before the button click that submits the form ?

          $element.find('#payButton').trigger("click");
      };

      init();
  }]);
</code>```

Here is the ui-router states configuration.

```<code>var app = angular.module('pay', ['ui.router', 'pay.controllers', 'pay.services', 'exceptionOverride', 'ngSanitize']);

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
        .state('home', {
            url: '/' ,
            templateUrl: 'search'
        })
        .state('payment', {
            url: '/payment',
            templateUrl: 'Payment'
        });

    //setting html5 removes the # from URL but causes routing problems at the moment.
    //$locationProvider.html5Mode(true);

    $urlRouterProvider.rule(function ($injector, $location) {
        //what this function returns will be set as the $location.url
        var path = $location.path(), normalized = path.toLowerCase();
        if (path != normalized) {
            $location.replace().path(normalized);
        }
        else if (path == '') {
            $location.path('/');
        }
    });
}]);
</code>```

答:
You can put the populations in the point you define the state which has MyCtrl as follows:

```<code>.state('myState', {
    // ...
    resolve: {
         Payment: ['dataService', function (dataService) {
             return dataService.GetPayment();
         }],
         // Same for other objects needed
    }
})
</code>```

And then in your Controller:

```<code>myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'Payment',
  function ($scope, $state, $element, Payment) {

      $scope.Payment = Payment;
      // Same for other objects needed

      // Rest code
}
</code>```

The code in the Controller would not start running before all actions and promises in the resolve section finish.

Update:

You can put init call inside a $timeout.

```<code>$timeout(function(){
    init();
});
</code>```

Of course, you have to inject $timeout in Controller function along with the other dependencies.

Body:
I am trying to auto post a form from a controller without any user interaction on the form. I have a private init() function in the controller that triggers a button click on the form.
But the hidden form fields did not get the values yet. How can I make sure the hidden fields will have values populated before the form submits?

Thank you for any suggestions.

 <form name="myForm" method="post" action="@Model.Settings["URL"]" ng-controller="MyCtrl">

        <input type="hidden" name="userid" value="{{UserSettings.Settings.UserId}}">
        <input type="hidden" name="amount" value="{{Payment.Amount}}">

        <button id="payButton" type="submit" class="action blue">Pay</button>

    </form>

 myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'dataService',
  function ($scope, $state, $element, service) {

      $scope.Payment = service.GetPayment());
      $scope.UserSettings = UserSettings;

      function init() {

        // How can I force to have values in the hidden form fields before the button click that submits the form ?

          $element.find('#payButton').trigger("click");
      };

      init();
  }]);

Here is the ui-router states configuration.

var app = angular.module('pay', ['ui.router', 'pay.controllers', 'pay.services', 'exceptionOverride', 'ngSanitize']);

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
        .state('home', {
            url: '/' ,
            templateUrl: 'search'
        })
        .state('payment', {
            url: '/payment',
            templateUrl: 'Payment'
        });

    //setting html5 removes the # from URL but causes routing problems at the moment.
    //$locationProvider.html5Mode(true);

    $urlRouterProvider.rule(function ($injector, $location) {
        //what this function returns will be set as the $location.url
        var path = $location.path(), normalized = path.toLowerCase();
        if (path != normalized) {
            $location.replace().path(normalized);
        }
        else if (path == '') {
            $location.path('/');
        }
    });
}]);

Body:
You can put the populations in the point you define the state which has MyCtrl as follows:

.state('myState', {
    // ...
    resolve: {
         Payment: ['dataService', function (dataService) {
             return dataService.GetPayment();
         }],
         // Same for other objects needed
    }
})

And then in your Controller:

myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'Payment',
  function ($scope, $state, $element, Payment) {

      $scope.Payment = Payment;
      // Same for other objects needed

      // Rest code
}

The code in the Controller would not start running before all actions and promises in the resolve section finish.

Update:

You can put init call inside a $timeout.

$timeout(function(){
    init();
});

Of course, you have to inject $timeout in Controller function along with the other dependencies.


问:
I'm creating an RSS reader and having trouble with feedburner feeds
I'm using the Google Feed API to get feeds and the results contain an link field which is great however a feedburner feed returns something to the effect of google.feedproxy.blahblahblah and I need the actual url for the html.  The google.feedproxy url will redirect.  Is there a way using Javascript for me to get the url that is being redirected to?  Or even just a more elegant way of getting the html url?

Any help is appreciated.

答: Grab the text in <feedburner:origLink>.  it's available in most of the feedburner feeds.</p>

ContentLicense: CC BY-SA 2.5


问:
Jquery autocomplete, get the selected value from first textbox and populate the second textbox
I wanted to populate the textbox based on the selected value in the first textbox autocomplete. However not sure how to get the selected value from first textbox and query the database for the list of values to show as autocomplete values in the second text box.

My jquery code so far:

```<code>$(document).ready(function() {
    $("#autocomplete").autocomplete({
             minLength: 7,
             delay: 1000,
        source: function(request, response) {
            $.ajax({
                url: "autocomplete",
                dataType: "json",
                async:false,
                data: {
                    term : request.term,
                    // country_id : $("#country_id").val()
                },
                success: function(data) {
                    response(data);
                }

            });
        },
    });
});
</code>```

HTML:

```<code><input type="text" name="autocomplete-person" id="autocomplete-per" class="form-control" placeholder="Enter person name" />
  <input type="text" name="autocomplete-aadress" id="autocomplete-adrs" class="form-control" placeholder="show address of seelected name" />
</code>```

答: On the success of your ajax call, you can put a function that makes another ajax call and get the data for the second input, using the data that you have on your response.</p>

Body:
I wanted to populate the textbox based on the selected value in the first textbox autocomplete. However not sure how to get the selected value from first textbox and query the database for the list of values to show as autocomplete values in the second text box.

My jquery code so far:

$(document).ready(function() {
    $("#autocomplete").autocomplete({
             minLength: 7,
             delay: 1000,
        source: function(request, response) {
            $.ajax({
                url: "autocomplete",
                dataType: "json",
                async:false,
                data: {
                    term : request.term,
                    // country_id : $("#country_id").val()
                },
                success: function(data) {
                    response(data);
                }

            });
        },
    });
});

HTML:

<input type="text" name="autocomplete-person" id="autocomplete-per" class="form-control" placeholder="Enter person name" />
  <input type="text" name="autocomplete-aadress" id="autocomplete-adrs" class="form-control" placeholder="show address of seelected name" />


问:
BCP SQL Server Invalid Date Format
I have a load of data to import into a Azure SQL database. The table I'm copying too has a time stamp field in smalldatetime format and then another 195 fields of floats. I'm trying to BCP a csv file into the table. The CSV file has the exact same format. The timestamps are identical in format but I keep getting an invalid date format error.

Example of TimeStamp from database:

```<code>2017-11-05 12:00:00
</code>```

Example of TimeStamp from csv file:

```<code>2017-11-27 00:16:37
</code>```

I have tried using bcp with -n and a format file generated with -n and a format file generated with -x. All give the invalid date format error.

```<code>bcp dbo.Meters format nul -n -S <URL> -d <databasename> -U <username> -P <password> -f format.fmt

bcp dbo.Meters IN "output.csv" -S <URL> -d <databasename> -U <username> -P <password> -f format.fmt -t ,
</code>```

I have also tried using the -c option and this gives a different error:

```<code>Fractional second precision exceeds the scale specified in the parameter binding.
</code>```

I couldn't find much on google relating to this but it seems to mean there are fractions of seconds in the timestamps in the csv file which exceed the size of the smalldatetime format in the database table. None of the timestamps in the csv file have any fractional seconds though.

Does anyone know why it thinks the dates are in different formats? Thanks in advance!

Sample of CSV file can be downloaded here.

Create table statement with different field names can be downloaded here.

答:
Solution thanks to Nick.McDermaid:

I created a staging table on the database with all the same column names as the destination table but with each column type as varchar.

Then bcp worked fine using the character option -c to upload into the staging table.

```<code>bcp dbo.Staging IN "output.csv" -S <URL> -d <databasename> -U <username> -P <password> -c -t ,
</code>```

Then all it needs is the following SQL code to update the actual table and remove the data from the staging table.

```<code>INSERT INTO dbo.Meters
SELECT * FROM dbo.Staging
GO

DELETE FROM dbo.Staging
GO
</code>```

Title: BCP SQL Server Invalid Date Format

Body:
I have a load of data to import into a Azure SQL database. The table I'm copying too has a time stamp field in smalldatetime format and then another 195 fields of floats. I'm trying to BCP a csv file into the table. The CSV file has the exact same format. The timestamps are identical in format but I keep getting an invalid date format error.

Example of TimeStamp from database:

2017-11-05 12:00:00

Example of TimeStamp from csv file:

2017-11-27 00:16:37

I have tried using bcp with -n and a format file generated with -n and a format file generated with -x. All give the invalid date format error.

bcp dbo.Meters format nul -n -S <URL> -d <databasename> -U <username> -P <password> -f format.fmt

bcp dbo.Meters IN "output.csv" -S <URL> -d <databasename> -U <username> -P <password> -f format.fmt -t ,

I have also tried using the -c option and this gives a different error:

Fractional second precision exceeds the scale specified in the parameter binding.

I couldn't find much on google relating to this but it seems to mean there are fractions of seconds in the timestamps in the csv file which exceed the size of the smalldatetime format in the database table. None of the timestamps in the csv file have any fractional seconds though.

Does anyone know why it thinks the dates are in different formats? Thanks in advance!

Sample of CSV file can be downloaded here.

Create table statement with different field names can be downloaded here.

Body:
Solution thanks to Nick.McDermaid:

I created a staging table on the database with all the same column names as the destination table but with each column type as varchar.

Then bcp worked fine using the character option -c to upload into the staging table.

bcp dbo.Staging IN "output.csv" -S <URL> -d <databasename> -U <username> -P <password> -c -t ,

Then all it needs is the following SQL code to update the actual table and remove the data from the staging table.

INSERT INTO dbo.Meters
SELECT * FROM dbo.Staging
GO

DELETE FROM dbo.Staging
GO


问:
oracle sql request column ambiguously defined
I am working on oracle 11g and tried to execute this request

```<code>select code_mod,INTITULE,code_et,nom ,avg(note)
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by code_mod,code_et
order by code_mod;
</code>```

but it says!

```<code> ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:
Error on line 6, colunn 19
</code>```

what is wrong in it? if I execute this request, it works

```<code>select *
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET;
</code>```

答:
You have column with the same name in more than one table involved in the query, so you must prefix the column with proper table name eg:</p>

```<code>select
    EXAM.code_mod, INTITULE, EXAM.code_et, nom, avg(note)
from
    note, exam, module, etudiant
where
    note.CODE_EX = exam.CODE_EX
    and EXAM.CODE_MOD=MODULE.CODE_MOD
    and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by
    EXAMcode_mod, EXAM.code_et, INTITULE, nom
order by
    EXAM.code_mod;
</code>```

Body:
I am working on oracle 11g and tried to execute this request

select code_mod,INTITULE,code_et,nom ,avg(note)
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by code_mod,code_et
order by code_mod;

but it says!

 ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:
Error on line 6, colunn 19

what is wrong in it? if I execute this request, it works

select *
from note,exam,module,etudiant
where note.CODE_EX = exam.CODE_EX
and EXAM.CODE_MOD=MODULE.CODE_MOD
and NOTE.CODE_ET = ETUDIANT.CODE_ET;

Body:
You have column with the same name in more than one table involved in the query, so you must prefix the column with proper table name eg:

select
    EXAM.code_mod, INTITULE, EXAM.code_et, nom, avg(note)
from
    note, exam, module, etudiant
where
    note.CODE_EX = exam.CODE_EX
    and EXAM.CODE_MOD=MODULE.CODE_MOD
    and NOTE.CODE_ET = ETUDIANT.CODE_ET
group by
    EXAMcode_mod, EXAM.code_et, INTITULE, nom
order by
    EXAM.code_mod;


问:
ADD a column to SQL table
I am trying to add a column to this query in SQL as below-</p>

答:
you can use xml to store all result from query to a column</p>

```<code>CUSIP=(Select gs.holdingsymbol
           from dbo.holdingsymbol_tbl gs where gs.holdingsymboltypeid=2 for xml path(''))
</code>```

ContentLicense: CC BY-SA 4.0

Title: ADD a column to SQL table

Body:
you can use xml to store all result from query to a column

CUSIP=(Select gs.holdingsymbol
           from dbo.holdingsymbol_tbl gs where gs.holdingsymboltypeid=2 for xml path(''))


问:
Vue.js 2 & Axios Scope Issue
I worked with this "issue" before but I don't really remember how to get properly the results. I am using Vue 2 to load some data in variables that I can load in the HTML side:

```<code>window.Vue = require('vue');
window.axios = require('axios');

const app = new Vue({
    el: '#app',
    data: {
        operaciones: [],
        sopts: []
    },
    created: function() {
        this.loadOperationTypes();
        console.log(this.operaciones); <-- SC
    },
    methods: {
        loadOperationTypes: function() {
            axios.post('/api/operaciones')
            .then(response => {
                console.log(response.data); <-- FC
                this.operaciones = response.data
            })
            .catch(error => {
                this.operaciones = error;
            });
        }
    }
});
</code>```

If I write console.log(response.data) in the Axios function scope (FC) it  prints:

But if I write console.log(response.data) in the created_ function() {} scope, it prints:

I already tried to use this like:

```<code>axios.post('/api/operaciones')
.then(response => {
    console.log(response.data);
    app.operaciones = response.data
})
</code>```

And

```<code>var $this = this;
axios.post('/api/operaciones')
.then(response => {
    console.log(response.data);
    $this.operaciones = response.data
})
</code>```

But is the same, any clues?

Thanks in advance.

答:
This is really a separate issue from scope. Any of the solutions you tried in your question will work to properly set this.operaciones. The issue is that you are dealing with an asynchronous operation.

The line

```<code>console.log(this.operaciones);
</code>```

in created will always log an empty array. That is because loadOperationTypes performs a asynchronous operation; meaning it takes time.

You seem to be expecting that everything in loadOperationTypes will complete before the console.log is executed, but that is not the case. loadOperationTypes will initiate the post to the server, and then the code will continue and execute the console.log.

Once a response is received from the server at a later point in time, then operaciones is populated with the response.

console.clear()

const app = new Vue({
    el: '#app',
    data: {
        operaciones: [],
        sopts: []
    },
    created: function() {
        this.loadOperationTypes();
        console.log("THIS WILL ALWAYS BE AN EMPTY ARRAY", this.operaciones);
    },
    methods: {
        loadOperationTypes: function() {
            axios.post('https://httpbin.org/post', ["some", "data"])
            .then(response => {
                console.log("THIS SHOULD HAVE DATA", response.data.json);
                this.operaciones = response.data.json
            })
            .catch(error => {
                this.operaciones = error;
            });
        }
    },
    watch: {
      operaciones(newVal){
        console.log("THIS WILL HAVE DATA WHEN operaciones IS POPULATED", newVal)
      }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>

<div id="app"></div></code>```

Title: Vue.js 2 & Axios Scope Issue

Body:
I worked with this "issue" before but I don't really remember how to get properly the results. I am using Vue 2 to load some data in variables that I can load in the HTML side:

window.Vue = require('vue');
window.axios = require('axios');

const app = new Vue({
    el: '#app',
    data: {
        operaciones: [],
        sopts: []
    },
    created: function() {
        this.loadOperationTypes();
        console.log(this.operaciones); <-- SC
    },
    methods: {
        loadOperationTypes: function() {
            axios.post('/api/operaciones')
            .then(response => {
                console.log(response.data); <-- FC
                this.operaciones = response.data
            })
            .catch(error => {
                this.operaciones = error;
            });
        }
    }
});

If I write console.log(response.data) in the Axios function scope (FC) it  prints:

But if I write console.log(response.data) in the created_ function() {} scope, it prints:

I already tried to use this like:

axios.post('/api/operaciones')
.then(response => {
    console.log(response.data);
    app.operaciones = response.data
})

And

var $this = this;
axios.post('/api/operaciones')
.then(response => {
    console.log(response.data);
    $this.operaciones = response.data
})

But is the same, any clues?

Thanks in advance.

Body:
This is really a separate issue from scope. Any of the solutions you tried in your question will work to properly set this.operaciones. The issue is that you are dealing with an asynchronous operation.

The line

console.log(this.operaciones);

in created will always log an empty array. That is because loadOperationTypes performs a asynchronous operation; meaning it takes time.

You seem to be expecting that everything in loadOperationTypes will complete before the console.log is executed, but that is not the case. loadOperationTypes will initiate the post to the server, and then the code will continue and execute the console.log.

Once a response is received from the server at a later point in time, then operaciones is populated with the response.

console.clear()

const app = new Vue({
    el: '#app',
    data: {
        operaciones: [],
        sopts: []
    },
    created: function() {
        this.loadOperationTypes();
        console.log("THIS WILL ALWAYS BE AN EMPTY ARRAY", this.operaciones);
    },
    methods: {
        loadOperationTypes: function() {
            axios.post('https://httpbin.org/post', ["some", "data"])
            .then(response => {
                console.log("THIS SHOULD HAVE DATA", response.data.json);
                this.operaciones = response.data.json
            })
            .catch(error => {
                this.operaciones = error;
            });
        }
    },
    watch: {
      operaciones(newVal){
        console.log("THIS WILL HAVE DATA WHEN operaciones IS POPULATED", newVal)
      }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>

<div id="app"></div>


问:
Combining Lucene.NET and SQL Server to retrieve entities
I want to implement a full text search engine on my website, and I ll go with Lucene.NET. My main data are stored in SQL Server using EF6.

The issue that I have is that there are multiple entities that I want to search on (eg Posts, Comments, Messages, Entries, etc). Some entities have the property Title, some other models have the property Content, and some other have Description, or a combination of all these.

So, I am thinking of implementing only one custom lucene search table, like the one below:

```<code>public class LuceneSearchResult
{
    public ModelType ModelType { get; set; }
    public int GenericId { get; set; }

    public string Title { get; set; }
    public string Content { get; set; }
    public string Description { get; set; }
}
</code>```

Now, ModelType is an enum (integer) that refers to an entity class (eg Posts, Comments, Entries, etc), and GenericId is the Id (integer primary key) of the specified ModelType. For example, the unique primary key (even though Lucene does not recognise one) would be ModelType=Post, GenericId=3.

I use this approach so when I search for a string, I will use MultiFieldQueryParser to look up at Title, Content, Description columns of the LuceneSearchResult. From the results, I will get the ModelType, and GenericId, which then I will use to retrieve the correct object from SQL Server using EF6.

I am going with this approach, so I don't create many Lucene tables, one for each of my entities, which are many.

Questions:

Is this a correct approach to this problem?

Is it efficient to search in Lucene to get the object that contains the string, and then retrieve the whole entity from the SQL Server?

Would it be more efficient if, in the LuceneSearchResultin, I create only one column combining ModelType and GenericId?

Thanks :)

答:
Is this a correct approach to this problem?

Assuming it supports all your search requirements, yes.

Is it efficient to search in Lucene to get the object that contains the string, and then retrieve the whole entity from the Sql Server?

Yes, this is a pretty common pattern, really. If you need to present a list of search results for a user to select from, before displaying the entire selected entity (i.e. like a google search results page), you would probably want store enough data in lucene to present the search result list, and only query the database when the user selects one of them.

Would it be more efficient if, in the LuceneSearchResultin, I create only one column combining ModelType and GenericId?

No, I don't see any particular reason that you should do that. Presumably these fields will be stored and not indexed (that is, you won't be querying on these fields), so I don't believe there would be any significant impact from this.

Body:
I want to implement a full text search engine on my website, and I ll go with Lucene.NET. My main data are stored in SQL Server using EF6.

The issue that I have is that there are multiple entities that I want to search on (eg Posts, Comments, Messages, Entries, etc). Some entities have the property Title, some other models have the property Content, and some other have Description, or a combination of all these.

So, I am thinking of implementing only one custom lucene search table, like the one below:

public class LuceneSearchResult
{
    public ModelType ModelType { get; set; }
    public int GenericId { get; set; }

    public string Title { get; set; }
    public string Content { get; set; }
    public string Description { get; set; }
}

Now, ModelType is an enum (integer) that refers to an entity class (eg Posts, Comments, Entries, etc), and GenericId is the Id (integer primary key) of the specified ModelType. For example, the unique primary key (even though Lucene does not recognise one) would be ModelType=Post, GenericId=3.

I use this approach so when I search for a string, I will use MultiFieldQueryParser to look up at Title, Content, Description columns of the LuceneSearchResult. From the results, I will get the ModelType, and GenericId, which then I will use to retrieve the correct object from SQL Server using EF6.

I am going with this approach, so I don't create many Lucene tables, one for each of my entities, which are many.

Questions:

Is this a correct approach to this problem?

Is it efficient to search in Lucene to get the object that contains the string, and then retrieve the whole entity from the SQL Server?

Would it be more efficient if, in the LuceneSearchResultin, I create only one column combining ModelType and GenericId?

Thanks :)


问:
How can Xcode successfully access data the program cannot?
I'm running Xcode 9, Swift 4, High Sierra. In my code I have a mapping that, cut out and stripped down, includes this as the first lines in the closure:

```<code>let foo = graph.edges.map { (edge: Edge<Node>) -> (Int, Int) in
    print(edge)
    let fromvertex = (edge.from as? VertexElement)
        .
        .
        .
}
</code>```

There's a breakpoint on the line let from vertex ...

When run, the code is successful up to the breakpoint, which is where the problem starts. If at that point I execute po edge.from in the debugger, I get the expected result. If I step one line, and so execute the assignment, I get Thread 1: EXC_BAD_ACCESS (code=2, address=*whatever*). I can then execute po edge.from or even po (edge.from as? VertexElement) at that point and still get the expected results.

How can this be? There's no optional involved in edge.from, and I'd think the data is there correctly since the debugger finds it.

Edge is (as you'd expect) a generic class, with the first part of the definition being this:

```<code>public class Edge<T>: NSObject, NSCoding, Codable where T: Hashable {
    public typealias Weight = SimWeight

    public let from: Vertex<T>
    public let to: Vertex<T>
    public var weight: Weight? = nil
        .
        .
        .
}
</code>```

and then, the first part of Vertex, also a generic, looks like this:

```<code>public struct Vertex<T>: Equatable, Codable where T: Hashable {
    public var data: T
    public let index: Int
    public var gridX: Int?
    public var gridY: Int?
        .
        .
        .
}
</code>```

Node is another, concrete class (not a generic)

Finally, I have address sanitization turned on.

All that said, I neither can see where the exception is coming from, nor why the debugger can get the data when the program cannot. Any ideas what's wrong (or even how to debug it?)

答:
I can only suspect a compiler problem, because it's fixed now by reorganizing the code. Specifically, I created this method within Edge:

```<code>func indirectEdge() throws -> IndirectEdge {
    guard let fromvx = self.from as? VertexElement,
        let tovx = self.to as? VertexElement,
        let weight = self.weight else {throw TypeError.notVertex}
    return IndirectEdge(from: fromvx.index, to: tovx.index, weight: weight)
}
</code>```

and then changed the code at the top of this post to be:

```<code>guard let indirectEdges = try? graph.edges.map({ (edge) throws -> IndirectEdge in
    return try edge.indirectEdge()
}) else {throw SimFileError.unimplementedOperation(why: "Don't know how to encode this graph")}
    .
    .
    .
</code>```

At that point everything began to work, without the exceptions. (yes, I changed the later code to accept the IndirectEdge; that code is further on and shouldn't have any effect.) What I expected was that the exception would move into the indirectEdge method, but that's not what happened. It's good the code works now, but scary that I can't figure out why.

Body:
I'm running Xcode 9, Swift 4, High Sierra. In my code I have a mapping that, cut out and stripped down, includes this as the first lines in the closure:

let foo = graph.edges.map { (edge: Edge<Node>) -> (Int, Int) in
    print(edge)
    let fromvertex = (edge.from as? VertexElement)
        .
        .
        .
}

There's a breakpoint on the line let from vertex ...

When run, the code is successful up to the breakpoint, which is where the problem starts. If at that point I execute po edge.from in the debugger, I get the expected result. If I step one line, and so execute the assignment, I get Thread 1: EXC_BAD_ACCESS (code=2, address=*whatever*). I can then execute po edge.from or even po (edge.from as? VertexElement) at that point and still get the expected results.

How can this be? There's no optional involved in edge.from, and I'd think the data is there correctly since the debugger finds it.

Edge is (as you'd expect) a generic class, with the first part of the definition being this:

public class Edge<T>: NSObject, NSCoding, Codable where T: Hashable {
    public typealias Weight = SimWeight

    public let from: Vertex<T>
    public let to: Vertex<T>
    public var weight: Weight? = nil
        .
        .
        .
}

and then, the first part of Vertex, also a generic, looks like this:

public struct Vertex<T>: Equatable, Codable where T: Hashable {
    public var data: T
    public let index: Int
    public var gridX: Int?
    public var gridY: Int?
        .
        .
        .
}

Node is another, concrete class (not a generic)

Finally, I have address sanitization turned on.

All that said, I neither can see where the exception is coming from, nor why the debugger can get the data when the program cannot. Any ideas what's wrong (or even how to debug it?)

Body:
I can only suspect a compiler problem, because it's fixed now by reorganizing the code. Specifically, I created this method within Edge:

func indirectEdge() throws -> IndirectEdge {
    guard let fromvx = self.from as? VertexElement,
        let tovx = self.to as? VertexElement,
        let weight = self.weight else {throw TypeError.notVertex}
    return IndirectEdge(from: fromvx.index, to: tovx.index, weight: weight)
}

and then changed the code at the top of this post to be:

guard let indirectEdges = try? graph.edges.map({ (edge) throws -> IndirectEdge in
    return try edge.indirectEdge()
}) else {throw SimFileError.unimplementedOperation(why: "Don't know how to encode this graph")}
    .
    .
    .

At that point everything began to work, without the exceptions. (yes, I changed the later code to accept the IndirectEdge; that code is further on and shouldn't have any effect.) What I expected was that the exception would move into the indirectEdge method, but that's not what happened. It's good the code works now, but scary that I can't figure out why.


问:
Data Virtualization and provisioning tools such as Delphix
Our DB department is considering purchasing a Delphix license, and I'm wondering if there are any other tools that provide the same features. Features that we need in our work environment that are provided by delphix are:

The ability to virtualize a whole database and store it in a sepearate server

Compresses the database to 1/3 of its actual size

gives the ability to use the compresses the database (in the delphix engine) without the need to clone the database to the target, instead, the engine provisions the compressed the db to the target in a matter of few minutes

Any update made in the target are unique and do not affect the data in other targets

All changes made are stored in the engine with the ability to rewind if needed

I looked into some tools such as informatica and Denodo bu I'm not an expert in the topic and can't tell whether they provide the same as Delphix or not.

答:
Denodo is a data virtualization tool, so does not mirror data (except for  caching).  It can provide a single point of interface and blend multiple data sources.  It has no 'rewind' capabilities'.

Informatica's most popular tool is Powercenter, an ETL/DWH tool. It won't store data, compress or rewind. There may be other Informatica solutions closer to what you're looking for.


问:
GNU parallel \bin\bash command not found
I'm following this tutorial here here, I installed GNU parallel and tested it using the ping command as per the read me here.

Trying:

```<code>parallel –j8 ./ A_asymm_refine.sh {} ::: {1..8}
</code>```

Gives:

```<code>[user@machine Documents]$ parallel –j8 ./ A_asymm_refine.sh {} ::: {1..8}
Academic tradition requires you to cite works you base your article on.
If you use programs that use GNU Parallel to process data for an article in a
scientific publication, please cite:

  O. Tange (2011): GNU Parallel - The Command-Line Power Tool,
  ;login: The USENIX Magazine, February 2011:42-47.

This helps funding further development; AND IT WON'T COST YOU A CENT.
If you pay 10000 EUR you should feel free to use GNU Parallel without citing.

To silence this citation notice: run 'parallel --citation'.

/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
</code>```

How can I troubleshoot the problem?

答:
Try this instead:</p>

```<code>parallel -j8 ./A_asymm_refine.sh {} ::: {1..8}
</code>```

Body:
I'm following this tutorial here here, I installed GNU parallel and tested it using the ping command as per the read me here.

Trying:

parallel –j8 ./ A_asymm_refine.sh {} ::: {1..8}

Gives:

[user@machine Documents]$ parallel –j8 ./ A_asymm_refine.sh {} ::: {1..8}
Academic tradition requires you to cite works you base your article on.
If you use programs that use GNU Parallel to process data for an article in a
scientific publication, please cite:

  O. Tange (2011): GNU Parallel - The Command-Line Power Tool,
  ;login: The USENIX Magazine, February 2011:42-47.

This helps funding further development; AND IT WON'T COST YOU A CENT.
If you pay 10000 EUR you should feel free to use GNU Parallel without citing.

To silence this citation notice: run 'parallel --citation'.

/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found
/usr/bin/bash: $'\342\200\223j8': command not found

How can I troubleshoot the problem?

Body:
Try this instead:

parallel -j8 ./A_asymm_refine.sh {} ::: {1..8}


问:
Python -- Including Duplicates in re.findall()
I'm trying to extract all titles from an Amazon HTML source. The problem I have is that when I do re.findall(), it doesn't keep duplicate titles.

Is there a way to keep duplicate titles with re.findall() ?

答:
I'm not the master of regex, but when I use re.findall() I see duplicates. Post your code and we will have something to work with.

```<code>import re
string = "Give me an example, me an example"
re.findall('me', string)
>>> ['me', 'me']
</code>```

Body:
I'm not the master of regex, but when I use re.findall() I see duplicates. Post your code and we will have something to work with.

import re
string = "Give me an example, me an example"
re.findall('me', string)
>>> ['me', 'me']


问:
targeting live_videos using facebook graph API 2.8
I've created a Live_Video following the instructions i've found here:
https://developers.facebook.com/docs/videos/live-video/production-broadcasts?locale=en_US#geotarget
with the API 2.8 using the following parameters:
planned_start_time=1512583432 and

targeting="countries": [ "CH" ]

got the following response:

    {
      "id": "1694620797236299",

      "stream_url": "rtmp://live-api-a.facebook.com:80/rtmp/1694620797236299?ds=1&a=ATg9BhMPftTTsfv3",

      "secure_stream_url": "rtmps://live-api-a.facebook.com:443/rtmp/1694620797236299?ds=1&a=ATg9BhMPftTTsfv3",

      "stream_secondary_urls": [
      ],
      "secure_stream_secondary_urls": [
      ]
    }

so, everything seems fine, BUT:

How do i check that the vision of the video is actually restricted to
Switzerland ?
Where is this info stored ?
How do I retrieve it ?

Thanks for the help.
greetings-
cp

答:
through the UI:
there is a gear wheel on the top part of the post that
responds to mouseOver with the geoblocking info of the livestreaming
If the livestreaming is blocked it reflects there.

Still working on getting the same info from the API ...


问:
change image opacity using javascript
how can I change image opacity using javascript? I'm going to create a fading effect using javascript, is there any sample? is there anything like image.opacity that can be changed through JS code? how is it set?

thanks

答:
First set the opacity explicitly in your HTML thus:

```<code><div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>
</code>```

otherwise it is 0 or null

this is then in my .js file

```<code>document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });
</code>```

Title: change image opacity using javascript

Body:
First set the opacity explicitly in your HTML thus:

<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>

otherwise it is 0 or null

this is then in my .js file

document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });


问:
Unmarshal JSON returns empty struct
Here's my JSON file:

```<code>{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
</code>```

Here's my code:

```<code>package config

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
    "os"
)

type ConfigType struct {
    Database DatabaseType `json:"database"`
}

type DatabaseType struct {
    Dialect string `json:"dialect"`
    Host string `json:"host"`
    User string `json:"user"`
    Pass string `json:"pass"`
    Name string `json:"name"`
}

func Config() {
    file, err := os.Open("./config/config.json")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    fileBytes, _ := ioutil.ReadAll(file)

    var Conf ConfigType
    json.Unmarshal(fileBytes, &Conf)

    fmt.Printf("File content:\n%v", string(fileBytes))
    fmt.Printf("Conf: %v\n", Conf)
    fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}
</code>```

And here is the output:

```<code>File content:
{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
Conf: {{    }}
Content:

Type: config.ConfigType%
</code>```

The package is imported to main and just the Config function is executed. I've looked at a lot of similar questions and it seems like I almost have the exact same code as in the answers but I can't get my code to work.

答:
Errors are not graciously returned to you to omit, unless you wanna get clueless about why your app doesn't work. Don't omit errors! ioutil.ReadAll() returns an error. json.Unmarshal() returns an error. Do check those!

Should you added error check, json.Unmarshal() returns:

```<code>panic: invalid character '"' after object key:value pair
</code>```

Try this on the Go Playground.

Your input JSON is invalid. You have a missing comma in the "dialect" line. Adding the missing comma (try it on the Go Playground):

```<code>Conf: {{mysql localhost root  sws}}
Content:
 localhost
Type: main.ConfigType
</code>```

Title: Unmarshal JSON returns empty struct

Body:
Here's my JSON file:

{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}

Here's my code:

package config

import (
    "fmt"
    "encoding/json"
    "io/ioutil"
    "log"
    "os"
)

type ConfigType struct {
    Database DatabaseType `json:"database"`
}

type DatabaseType struct {
    Dialect string `json:"dialect"`
    Host string `json:"host"`
    User string `json:"user"`
    Pass string `json:"pass"`
    Name string `json:"name"`
}

func Config() {
    file, err := os.Open("./config/config.json")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    fileBytes, _ := ioutil.ReadAll(file)

    var Conf ConfigType
    json.Unmarshal(fileBytes, &Conf)

    fmt.Printf("File content:\n%v", string(fileBytes))
    fmt.Printf("Conf: %v\n", Conf)
    fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf)
}

And here is the output:

File content:
{
    "database": {
        "dialect": "mysql"
        "host": "localhost",
        "user": "root",
        "pass": "",
        "name": "sws"
    }
}
Conf: {{    }}
Content:

Type: config.ConfigType%

The package is imported to main and just the Config function is executed. I've looked at a lot of similar questions and it seems like I almost have the exact same code as in the answers but I can't get my code to work.

Body:
Errors are not graciously returned to you to omit, unless you wanna get clueless about why your app doesn't work. Don't omit errors! ioutil.ReadAll() returns an error. json.Unmarshal() returns an error. Do check those!

Should you added error check, json.Unmarshal() returns:

panic: invalid character '"' after object key:value pair

Try this on the Go Playground.

Your input JSON is invalid. You have a missing comma in the "dialect" line. Adding the missing comma (try it on the Go Playground):

Conf: {{mysql localhost root  sws}}
Content:
 localhost
Type: main.ConfigType


问:
Angular get value of dynamically generated html elements
I am generating html div elements dynamically to render a JSON response. I want get values of elements inside those div elements using angularjs but cant seem to do that. Here is my code:

HTML:

```<code><div class="col-sm-4" ng-repeat="product in products">
  <div class="product-image-wrapper">
    <div class="single-products">
      <div class="productinfo text-center">
        <!-- <img src="images/home/product1.jpg" alt="" /> -->
        <img data-ng-src="data:image/png;base64,{{product.prod_icon_base64}}" alt="" />
        <h2 class="price" id="p">{{product.prod_price}}</h2>
        <p>{{product.prod_name}}</p>
        <a ng-click="getPrice()" value="{{product.prod_price}}" class=" btn btn-default add-to-cart "><i class="fa fa-shopping-cart "></i>Add to cart</a>
      </div>
      <div class="product-overlay ">
        <div class="overlay-content ">
          <h2 class="price " id="p ">{{product.prod_price}}</h2>

          <p>{{product.prod_name}}</p>
          <a ng-click="getPrice() " class="btn btn-default add-to-cart " value="{{product.prod_price}} "><i class="fa fa-shopping-cart "></i>Add to cart</a>
        </div>
      </div>
    </div>

  </div>
</div>
</div>
</code>```

JS:

```<code>$scope.getPrice=function(){
    var price=document.getElementsByClassName(".price").val()
    alert(price.data)
}
</code>```

But this is not working. How can i fix this?

答:
Approach is all wrong and you are trying to use a jQuery method on a collection of elements.

An  tag also has no value property

Pass the product object into the ng-click function.

```<code><a ng-click="getPrice(product)" class=" btn btn-default add-to-cart ">
    <i class="fa fa-shopping-cart "></i>Add to cart
</a>
</code>```

JS

```<code>$scope.getPrice=function(product){
    console.log(product.prod_price);
}
</code>```

Body:
I am generating html div elements dynamically to render a JSON response. I want get values of elements inside those div elements using angularjs but cant seem to do that. Here is my code:

HTML:

{{product.prod_price}}

{{product.prod_name}}

        Add to cart

{{product.prod_price}}

{{product.prod_name}}

          Add to cart

JS:

$scope.getPrice=function(){
    var price=document.getElementsByClassName(".price").val()
    alert(price.data)
}

But this is not working. How can i fix this?

Body:
Approach is all wrong and you are trying to use a jQuery method on a collection of elements.

An <a> tag also has no value property

Pass the product object into the ng-click function.

<a ng-click="getPrice(product)" class=" btn btn-default add-to-cart ">
    <i class="fa fa-shopping-cart "></i>Add to cart
</a>

JS

$scope.getPrice=function(product){
    console.log(product.prod_price);
}


问:
WCF with discovery fails with socket not valid in its context on XP?
I'm trying to use WCF's discovery mechanism in .NET 4.0.  It works on Windows 7 but fails on an XP machine with a socket exception saying that "the requested address is not valid in its context" (the endpoint is soap.udp://239.255.255.250:3702).

Is the Windows 7 vs XP a red herring?  netstat doesn't seem to show any conflicts.  What am I missing here?

I've created a simplified test service that shows the problem using the following config:

```<code><configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata/>
          <serviceDiscovery />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <endpointDiscovery />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="HelloWorldService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Demo"/>
          </baseAddresses>
        </host>
        <endpoint kind="mexEndpoint" />
        <endpoint kind="udpDiscoveryEndpoint" />
        <endpoint contract="Test.IHelloWorld"
                  address="/Hello"
                  binding="basicHttpBinding" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
</code>```

答: Is the XP machine behind a firewall or router? To be specific, does the address 239.255.255.250 really belong to the XP machine, or does it actually use a NAT address? Try running ipconfig to see what it thinks it has.</p>

Body:
I'm trying to use WCF's discovery mechanism in .NET 4.0.  It works on Windows 7 but fails on an XP machine with a socket exception saying that "the requested address is not valid in its context" (the endpoint is soap.udp://239.255.255.250:3702).

Is the Windows 7 vs XP a red herring?  netstat doesn't seem to show any conflicts.  What am I missing here?

I've created a simplified test service that shows the problem using the following config:

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata/>
          <serviceDiscovery />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <endpointDiscovery />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="HelloWorldService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Demo"/>
          </baseAddresses>
        </host>
        <endpoint kind="mexEndpoint" />
        <endpoint kind="udpDiscoveryEndpoint" />
        <endpoint contract="Test.IHelloWorld"
                  address="/Hello"
                  binding="basicHttpBinding" />
      </service>
    </services>
  </system.serviceModel>
</configuration>


问:
Subtracting a value from each element in a 2d array within a dictionary
I am trying to subtract a value (dark_val) from all values within a 2D array that is within a dictionary. Currently I am looping through each key and extracting the values to a list and then using list comprehension:

```<code>def dark_subtract(dic, dark_val):

    band_values = []

    # loop through the keys and variables to lists
    for key, value in dic.items():
        band_values.append(value)

    band_values[:] = [x - dark_val for x in band_values]

    return band_values
</code>```

Ideally, however, I would like to iterate within the dictionary so that I returning a dictionary rather than a list (i.e. band_values).

I have tried the following and it doesn't bring up any errors but doesn't change the values either:

```<code>def dark_subtract(dic, dark_val):
    """
    Must be a dictionary input and a variable containing dark value
    """
    for entry in dic:
        if type(dic[entry]) is dict:
            dic[entry] = dark_subtract(dic[entry])
        else:
            dic[entry] - 100

    return dic
    print dic
</code>```

The way I call the function is as follows:

```<code>dark_dic = dark_subtract(dic, d_value)
print "This is the original values:\n", dic
print "This is the dark current corrected values:\n", dark_dic
</code>```

When printed the dictionary dic looks like:

```<code>{'Band_1': array([[26176, 25920, 26816, ..., 53632, 53440, 52544],
       [25408, 24448, 23872, ..., 46592, 47040, 49216],
       [27264, 25024, 25792, ..., 50368, 51648, 51648],
       ...,
       [32960, 32576, 32512, ..., 13568, 14528, 14720],
       [38784, 36416, 35648, ..., 18816, 15680, 16512],
       [33152, 32512, 32192, ..., 14464, 14720, 14784]], dtype=uint16)}
</code>```

The dark_val is just an integer (currently set to 75)

Any ideas?

答:
You already have a NumPy array. Therefore, you can subtract the integer directly:</p>

```<code> for key, value in dic.items():
      dic[key] = value - dark_val
</code>```

Body:
I am trying to subtract a value (dark_val) from all values within a 2D array that is within a dictionary. Currently I am looping through each key and extracting the values to a list and then using list comprehension:

def dark_subtract(dic, dark_val):

    band_values = []

    # loop through the keys and variables to lists
    for key, value in dic.items():
        band_values.append(value)

    band_values[:] = [x - dark_val for x in band_values]

    return band_values

Ideally, however, I would like to iterate within the dictionary so that I returning a dictionary rather than a list (i.e. band_values).

I have tried the following and it doesn't bring up any errors but doesn't change the values either:

def dark_subtract(dic, dark_val):
    """
    Must be a dictionary input and a variable containing dark value
    """
    for entry in dic:
        if type(dic[entry]) is dict:
            dic[entry] = dark_subtract(dic[entry])
        else:
            dic[entry] - 100

    return dic
    print dic

The way I call the function is as follows:

dark_dic = dark_subtract(dic, d_value)
print "This is the original values:\n", dic
print "This is the dark current corrected values:\n", dark_dic

When printed the dictionary dic looks like:

{'Band_1': array([[26176, 25920, 26816, ..., 53632, 53440, 52544],
       [25408, 24448, 23872, ..., 46592, 47040, 49216],
       [27264, 25024, 25792, ..., 50368, 51648, 51648],
       ...,
       [32960, 32576, 32512, ..., 13568, 14528, 14720],
       [38784, 36416, 35648, ..., 18816, 15680, 16512],
       [33152, 32512, 32192, ..., 14464, 14720, 14784]], dtype=uint16)}

The dark_val is just an integer (currently set to 75)

Any ideas?

Body:
You already have a NumPy array. Therefore, you can subtract the integer directly:

 for key, value in dic.items():
      dic[key] = value - dark_val


问:
Change button text on click
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

```<code>onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });
</code>```

My question is: How can I do this thing in HTML, by using the <button> tag?

答:
HTML

<button id="but" onclick="clickme()">click me </button>

JS

```<code><script>
function clickme(){
document.getElementById("but").innerHTML = "changed";
}
</script>
</code>```

Title: Change button text on click

Body:
So, I followed an online course from www.code.org to accomodate myself with JavaScript. I used elements such as setProperty(); and onEvent();. I used an online editor to add a button and the following code to change the button's text when the user clicks it:

onEvent("button1","click", function()
 {
  setProperty("button1","text","Hello there!");
 });

My question is: How can I do this thing in HTML, by using the <button> tag?

Body:
HTML

<button id="but" onclick="clickme()">click me </button>

JS

<script>
function clickme(){
document.getElementById("but").innerHTML = "changed";
}
</script>


问:
How does spock determine which iteratable is greater than the other?
I'm reading this doc in spock: http://spockframework.org/spock/docs/1.1/data_driven_testing.html and came across Data Variable Assignment part which has this snippet of code:

```<code>a = 3
b = Math.random() * 100
c = a > b ? a : b
</code>```

but what if I tried using an iterable

```<code>a << [6, 2, 0]
b << [4, 10, 10]
c = a > b ? a : b
</code>```

答:
It doesn't.

Spock does heavy rewriting of your test specifications (by registering AST transformations with the groovy compiler).

For the where: clause it creates code to iterate over to provided lists for a and b (and assigning each value in turn to these local variables) and it runs the code for c = a > b ? a : b on each iteration.

The code transformation for the where: clause is located in the class org.spockframework.compiler.WhereBlockRewriter (https://github.com/spockframework/spock/blob/master/spock-core/src/main/java/org/spockframework/compiler/WhereBlockRewriter.java)

Body:
I'm reading this doc in spock: http://spockframework.org/spock/docs/1.1/data_driven_testing.html and came across Data Variable Assignment part which has this snippet of code:

a = 3
b = Math.random() * 100
c = a > b ? a : b

but what if I tried using an iterable

a << [6, 2, 0]
b << [4, 10, 10]
c = a > b ? a : b


问:
Svn change directory
I want to change the directory where I add files using svn. I tried

```<code>svn switch --relocate https://old_directory https://new_directory
</code>```

It runs with no error but when I do svn info the URL is still the old one (actually it looks like svn+ssh://old_directory instead of https://old_directory).
I also tried

```<code> svn switch --relocate `svn+ssh://old_directory svn+ssh://new_directory`
</code>```

but I get this message svn: Relocate can only change the repository part of an URL and still nothing changes.

Please can someone tell me how to do this?

答:
You don't need the --relocate switch, that switch is actually deprecated if you're using a more recent version of svn.

Simply navigating to your checked out directory in the command line and calling svn switch https://new_directory should fix the issue.

Now, if it's the same directory but the URL has changed, that's a completely different story. Then you'd want to use svn relocate. Again you'd have to navigate to the directory (cd) via the command line and run:

```<code>svn relocate https://new_directory
</code>```

Here is a quote from redbean that helps me understand the difference. Judging by your wording in the first sentence it sounds like you just want to change directories, but in the chance that I didn't interpret it correctly, here is the svn's explanation:

Users often get confused about the difference between svn switch and svn relocate. Here's the rule of thumb:

If the working copy needs to reflect a new directory within the repository, use svn switch.

If the working copy still reflects the same repository directory, but the location of the repository itself has changed, use svn relocate.

Title: Svn change directory

Body:
I want to change the directory where I add files using svn. I tried

svn switch --relocate https://old_directory https://new_directory

It runs with no error but when I do svn info the URL is still the old one (actually it looks like svn+ssh://old_directory instead of https://old_directory).
I also tried

 svn switch --relocate `svn+ssh://old_directory svn+ssh://new_directory`

but I get this message svn: Relocate can only change the repository part of an URL and still nothing changes.

Please can someone tell me how to do this?

Body:
You don't need the --relocate switch, that switch is actually deprecated if you're using a more recent version of svn.

Simply navigating to your checked out directory in the command line and calling svn switch https://new_directory should fix the issue.

Now, if it's the same directory but the URL has changed, that's a completely different story. Then you'd want to use svn relocate. Again you'd have to navigate to the directory (cd) via the command line and run:

svn relocate https://new_directory

Here is a quote from redbean that helps me understand the difference. Judging by your wording in the first sentence it sounds like you just want to change directories, but in the chance that I didn't interpret it correctly, here is the svn's explanation:

Users often get confused about the difference between svn switch and svn relocate. Here's the rule of thumb:

If the working copy needs to reflect a new directory within the repository, use svn switch.

If the working copy still reflects the same repository directory, but the location of the repository itself has changed, use svn relocate.


问:
nginx alias to reflect in PHP_SELF (fpm)
I'm having a file structure like this:

nginx default root:

```<code>~/marketplace/
</code>```

attempting to create an alias to:

```<code>~/marketplace/endpoints/sdk/tag.php
</code>```

under URI location /tagframe.htm

Basically, when I go to http://marketplace/tagframe.htm?t=1&c=2 I need to route the request to ~/marketplace/endpoints/sdk/tag.php with the $query_string preserved

While this works:

```<code>location /tagframe.htm {
    try_files $uri /endpoints/sdk/tag.php$is_args$args;
}
</code>```

It populates PHP_SELF with the actual path of the file (tag.php), and not URI part (tagframe.htm) which is what I need - for it to think that /tagframe.htm is a real file and populate it into PHP_SELF.

For example Lighttpd does it through its

```<code>alias.url /tagframe.htm => ~/marketplace/endpoints/sdk/tag.php
</code>```

And PHP_SELF shows me /tagframe.htm

An attempt to trick it was:

```<code>location /tagframe.htm {
    alias $root_path/endpoints/sdk;

    rewrite (.*) /endpoints/sdk/tag.php?$query_string;

    include php-fpm;
}
</code>```

P.S $root_path is my map default value of project root (hacky), php-fpm file is default fast_cgi proxy to php:

```<code>location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/tmp/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SERVER_NAME $host;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}
</code>```

Any ideas what am I doing wrong?

答:
You're misusing PHP_SELF. It's intended to show the actual script file name that is running, not the URL.

What you seem to be looking for is REQUEST_URI, i.e.:

```<code>$_SERVER["REQUEST_URI"]
</code>```

OwnerDisplayName: Boris Lapouga

Body:
I'm having a file structure like this:

nginx default root:

~/marketplace/

attempting to create an alias to:

~/marketplace/endpoints/sdk/tag.php

under URI location /tagframe.htm

Basically, when I go to http://marketplace/tagframe.htm?t=1&c=2 I need to route the request to ~/marketplace/endpoints/sdk/tag.php with the $query_string preserved

While this works:

location /tagframe.htm {
    try_files $uri /endpoints/sdk/tag.php$is_args$args;
}

It populates PHP_SELF with the actual path of the file (tag.php), and not URI part (tagframe.htm) which is what I need - for it to think that /tagframe.htm is a real file and populate it into PHP_SELF.

For example Lighttpd does it through its

alias.url /tagframe.htm => ~/marketplace/endpoints/sdk/tag.php

And PHP_SELF shows me /tagframe.htm

An attempt to trick it was:

location /tagframe.htm {
    alias $root_path/endpoints/sdk;

    rewrite (.*) /endpoints/sdk/tag.php?$query_string;

    include php-fpm;
}

P.S $root_path is my map default value of project root (hacky), php-fpm file is default fast_cgi proxy to php:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/tmp/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SERVER_NAME $host;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

Any ideas what am I doing wrong?

Body:
You're misusing PHP_SELF. It's intended to show the actual script file name that is running, not the URL.

What you seem to be looking for is REQUEST_URI, i.e.:

$_SERVER["REQUEST_URI"]

OwnerDisplayName: Michael Hampton


问:
Golang Variadic Constructor Function? Create a Person Contact in Golang?
I am making a contact application for learning.  I have a NewContact().

```<code>// Contact - defines the fields of an entire Contact
type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}
// NewContact - Creates a new contact
func NewContact(first string, last string) *Contact {
    c := &Contact{}
    c.FirstName = first
    c.LastName = last

    return c

}
</code>```

This does work however....I can require a FirstName and LastName BUT how would I make ALL the other field arguments optional?  Thank you in advance.

答:
Only your use case, domain and the design can tell which approach is preferable. But you can:

1 - Use chaining methods:

```<code>func main() {
    c := new(Contact)
    c = c.SetEmail("...").SetFirstName("...").SetLastName("...")
}

type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}

func (c *Contact) SetTitle(v string) *Contact     { c.Title = v; return c }
func (c *Contact) SetFirstName(v string) *Contact { c.FirstName = v; return c }
func (c *Contact) SetLastName(v string) *Contact  { c.LastName = v; return c }
func (c *Contact) SetHomePhone(v string) *Contact { c.HomePhone = v; return c }
func (c *Contact) SetWorkPhone(v string) *Contact { c.WorkPhone = v; return c }
func (c *Contact) SetMobile(v string) *Contact    { c.Mobile = v; return c }
func (c *Contact) SetAddress(v *Address) *Contact { c.Address = v; return c }
func (c *Contact) SetEmail(v string) *Contact     { c.Email = v; return c }
</code>```

2 - Use functional options:

```<code>func main() {
    c := NewContact(FirstName("..."), LastName("..."))
    _ = c
}

type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}

func NewContact(options ...ContactOption) *Contact {
    c := new(Contact)
    for _, opt := range options {
        opt(c)
    }
    return c
}

type ContactOption func(*Contact)

func Title(v string) ContactOption        { return func(c *Contact) { c.Title = v } }
func FirstName(v string) ContactOption    { return func(c *Contact) { c.FirstName = v } }
func LastName(v string) ContactOption     { return func(c *Contact) { c.LastName = v } }
func HomePhone(v string) ContactOption    { return func(c *Contact) { c.HomePhone = v } }
func WorkPhone(v string) ContactOption    { return func(c *Contact) { c.WorkPhone = v } }
func Mobile(v string) ContactOption       { return func(c *Contact) { c.Mobile = v } }
func SetAddress(v *Address) ContactOption { return func(c *Contact) { c.Address = v } }
func Email(v string) ContactOption        { return func(c *Contact) { c.Email = v } }
</code>```

Body:
I am making a contact application for learning.  I have a NewContact().

// Contact - defines the fields of an entire Contact
type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}
// NewContact - Creates a new contact
func NewContact(first string, last string) *Contact {
    c := &Contact{}
    c.FirstName = first
    c.LastName = last

    return c

}

This does work however....I can require a FirstName and LastName BUT how would I make ALL the other field arguments optional?  Thank you in advance.

Body:
Only your use case, domain and the design can tell which approach is preferable. But you can:

1 - Use chaining methods:

func main() {
    c := new(Contact)
    c = c.SetEmail("...").SetFirstName("...").SetLastName("...")
}

type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}

func (c *Contact) SetTitle(v string) *Contact     { c.Title = v; return c }
func (c *Contact) SetFirstName(v string) *Contact { c.FirstName = v; return c }
func (c *Contact) SetLastName(v string) *Contact  { c.LastName = v; return c }
func (c *Contact) SetHomePhone(v string) *Contact { c.HomePhone = v; return c }
func (c *Contact) SetWorkPhone(v string) *Contact { c.WorkPhone = v; return c }
func (c *Contact) SetMobile(v string) *Contact    { c.Mobile = v; return c }
func (c *Contact) SetAddress(v *Address) *Contact { c.Address = v; return c }
func (c *Contact) SetEmail(v string) *Contact     { c.Email = v; return c }

2 - Use functional options:

func main() {
    c := NewContact(FirstName("..."), LastName("..."))
    _ = c
}

type Contact struct {
    Title     string
    FirstName string
    LastName  string
    HomePhone string
    WorkPhone string
    Mobile    string
    Address   *Address
    Email     string
}

func NewContact(options ...ContactOption) *Contact {
    c := new(Contact)
    for _, opt := range options {
        opt(c)
    }
    return c
}

type ContactOption func(*Contact)

func Title(v string) ContactOption        { return func(c *Contact) { c.Title = v } }
func FirstName(v string) ContactOption    { return func(c *Contact) { c.FirstName = v } }
func LastName(v string) ContactOption     { return func(c *Contact) { c.LastName = v } }
func HomePhone(v string) ContactOption    { return func(c *Contact) { c.HomePhone = v } }
func WorkPhone(v string) ContactOption    { return func(c *Contact) { c.WorkPhone = v } }
func Mobile(v string) ContactOption       { return func(c *Contact) { c.Mobile = v } }
func SetAddress(v *Address) ContactOption { return func(c *Contact) { c.Address = v } }
func Email(v string) ContactOption        { return func(c *Contact) { c.Email = v } }


问:
Using For loop in Pandas with groupby function
unGrouped is a dataframe that looks like this:

```<code>         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN
</code>```

I have the following code:

```<code>for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount
</code>```

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

答:
Using numpy

```<code>v, n = np.unique(df.borough.values, return_counts=True)
d=dict(zip(v, n))
d['BRONX']
Out[218]: 2
</code>```

Body:
unGrouped is a dataframe that looks like this:

         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN

I have the following code:

for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

Body:
Using numpy

v, n = np.unique(df.borough.values, return_counts=True)
d=dict(zip(v, n))
d['BRONX']
Out[218]: 2


问:
Printing address of struct members in flexible member array of structs
I have a struct which contains a flexible member array:

```<code>typedef struct bar {
  uint8_t  bar_a;
  uint16_t bar_b;
} bar_t;

typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    *bars[];
} foo_t;
</code>```

I'm trying to use foo and bar as data structures to copy data over to uint8_t buffer[50].

```<code>#define NUMBER_OF_BARS 1;
static uint8_t buffer[50];

static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    memcpy(&foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}

int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n",
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n",
           &foo->bars[i], &foo->bars[i]->bar_a, &foo->bars[i]->bar_b);
  }
  return 0;
}
</code>```

Now I would have expected this to print the following (i.e. a contiguous block of memory):

```<code>foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x1f95 0x1f96]
</code>```

Instead, I'm getting the following:

```<code>foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x0 0x1]
</code>```

What am I doing wrong?

答:
Since foo.bars is an array of pointers, you need to allocate memory for the objects they point to, and then copy to that memory.

```<code>static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    foo->bars[i] = malloc(sizeof(bar_t));
    memcpy(foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}
</code>```

Or you could declare it as an array of structures instead of pointers.

```<code>typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    bars[];
} foo_t;
</code>```

and change how you access them in main()

```<code>int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n",
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n",
           &foo->bars[i], &foo->bars[i].bar_a, &foo->bars[i].bar_b);
  }
  return 0;
}
</code>```

Body:
I have a struct which contains a flexible member array:

typedef struct bar {
  uint8_t  bar_a;
  uint16_t bar_b;
} bar_t;

typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    *bars[];
} foo_t;

I'm trying to use foo and bar as data structures to copy data over to uint8_t buffer[50].

#define NUMBER_OF_BARS 1;
static uint8_t buffer[50];

static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    memcpy(&foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}

int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n",
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n",
           &foo->bars[i], &foo->bars[i]->bar_a, &foo->bars[i]->bar_b);
  }
  return 0;
}

Now I would have expected this to print the following (i.e. a contiguous block of memory):

foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x1f95 0x1f96]

Instead, I'm getting the following:

foo ... [0x1f92 0x1f92 0x1f94 0x1f95]
bar ... [0x1f95 0x0 0x1]

What am I doing wrong?

Body:
Since foo.bars is an array of pointers, you need to allocate memory for the objects they point to, and then copy to that memory.

static foo_t *
copy_to_buf(void *buf)
{
  int i;
  foo_t *foo = (foo_t *)buf;
  bar_t bar;

  /* Set foo_a */
  foo->foo_a = 1;
  foo->n_bars = NUMBER_OF_BARS;
  /* Set bars */
  for(i=0; i < foo->n_bars; i++) {
    bar.bar_a = 0xFF;
    bar.bar_b = 1234;
    foo->bars[i] = malloc(sizeof(bar_t));
    memcpy(foo->bars[i], &bar, sizeof(bar_t));
  }
  return foo;
}

Or you could declare it as an array of structures instead of pointers.

typedef struct foo {
  uint16_t foo_a;
  uint_8_t n_bars;
  bar_t    bars[];
} foo_t;

and change how you access them in main()

int main()
{
  int i;
  foo_t *foo = copy_to_buf(&buffer);
  printf("foo ... [%p %p %p %p]\n",
         &foo, &foo->foo_a, &foo->n_bars &foo->bars);
  for(i=0; i < foo->n_bars; i++) {
    printf("bar ... [%p %p %p]\n",
           &foo->bars[i], &foo->bars[i].bar_a, &foo->bars[i].bar_b);
  }
  return 0;
}


问:
babelHelpers.js throws Super expression must either be null or a function, not undefined
I just updated to RN 0.27 from 0.24 and all these "Super expression must either be null or a function, not undefined" errors started to pop up. After some research I realized there was a breaking change in RN 0.26 so i changed my import statements as indicated in
https://github.com/facebook/react-native/releases/tag/v0.25.1
and other StackOverflow posts on the subject. After changing all of my component classes I still see this:

The inherits function in babelHelpers.js is:

```<code>babelHelpers.inherits = function (subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function,not " + typeof superClass);
}
</code>```

What is the problem with it? Looks like this is part of react-native library.

I know there is a transform available here to fix the "import problem" in general. Has anyone run it successfully?

BTW - here are my dependencies currently used:

```<code>"dependencies": {
  "@remobile/react-native-splashscreen": "^1.0.3",
  "babel-polyfill": "^6.9.1",
  "react": "^15.1.0",
  "react-native": "^0.27.2",
  "react-native-navbar": "^1.5.0",
  "react-native-side-menu": "^0.18.1",
  "realm": "^0.13.2"
},
"devDependencies": {
  "babel-jest": "^12.1.0",
  "babel-polyfill": "^6.9.1",
  "jest-cli": "^12.1.1",
  "react-addons-test-utils": "^15.1.0"
}
</code>```

Thank you in advance for your help.

答:
My problem was that in index.android.js I was using a component class to derive AndroidApp from which didn't exist (anymore). The error was a result of the superClass argument passed to babelHelpers.inherits() being undefined.

The error message isn't really that helpful because the inherits() function only checks if superClass is not null. It would be nice if it checked for undefined too.

Body:
I just updated to RN 0.27 from 0.24 and all these "Super expression must either be null or a function, not undefined" errors started to pop up. After some research I realized there was a breaking change in RN 0.26 so i changed my import statements as indicated in
https://github.com/facebook/react-native/releases/tag/v0.25.1
and other StackOverflow posts on the subject. After changing all of my component classes I still see this:

The inherits function in babelHelpers.js is:

babelHelpers.inherits = function (subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function,not " + typeof superClass);
}

What is the problem with it? Looks like this is part of react-native library.

I know there is a transform available here to fix the "import problem" in general. Has anyone run it successfully?

BTW - here are my dependencies currently used:

"dependencies": {
  "@remobile/react-native-splashscreen": "^1.0.3",
  "babel-polyfill": "^6.9.1",
  "react": "^15.1.0",
  "react-native": "^0.27.2",
  "react-native-navbar": "^1.5.0",
  "react-native-side-menu": "^0.18.1",
  "realm": "^0.13.2"
},
"devDependencies": {
  "babel-jest": "^12.1.0",
  "babel-polyfill": "^6.9.1",
  "jest-cli": "^12.1.1",
  "react-addons-test-utils": "^15.1.0"
}

Thank you in advance for your help.


问:
Custom alertDialog in the listView
I can not make a custom Alertdialog in the listview.
The code below works correctly in the MainActivity, but in the customAdapter the "getLayoutInflater ()" is in red:</p>

```<code>android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
                        View mView = getLayoutInflater().inflate(R.layout.custom_dialog_profil, null);

                        cBuilder.setView(mView);
                        android.support.v7.app.AlertDialog dialog = cBuilder.create();
                        dialog.show();
</code>```

答: you can change getLayoutInflater to LayoutInflater.from(context) instead

Title: Custom alertDialog in the listView

Body:
I can not make a custom Alertdialog in the listview.
The code below works correctly in the MainActivity, but in the customAdapter the "getLayoutInflater ()" is in red:

android.support.v7.app.AlertDialog.Builder cBuilder = new android.support.v7.app.AlertDialog.Builder(context);
                        View mView = getLayoutInflater().inflate(R.layout.custom_dialog_profil, null);

                        cBuilder.setView(mView);
                        android.support.v7.app.AlertDialog dialog = cBuilder.create();
                        dialog.show();


问:
Compare 2 integers in a do while loop
Write a program that has the user enter integers between 0 and 9999 until the user enters some integer twice.  Program should to the console window how many distinct integers were entered.

How do i make the condition for the while loop? Or how do i compare if 2 integers entered by user in a do while loop are equal?

```<code>int n1,n2,count=0;
do {
     Scanner kb = new Scanner(System.in);
     System.out.print("Enter an int: ");
     n1= kb.nextInt();
     n2= kb.nextInt();
     count++;
} while(n1 != n2);
System.out.println("you entered " + count + "times");
</code>```

This is why i tried

答:
Hope this helps</p>

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//one class needs to have a main() method
public class Beta {
    // arguments are passed using the text field below this editor
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        boolean doExist = false;
        int inputVal;
        do {
            System.out.print("\nEnter an Integer:");
            inputVal = kb.nextInt();
            doExist = list.contains(inputVal);
            if (!doExist) {
                list.add(inputVal);
            }

        } while (!doExist);

        System.out.println("The Number of Non Duplicate Integers:"+list.size());

    }
}
</code>```

Title: Compare 2 integers in a do while loop

Body:
Write a program that has the user enter integers between 0 and 9999 until the user enters some integer twice.  Program should to the console window how many distinct integers were entered.

How do i make the condition for the while loop? Or how do i compare if 2 integers entered by user in a do while loop are equal?

int n1,n2,count=0;
do {
     Scanner kb = new Scanner(System.in);
     System.out.print("Enter an int: ");
     n1= kb.nextInt();
     n2= kb.nextInt();
     count++;
} while(n1 != n2);
System.out.println("you entered " + count + "times");

This is why i tried

Body:
Hope this helps

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//one class needs to have a main() method
public class Beta {
    // arguments are passed using the text field below this editor
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        boolean doExist = false;
        int inputVal;
        do {
            System.out.print("\nEnter an Integer:");
            inputVal = kb.nextInt();
            doExist = list.contains(inputVal);
            if (!doExist) {
                list.add(inputVal);
            }

        } while (!doExist);

        System.out.println("The Number of Non Duplicate Integers:"+list.size());

    }
}


问:
acts_as_taggable_on Gem not working for Rails 5
I made a rails application and added the acts-as-taggable-on gem, ran the rake db:migrate and added the field to Article.rb.  I seem to get this error with a rail 5.1 app.  I can't figure out what it is.

GemFile

```<code>gem 'acts-as-taggable-on', '~> 4.0'
</code>```

Article.rb

```<code>class Article < ApplicationRecord
    include TheComments::Commentable

     acts_as_taggable_on :tags

        belongs_to :user

      # Denormalization methods
      # Check the documentation for information on advanced usage
        def commentable_title
        title
      end

      def commentable_url
        ['', self.class.to_s.tableize, id].join('/')
      end

      def commentable_state
        :published.to_s
      end
    end
</code>```

However I get this error:

```<code>Running via Spring preloader in process 18395
Loading development environment (Rails 5.1.2)
2.4.0-rc1 :001 > Article
NoMethodError: undefined method `acts_as_taggable_on' for Article (call 'Article.connection' to establish a connection):Class
    from app/models/article.rb:6:in `<class:Article>'
    from app/models/article.rb:1:in `<top (required)>'
    from (irb):1
2.4.0-rc1 :002 > Article
NoMethodError: undefined method `acts_as_taggable_on' for Article (call 'Article.connection' to establish a connection):Class
    from app/models/article.rb:6:in `<class:Article>'
    from app/models/article.rb:1:in `<top (required)>'
</code>```

答:
They have version 5 which is not mentioned. The documentation says that version 4 works with both Rails 4 and 5 which is inaccurate. I added the following to my Gemfile and got it working. The GitHub link is my reference point.

```<code>gem "acts-as-taggable-on", "~> 5.0"
</code>```

https://github.com/mbleigh/acts-as-taggable-on/issues/866

Body:
I made a rails application and added the acts-as-taggable-on gem, ran the rake db:migrate and added the field to Article.rb.  I seem to get this error with a rail 5.1 app.  I can't figure out what it is.

GemFile

gem 'acts-as-taggable-on', '~> 4.0'

Article.rb

class Article < ApplicationRecord
    include TheComments::Commentable

     acts_as_taggable_on :tags

        belongs_to :user

      # Denormalization methods
      # Check the documentation for information on advanced usage
        def commentable_title
        title
      end

      def commentable_url
        ['', self.class.to_s.tableize, id].join('/')
      end

      def commentable_state
        :published.to_s
      end
    end

However I get this error:

Running via Spring preloader in process 18395
Loading development environment (Rails 5.1.2)
2.4.0-rc1 :001 > Article
NoMethodError: undefined method `acts_as_taggable_on' for Article (call 'Article.connection' to establish a connection):Class
    from app/models/article.rb:6:in `<class:Article>'
    from app/models/article.rb:1:in `<top (required)>'
    from (irb):1
2.4.0-rc1 :002 > Article
NoMethodError: undefined method `acts_as_taggable_on' for Article (call 'Article.connection' to establish a connection):Class
    from app/models/article.rb:6:in `<class:Article>'
    from app/models/article.rb:1:in `<top (required)>'

Body:
They have version 5 which is not mentioned. The documentation says that version 4 works with both Rails 4 and 5 which is inaccurate. I added the following to my Gemfile and got it working. The GitHub link is my reference point.

gem "acts-as-taggable-on", "~> 5.0"

https://github.com/mbleigh/acts-as-taggable-on/issues/866


问:
How to remove constraints from all subviews inside my superview?
I have a UIView that contains multiple UIView subviews that has its own constraints. How do I remove the subviews' constraints?</p>

```<code>//only removes the constraints on self.view
[self.view removeConstraints:self.view.constraints];

//I get warning: Incompatible pointer types sending 'NSArray *' to parameter of type 'NSLayoutConstraint'
[self.subview1 removeConstraints:self.subview1.constraints];
</code>```

答:
I wrote an extension on UIView:

```<code>extension UIView{

    func removeConstraintsFromAllEdges(of view: UIView){

        for constraint in constraints{
            if (constraint.firstItem.view == view || constraint.secondItem?.view == view){
                removeConstraint(constraint)
            }
        }
    }

    func addConstraintsToAllEdges(of view: UIView){
        let leading = leadingAnchor.constraint(equalTo: view.leadingAnchor)
        let top = topAnchor.constraint(equalTo: view.topAnchor)
        let trailing = trailingAnchor.constraint(equalTo: view.trailingAnchor)
        let bottom = bottomAnchor.constraint(equalTo: view.bottomAnchor)

        NSLayoutConstraint.activate([leading, top, trailing, bottom])
    }
}
</code>```

Interesting note is secondItem is an optional property of NSLayoutConstraint while firstItem is non-optional. Why? Because sometimes you may need to constrain a view's height to a constant value, so you there is no other view involved.

Body:
I have a UIView that contains multiple UIView subviews that has its own constraints. How do I remove the subviews' constraints?

//only removes the constraints on self.view
[self.view removeConstraints:self.view.constraints];

//I get warning: Incompatible pointer types sending 'NSArray *' to parameter of type 'NSLayoutConstraint'
[self.subview1 removeConstraints:self.subview1.constraints];

Body:
I wrote an extension on UIView:

extension UIView{

    func removeConstraintsFromAllEdges(of view: UIView){

        for constraint in constraints{
            if (constraint.firstItem.view == view || constraint.secondItem?.view == view){
                removeConstraint(constraint)
            }
        }
    }

    func addConstraintsToAllEdges(of view: UIView){
        let leading = leadingAnchor.constraint(equalTo: view.leadingAnchor)
        let top = topAnchor.constraint(equalTo: view.topAnchor)
        let trailing = trailingAnchor.constraint(equalTo: view.trailingAnchor)
        let bottom = bottomAnchor.constraint(equalTo: view.bottomAnchor)

        NSLayoutConstraint.activate([leading, top, trailing, bottom])
    }
}

Interesting note is secondItem is an optional property of NSLayoutConstraint while firstItem is non-optional. Why? Because sometimes you may need to constrain a view's height to a constant value, so you there is no other view involved.