问:
Appending data Column wise while writing into new csv
I have a CSV file having approx 800 columns with different no. of data and I am calculating the Amplitude of each column and some other parameters . But when i write the data in a csv file it got appended in a single column and i want to append the data column wise in a different file.

Suppose: Following is the data.

```<code>col_1       col_2       col_3    col_4       col_5
1.1612      0.3067    -1.1993    0.2182     -0.9918
2.0096     -0.0519    -1.0422    0.0748      0.0259
1.6678      1.1963    -0.1755    0.0198     -0.2106
0.4608      0.676     -0.7721    0.6531      0.5783
0.5463      0.7111    -0.7782    0.4303     -0.3082
-0.1022     0.9064    -0.6317    0.5188     -1.2695
0.4211      0.5859     0.1846    0.1434     -0.4181
1.2848     -0.5249     1.1307   -0.5768      0.0336
0.7813      0.6989              -0.0885     -0.5295
0.4288      1.0056               0.2213
            0.8469               0.9048
</code>```

Script :

```<code>i=1
for(i in 1:5){
  readfile <- read.csv("test.CSV" , header = FALSE,  skip = 1)[,i]
  readfile
  colnm <- na.omit(readfile)
  colnm
  arr_colmn <- array(colnm)
  arr_colmn
  no._of_rows <- nrow(arr_colmn)   ### For single column row count
  no._of_rows
##other calculation not mentioned
  AMP <-  abs(fft(arr_colmn,inverse = FALSE))
  YY <- data.frame(AMP)
  write.table(YY, "test_1.csv", append = TRUE,col.names = TRUE, row.names = FALSE, sep = ",")
   i=i+1
}`
</code>```

Required Result

```<code>Col_1_Result   col_2_Result      Col_3_Result............
8.3432          3.000             0.611
17.2494         14.42             0.8412
7.72650         15.76
.               .
.               .
.               .
.               .
</code>```

Body:
I have a CSV file having approx 800 columns with different no. of data and I am calculating the Amplitude of each column and some other parameters . But when i write the data in a csv file it got appended in a single column and i want to append the data column wise in a different file.

Suppose: Following is the data.

col_1       col_2       col_3    col_4       col_5
1.1612      0.3067    -1.1993    0.2182     -0.9918
2.0096     -0.0519    -1.0422    0.0748      0.0259
1.6678      1.1963    -0.1755    0.0198     -0.2106
0.4608      0.676     -0.7721    0.6531      0.5783
0.5463      0.7111    -0.7782    0.4303     -0.3082
-0.1022     0.9064    -0.6317    0.5188     -1.2695
0.4211      0.5859     0.1846    0.1434     -0.4181
1.2848     -0.5249     1.1307   -0.5768      0.0336
0.7813      0.6989              -0.0885     -0.5295
0.4288      1.0056               0.2213
            0.8469               0.9048

Script :

i=1
for(i in 1:5){
  readfile <- read.csv("test.CSV" , header = FALSE,  skip = 1)[,i]
  readfile
  colnm <- na.omit(readfile)
  colnm
  arr_colmn <- array(colnm)
  arr_colmn
  no._of_rows <- nrow(arr_colmn)   ### For single column row count
  no._of_rows
##other calculation not mentioned
  AMP <-  abs(fft(arr_colmn,inverse = FALSE))
  YY <- data.frame(AMP)
  write.table(YY, "test_1.csv", append = TRUE,col.names = TRUE, row.names = FALSE, sep = ",")
   i=i+1
}`

Required Result

Col_1_Result   col_2_Result      Col_3_Result............
8.3432          3.000             0.611
17.2494         14.42             0.8412
7.72650         15.76
.               .
.               .
.               .
.               .

Body:
I don't really understand how you generate your output table, the code you provide doesn't seem to reproduce the table; unfortunately your additional comments didn't really help either.

That aside, I think you want to calculate some form of summary statistics for columns of different length.

In the following example, I calculate the mean and sd for every column and store the results in a dataframe. Note that there is no need for a for loop, just lapply a function to every column of your dataframe.

# Your sample data
data <- structure(list(V1 = c(1.1612, 2.0096, 1.6678, 0.4608, 0.5463,
-0.1022, 0.4211, 1.2848, 0.7813, 0.4288, -0.3342, 0.2777, 0.8392,
-0.5539, -0.8286, -0.9506, -1.1383, -1.7395, -0.7492), V2 = c(0.3067,
-0.0519, 1.1963, 0.676, 0.7111, 0.9064, 0.5859, -0.5249, 0.6989,
1.0056, 0.8469, 1.1276, 2.3087, -0.8514, -1.1398, NA, NA, NA,
NA), V3 = c(-1.1993, -1.0422, -0.1755, -0.7721, -0.7782, -0.6317,
0.1846, 1.1307, -0.5127, -0.6622, 0.3677, 0.2151, -0.0458, -1.7883,
-0.9445, 0.5524, -0.9857, -0.9644, -1.6342), V4 = c(0.2182, 0.0748,
0.0198, 0.6531, 0.4303, 0.5188, 0.1434, -0.5768, -0.0885, 0.2213,
0.9048, -0.0305, -1.3046, -0.4242, 0.1053, 0.9766, -0.5783, 0.7462,
NA), V5 = c(-0.9918, 0.0259, -0.2106, 0.5783, -0.3082, -1.2695,
-0.4181, 0.0336, -0.5295, -0.415, 1.2634, 0.769, -0.1862, -0.7126,
-0.2716, -0.3479, 1.1002, NA, NA)), .Names = c("V1", "V2", "V3",
"V4", "V5"), class = "data.frame", row.names = c(NA, -19L))

# Calculate mean and sd for every column; ignore NA's
df  <- do.call(rbind.data.frame, lapply(d, function(x)
    c(mean(x, na.rm = TRUE), sd(x, na.rm = TRUE))));
colnames(df) <- c("mean", "sd");
df;
#    mean        sd
#1  0.1832684 1.0095877
#2  0.5201400 0.8748568
#3 -0.5098053 0.7594946
#4  0.1116500 0.5779139
#5 -0.1112118 0.6902565

# Write to file
write.csv(df, file = "output.csv", row.names = FALSE, quote = FALSE);


来源: stackexchange

问:
angular 1 [$injector:unpr]
i have error in my app:

```<code>vendor-cms.js:119 Error: [$injector:unpr] http://errors.angularjs.org/1.4.14/$injector/unpr?p0=ProductProvider%20%3C-%20Product%20%3C-%20TrashListCtrl
    at http://123.com/js/dist/vendor-cms.js:17:417
    at http://123.com/js/dist/vendor-cms.js:52:240
    at Object.d [as get] (http://gfexxx.com/js/dist/vendor-cms.js:50:220)
    at http://123.com/js/dist/vendor-cms.js:52:314
    at d (http://123.com/js/dist/vendor-cms.js:50:220)
    at e (http://123.com/js/dist/vendor-cms.js:50:490)
    at Object.instantiate (http://123.com/js/dist/vendor-cms.js:51:136)
    at http://123.com/js/dist/vendor-cms.js:92:306
    at http://123.com/js/dist/vendor-cms.js:661:23742
    at ca (http://123.com/js/dist/vendor-cms.js:85:90) <div ui-view="" class="content ng-scope" data-ng-animate="1">
</code>```

i  google but cant realize whats happend here:

```<code>start = ->
  angular.module('VitalCms.controllers.trash', [])
    .config(['$stateProvider', trashConfig])
    .controller('TrashListCtrl', TrashListCtrl)

trashConfig = ($stateProvider) ->
  $stateProvider
    .state('trash'
      url: '/trash'
      templateUrl: '/cms/partials/trash/index.html'
      controller: 'TrashListCtrl'
      ncyBreadcrumb:
        label: 'Корзина')

class TrashListCtrl
  @$inject: ['$scope', 'Page', 'Form', 'Product', 'News']

  constructor: ($scope, Page, Form, Product, News) ->
    $scope.displayFull = true
    $scope.resources =
      pages:
        model: Page
        list: Page.listDeleted()
      forms:
        model: Form
        list: Form.listDeleted()
      products:
        model: Product
        list: Product.listDeleted()
      news:
        model: News
        list: News.listDeleted()

    $scope.deleteDoc = (resource, doc) ->
      index = $scope.resources[resource].list.indexOf(doc)

      doc.$delete ->
        $scope.resources[resource].list.splice index, 1
        $scope.alerts.push
          msg: ''
          type: 'success'

    $scope.restoreDoc = (resource, doc) ->
      index = $scope.resources[resource].list.indexOf(doc)
      doc.$restore ->
        $scope.resources[resource].list.splice index, 1
        $scope.alerts.push
          msg: ''
          type: 'success'

start()
</code>```

so i have controller and then injecting it, so why is the error there ?
if i go to angular docs they say its unknown provider, but it seems  is defined and spelled correctly. whats going wrong there ?

答: The error page already explains the problem in human-readable form. In order for Product service to be injected into the controller, it should be defined. And Product wasn't defined.

ContentLicense: CC BY-SA 3.0

Title: angular 1 [$injector:unpr]

Body:
i have error in my app:

vendor-cms.js:119 Error: [$injector:unpr] http://errors.angularjs.org/1.4.14/$injector/unpr?p0=ProductProvider%20%3C-%20Product%20%3C-%20TrashListCtrl
    at http://123.com/js/dist/vendor-cms.js:17:417
    at http://123.com/js/dist/vendor-cms.js:52:240
    at Object.d [as get] (http://gfexxx.com/js/dist/vendor-cms.js:50:220)
    at http://123.com/js/dist/vendor-cms.js:52:314
    at d (http://123.com/js/dist/vendor-cms.js:50:220)
    at e (http://123.com/js/dist/vendor-cms.js:50:490)
    at Object.instantiate (http://123.com/js/dist/vendor-cms.js:51:136)
    at http://123.com/js/dist/vendor-cms.js:92:306
    at http://123.com/js/dist/vendor-cms.js:661:23742
    at ca (http://123.com/js/dist/vendor-cms.js:85:90)

i  google but cant realize whats happend here:

start = ->
  angular.module('VitalCms.controllers.trash', [])
    .config(['$stateProvider', trashConfig])
    .controller('TrashListCtrl', TrashListCtrl)

trashConfig = ($stateProvider) ->
  $stateProvider
    .state('trash'
      url: '/trash'
      templateUrl: '/cms/partials/trash/index.html'
      controller: 'TrashListCtrl'
      ncyBreadcrumb:
        label: 'Корзина')

class TrashListCtrl
  @$inject: ['$scope', 'Page', 'Form', 'Product', 'News']

  constructor: ($scope, Page, Form, Product, News) ->
    $scope.displayFull = true
    $scope.resources =
      pages:
        model: Page
        list: Page.listDeleted()
      forms:
        model: Form
        list: Form.listDeleted()
      products:
        model: Product
        list: Product.listDeleted()
      news:
        model: News
        list: News.listDeleted()

    $scope.deleteDoc = (resource, doc) ->
      index = $scope.resources[resource].list.indexOf(doc)

      doc.$delete ->
        $scope.resources[resource].list.splice index, 1
        $scope.alerts.push
          msg: ''
          type: 'success'

    $scope.restoreDoc = (resource, doc) ->
      index = $scope.resources[resource].list.indexOf(doc)
      doc.$restore ->
        $scope.resources[resource].list.splice index, 1
        $scope.alerts.push
          msg: ''
          type: 'success'

start()

so i have controller and then injecting it, so why is the error there ?
if i go to angular docs they say its unknown provider, but it seems  is defined and spelled correctly. whats going wrong there ?


问:
Pass user's primary key (pk) from previous page to current page
I'm building a review page, where an annoymous user leaves a review on a user's page (my user is called Agent).  The Review model has an agent field, specifying a ForeignKey relationship with Agent.

urls

```<code>url(r'^(?P<pk>\d+)/review/$', views.leave_review, name='leave_review'),
</code>```

HTML code to get to the leave_review page:

```<code><form action="{% url 'leave_review' pk=agent.pk %}" method="post">
    {% csrf_token %}
    <button class="button3"><span>Leave review</span></button>
</form>
</code>```

Leave review views.py

```<code>def leave_review(request, pk):
    if request.method == 'POST':

        form = ReviewForm(request.POST)

        if form.is_valid():
            form.agent = Agent.objects.get(pk=pk)
            form.save()
            return redirect('review_success.html')
    else:
        form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})
</code>```

models.py

```<code>class Review(models.Model):
    # ... Other fields

    agent = models.ForeignKey(Agent, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.agent is None:  # Set default reference
            self.agent = Agent.objects.get(id=1)
        super(Review, self).save(*args, **kwargs)
</code>```

I'm currently getting a ValueError, Cannot assign "''": "Review.agent" must be a "Agent" instance.  I believe I specified the 'pk' correctly in this case,but it is not being picked up.  What's wrong here?

Full trackback

```<code>Environment:

Request Method: POST
Request URL: http://localhost:8000/agents/2/review/?csrfmiddlewaretoken=CIxNqtEaFjFIfVwmB6SyV2SAF1VuiDgEf3Di7qZoucG4thIn9ixCbe7GO2UuuW85

Django Version: 1.11.5
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'bungol.accounts',
 'bungol.databases',
 'bungol.coresite',
 'bungol.listings',
 'django_extensions',
 'djstripe']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Valachio\Google Drive\Bungol\bungolv4\bungol\databases\views.py" in leave_review
  69.         if form.is_valid():

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in full_clean
  386.         self._post_clean()

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\models.py" in _post_clean
  408.             self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\models.py" in construct_instance
  65.             f.save_form_data(instance, cleaned_data[f.name])

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
  853.         setattr(instance, self.name, data)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
  216.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /agents/2/review/
Exception Value: Cannot assign "''": "Review.agent" must be a "Agent" instance.
</code>```

```<code>class ReviewForm(forms.ModelForm):

    REVIEWER_TYPE = (
        # ... some choices
    )

    LOCATION = (
        # ... some choices
    )

    STARS = (
        # ... some choices
    )

    reviewer_type = forms.ChoiceField(widget=forms.RadioSelect, choices=REVIEWER_TYPE)
    property_type = forms.ChoiceField(widget=forms.RadioSelect, choices=BuyerListing.PROPERTY_TYPE)
    number_of_bedrooms = forms.ChoiceField(choices=BuyerListing.BEDS_OPTION)
    location = forms.ChoiceField(choices=LOCATION)
    stars = forms.ChoiceField(widget=forms.RadioSelect, choices=STARS)
    agent = forms.ChoiceField(widget = forms.HiddenInput(), required=False)

    class Meta:
        model = Review
        fields = ['agent', 'reviewer_first_name', 'reviewer_last_name', 'reviewer_email', 'reviewer_type', 'transaction_id', 'location', 'property_type', 'number_of_bedrooms', 'stars', 'content']
</code>```

答:
This line in the view is useless:

```<code>form.agent = Agent.objects.get(pk=pk)
</code>```

A form instance is not like a django model, you cannot set a field attribute like this. To do so, you got two solutions:

You could get the object from the form first, set the agent and save the object afterward. So remove the agent field from your form, and make your code in the view like this:

```<code>def leave_review(request, pk):
    if request.method == 'POST':

        form = ReviewForm(request.POST)

        if form.is_valid():
            review = form.save(commit=False)  # Getting the unsaved `Review` instance from the form
            review.agent = Agent.objects.get(pk=pk)  # Set the agent on the `Review` instance
            review.save()  # Finally save the `Review` instance

            return redirect('review_success.html')
        else:
            form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})
</code>```

Documentation about the save method in the Django forms

If you really need to have this agent field in your form (But as it is a hidden field, I assume you don't ?) you could pass the value from the form initial keyword, like stated in this answer (Documentation):

```<code>def leave_review(request, pk):
    if request.method == 'POST':

        # Passing initial data to the form so our `agent` field will be populated
        data = {'agent': Agent.objects.get(pk=pk)}
        form = ReviewForm(request.POST, initial=data)

        if form.is_valid():
            review.save()

            return redirect('review_success.html')
        else:
            form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})
</code>```

Body:
I'm building a review page, where an annoymous user leaves a review on a user's page (my user is called Agent).  The Review model has an agent field, specifying a ForeignKey relationship with Agent.

urls

url(r'^(?P<pk>\d+)/review/$', views.leave_review, name='leave_review'),

HTML code to get to the leave_review page:

<form action="{% url 'leave_review' pk=agent.pk %}" method="post">
    {% csrf_token %}
    <button class="button3">Leave review</button>
</form>

Leave review views.py

def leave_review(request, pk):
    if request.method == 'POST':

        form = ReviewForm(request.POST)

        if form.is_valid():
            form.agent = Agent.objects.get(pk=pk)
            form.save()
            return redirect('review_success.html')
    else:
        form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})

models.py

class Review(models.Model):
    # ... Other fields

    agent = models.ForeignKey(Agent, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if self.agent is None:  # Set default reference
            self.agent = Agent.objects.get(id=1)
        super(Review, self).save(*args, **kwargs)

I'm currently getting a ValueError, Cannot assign "''": "Review.agent" must be a "Agent" instance.  I believe I specified the 'pk' correctly in this case,but it is not being picked up.  What's wrong here?

Full trackback

Environment:

Request Method: POST
Request URL: http://localhost:8000/agents/2/review/?csrfmiddlewaretoken=CIxNqtEaFjFIfVwmB6SyV2SAF1VuiDgEf3Di7qZoucG4thIn9ixCbe7GO2UuuW85

Django Version: 1.11.5
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'bungol.accounts',
 'bungol.databases',
 'bungol.coresite',
 'bungol.listings',
 'django_extensions',
 'djstripe']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Valachio\Google Drive\Bungol\bungolv4\bungol\databases\views.py" in leave_review
  69.         if form.is_valid():

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\forms.py" in full_clean
  386.         self._post_clean()

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\models.py" in _post_clean
  408.             self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\forms\models.py" in construct_instance
  65.             f.save_form_data(instance, cleaned_data[f.name])

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
  853.         setattr(instance, self.name, data)

File "C:\Python 3.6.2 (32bit)\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
  216.                     self.field.remote_field.model._meta.object_name,

Exception Type: ValueError at /agents/2/review/
Exception Value: Cannot assign "''": "Review.agent" must be a "Agent" instance.

class ReviewForm(forms.ModelForm):

    REVIEWER_TYPE = (
        # ... some choices
    )

    LOCATION = (
        # ... some choices
    )

    STARS = (
        # ... some choices
    )

    reviewer_type = forms.ChoiceField(widget=forms.RadioSelect, choices=REVIEWER_TYPE)
    property_type = forms.ChoiceField(widget=forms.RadioSelect, choices=BuyerListing.PROPERTY_TYPE)
    number_of_bedrooms = forms.ChoiceField(choices=BuyerListing.BEDS_OPTION)
    location = forms.ChoiceField(choices=LOCATION)
    stars = forms.ChoiceField(widget=forms.RadioSelect, choices=STARS)
    agent = forms.ChoiceField(widget = forms.HiddenInput(), required=False)

    class Meta:
        model = Review
        fields = ['agent', 'reviewer_first_name', 'reviewer_last_name', 'reviewer_email', 'reviewer_type', 'transaction_id', 'location', 'property_type', 'number_of_bedrooms', 'stars', 'content']

Body:
This line in the view is useless:

form.agent = Agent.objects.get(pk=pk)

A form instance is not like a django model, you cannot set a field attribute like this. To do so, you got two solutions:

You could get the object from the form first, set the agent and save the object afterward. So remove the agent field from your form, and make your code in the view like this:

def leave_review(request, pk):
    if request.method == 'POST':

        form = ReviewForm(request.POST)

        if form.is_valid():
            review = form.save(commit=False)  # Getting the unsaved `Review` instance from the form
            review.agent = Agent.objects.get(pk=pk)  # Set the agent on the `Review` instance
            review.save()  # Finally save the `Review` instance

            return redirect('review_success.html')
        else:
            form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})

Documentation about the save method in the Django forms

If you really need to have this agent field in your form (But as it is a hidden field, I assume you don't ?) you could pass the value from the form initial keyword, like stated in this answer (Documentation):

def leave_review(request, pk):
    if request.method == 'POST':

        # Passing initial data to the form so our `agent` field will be populated
        data = {'agent': Agent.objects.get(pk=pk)}
        form = ReviewForm(request.POST, initial=data)

        if form.is_valid():
            review.save()

            return redirect('review_success.html')
        else:
            form = ReviewForm()

    return render(request, 'leave_review.html', {'form': form})


问:
Error when calculating max value for double variable in C
I followed the solution here: How to Calculate Double + Float Precision and have been unable to calculate the maximum value for variables of type double.

I run:

```<code>double dbl_max = pow(2, pow(2, 10)) * (1-pow(2, -53));
printf("%.2e", dbl_max);

Result: inf
</code>```

Or:

```<code> double dbl_max = (pow(2, pow(2, 10)));
 printf("%.2e", dbl_max);

Result: inf
</code>```

Or:

```<code>double dbl_max = pow(2, pow(2, 9)) * (1-pow(2, -53));
printf("%.2e", dbl_max);

Result: 1.34e+154
</code>```

Why isn't the calculation fitting into the variable? The top sample above works just fine for float variables.

答:
The intermediate exponent is one too high.
  Change pow(2, 10) to (pow(2, 10) - 1) and it
  should work.  You can compensate by multiplying the final result by
  2.
                      – Tom Karzes

```<code>double dbl_max = pow(2, pow(2, 10)-1) * (1-pow(2, -53)) * 2;
printf("%.2e", dbl_max);
</code>```

Body:
I followed the solution here: How to Calculate Double + Float Precision and have been unable to calculate the maximum value for variables of type double.

I run:

double dbl_max = pow(2, pow(2, 10)) * (1-pow(2, -53));
printf("%.2e", dbl_max);

Result: inf

Or:

 double dbl_max = (pow(2, pow(2, 10)));
 printf("%.2e", dbl_max);

Result: inf

Or:

double dbl_max = pow(2, pow(2, 9)) * (1-pow(2, -53));
printf("%.2e", dbl_max);

Result: 1.34e+154

Why isn't the calculation fitting into the variable? The top sample above works just fine for float variables.

Body:
The intermediate exponent is one too high.
  Change pow(2, 10) to (pow(2, 10) - 1) and it
  should work.  You can compensate by multiplying the final result by
  2.
                      – Tom Karzes

double dbl_max = pow(2, pow(2, 10)-1) * (1-pow(2, -53)) * 2;
printf("%.2e", dbl_max);


问:
MATLAB, Convert 4049 rows x 50 columns of spectrograph data into 3D plot
```<code>%Sampling Frequency
f=8000;

%Sampling Time
t=5;
%Data imported from microsoft Excel
matrix=Book2S1;

%Size Matrix
s=size(matrix);
h=s(1,1);
w=s(1,2);

%Set Up Rows and Columns
rows=(0:(f/2)/(h-1):f/2);
columns=(0:t/(w-1):t);

%plot
mesh(columns,rows,matrix);
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density, V^2/Hz')`enter code here
</code>```

This is the code that I type in to attempt to get a 3D plot. The goal is for me to obtain a plot that looks like the image listed below, but I continue getting a mesh error

Error using mesh (line 139)
Data inputs must be numeric, datetime, duration, categorical arrays or objects which can be converted to
double.

Error in Lab_3_1 (line 21)
mesh(columns,rows,matrix);

What my plot is supposed to look like.
The picture didn't want to get saved after being cropped, sorry people.

The following is a link to half of the data being used for this plot.
https://docs.google.com/spreadsheets/d/e/2PACX-1vRMWfmFYDnwMSPzahD8k-aWAXHstbNRdlY4gmOHJoXkLaBb4PY7zF5-41yFkQHR4g0w3LrMFiz3ZqWJ/pubhtml

答:
I figured out that the values that were imported into MATLAB were converted into string values. I stopped using the import button and used the xlsread function instead, and that allowed me to import the numerical values without them being converted into strings.

Finished Code

Resulting 3D Plot

Thank you guys for the help and looking over the problem.

Body:
%Sampling Frequency
f=8000;

%Sampling Time
t=5;
%Data imported from microsoft Excel
matrix=Book2S1;

%Size Matrix
s=size(matrix);
h=s(1,1);
w=s(1,2);

%Set Up Rows and Columns
rows=(0:(f/2)/(h-1):f/2);
columns=(0:t/(w-1):t);

%plot
mesh(columns,rows,matrix);
xlabel('Time, s')
ylabel('Frequency, Hz')
zlabel('Power Spectral Density, V^2/Hz')`enter code here

This is the code that I type in to attempt to get a 3D plot. The goal is for me to obtain a plot that looks like the image listed below, but I continue getting a mesh error

Error using mesh (line 139)
Data inputs must be numeric, datetime, duration, categorical arrays or objects which can be converted to
double.

Error in Lab_3_1 (line 21)
mesh(columns,rows,matrix);

What my plot is supposed to look like.
The picture didn't want to get saved after being cropped, sorry people.

The following is a link to half of the data being used for this plot.
https://docs.google.com/spreadsheets/d/e/2PACX-1vRMWfmFYDnwMSPzahD8k-aWAXHstbNRdlY4gmOHJoXkLaBb4PY7zF5-41yFkQHR4g0w3LrMFiz3ZqWJ/pubhtml


问:
How to change python version for use with pyinstaller
I am trying to convert a .py file to an exe. My file, hello.py, reads:

```<code>print "Hello, World!"
</code>```

I am currently trying to use pyinstaller. However when I run the command

```<code>pyinstaller hello.py
</code>```

I get the error message "tuple index out of range" which I have been told means my version of python is unsupported. In particular it would seem the situation is that pyinstaller thinks I am trying to compile python 3.6 code into an exe. But I have python 2.7 and python 3.6 installed. How do I let it know that I want it to regard the code as python 2.7 code?

答:
I ran two a couple things.
If you uninstall python3, it works with python2.
If you have python3 installed (and it is the primary), and have pyinstaller installed in python3, it wont work (python3 pyinstaller used).
If you have python3 installed, but do not have it installed in python3 or uninstalled it (pip3 uninstall pyinstaller), pyinstaller works.

Checking the environmental variables (windows 10) PATH had python3 first. This may be the issue and may not be resolved because it is checking python3 directories first, and picks up pyinstaller for python3. pyinstaller does not check the file either (#!/usr/env/bin python2).

Unless pyinstaller puts an option relating to this issue, there may be no solution short of uninstalling pyinstaller from python3 temporarily.

note
could also use py2exe, using py2exe for python2, pyinstaller for python3

Body:
I am trying to convert a .py file to an exe. My file, hello.py, reads:

print "Hello, World!"

I am currently trying to use pyinstaller. However when I run the command

pyinstaller hello.py

I get the error message "tuple index out of range" which I have been told means my version of python is unsupported. In particular it would seem the situation is that pyinstaller thinks I am trying to compile python 3.6 code into an exe. But I have python 2.7 and python 3.6 installed. How do I let it know that I want it to regard the code as python 2.7 code?


问:
Azure ARM Template Unit Test
How to test Azure ARM Templates and validate them whether these are written correctly or not from local VM.
I have tried it from Power Shell but it just validate only. I want to Unit Test the ARM templates</p>

答:
You can do unit test the ARM Templates with PESTER. If you are unfamiliar with pester, you can refer to this document.

Example ARM Template

The example template being tested allows for the selection of whether managed or un-managed disk are used for the VM. The template can be found here https://github.com/bentaylorwork/azure-arm-templates/tree/master/disk-management-selection.

Example Pester Test
The Pester test below will check if the correct disk types are being deployed based on user input of whether the vm’s disks should be based on managed or un-managed disks. The file can be found here:
https://github.com/bentaylorwork/azure-arm-templates/blob/master/disk-management-selection/tests/unit.tests.ps1   You can save it to your local machine as test.ps1 file.

Running The Test

NOTE: The blog's script has an error with not defined  $parameterHash, So , you can use my following scripts to execute:

```<code><#
    Steps to run:
    1) Login to Azure
    2) Select correct subscription
    3) Alter the path below to where you have the have saved the pester test locally
#>

$pesterParamters = @{
    Path       = 'C:\Users\Administrator\Desktop\test.ps1'
    Parameters = @{
                        templateUri                 = 'https://raw.githubusercontent.com/bentaylorwork/azure-arm-templates/master/disk-management-selection/azuredeploy.json'
                        templateParameterObject     = @{
                            resourcePrefix = 'pester'
                            adminPassword  = 'SuperSecurePlainTextPassword123!!'
                        }
                  }
}

$parameterHash= @{
                            resourcePrefix = 'pester'
                            adminPassword  = 'SuperSecurePlainTextPassword123!!'
                        }

Invoke-Pester -Script $pesterParamters
</code>```

Example Output From A Successful Test

You can see more details about Unit testing conditions in ARM templates with pester in this blog.

Additionally, I also recommend a tool to check ARM templates: Azure ARM templates checker. It is a quick and dirty tool to check if all parameters or variables used in the template have been defined. You can see more details about ARM templates checker in this link.

ContentLicense: CC BY-SA 4.0

Title: Azure ARM Template Unit Test

Body:
You can do unit test the ARM Templates with PESTER. If you are unfamiliar with pester, you can refer to this document.

Example ARM Template

The example template being tested allows for the selection of whether managed or un-managed disk are used for the VM. The template can be found here https://github.com/bentaylorwork/azure-arm-templates/tree/master/disk-management-selection.

Example Pester Test
The Pester test below will check if the correct disk types are being deployed based on user input of whether the vm’s disks should be based on managed or un-managed disks. The file can be found here:
https://github.com/bentaylorwork/azure-arm-templates/blob/master/disk-management-selection/tests/unit.tests.ps1   You can save it to your local machine as test.ps1 file.

Running The Test

NOTE: The blog's script has an error with not defined  $parameterHash, So , you can use my following scripts to execute:

<#
    Steps to run:
    1) Login to Azure
    2) Select correct subscription
    3) Alter the path below to where you have the have saved the pester test locally
#>

$pesterParamters = @{
    Path       = 'C:\Users\Administrator\Desktop\test.ps1'
    Parameters = @{
                        templateUri                 = 'https://raw.githubusercontent.com/bentaylorwork/azure-arm-templates/master/disk-management-selection/azuredeploy.json'
                        templateParameterObject     = @{
                            resourcePrefix = 'pester'
                            adminPassword  = 'SuperSecurePlainTextPassword123!!'
                        }
                  }
}

$parameterHash= @{
                            resourcePrefix = 'pester'
                            adminPassword  = 'SuperSecurePlainTextPassword123!!'
                        }

Invoke-Pester -Script $pesterParamters

Example Output From A Successful Test

You can see more details about Unit testing conditions in ARM templates with pester in this blog.

Additionally, I also recommend a tool to check ARM templates: Azure ARM templates checker. It is a quick and dirty tool to check if all parameters or variables used in the template have been defined. You can see more details about ARM templates checker in this link.


问:
Javascript rock paper scissors project

var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

function choice(pick){
 prompt("rock paper or snip");
}
if(playerOne === rock && playerTwo === snip){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === paper && playerTwo === rock){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === snip && playerTwo === paper){
    alert(playerOneName + " " + "Wins");
}else if(playerTwo === rock && playerOne === snip){
   alert(playerTwoName + " " + "Wins");
}else if(playerTwo === paper && playerOne === rock){
    alert(playerTwoName + " " + "Wins");
}else if(playerTwo === snip && playerOne === paper){
   alert(playerTwoName + " " + "Wins");
}else if(playerOne === playerTwo){
 alert("it's a tie try again");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="rps.js"></script>
</head>
<body>

<ul>
 <li>Rock</li>
 <li>Paper</li>
 <li>Snip</li>
</ul>
</body>
</html></code>```

Hello All,
I'm back with a very new question. For some reason when I run my code for this game of rock paper scissors... it's constantly telling me that player one wins. The issue that I discovered is that it's always choosing the if statement and not the else if. If someone could help that would be great!
Thanks again for your time.Also this is my first week learning javascript... It's kinda of sad that this many people would down vote my question... This is the reason why most people are afraid to ask question fyi...

答:
You have to return the entered value from window.prompt. i.e

function choice(pick){
    var answer = prompt("rock paper or snip");
    return answer;
}

This way you can get what the user had typed in the window prompt. There are some case where you may have to check for null values though.
More reading here at Mozilla Docs

Title: Javascript rock paper scissors project

Body:
var rock = rock;
var paper= paper;
var snip = snip;

var playerOneName= prompt("what is your name");
playerOne = choice();
var playerTwoName = prompt("what is your name");
playerTwo=choice();

function choice(pick){
 prompt("rock paper or snip");
}
if(playerOne === rock && playerTwo === snip){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === paper && playerTwo === rock){
    alert(playerOneName + " " + "Wins");
}else if(playerOne === snip && playerTwo === paper){
    alert(playerOneName + " " + "Wins");
}else if(playerTwo === rock && playerOne === snip){
   alert(playerTwoName + " " + "Wins");
}else if(playerTwo === paper && playerOne === rock){
    alert(playerTwoName + " " + "Wins");
}else if(playerTwo === snip && playerOne === paper){
   alert(playerTwoName + " " + "Wins");
}else if(playerOne === playerTwo){
 alert("it's a tie try again");
}

<!doctype html>
<!DOCTYPE html>

 <title></title>

Rock

Paper

Snip

Hello All,
I'm back with a very new question. For some reason when I run my code for this game of rock paper scissors... it's constantly telling me that player one wins. The issue that I discovered is that it's always choosing the if statement and not the else if. If someone could help that would be great!
Thanks again for your time.Also this is my first week learning javascript... It's kinda of sad that this many people would down vote my question... This is the reason why most people are afraid to ask question fyi...


问:
HTML5 Forms Cheat Sheet
Can anybody recommend a nice compact HTML5 Forms Cheat Sheet including the new input types AND their attributes? Have searched high and low but can only find HTML Cheat Sheets for TAGS.

Thanks!

答:
You could also just keep a shortcut to the MDN HTML Reference:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element

Title: HTML5 Forms Cheat Sheet


问:
How to combine two similar functions that convert between hiragana and katakana?
I have two functions that convert between katakana and hiragana and they look the same:

```<code>katakana_minus_hiragana = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A

def is_hirgana(char):
    return 0x3040 < ord(char[0]) and ord(char[0]) < 0x3097

def is_katakana(char):
    return 0x30a0 < ord(char[0]) and ord(char[0]) < 0x30f7

def hiragana_to_katakana(hiragana_text):
    katakana_text = ""
    max_len = 0
    for i, char in enumerate(hiragana_text):
        if is_hirgana(char):
            katakana_text += chr(ord(char) + katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return katakana_text, max_len

def katakana_to_hiragana(katakana_text):
    hiragana_text = ""
    max_len = 0
    for i, char in enumerate(katakana_text):
        if is_katakana(char):
            hiragana_text += chr(ord(char) - katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return hiragana_text, max_len
</code>```

Is there a way to simplify hiragana_to_katakana() and katakana_to_hiragana() into a duck-type function or a super/meta function?

E.g. something like

```<code>def convert_hk_kh(text, charset_range, offset):
    charset_start, charset_end = charset_range
    output_text = ""
    max_len = 0
    for i, char in enumerate(text):
        if charset_start < ord(char[0]) and ord(char[0]) < charset_end:
            output_text += chr(ord(char) + offset)
            max_len +=1
        else:
            break
    return output_text, max_len

def katakana_to_hiragana(katakana_text):
    return convert_hk_kh(katakana_text, (0x30a0, 0x30f7), -katakana_minus_hiragana)

def hiragana_to_katakana(hiragana_text):
    return convert_hk_kh(hiragana_text, (0x3040, 0x3097), katakana_minus_hiragana)
</code>```

Are there other pythonic ways to simplify the two functions that are very similar?

EDITED

There's also https://github.com/olsgaard/Japanese_nlp_scripts which seems to do the same thing with str.translate. Is that more efficient? More pythonic?

答:
I'd do something like this:

```<code>KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041  # KATAKANA LETTER A - HIRAGANA A

def shift_chars_prefix(text, amount, condition):
    output = ''

    for last_index, char in enumerate(text):
        if not condition(char):
            break

        output += chr(ord(char) + amount)

    return output, last_index

def katakana_to_hiragana(text):
    return shift_chars_prefix(text, -KATAKANA_HIRGANA_SHIFT, lambda c: '\u30a0' < c < '\u30f7')

def hiragana_to_katakana(text):
    return shift_chars_prefix(text, KATAKANA_HIRGANA_SHIFT, lambda c: '\u3040' < c < '\u3097')
</code>```

You can also use regex if you don't return the length of the replaced prefix:

```<code>import re

KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041  # KATAKANA LETTER A - HIRAGANA A

def shift_by(n):
    def replacer(match):
        return ''.join(chr(ord(c) + n) for c in match.group(0))

    return replacer

def katakana_to_hiragana(text):
    return re.sub(r'^[\u30a1-\u30f6]+', shift_by(KATAKANA_HIRGANA_SHIFT), text)

def hiragana_to_katakana(text):
    return re.sub(r'^[\u3041-\u3096]+', shift_by(-KATAKANA_HIRGANA_SHIFT), text)
</code>```

Body:
I have two functions that convert between katakana and hiragana and they look the same:

katakana_minus_hiragana = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A

def is_hirgana(char):
    return 0x3040 < ord(char[0]) and ord(char[0]) < 0x3097

def is_katakana(char):
    return 0x30a0 < ord(char[0]) and ord(char[0]) < 0x30f7

def hiragana_to_katakana(hiragana_text):
    katakana_text = ""
    max_len = 0
    for i, char in enumerate(hiragana_text):
        if is_hirgana(char):
            katakana_text += chr(ord(char) + katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return katakana_text, max_len

def katakana_to_hiragana(katakana_text):
    hiragana_text = ""
    max_len = 0
    for i, char in enumerate(katakana_text):
        if is_katakana(char):
            hiragana_text += chr(ord(char) - katakana_minus_hiragana)
            max_len += 1
        else:
            break
    return hiragana_text, max_len

Is there a way to simplify hiragana_to_katakana() and katakana_to_hiragana() into a duck-type function or a super/meta function?

E.g. something like

def convert_hk_kh(text, charset_range, offset):
    charset_start, charset_end = charset_range
    output_text = ""
    max_len = 0
    for i, char in enumerate(text):
        if charset_start < ord(char[0]) and ord(char[0]) < charset_end:
            output_text += chr(ord(char) + offset)
            max_len +=1
        else:
            break
    return output_text, max_len

def katakana_to_hiragana(katakana_text):
    return convert_hk_kh(katakana_text, (0x30a0, 0x30f7), -katakana_minus_hiragana)

def hiragana_to_katakana(hiragana_text):
    return convert_hk_kh(hiragana_text, (0x3040, 0x3097), katakana_minus_hiragana)

Are there other pythonic ways to simplify the two functions that are very similar?

EDITED

There's also https://github.com/olsgaard/Japanese_nlp_scripts which seems to do the same thing with str.translate. Is that more efficient? More pythonic?

Body:
I'd do something like this:

KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041  # KATAKANA LETTER A - HIRAGANA A

def shift_chars_prefix(text, amount, condition):
    output = ''

    for last_index, char in enumerate(text):
        if not condition(char):
            break

        output += chr(ord(char) + amount)

    return output, last_index

def katakana_to_hiragana(text):
    return shift_chars_prefix(text, -KATAKANA_HIRGANA_SHIFT, lambda c: '\u30a0' < c < '\u30f7')

def hiragana_to_katakana(text):
    return shift_chars_prefix(text, KATAKANA_HIRGANA_SHIFT, lambda c: '\u3040' < c < '\u3097')

You can also use regex if you don't return the length of the replaced prefix:

import re

KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041  # KATAKANA LETTER A - HIRAGANA A

def shift_by(n):
    def replacer(match):
        return ''.join(chr(ord(c) + n) for c in match.group(0))

    return replacer

def katakana_to_hiragana(text):
    return re.sub(r'^[\u30a1-\u30f6]+', shift_by(KATAKANA_HIRGANA_SHIFT), text)

def hiragana_to_katakana(text):
    return re.sub(r'^[\u3041-\u3096]+', shift_by(-KATAKANA_HIRGANA_SHIFT), text)


问:
Proper way to optimize the input in TensorFlow for visualization
I have trained a model in TensorFlow and now I would like to visualize which inputs maximally activate an output. I'd like to know what the cleanest way to do this is.

I had thought to do this by creating a trainable input variable which I can assign once per run. Then by using an appropriate loss function and using an optimizer with a var_list containing just this input variable I would update this input variable until convergence. i.e.

```<code>trainable_input = tf.get_variable(
    'trainable_input',
    shape=data_op.get_shape(),
    dtype=data_op.dtype,
    initializer=tf.zeros_initializer(),
    trainable=True,
    collections=[tf.GraphKeys.LOCAL_VARIABLES])
trainable_input_assign_op = tf.assign(trainable_input, data_op)
data_op = trainable_input

# ... run the rest of the graph building code here, now with a trainable input

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
# loss_op is defined on one of the outputs
train_op = optimizer.minimize(loss_op, var_list=[trainable_input])
</code>```

However, when I do this I run into issues. If I try to restore the pre-trained graph using a Supervisor, then it naturally complains that the new variables created by the AdamOptimizer do not exist in the graph I'm trying to restore. I can remedy this by using get_slots to get the variables the AdamOptimizer creates and manually adding those variables to the tf.GraphKeys.LOCAL_VARIABLES collection, but it feels pretty hacky and I'm not sure what the consequences of this would be. I can also exclude those variables explicitly from the Saver that is passed to the Supervisor without adding them to the tf.GraphKeys.LOCAL_VARIABLES collection, but then I get an exception that they do not get properly initialized by the Supervisor:

```<code>File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 973, in managed_session
self.stop(close_summary_writer=close_summary_writer)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 801, in stop
stop_grace_period_secs=self._stop_grace_secs)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/coordinator.py", line 386, in join
six.reraise(*self._exc_info_to_raise)
File "/usr/local/lib/python3.5/site-packages/six.py", line 686, in reraise
raise value
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 962, in managed_session
start_standard_services=start_standard_services)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 719, in prepare_or_wait_for_session
init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/session_manager.py", line 280, in prepare_session
self._local_init_op, msg))
RuntimeError: Init operations did not make model ready.  Init op: init, init fn: None, local_init_op: name: "group_deps_5"
op: "NoOp"
input: "^init_1"
input: "^init_all_tables"
, error: Variables not initialized: trainable_input/trainable_input/Adam, trainable_input/trainable_input/Adam_1
</code>```

I'm not really sure why these variables are not getting initialized since I have used that technique before to exclude some variables from the restore process (GLOBAL and LOCAL) and they seem to get initialized as expected.

In short, my question is whether there is a simple way to add an optimizer to the graph and do a checkpoint restore (where the checkpoint does not contain the optimizer variables) without having to muck around with the internals of the optimizer. If that's not possible, then is there any downside to just adding the optimizer variables to the LOCAL_VARIABLES collection?

答:
The same error occurs when I use slim library. In fact, the slim.learning.train() uses tf.train.Supervisor inside. I hope my answer on this GitHub issue may help your Supervisor problem.

I have the same problem with you. I solve it by doing following two steps.

1. pass the parameter saver to slim.learning.train()

```<code>ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
saver = tf.train.Saver(var_list=optimistic_restore_vars(ckpt.model_checkpoint_path) if ckpt else None)
</code>```

where function optimistic_restore_vars is defined as

```<code>def optimistic_restore_vars(model_checkpoint_path):
    reader = tf.train.NewCheckpointReader(model_checkpoint_path)
    saved_shapes = reader.get_variable_to_shape_map()
    var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables() if var.name.split(':')[0] in saved_shapes])
    restore_vars = []
    name2var = dict(zip(map(lambda x:x.name.split(':')[0], f.global_variables()), tf.global_variables()))
    with tf.variable_scope('', reuse=True):
        for var_name, saved_var_name in var_names:
            curr_var = name2var[saved_var_name]
            var_shape = curr_var.get_shape().as_list()
            if var_shape == saved_shapes[saved_var_name]:
                restore_vars.append(curr_var)
    return restore_vars
</code>```

```</p>

<h3>2. pass the parameter <code>local_init_op</code> to <code>slim.learning.train()</code> to initialize the added new variables</h3>

```local_init_op = tf.global_variables_initializer()
```

<h3>In last, the code should look like this</h3>

```ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
saver = tf.train.Saver(var_list=optimistic_restore_vars ckpt.model_checkpoint_path) if ckpt else None)
local_init_op = tf.global_variables_initializer()

###########################
# Kicks off the training. #
###########################
learning.train(
    train_tensor,
    saver=saver,
    local_init_op=local_init_op,
    logdir=FLAGS.train_dir,
    master=FLAGS.master,
    is_chief=(FLAGS.task == 0),
    init_fn=_get_init_fn(),
    summary_op=summary_op,
    number_of_steps=FLAGS.max_number_of_steps,
    log_every_n_steps=FLAGS.log_every_n_steps,
    save_summaries_secs=FLAGS.save_summaries_secs,
    save_interval_secs=FLAGS.save_interval_secs,
    sync_optimizer=optimizer if FLAGS.sync_replicas else None
)
```

Body:
I have trained a model in TensorFlow and now I would like to visualize which inputs maximally activate an output. I'd like to know what the cleanest way to do this is.

I had thought to do this by creating a trainable input variable which I can assign once per run. Then by using an appropriate loss function and using an optimizer with a var_list containing just this input variable I would update this input variable until convergence. i.e.

trainable_input = tf.get_variable(
    'trainable_input',
    shape=data_op.get_shape(),
    dtype=data_op.dtype,
    initializer=tf.zeros_initializer(),
    trainable=True,
    collections=[tf.GraphKeys.LOCAL_VARIABLES])
trainable_input_assign_op = tf.assign(trainable_input, data_op)
data_op = trainable_input

# ... run the rest of the graph building code here, now with a trainable input

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
# loss_op is defined on one of the outputs
train_op = optimizer.minimize(loss_op, var_list=[trainable_input])

However, when I do this I run into issues. If I try to restore the pre-trained graph using a Supervisor, then it naturally complains that the new variables created by the AdamOptimizer do not exist in the graph I'm trying to restore. I can remedy this by using get_slots to get the variables the AdamOptimizer creates and manually adding those variables to the tf.GraphKeys.LOCAL_VARIABLES collection, but it feels pretty hacky and I'm not sure what the consequences of this would be. I can also exclude those variables explicitly from the Saver that is passed to the Supervisor without adding them to the tf.GraphKeys.LOCAL_VARIABLES collection, but then I get an exception that they do not get properly initialized by the Supervisor:

File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 973, in managed_session
self.stop(close_summary_writer=close_summary_writer)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 801, in stop
stop_grace_period_secs=self._stop_grace_secs)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/coordinator.py", line 386, in join
six.reraise(*self._exc_info_to_raise)
File "/usr/local/lib/python3.5/site-packages/six.py", line 686, in reraise
raise value
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 962, in managed_session
start_standard_services=start_standard_services)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 719, in prepare_or_wait_for_session
init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
File "/usr/local/lib/python3.5/site-packages/tensorflow/python/training/session_manager.py", line 280, in prepare_session
self._local_init_op, msg))
RuntimeError: Init operations did not make model ready.  Init op: init, init fn: None, local_init_op: name: "group_deps_5"
op: "NoOp"
input: "^init_1"
input: "^init_all_tables"
, error: Variables not initialized: trainable_input/trainable_input/Adam, trainable_input/trainable_input/Adam_1

I'm not really sure why these variables are not getting initialized since I have used that technique before to exclude some variables from the restore process (GLOBAL and LOCAL) and they seem to get initialized as expected.

In short, my question is whether there is a simple way to add an optimizer to the graph and do a checkpoint restore (where the checkpoint does not contain the optimizer variables) without having to muck around with the internals of the optimizer. If that's not possible, then is there any downside to just adding the optimizer variables to the LOCAL_VARIABLES collection?

Body:
The same error occurs when I use slim library. In fact, the slim.learning.train() uses tf.train.Supervisor inside. I hope my answer on this GitHub issue may help your Supervisor problem.

I have the same problem with you. I solve it by doing following two steps.

1. pass the parameter saver to slim.learning.train()

ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
saver = tf.train.Saver(var_list=optimistic_restore_vars(ckpt.model_checkpoint_path) if ckpt else None)

where function optimistic_restore_vars is defined as

def optimistic_restore_vars(model_checkpoint_path):
    reader = tf.train.NewCheckpointReader(model_checkpoint_path)
    saved_shapes = reader.get_variable_to_shape_map()
    var_names = sorted([(var.name, var.name.split(':')[0]) for var in tf.global_variables() if var.name.split(':')[0] in saved_shapes])
    restore_vars = []
    name2var = dict(zip(map(lambda x:x.name.split(':')[0], f.global_variables()), tf.global_variables()))
    with tf.variable_scope('', reuse=True):
        for var_name, saved_var_name in var_names:
            curr_var = name2var[saved_var_name]
            var_shape = curr_var.get_shape().as_list()
            if var_shape == saved_shapes[saved_var_name]:
                restore_vars.append(curr_var)
    return restore_vars

```

2. pass the parameter local_init_op to slim.learning.train() to initialize the added new variables

local_init_op = tf.global_variables_initializer()

In last, the code should look like this

ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
saver = tf.train.Saver(var_list=optimistic_restore_vars ckpt.model_checkpoint_path) if ckpt else None)
local_init_op = tf.global_variables_initializer()

###########################
# Kicks off the training. #
###########################
learning.train(
    train_tensor,
    saver=saver,
    local_init_op=local_init_op,
    logdir=FLAGS.train_dir,
    master=FLAGS.master,
    is_chief=(FLAGS.task == 0),
    init_fn=_get_init_fn(),
    summary_op=summary_op,
    number_of_steps=FLAGS.max_number_of_steps,
    log_every_n_steps=FLAGS.log_every_n_steps,
    save_summaries_secs=FLAGS.save_summaries_secs,
    save_interval_secs=FLAGS.save_interval_secs,
    sync_optimizer=optimizer if FLAGS.sync_replicas else None
)


问:
php juniper lot hotel soap web service not working
am trying to consume juniper soap web service but I am getting errors
the following is the code I am using

```<code> $client = new SoapClient('http://xml2.bookingengine.es/WebService/JP/WebServiceJP.asmx?WSDL', array("trace" => 1, "exception" => 1));$parameters = [
    'HotelListRQ' => [
        'version' => '1.1',
        'language' => 'en',
        'login' => ['email' => 'Email@email.com', 'password' => 'xxxxxxxx'],
        'HotelListRequest' => ['ZoneCode' => '55153']    ]];
$bookingList = $client->HotelList($parameters);
echo json_encode($bookingList);
</code>```

and the output is

{"HotelListRS":{"Errors":{"Error":{"Text":" Please add the
  'Accept-Encoding: gzip, deflate' header in your petition. This can
  reduce the transmission time and response size by about 75-95%. See
  more here:
  http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html","Code":"COMPRESSION_REQUIRED"}},"Url":"http://xml2.bookingengine.es","TimeStamp":"2017-10-18T13:21:09.69911+02:00","IntCode":"lTi3rTnUmLR/a7qZHG2RbvurJ1USoOdKCz2UX3Y19y0="}}

答:
it works with the SOAP client definition like that</p>

```<code>   $client = new SoapClient(
        'http://xml2.bookingengine.es/WebService/JP/WebServiceJP.asmx?WSDL',
        array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | SOAP_COMPRESSION_DEFLATE, 'trace' => 1)
    );
</code>```

Body:
am trying to consume juniper soap web service but I am getting errors
the following is the code I am using

 $client = new SoapClient('http://xml2.bookingengine.es/WebService/JP/WebServiceJP.asmx?WSDL', array("trace" => 1, "exception" => 1));$parameters = [
    'HotelListRQ' => [
        'version' => '1.1',
        'language' => 'en',
        'login' => ['email' => 'Email@email.com', 'password' => 'xxxxxxxx'],
        'HotelListRequest' => ['ZoneCode' => '55153']    ]];
$bookingList = $client->HotelList($parameters);
echo json_encode($bookingList);

and the output is

{"HotelListRS":{"Errors":{"Error":{"Text":" Please add the
  'Accept-Encoding: gzip, deflate' header in your petition. This can
  reduce the transmission time and response size by about 75-95%. See
  more here:
  http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html","Code":"COMPRESSION_REQUIRED"}},"Url":"http://xml2.bookingengine.es","TimeStamp":"2017-10-18T13:21:09.69911+02:00","IntCode":"lTi3rTnUmLR/a7qZHG2RbvurJ1USoOdKCz2UX3Y19y0="}}

Body:
it works with the SOAP client definition like that

   $client = new SoapClient(
        'http://xml2.bookingengine.es/WebService/JP/WebServiceJP.asmx?WSDL',
        array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | SOAP_COMPRESSION_DEFLATE, 'trace' => 1)
    );


问:
database datatype performance: int or string
I'm storing phone country codes. They range from 1 to about 300. What's going to be more performant for datatype: int or string? I'm using SQL server 2008 and linq-to-sql.

Thanks.

答:
How are you going to be using them and do any have leading zeros?

If you are going to be combining with phone numbers that are usually stored as string, you want to store them as a string as well or you will waste processing power converting them in every query.

If you aren't planning on doing math or joins with it, it is problably a bad idea to store as a number. Your data set is likely so small and the strings so tiny (300 is the max value) that using an int would probably gain you nothing in a join either.

ContentLicense: CC BY-SA 2.5


问:
Cannot load type from load type 'System.Drawing.Font' from assembly 'System.Drawing, Version=4.0.0.0
I know there are similar questions but i couldn't find the answer so i will ask a specif question.
I have a simple .net core console application.
I'm using the Syncfusion.DocIO.Base and Syncfusion.Core assemblies to create a WordDocument from a stream like this:

```<code>var word = new WordDocument(rtfStream, FormatType.Rtf);
</code>```

here i get the error message:
Could not load type 'System.Drawing.Font' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'

Do you have any idea where can i look to reslove this problem?`

答:
You have referred base assemblies which contains “System.Drawing” reference which is not supported in ASP.NET Core application.

So, please refer the following assemblies/NuGet packages to work with Word documents using Essential DocIO in ASP.NET Core.

```<code>Syncfusion.Compression.Portable
Syncfusion.DocIO.Portable
Syncfusion.OfficeChart.Portable
</code>```

You can find the installed assemblies and NuGet packages from below location.

$system drive:\Users\$user.nuget\packages\Syncfusion.DocIO.Portable
Eg : C:\Users\username.nuget\packages\Syncfusion.DocIO.Portable

You can find the ASP.NET Core NuGet packages in online from below link.
http://nuget.syncfusion.com/package/aspnetcore

Please refer the below link to know more about migration changes for ASP.NET Core.
https://help.syncfusion.com/aspnet-core/release-notes/migratingtov15.3.0.26?type=all

Please refer the below UG documentation links to know more about ASP.NET Core configuration with Essential DocIO.

https://help.syncfusion.com/aspnet-core/gettingstarted/getting-started-1-1-0
https://help.syncfusion.com/aspnet-core/installation

https://help.syncfusion.com/aspnet-core/gettingstarted/getting-started-1-1-0#configure-syncfusion-file-format-components-in-aspnet-core-application

https://help.syncfusion.com/aspnet-core/docio/overview

For further questions please contact our support team at support@syncfusion.com to get a prompt assistance on this.

Body:
I know there are similar questions but i couldn't find the answer so i will ask a specif question.
I have a simple .net core console application.
I'm using the Syncfusion.DocIO.Base and Syncfusion.Core assemblies to create a WordDocument from a stream like this:

var word = new WordDocument(rtfStream, FormatType.Rtf);

here i get the error message:
Could not load type 'System.Drawing.Font' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'

Do you have any idea where can i look to reslove this problem?`

Body:
You have referred base assemblies which contains “System.Drawing” reference which is not supported in ASP.NET Core application.

So, please refer the following assemblies/NuGet packages to work with Word documents using Essential DocIO in ASP.NET Core.

Syncfusion.Compression.Portable
Syncfusion.DocIO.Portable
Syncfusion.OfficeChart.Portable

You can find the installed assemblies and NuGet packages from below location.

$system drive:\Users\$user.nuget\packages\Syncfusion.DocIO.Portable
Eg : C:\Users\username.nuget\packages\Syncfusion.DocIO.Portable

You can find the ASP.NET Core NuGet packages in online from below link.
http://nuget.syncfusion.com/package/aspnetcore

Please refer the below link to know more about migration changes for ASP.NET Core.
https://help.syncfusion.com/aspnet-core/release-notes/migratingtov15.3.0.26?type=all

Please refer the below UG documentation links to know more about ASP.NET Core configuration with Essential DocIO.

https://help.syncfusion.com/aspnet-core/gettingstarted/getting-started-1-1-0
https://help.syncfusion.com/aspnet-core/installation

https://help.syncfusion.com/aspnet-core/gettingstarted/getting-started-1-1-0#configure-syncfusion-file-format-components-in-aspnet-core-application

https://help.syncfusion.com/aspnet-core/docio/overview

For further questions please contact our support team at support@syncfusion.com to get a prompt assistance on this.


问:
How to create table to store large data in SQL Server 2008
I am developing a VB.NET application that will communicate with an external device over serial port. It is a testing device in which a single lamp will be tested for 2000 hours continuously.

This device will give data pertaining lamp parameter (e.g. current) every 10 seconds, that means I will have 720000 readings per test. This data will be logged into some database for future reference.

I searched on the internet about saving such a big amount of data, but learnt that no database supports these many columns in a single table.

Please guide me as to how to log such a huge data.

答: Don't use columns. Use records. One reading = one record. Your table should have columns for a testID, timestamp, and reading value.</p>


问:
How to decode p7s sign properly
I have 2 pkcs7 signs. One of the can be easily decoded with http://lapo.it/asn1js/, while another cannot. I've opened those 2 files with Windows Notepad and one of them(which can be easily decoded) is shown like this(only the beginning)

0‚я   *†H†ч
 ‚р0‚м10

Weird, but this can be decoded. Moreover, notepad says that it's ANSI encoding.

On the other hand, my second file looks like 'normal'

MIIMMwYJKoZIhvcNAQcCoIIMJDCCDCACAQExDDAKBgYqhQMCAgkFADALBgkqhkiG

and so on and so forth.
Notepad says it's UTF-8 encoding. But I cannot verify who's the owner with ASN.1 decoder. The file just cannot be processed at all. I can figure this out only with Windows build-in utility. How can I make it to be decoded normally with ASN.1?

答: I finally found the solution. In the first case p7s sign is hex-encoded, while in the second it's Base64 encoded. Based on this I should choose decoding algorithm.

Title: How to decode p7s sign properly


问:
android can not get built jwPlayer maven repository
When I try to build my android application, It does not get built due to an error from JwPlayer in maven repository.

I got the following error:

```<code>Error:Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.
<a href="openFile:/home/masoudkh/AndroidStudioProjects/Tootak/app/build.gradle">Open File</a><br><a href="Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.">Show Details</a>
</code>```

答:
It seems the SSL Certificate had expired for mvn.jwplayer.com. It is now back online as I have successfully built my Android Studio project with Maven.

For future reference, you can always use the AAR’s to build your Android Studio Project available in your JW Player Dashboard or use the HTTP version of our Maven domain.

```<code>maven {
    url 'http://mvn.jwplayer.com/content/repositories/releases/'
}
</code>```

Body:
When I try to build my android application, It does not get built due to an error from JwPlayer in maven repository.

I got the following error:

Error:Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.longtailvideo.jwplayer:jwplayer-common:+.
Open File
Show Details

Body:
It seems the SSL Certificate had expired for mvn.jwplayer.com. It is now back online as I have successfully built my Android Studio project with Maven.

For future reference, you can always use the AAR’s to build your Android Studio Project available in your JW Player Dashboard or use the HTTP version of our Maven domain.

maven {
    url 'http://mvn.jwplayer.com/content/repositories/releases/'
}


问:
How can I log a hyperlink click?
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</code>```

to the Site.Master file.

And

```<code>public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}
</code>```

to the HomeController.cs file

And

```<code><p>
    <a id="lnkTestPost" href="/home/about">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething");
        });
    </script>
</p>
</code>```

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

答:
I think the browser could easily navigate to the URL before logging the click.  How about:</p>

```<code><p>
    <a id="lnkTestPost" href="#">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething", function(data) {
              // only tell the browse to navigate away once its logged
              window.location = '/home/about';
            });
        });
    </script>
</p>
</code>```

Title: How can I log a hyperlink click?

Body:
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

to the Site.Master file.

And

public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}

to the HomeController.cs file

And

    Test Post

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

Body:
I think the browser could easily navigate to the URL before logging the click.  How about:

<p>
    <a id="lnkTestPost" href="#">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething", function(data) {
              // only tell the browse to navigate away once its logged
              window.location = '/home/about';
            });
        });
    </script>
</p>


问:
Kafka - How to read more than 10 rows
I made connector that read from database with jdbc, and consuming it from a Spark application. The app read the database data well, BUT it read only first 10 row and seems to ignore rest of them. How should I get rest, so I can compute with all data.

Here are my spark code:

```<code>val brokers = "http://127.0.0.1:9092"
val topics = List("postgres-accounts2")
val sparkConf = new SparkConf().setAppName("KafkaWordCount")
//sparkConf.setMaster("spark://sda1:7077,sda2:7077")
sparkConf.setMaster("local[2]")
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
sparkConf.registerKryoClasses(Array(classOf[Record]))

val ssc = new StreamingContext(sparkConf, Seconds(2))
ssc.checkpoint("checkpoint")

 // Create direct kafka stream with brokers and topics
//val topicsSet = topics.split(",")

val kafkaParams = Map[String, Object](
  "schema.registry.url" -> "http://127.0.0.1:8081",
  "bootstrap.servers" -> "http://127.0.0.1:9092",
  "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
  "value.deserializer" -> "io.confluent.kafka.serializers.KafkaAvroDeserializer",
  "group.id" -> "use_a_separate_group_id_for_each_stream",
  "auto.offset.reset" -> "earliest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

val messages = KafkaUtils.createDirectStream[String, Record](
  ssc,
  PreferConsistent,
  Subscribe[String, Record](topics, kafkaParams)
)

val data = messages.map(record => {
    println( record) // print only first 10
    // compute here?
    (record.key, record.value)
})

data.print()

// Start the computation
ssc.start()
ssc.awaitTermination()
</code>```

答:
I believe the issue lies in that Spark is lazy and will only read the data that is actually used.

By default, print will show the first 10 elements in a stream. Since the code does not contain any other actions in addition to the two print there is no need to read more than 10 rows of data. Try using count or another action to confirm that it is working.

Title: Kafka - How to read more than 10 rows

Body:
I made connector that read from database with jdbc, and consuming it from a Spark application. The app read the database data well, BUT it read only first 10 row and seems to ignore rest of them. How should I get rest, so I can compute with all data.

Here are my spark code:

val brokers = "http://127.0.0.1:9092"
val topics = List("postgres-accounts2")
val sparkConf = new SparkConf().setAppName("KafkaWordCount")
//sparkConf.setMaster("spark://sda1:7077,sda2:7077")
sparkConf.setMaster("local[2]")
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
sparkConf.registerKryoClasses(Array(classOf[Record]))

val ssc = new StreamingContext(sparkConf, Seconds(2))
ssc.checkpoint("checkpoint")

 // Create direct kafka stream with brokers and topics
//val topicsSet = topics.split(",")

val kafkaParams = Map[String, Object](
  "schema.registry.url" -> "http://127.0.0.1:8081",
  "bootstrap.servers" -> "http://127.0.0.1:9092",
  "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
  "value.deserializer" -> "io.confluent.kafka.serializers.KafkaAvroDeserializer",
  "group.id" -> "use_a_separate_group_id_for_each_stream",
  "auto.offset.reset" -> "earliest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

val messages = KafkaUtils.createDirectStream[String, Record](
  ssc,
  PreferConsistent,
  Subscribe[String, Record](topics, kafkaParams)
)

val data = messages.map(record => {
    println( record) // print only first 10
    // compute here?
    (record.key, record.value)
})

data.print()

// Start the computation
ssc.start()
ssc.awaitTermination()


问:
Blender And UE4 - Noob : Using Model W/ Animations
I'm very sorry, but I tried looking everywhere and I cant fins an answer. I made a model in blender, and exported it as an .fbx file, imported it into UE4 third person default project. I tried  with and without a custom project. I need help getting my mesh into the blueprint animation.

In short, how do I get the character I made in blender to replace the character blueprint that comes default.

答:
Essentially you would create your own blueprint object or character model (programming model) which references the fbx file and the animations required.

There are tutorials on doing this as it is quite involved, I suggest Udemy or one of the other groups for online training.


问:
DOS Database - help needed to recognize what is it
today I got a copy of an old system from which I need to import data. The system is written in C and runs in DOS. It uses some kind of database. The file format seems to be rather simple(1 file = 1 table, header contains some description and then records, fields are delimited by 0 ASCII character, but it's not that simple as it seems).

The question is: how to recognize what database is used?

Is there any kind of software that maybe opens many formats?

Or is there any software that could help me?

Or any links to sites describing dos databases?

Or just anything that can help will be appreciated:)

PS> I can post some small files from the db if anyone wants to try guessing.

One small db file:

http://www.2shared.com/file/9137583/f840f261/WCENNIK.html

答: Is the original application functional?  Poke around a bit, and you may find a way to export the data.  Another thing to try is to "print" application reports to text file.  </p>


问:
Sublime and q files Automatic Build Setup, on Mac OS
I am working with Sublime and also running some q/kdb scripts from Sublime.
I have a "q Build" set up and works fine when I manually change the build.
But I tend to switch between q and other languages quiet often and each time I need to manually change the build type.

How can I setup all *.q files to be run automatically with the q build setup I already have only by doing the usual Command + B?

```<code>{
"cmd": ["[full q path]", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.q",

}
</code>```

答:
When you have the Build System set to Automatic (e.g. Tools > Build System > Automatic from the menu), Sublime should select the correct build system for the currently focused file as long as the build file is set up correctly.

Based on the build system you have outlined above, as long as you have some package installed that is providing a custom syntax for this package (e.g. the q KBD package) that assigns the scope source.q as a base scope, this should work fine in this case.

To verify, while a q file has the input focus, select Tools > Developer > Show Scope Name from the menu (or press the associated key) and make sure that the scope begins with source.q (the package above does this). The scope that you see may be longer than this depending on where you are in the file, but as long as it starts with this, you should be OK.

If that's not the scope that you see, then the reason the build as you've outlined it is not automatically selected is because the package you're using uses a different scope, or you don't have a q package installed (this is the case if the scope you see is text.plain, for example).

The solution in that case would be to either update the scope based on the package you're using or install the above package (if you don't have anything related to this already installed).

In lieu of installing a support package that provides a syntax, you could also modify the build to be as follows, which should tell it it to use the build for all *.q files regardless of their scope. Arguably the package install method is superior since it would give you syntax highlighting for your files as well.

{
    "cmd": ["[full q path]", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "file_patterns": ["*.q"]
}
```

Body:
I am working with Sublime and also running some q/kdb scripts from Sublime.
I have a "q Build" set up and works fine when I manually change the build.
But I tend to switch between q and other languages quiet often and each time I need to manually change the build type.

How can I setup all *.q files to be run automatically with the q build setup I already have only by doing the usual Command + B?

{
"cmd": ["[full q path]", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.q",

}


问:
Programmatically reduce log in a spark shell
Can I programmatically reduce the log in a spark shell by removing all the "INFO" flags?
It is spamming my window and I can't analyze the real output
For example:

```<code>15/01/09 12:23:02 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 649 bytes result sent to driver
15/01/09 12:23:02 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 500 ms on localhost (1/1)
15/01/09 12:23:02 INFO DAGScheduler: Stage 0 (count at MainApp.scala:31) finished in 0.520 s
15/01/09 12:23:02 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
15/01/09 12:23:02 INFO DAGScheduler: Job 0 finished: count at MainApp.scala:31, took 0.639191 s
</code>```

Looking for any alternatives if you have some!

答:
Just add this inside your Spark Source Code and it removes logs</p>

```<code>import org.apache.log4j.Logger
import org.apache.log4j.Level

Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)
</code>```

Body:
Can I programmatically reduce the log in a spark shell by removing all the "INFO" flags?
It is spamming my window and I can't analyze the real output
For example:

15/01/09 12:23:02 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 649 bytes result sent to driver
15/01/09 12:23:02 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 500 ms on localhost (1/1)
15/01/09 12:23:02 INFO DAGScheduler: Stage 0 (count at MainApp.scala:31) finished in 0.520 s
15/01/09 12:23:02 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
15/01/09 12:23:02 INFO DAGScheduler: Job 0 finished: count at MainApp.scala:31, took 0.639191 s

Looking for any alternatives if you have some!

Body:
Just add this inside your Spark Source Code and it removes logs

import org.apache.log4j.Logger
import org.apache.log4j.Level

Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)


问:
Putting current time into label
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.</p>

```<code>NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
</code>```

答:
Place a scheduled timer in your uiview did show (or did load) method:

```<code>[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
    target:self
    selector:@selector(updateTime:)
    userInfo:nil
    repeats:YES];
</code>```

Then, put this method in your View Controller:

```<code>- (void) updateTime:(id)sender
{
    NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY HH:mm:SS"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer.  I didn't check this for bugs.
}
</code>```

This will call the "updateTime:" method once a second, updating your controller.

Title: Putting current time into label

Body:
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.

NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];

Body:
Place a scheduled timer in your uiview did show (or did load) method:

[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
    target:self
    selector:@selector(updateTime:)
    userInfo:nil
    repeats:YES];

Then, put this method in your View Controller:

- (void) updateTime:(id)sender
{
    NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY HH:mm:SS"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer.  I didn't check this for bugs.
}

This will call the "updateTime:" method once a second, updating your controller.


问:
Test - FirebaseApp is not initialized in this process
I'm trying to run a test with Robolectric and it has an integration with Firebase. I have a project MyProject - Test that I'll be using to run the tests in a real instance of the database.

The problem is that, when running cleanup before test, I have the error:

```<code>java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.

at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.cgbros.silkhub.activity.listener.LoginActivityUnitTest.cleanUp(LoginActivityUnitTest.kt:26) <28 internal calls>
</code>```

The test file:
https://gist.github.com/augustoerico/e88d3e5b59ae5d023d83c114b8ffa708
(I tried to copy-paste the source here. Failed miserably...)

Any insights on how I can make this work?

Thank you!

答:
Ok, I've figured it out. It's actually a conceptual problem. The problem is that I'm trying to use the Firebase Android SDK to run a test outside of the Android context. I mean, my test is not an Android application, and I'm trying to use the Android SDK. All FirebaseApp.initializeApp() need a Context as a parameter.

So, what I have to do is to find a way to interact with my FirebaseDatabase. I think I can go with firebase-admin, or maybe use this one: https://github.com/bane73/firebase4j

Thank you for taking the time to help me (:

** Update **

I've opted to go with the Firebase REST API https://firebase.google.com/docs/reference/rest/database/

For future reference, I'm giving public full access, by tweaking the rules, so it is easier to write the tests setup and cleanup.

Body:
I'm trying to run a test with Robolectric and it has an integration with Firebase. I have a project MyProject - Test that I'll be using to run the tests in a real instance of the database.

The problem is that, when running cleanup before test, I have the error:

java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.

at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
at com.cgbros.silkhub.activity.listener.LoginActivityUnitTest.cleanUp(LoginActivityUnitTest.kt:26) <28 internal calls>

The test file:
https://gist.github.com/augustoerico/e88d3e5b59ae5d023d83c114b8ffa708
(I tried to copy-paste the source here. Failed miserably...)

Any insights on how I can make this work?

Thank you!


问:
Dialog box to save file as on existing script
I have the following code but I am trying to get it to prompt user with a dynamic dialog box to get the output file to "save as".

```<code>$pathtsv = "c:\test.txt"
$pathxlsx = "c:\NBP ESP-152 REV F TEMPLATE.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true

$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel

$temp = $excel.Workbooks.Item(2)  #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy()  #copy data

$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data

#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()
</code>```

So I tried adding in:

```<code>$SaveFileDialog = New-Object windows.forms.savefiledialog
    $SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
</code>```

but it does not seem to be working.  Not sure why, maybe because I am still newbish to powershell scripting.  I just want to get it to end on the save as dialog box, would be fine.  Do I have to cut the end of the original out?  (IE. does this get cut out?

```<code>$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()
</code>```

)

答:
You need to do a few things to make this work. First, add a reference to System.Windows.Forms

```<code>Add-Type -AssemblyName System.Windows.Forms
</code>```

After your copy/paste operations create the dialog and set a couple properties

```<code>$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
$SaveFileDialog.Filter = 'All files (*.*)|*.*'
</code>```

This is where you will need to decide what you want to do when showing the dialog. Do you allow the user to cancel, how do you handle empty paths, incorrect extensions, etc... For the sake of example, I am going to simply continue to show it until a path is chosen. I am not endorsing this as a good choice.

```<code>$dialogResult = $null
while($dialogResult -ne "OK"){
    $dialogResult = $SaveFileDialog.ShowDialog()
}
</code>```

You can then access the selected path with the FileName property and perform and checks needed on it

```<code>$SaveFileDialog.FileName
</code>```

Pass this to the excel workbook's SaveAs method. See this answer for details on this method https://stackoverflow.com/a/25289878/3594883

```<code>$WorkBook.SaveAs($SaveFileDialog.FileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)
</code>```

Finally close your workbook and excel. Perform cleanup etc.

Body:
I have the following code but I am trying to get it to prompt user with a dynamic dialog box to get the output file to "save as".

$pathtsv = "c:\test.txt"
$pathxlsx = "c:\NBP ESP-152 REV F TEMPLATE.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true

$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel

$temp = $excel.Workbooks.Item(2)  #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy()  #copy data

$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data

#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

So I tried adding in:

$SaveFileDialog = New-Object windows.forms.savefiledialog
    $SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()

but it does not seem to be working.  Not sure why, maybe because I am still newbish to powershell scripting.  I just want to get it to end on the save as dialog box, would be fine.  Do I have to cut the end of the original out?  (IE. does this get cut out?

$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

)

Body:
You need to do a few things to make this work. First, add a reference to System.Windows.Forms

Add-Type -AssemblyName System.Windows.Forms

After your copy/paste operations create the dialog and set a couple properties

$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
$SaveFileDialog.Filter = 'All files (*.*)|*.*'

This is where you will need to decide what you want to do when showing the dialog. Do you allow the user to cancel, how do you handle empty paths, incorrect extensions, etc... For the sake of example, I am going to simply continue to show it until a path is chosen. I am not endorsing this as a good choice.

$dialogResult = $null
while($dialogResult -ne "OK"){
    $dialogResult = $SaveFileDialog.ShowDialog()
}

You can then access the selected path with the FileName property and perform and checks needed on it

$SaveFileDialog.FileName

Pass this to the excel workbook's SaveAs method. See this answer for details on this method https://stackoverflow.com/a/25289878/3594883

$WorkBook.SaveAs($SaveFileDialog.FileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)

Finally close your workbook and excel. Perform cleanup etc.


问:
How to send proper response from Promise
I have axios to get data from Server in CustomerService.js

```<code>UpdateCustomer(customer){
        let vm = this;
        return new Promise((resolve, reject) => {
            Axios.post("/members/update", customer)
            .then(function (response) {
                if (!response.success){
                    reject(response.message);
                }else{
                    resolve(vm.CommonService.parseJson(response.data));
                }
            })
            .catch(function (error) {
                 reject(error);
            });
        });
    }
</code>```

In my vue component file I am receving this rsponse but problem I am getting response in both then and catch and it throws error.

```<code>vm.CustomerService.UpdateCustomer({customer})
            .then(function (data) {
                vm.app.Success("Success");
                vm.postCustomerTask(data);
            })
            .catch(function (error) {
                vm.app.Fail(error);
            });
</code>```

I am getting Json parse error. I dont seem to find exact problem. All I can think of is reject from UpdateCustomer is going in then in vue component.

答:
I think you have wrong logic in the if-else statements. You have rejected under the success logic.

```<code>if (response.success){
   resolve(vm.CommonService.parseJson(response.data));
} else {
   reject(response.message);
}
</code>```

Body:
I have axios to get data from Server in CustomerService.js

UpdateCustomer(customer){
        let vm = this;
        return new Promise((resolve, reject) => {
            Axios.post("/members/update", customer)
            .then(function (response) {
                if (!response.success){
                    reject(response.message);
                }else{
                    resolve(vm.CommonService.parseJson(response.data));
                }
            })
            .catch(function (error) {
                 reject(error);
            });
        });
    }

In my vue component file I am receving this rsponse but problem I am getting response in both then and catch and it throws error.

vm.CustomerService.UpdateCustomer({customer})
            .then(function (data) {
                vm.app.Success("Success");
                vm.postCustomerTask(data);
            })
            .catch(function (error) {
                vm.app.Fail(error);
            });

I am getting Json parse error. I dont seem to find exact problem. All I can think of is reject from UpdateCustomer is going in then in vue component.

Body:
I think you have wrong logic in the if-else statements. You have rejected under the success logic.

if (response.success){
   resolve(vm.CommonService.parseJson(response.data));
} else {
   reject(response.message);
}