问:
regex to remove first part of pathName
I got a string which is actually part of an url, like this:

```<code>/m/some/url/string
</code>```

I need to remove 1st part of this string, e.g. /m/ to look it like this:

```<code>some/url/string
</code>```

I tried this code:

```<code>var pathName = '/m/some/url/string';
pathName = pathName.replace(/^\/.[^\/]+\//g, '');
console.log(pathName);//same string here as it was
</code>```

and verified in regex101.com that it worked. But when I launched this code in console, the string remained unchanged. Any ideas how to fix it? Thank you

EDIT_1 Strangely enough, but it is working with /my/ but not working with /m/. Any ideas why?

答:
Strangely enough, but it is working with /my/ but not working with /m/. Any ideas why?

Nothing strange here, your \/.[^\/]+ regex is working with /my/ and isn't working with /m/ because it expects at least two characters after the first / because . matches exactly one character and [^\/]+ matches at least one character, and m is 1 character that's why it wasn't matched.

So you need to remove the firts . in your regex :

```<code>/^\/[^\/]+\//g
</code>```

Or you can just use .replace(/^\/[\w\d]+\//, '') like this:

```<code>str = str.replace(/^\/[\w\d]+\//, '');
</code>```

Demo:

var str = "/m/some/url/string";
str = str.replace(/^\/[\w\d]+\//, '');
console.log(str);```

Title: regex to remove first part of pathName

Body:
I got a string which is actually part of an url, like this:

/m/some/url/string

I need to remove 1st part of this string, e.g. /m/ to look it like this:

some/url/string

I tried this code:

var pathName = '/m/some/url/string';
pathName = pathName.replace(/^\/.[^\/]+\//g, '');
console.log(pathName);//same string here as it was

and verified in regex101.com that it worked. But when I launched this code in console, the string remained unchanged. Any ideas how to fix it? Thank you

EDIT_1 Strangely enough, but it is working with /my/ but not working with /m/. Any ideas why?

Body:
Strangely enough, but it is working with /my/ but not working with /m/. Any ideas why?

Nothing strange here, your \/.[^\/]+ regex is working with /my/ and isn't working with /m/ because it expects at least two characters after the first / because . matches exactly one character and [^\/]+ matches at least one character, and m is 1 character that's why it wasn't matched.

So you need to remove the firts . in your regex :

/^\/[^\/]+\//g

Or you can just use .replace(/^\/[\w\d]+\//, '') like this:

str = str.replace(/^\/[\w\d]+\//, '');

Demo:

var str = "/m/some/url/string";
str = str.replace(/^\/[\w\d]+\//, '');
console.log(str);


来源: stackexchange

答: Running WAMP and i had same issue, opted for the traditional stop and start all services and that did it for me. I was able to create the database after that, really don't know why i wasn't able to create it at first as i had no issue with space or permission. Well i hope this helps the WAMP users</p>

ContentLicense: CC BY-SA 3.0

Title: ERROR 1006 (HY000) Can't create database (errno: 13) MySQL 5.6.12

Body:
I am facing problem creating the database and it results in following error.

mysql> show grants for 'admin'@'%';
+---------------------------------------------------------------------------------------------------------------------------------+
| Grants for admin@%                                                                                |
+---------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY PASSWORD '*4ACFE3202A5FF5CF467898FC58AAB1D615029441' WITH GRANT OPTION |
+---------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> create database abc;
ERROR 1006 (HY000): Can't create database 'abc' (errno: 13)

Here is my users table.

mysql> select host, user from mysql.user;
+-------------+-------+
| host        | user  |
+-------------+-------+
| %           | admin |
| 127.0.0.1   | root  |
| ::1         | root  |
| IVM-MMC-DGW | root  |
| localhost   | admin |
| localhost   | root  |
+-------------+-------+
6 rows in set (0.00 sec)

mysql> show grants;
+-----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for admin@localhost                                                                                |
+-----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '*4ACFE3202A5FF5CF467898FC58AAB1D615029441' WITH GRANT OPTION |
+-----------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

I can create and remove table in the existing database.

The data directory already has mysql:mysql privileges and also the logged in user has privilege to create the new database.

What configuration is missing here ?


问:
"Compile pdf" in Rstudio works but knit2pdf does not work in R or RStudio
I'm hoping someone can point me to the internal setting that can fix my issue with compiling tex docs from R.

My issues is that texi2pdf and knit2pdf throw warnings and do not generate a pdf.

I can get Rnw files to compile using the "Compile pdf" button in RStudio, I can knit rnw files into text files, and I can get my tex files to compile into pdf using TeXnicCenter, but I can't get the texi2pdf or knit2pdf functions to work in R.

In Windows 7 on one machine with TexLive installed and on another machine with MikTex 2.9 installed, when I run the following:

```<code>library(knitr)
f = system.file("examples", "knitr-minimal.Rnw", package = "knitr")
knit(f)  # compile to tex
texi2pdf(gsub('Rnw', 'tex', f))
</code>```

the first part works (rnw->tex), but the texi2pdf (tex->pdf) results in:

```<code>Warning message:
running command '"C:\PROGRA~2\MIKTEX~1.9\miktex\bin\texify.exe" --quiet --pdf
"C:/Program Files/R/R-3.3.3/library/knitr/examples/knitr-minimal.tex" --max-
iterations=20 -I "C:/PROGRA~1/R/R-33~1.3/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-33~1.3/share/texmf/bibtex/bst"' had status 1
</code>```

The same is true if I run knit2pdf(f), I get the same warning message + a pop up "pdflatex.EXE has stopped working".

One other thing I don't understand is that I have MikTex 2.9 in my path, but the warning message references MikTex 1.9, which is not installed on my machine and is not in the path.

答:
This isn't so much a fix as a work around...</p>

```<code>library(knitr)
setwd(system.file("examples", package = "knitr"))
knit("knitr-minimal.Rnw")  # compile to tex
system('pdflatex knitr-minimal.tex')
</code>```

Body:
I'm hoping someone can point me to the internal setting that can fix my issue with compiling tex docs from R.

My issues is that texi2pdf and knit2pdf throw warnings and do not generate a pdf.

I can get Rnw files to compile using the "Compile pdf" button in RStudio, I can knit rnw files into text files, and I can get my tex files to compile into pdf using TeXnicCenter, but I can't get the texi2pdf or knit2pdf functions to work in R.

In Windows 7 on one machine with TexLive installed and on another machine with MikTex 2.9 installed, when I run the following:

library(knitr)
f = system.file("examples", "knitr-minimal.Rnw", package = "knitr")
knit(f)  # compile to tex
texi2pdf(gsub('Rnw', 'tex', f))

the first part works (rnw->tex), but the texi2pdf (tex->pdf) results in:

Warning message:
running command '"C:\PROGRA~2\MIKTEX~1.9\miktex\bin\texify.exe" --quiet --pdf
"C:/Program Files/R/R-3.3.3/library/knitr/examples/knitr-minimal.tex" --max-
iterations=20 -I "C:/PROGRA~1/R/R-33~1.3/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-33~1.3/share/texmf/bibtex/bst"' had status 1

The same is true if I run knit2pdf(f), I get the same warning message + a pop up "pdflatex.EXE has stopped working".

One other thing I don't understand is that I have MikTex 2.9 in my path, but the warning message references MikTex 1.9, which is not installed on my machine and is not in the path.

Body:
This isn't so much a fix as a work around...

library(knitr)
setwd(system.file("examples", package = "knitr"))
knit("knitr-minimal.Rnw")  # compile to tex
system('pdflatex knitr-minimal.tex')


问:
Passing template tabs value while creating envelope
I know there exists an question similar to the one which I am going to ask but that question was asked 4 years back and no concrete answer is given. Link for the question is here

I am creating an envelope using existing template and everything works smooth as butter. But, when I try to pre fill tabs value in template, tabs values are not being added to envelope. I have tried two different JSON requests, one with tabId and one with tabLabel. None of them worked.

Try 1:

```<code>{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabId":"bb56d91a-1665-4817-99a6-643c67defbc1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabId":"ba5p67cb-bcf5-42b0-aa04-a0cfec448ddc",
                    "value":"Temporary companyname"
                }]
            }
         }]
}
</code>```

Try 2:

```<code>{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabLabel":"CustomField1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabLabel":"Company 2fdbb190-2f3e-4d39-8202-e15b9a1c332a,
                    "value":"Temporary companyname"
                }]
            }
         }]
}
</code>```

Can someone tell me if I am doing wrong.

答:
You cannot prepopulate FullNameTab, EmailTab, CompanyTab, TitleTab using API call. FullName and Email tabs get populated automatically when your recipient starts the signing process, DocuSign knows the signers name and email as you have set these values as below:

```<code>"name":"xyz",
"email":"temp@email.com"
</code>```

CompanyTab and TitleTab is automatically added by DocuSign if the recipient has any DocuSign account and there values are present in their user profile. If not, then these tabs will be text field and signers can type their company name and titles.

So if you want to prepopulate anything then you need to use TextTabs, and then you can populate values to those text tabs using JSON request using tablabel.

Body:
I know there exists an question similar to the one which I am going to ask but that question was asked 4 years back and no concrete answer is given. Link for the question is here

I am creating an envelope using existing template and everything works smooth as butter. But, when I try to pre fill tabs value in template, tabs values are not being added to envelope. I have tried two different JSON requests, one with tabId and one with tabLabel. None of them worked.

Try 1:

{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabId":"bb56d91a-1665-4817-99a6-643c67defbc1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabId":"ba5p67cb-bcf5-42b0-aa04-a0cfec448ddc",
                    "value":"Temporary companyname"
                }]
            }
         }]
}

Try 2:

{
    "status":"sent",
    "emailSubject":"Testing with DocuSign",
    "templateId":"124faf68-3b42-43b9-9b6d-814d465e161d",
    "templateRoles":
        [{
            "roleName":"Climber",
            "name":"xyz",
            "email":"temp@email.com",
            "clientUserId":"126789",
            "tabs":{
                "fullNameTabs":[{
                    "tabLabel":"CustomField1",
                    "value":"abc"
                }],
                "companyTabs":[{
                    "tabLabel":"Company 2fdbb190-2f3e-4d39-8202-e15b9a1c332a,
                    "value":"Temporary companyname"
                }]
            }
         }]
}

Can someone tell me if I am doing wrong.

Body:
You cannot prepopulate FullNameTab, EmailTab, CompanyTab, TitleTab using API call. FullName and Email tabs get populated automatically when your recipient starts the signing process, DocuSign knows the signers name and email as you have set these values as below:

"name":"xyz",
"email":"temp@email.com"

CompanyTab and TitleTab is automatically added by DocuSign if the recipient has any DocuSign account and there values are present in their user profile. If not, then these tabs will be text field and signers can type their company name and titles.

So if you want to prepopulate anything then you need to use TextTabs, and then you can populate values to those text tabs using JSON request using tablabel.


问:
How to add and remove nested model fields dynamically using Haml and Formtastic
We've all seen the brilliant complex forms railscast where Ryan Bates explains how to dynamically add or remove nested objects within the parent object form using Javascript.

Has anyone got any ideas about how these methods need to be modified so as to work with Haml Formtastic?

To add some context here's a simplified version of the problem I'm currently facing:

# Teacher form (which has nested subject forms) [from my application]

```<code>- semantic_form_for(@teacher) do |form|
  - form.inputs do
    = form.input :first_name
    = form.input :surname
    = form.input :city
    = render 'subject_fields', :form => form
    = link_to_add_fields "Add Subject", form, :subjects
</code>```

# Individual Subject form partial [from my application]

```<code>- form.fields_for :subjects do |ff|
  #subject_field
    = ff.input :name
    = ff.input :exam
    = ff.input :level
    = ff.hidden_field :_destroy
    = link_to_remove_fields "Remove Subject", ff
</code>```

# Application Helper (straight from Railscasts)

```<code>  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}  \")"))
  end
</code>```

#Application.js (straight from Railscasts)

```<code>  function remove_fields(link) {
  $(link).previous("input[type=hidden]").value = "1";
  $(link).up(".fields").hide();
  }

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).up().insert({
    before: content.replace(regexp, new_id)
  });
  }
</code>```

The problem with implementation seems to be with the javascript methods - the DOM tree of a Formtastic form differs greatly from a regular rails form.

I've seen this question asked online a few times but haven't come across an answer yet - now you know that help will be appreciated by more than just me!

Jack

答:
I've been beating my head against this one on and off for years, and I just today came up with something I'm proud of - elegant, unobtrusive, and you can do it only two or three (really long) lines of code.

ParentFoo has_many NestedBars, with appropriate accepts_nested_parameters and all those goodies.  You render a set of fields for a nested_bar into a data-add-nested attribute on the link, using the :child_index to set a string that you can replace later.  You pass that string in a second parameter, data-add-nested-replace

parent_foos/_form.html.haml

```<code>- semantic_form_for @parent_foo do |f|
  -# render existing records
  - f.semantic_fields_for :nested_bars do |i|
    = render 'nested_bar_fields', :f => i

  # magic!
  - reuse_fields = f.semantic_fields_for :nested_bars, @parent_foo.nested_bars.build, :child_index => 'new_nested_bar_fields' do |n| render('nested_bar_fields', :f => n) end
  = link_to 'Add nested bar', '#', 'data-add-nested' => reuse_fields, 'data-add-nested-replace' => 'new_nested_bar_fields'
</code>```

the nested fields partial is nothing fancy

parent_foos/_nested_bar_fields.html.haml

```<code>- f.inputs do
  = f.input :name
  = f.input :_delete, :as => :boolean
</code>```

In your jQuery you bind the click of elements with a data-add-nested field (I've used live() here so ajax-loaded forms will work) to insert the fields into the DOM, replacing the string with a new ID.  Here I'm doing the simple thing of inserting the new fields before() the link, but you could also provide an add-nested-replace-target attribute on the link saying where in the DOM you want the new fields to wind up.

application.js

```<code>$('a[data-add-nested]').live('click', function(){
  var regexp = new RegExp($(this).data('add-nested-replace'), "g")
  $($(this).data('add-nested').replace(regexp, (new Date).getTime())).insertBefore($(this))
})
</code>```

You could put this in a helper, of course; I'm presenting it here directly in the view so the principle is clear without mucking about in metaprogramming.  If you're worried about names colliding, you could generate a unique ID in that helper and pass it in nested-replace.

getting fancy with the delete behaviour is left as an exercise for the reader.

(shown for Rails 2 because that's the site I'm working on today - almost the same in Rails 3)

ContentLicense: CC BY-SA 2.5

Body:
We've all seen the brilliant complex forms railscast where Ryan Bates explains how to dynamically add or remove nested objects within the parent object form using Javascript.

Has anyone got any ideas about how these methods need to be modified so as to work with Haml Formtastic?

To add some context here's a simplified version of the problem I'm currently facing:

# Teacher form (which has nested subject forms) [from my application]

- semantic_form_for(@teacher) do |form|
  - form.inputs do
    = form.input :first_name
    = form.input :surname
    = form.input :city
    = render 'subject_fields', :form => form
    = link_to_add_fields "Add Subject", form, :subjects

# Individual Subject form partial [from my application]

- form.fields_for :subjects do |ff|
  #subject_field
    = ff.input :name
    = ff.input :exam
    = ff.input :level
    = ff.hidden_field :_destroy
    = link_to_remove_fields "Remove Subject", ff

# Application Helper (straight from Railscasts)

  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}  \")"))
  end

#Application.js (straight from Railscasts)

  function remove_fields(link) {
  $(link).previous("input[type=hidden]").value = "1";
  $(link).up(".fields").hide();
  }

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).up().insert({
    before: content.replace(regexp, new_id)
  });
  }

The problem with implementation seems to be with the javascript methods - the DOM tree of a Formtastic form differs greatly from a regular rails form.

I've seen this question asked online a few times but haven't come across an answer yet - now you know that help will be appreciated by more than just me!

Jack

Body:
I've been beating my head against this one on and off for years, and I just today came up with something I'm proud of - elegant, unobtrusive, and you can do it only two or three (really long) lines of code.

ParentFoo has_many NestedBars, with appropriate accepts_nested_parameters and all those goodies.  You render a set of fields for a nested_bar into a data-add-nested attribute on the link, using the :child_index to set a string that you can replace later.  You pass that string in a second parameter, data-add-nested-replace

parent_foos/_form.html.haml

- semantic_form_for @parent_foo do |f|
  -# render existing records
  - f.semantic_fields_for :nested_bars do |i|
    = render 'nested_bar_fields', :f => i

  # magic!
  - reuse_fields = f.semantic_fields_for :nested_bars, @parent_foo.nested_bars.build, :child_index => 'new_nested_bar_fields' do |n| render('nested_bar_fields', :f => n) end
  = link_to 'Add nested bar', '#', 'data-add-nested' => reuse_fields, 'data-add-nested-replace' => 'new_nested_bar_fields'

the nested fields partial is nothing fancy

parent_foos/_nested_bar_fields.html.haml

- f.inputs do
  = f.input :name
  = f.input :_delete, :as => :boolean

In your jQuery you bind the click of elements with a data-add-nested field (I've used live() here so ajax-loaded forms will work) to insert the fields into the DOM, replacing the string with a new ID.  Here I'm doing the simple thing of inserting the new fields before() the link, but you could also provide an add-nested-replace-target attribute on the link saying where in the DOM you want the new fields to wind up.

application.js

$('a[data-add-nested]').live('click', function(){
  var regexp = new RegExp($(this).data('add-nested-replace'), "g")
  $($(this).data('add-nested').replace(regexp, (new Date).getTime())).insertBefore($(this))
})

You could put this in a helper, of course; I'm presenting it here directly in the view so the principle is clear without mucking about in metaprogramming.  If you're worried about names colliding, you could generate a unique ID in that helper and pass it in nested-replace.

getting fancy with the delete behaviour is left as an exercise for the reader.

(shown for Rails 2 because that's the site I'm working on today - almost the same in Rails 3)


问:
Unit-testing directive controllers in Angular without making controller global
In Vojta Jina's excellent repository where he demonstrates testing of directives, he defines the directive controller outside of the module wrapper. See here:
https://github.com/vojtajina/ng-directive-testing/blob/master/js/tabs.js

Isn't that bad practice and pollute the global namespace?

If one were to have another place where it might be logical to call something TabsController, wouldn't that break stuff?

The tests for the mentioned directive is to be found here: https://github.com/vojtajina/ng-directive-testing/commit/test-controller

Is it possible to test directive controllers separate from the rest of the directive, without placing the controller in a global namespace?

It would be nice to encapsulate the whole directive within the app.directive(...) definition.

答:
Use IIFE, which is a common technique to avoid global namespace conflict & it also save tricky inline gymnastics, plus provide freedom in your scope.</p>

```<code> (function(){

  angular.module('app').directive('myDirective', function(){
     return {
       .............
       controller : MyDirectiveController,
       .............
     }
  });

  MyDirectiveController.$inject = ['$scope'];

  function MyDirectiveController ($scope) {

  }

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

Body:
Use IIFE, which is a common technique to avoid global namespace conflict & it also save tricky inline gymnastics, plus provide freedom in your scope.

 (function(){

  angular.module('app').directive('myDirective', function(){
     return {
       .............
       controller : MyDirectiveController,
       .............
     }
  });

  MyDirectiveController.$inject = ['$scope'];

  function MyDirectiveController ($scope) {

  }

})();


问:
Search Cell for no mention of a specific string
I have some code that currently searches  column A for the mention of 27 and copies the cells in column B, same row as 27 into Column C. Is there a way to modify this code to copy the values of cells when 27 is not in Column A. Does that make sense?

The sample worksheet contains the number 27 in Cells (A1:A30) and the number 1 in Cells (B1:B30); except in A5, where it's 28, and B5 where it's 2.
I know, in this case, i could search for 28, but the main reason for this code is that there will be more than 1 value that could be different i.e. a 26 or 22 , as well as 30 etc.

When I was thinking about this, I assumed that I had to change the line If Not foundCel Is Nothing Then to something different, but I may be barking up the wrong tree here.

```<code>Option Explicit

Sub Button1_Click()

    Dim v As Long

    v = 1
    findStr = "27"
    Set foundCel = Range("A:A").Find(What:=findStr)

    If Not foundCel Is Nothing Then              'Yes'

        firstAddress = foundCel.Address

        Do

            Range("C" & v).Value = foundCel.Offset(0, 1).Value
            Set foundCel = Range("A:A").FindNext(foundCel)
            v = v + 1

        Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress

    End If

End Sub
</code>```

Thanks for any help you can provide.

答:
Here you go, tests for 27 not being present in the string of column1 (A), if it is not it copies column2 (B) to column3 (C):

```<code>Private Sub Button1_Click()

'Searches all text in Column 2 on a Sheet for the string located in Column 1

Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim i As Integer

Dim Col1 As Double
Dim Col2 As Double
DIM Col3 As Double

Dim Col1_rowSTART As Double
Dim Col1_rowEND As Double

Dim strTest As String

'Set up parameter that we know
Set ThisWB = ActiveWorkbook
Set ThisWS = ActiveSheet
Col1 = 1
Col2 = 2
Col3 = 3
strTest = "27"
'Define Starting Row for each column
Col1_rowSTART = 1

'Define ending row for each column
Col1_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col1).End(xlUp).Row

For i = Col1_rowSTART To Col1_rowEND
    'make a string out of each cell value in Col1
    'Check if 27 is NOT in the cell string being tested
    'to test if it IS change to > 0
    If InStr(CStr(ThisWS.Cells(i, Col1)), strTest) = 0 Then
            ThisWS.Cells(i, Col3).Value = ThisWS.Cells(i, Col2)
    End If

Next i

MsgBox ("27 Search Complete!")

End Sub
</code>```

Quick and dirty.  Cheers.
-WWC

Body:
I have some code that currently searches  column A for the mention of 27 and copies the cells in column B, same row as 27 into Column C. Is there a way to modify this code to copy the values of cells when 27 is not in Column A. Does that make sense?

The sample worksheet contains the number 27 in Cells (A1:A30) and the number 1 in Cells (B1:B30); except in A5, where it's 28, and B5 where it's 2.
I know, in this case, i could search for 28, but the main reason for this code is that there will be more than 1 value that could be different i.e. a 26 or 22 , as well as 30 etc.

When I was thinking about this, I assumed that I had to change the line If Not foundCel Is Nothing Then to something different, but I may be barking up the wrong tree here.

Option Explicit

Sub Button1_Click()

    Dim v As Long

    v = 1
    findStr = "27"
    Set foundCel = Range("A:A").Find(What:=findStr)

    If Not foundCel Is Nothing Then              'Yes'

        firstAddress = foundCel.Address

        Do

            Range("C" & v).Value = foundCel.Offset(0, 1).Value
            Set foundCel = Range("A:A").FindNext(foundCel)
            v = v + 1

        Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress

    End If

End Sub

Thanks for any help you can provide.

Body:
Here you go, tests for 27 not being present in the string of column1 (A), if it is not it copies column2 (B) to column3 (C):

Private Sub Button1_Click()

'Searches all text in Column 2 on a Sheet for the string located in Column 1

Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim i As Integer

Dim Col1 As Double
Dim Col2 As Double
DIM Col3 As Double

Dim Col1_rowSTART As Double
Dim Col1_rowEND As Double

Dim strTest As String

'Set up parameter that we know
Set ThisWB = ActiveWorkbook
Set ThisWS = ActiveSheet
Col1 = 1
Col2 = 2
Col3 = 3
strTest = "27"
'Define Starting Row for each column
Col1_rowSTART = 1

'Define ending row for each column
Col1_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col1).End(xlUp).Row

For i = Col1_rowSTART To Col1_rowEND
    'make a string out of each cell value in Col1
    'Check if 27 is NOT in the cell string being tested
    'to test if it IS change to > 0
    If InStr(CStr(ThisWS.Cells(i, Col1)), strTest) = 0 Then
            ThisWS.Cells(i, Col3).Value = ThisWS.Cells(i, Col2)
    End If

Next i

MsgBox ("27 Search Complete!")

End Sub

Quick and dirty.  Cheers.
-WWC


问:
Full Calendar event render, jQuery
Is it possible to edit events on full calendar? For the moment I see only texts on the events but what I want to do is to import pictures also, so it should have Name, Profession, Date. I tried to edit it via prepend jQuery, so I wrote

```<code>$(element).find('.fc-title').prepend('<div class="example" ></div>');
</code>```

and when I drag the event into it it should remove the date from there and show it inside event div

答:
You'll need to update your CSS for '.fc-title'

Either:

element.find('.fc-title').css({ 'white-space:': 'normal !important' });

or CSS:

.fc-title {
    white-space: normal !important;
  }

Title: Full Calendar event render, jQuery

Body:
Is it possible to edit events on full calendar? For the moment I see only texts on the events but what I want to do is to import pictures also, so it should have Name, Profession, Date. I tried to edit it via prepend jQuery, so I wrote

$(element).find('.fc-title').prepend('

');

and when I drag the event into it it should remove the date from there and show it inside event div


问:
docker-compose.yml using 10up/phpfpm and httd:latest cannot run php files
I'd like to start by saying that I am absolutely new to Docker and docker-compose.yml so I request your patient from the beginning.

So, I'd just composed my first docker-compose.yml file that looks like the following code:

```<code>version: '3'
services:
    mysql:
        image: mysql:latest
        volumes:
            - $PWD/data/db:/var/lib/mysql
        restart: always
        ports:
            - 3306:3306
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: appdb
            MYSQL_USER: root
            MYSQL_PASSWORD: root
    phpfpm:
        image: 10up/phpfpm
        depends_on:
            - mysql
            - phpmyadmin
        volumes:
            - $PWD/web:/var/www/html
        restart: always
        extra_hosts:
            - docker-local.dev:172.18.0.1
    apache:
        image: httpd:latest
        depends_on:
            - phpfpm
        ports:
            - 80:80
        restart: "always"
        volumes:
            - $PWD/web:/usr/local/apache2/htdocs
    phpmyadmin:
        image: phpmyadmin/phpmyadmin:latest
        links:
            - mysql
        environment:
            PMA_HOST: mysql
            PMA_PORT: 3306
            PMA_USER: root
            PMA_PASSWORD: root
            MYSQL_ROOT_PASSWORD: root
            MYSQL_USER: root
            MYSQL_PASSWORD: root
        ports:
            - 8080:80
        depends_on:
            - mysql
    mailcatcher:
        image: schickling/mailcatcher
        restart: always
        ports:
            - "1025:1025"
            - "1080:1080"
        environment:
            MAILCATCHER_PORT: 1025
</code>```

My file system layout is like that:

```<code>/
    /web
        info.php
    docker-compose.yml
</code>```

Contents in info.php are the following:

```<code><?php
phpinfo();
</code>```

The thing is that when I run the docker using the command docker-compose up I don't get any errors, the MySQL, Apache and phpMyAdmin and mailcatcher seems to work as it should, but when I try to visit the URL http://localhost/info.php I see the contents of the file and not the output of the function phpinfo().

What could be wrong with it?

Have I something wrong and I don't see it?

NOTE: This is a dev machine, so I don't mind for the security and the credentials that are shared along with my code :).

答:
You're using an Apache2 (httpd) image; not PHP. This is the image you are using.

In the documentation of that page, it states:

This image only contains Apache httpd with the defaults from upstream. There is no PHP installed, but it should not be hard to extend. On the other hand, if you just want PHP with Apache httpd see the PHP image and look at the -apache tags. If you want to run a simple HTML server, add a simple Dockerfile to your project where public-html/ is the directory containing all your HTML.

Body:
I'd like to start by saying that I am absolutely new to Docker and docker-compose.yml so I request your patient from the beginning.

So, I'd just composed my first docker-compose.yml file that looks like the following code:

version: '3'
services:
    mysql:
        image: mysql:latest
        volumes:
            - $PWD/data/db:/var/lib/mysql
        restart: always
        ports:
            - 3306:3306
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: appdb
            MYSQL_USER: root
            MYSQL_PASSWORD: root
    phpfpm:
        image: 10up/phpfpm
        depends_on:
            - mysql
            - phpmyadmin
        volumes:
            - $PWD/web:/var/www/html
        restart: always
        extra_hosts:
            - docker-local.dev:172.18.0.1
    apache:
        image: httpd:latest
        depends_on:
            - phpfpm
        ports:
            - 80:80
        restart: "always"
        volumes:
            - $PWD/web:/usr/local/apache2/htdocs
    phpmyadmin:
        image: phpmyadmin/phpmyadmin:latest
        links:
            - mysql
        environment:
            PMA_HOST: mysql
            PMA_PORT: 3306
            PMA_USER: root
            PMA_PASSWORD: root
            MYSQL_ROOT_PASSWORD: root
            MYSQL_USER: root
            MYSQL_PASSWORD: root
        ports:
            - 8080:80
        depends_on:
            - mysql
    mailcatcher:
        image: schickling/mailcatcher
        restart: always
        ports:
            - "1025:1025"
            - "1080:1080"
        environment:
            MAILCATCHER_PORT: 1025

My file system layout is like that:

/
    /web
        info.php
    docker-compose.yml

Contents in info.php are the following:

<?php
phpinfo();

The thing is that when I run the docker using the command docker-compose up I don't get any errors, the MySQL, Apache and phpMyAdmin and mailcatcher seems to work as it should, but when I try to visit the URL http://localhost/info.php I see the contents of the file and not the output of the function phpinfo().

What could be wrong with it?

Have I something wrong and I don't see it?

NOTE: This is a dev machine, so I don't mind for the security and the credentials that are shared along with my code :).


问:
How to DRY on CRUD parts of my Rails app?
I am writing an app which - similarly to many apps out there - is 90% regular CRUD things and 10% "juice", where we need nasty business logic and more flexibility and customization.

Regarding this 90%, I was trying to stick to the DRY principle as much as I can. As long as controllers go, I have found resource_controller to really work, and I could get rid of all the controllers on that area, replacing them with a generic one.

Now I'd like to know how to get the same with the views. On this app I have an overall, application.html.erb layout and then I must have another layout layer, common for all CRUD views and finally a "core" part:

On index.html.erb all I need to generate a simple table with the fields and labels I indicate.

For new and edit, also generic form edition, indicating labels and fields (with a possibility of providing custom fields if needed).

I am not sure I will need show, but if I do it would be the same as new and edit.

What plugins and tools (or even articles and general pointer) would help me to get that done?

Thanks,
Felipe.

答:
You could run script/generate scaffold test name:string description:text valid:boolean and look at the views that generates (and run script/destroy scaffold test to remove the files). That will give you a good sense of the standard way to write the 4 default Rails views.

I would also recommend reading the relevant chapters in "Agile Web Development with Rails" and "The Rails Way".

If you have existing views that need to be cleaned up, this episode of Railscasts is great: Cleaning Up the View

Dary

OwnerDisplayName: kolrie

OwnerDisplayName: Dary


问:
Filling missing time values in an array
In my Java project i make a GET request and i recieve a JSON using Volley.
The data i'm receiving are (unix time as long, float number) and each dataPoint is 10 minutes apart from the other (600 000 ms).
The problem is that when the float value is actually zero the web api i'm using doesn't return any dataPoint so i may have something like this (unix time semplified):

p1 = (0, 100)

p2 = (10, 120)

p3 = (20, 88)

p4 = (30, 86)

(Here is the gap)

p5 = (80, 111)

p6 = (90, 128)

p7 = (100, 135)

how can i transfor that to this:

p1 = (0, 100)

p2 = (10, 120)

p3 = (20, 88)

p4 = (30, 86)

p5 = (40, 0)

p6 = (50, 0)

p7 = (60, 111)

p8 = (70, 128)

p9 = (80, 135)

答:
If you start with an array that will receive the dataPoints from the api, simply add a new entry in the array with the desired name(p1, p2, p3) and add a new entry everytime you make a request.

Point[0] -> (0, 100)

Point[1] -> (10, 120)

Point[2] -> null

Point[3] -> null

Point[4] -> (40, 900)....etc

With this array(list?) you then can use another method to transform its output (p1 = (0, 100), etc...)

Title: Filling missing time values in an array


问:
Moving Elements In A Stack

I have a Stack that's implemented using an array, it takes 6 character as an input from the user (Small Case and Upper Case Letters). Then transfers the Upper Case Letters to another stack (Removing it from the original one)

I have the following code, it moves elements along the stack to the top then pops it once it's at the top and pushes it onto the new array.

```<code>for (int i = P->top(); i >= 0; i--)
{
  if (P->data[i] >= 65 && P->data[i] <= 90)
  {
    for (int j = i; j < P->top(); i++)
    {
      char swap = P->data[i + 1];
      P->data[i + 1] = P->data[i];
      P->data[i] = swap;
      stackT.push(P->pop());
      i = P->top();
    }
  }
}
</code>```

I should have another array with Upper Case letters and the original one with lowercase letters.

It gets weird results, sometimes it completely destroys the original array, sometimes it only transfer one Upper Case element and messes up the others.

I'm just out of ideas.

And yes, the problem is limited to the use of Stacks and no it's not a Homework.

Thanks in advance!

答:
Don't mess around with moving things inside the stack.

(I expect that the purpose of this exercise is that you use only stack operations, and a stack can only be modified at the "top" - anything else is not a stack.)

Instead use a third, temporary, stack.

```<code>stack original = .. whatever ...;
stack uppercase;
stack other;
// Classify the contents
while (!original.empty())
{
    char c = original.top();
    original.pop();
    if (std::isupper(c))
    {
        uppercase.push(c);
    }
    else
    {
        other.push(c);
    }
}
// Restore the non-uppercase stack.
while (!other.empty())
{
    original.push(other.top());
    other.pop();
}
</code>```

Title: Moving Elements In A Stack

Body:
I have a Stack that's implemented using an array, it takes 6 character as an input from the user (Small Case and Upper Case Letters). Then transfers the Upper Case Letters to another stack (Removing it from the original one)

I have the following code, it moves elements along the stack to the top then pops it once it's at the top and pushes it onto the new array.

for (int i = P->top(); i >= 0; i--)
{
  if (P->data[i] >= 65 && P->data[i] <= 90)
  {
    for (int j = i; j
top(); i++)
    {
      char swap = P->data[i + 1];
      P->data[i + 1] = P->data[i];
      P->data[i] = swap;
      stackT.push(P->pop());
      i = P->top();
    }
  }
}

I should have another array with Upper Case letters and the original one with lowercase letters.

It gets weird results, sometimes it completely destroys the original array, sometimes it only transfer one Upper Case element and messes up the others.

I'm just out of ideas.

And yes, the problem is limited to the use of Stacks and no it's not a Homework.

Thanks in advance!

Body:
Don't mess around with moving things inside the stack.

(I expect that the purpose of this exercise is that you use only stack operations, and a stack can only be modified at the "top" - anything else is not a stack.)

Instead use a third, temporary, stack.

stack original = .. whatever ...;
stack uppercase;
stack other;
// Classify the contents
while (!original.empty())
{
    char c = original.top();
    original.pop();
    if (std::isupper(c))
    {
        uppercase.push(c);
    }
    else
    {
        other.push(c);
    }
}
// Restore the non-uppercase stack.
while (!other.empty())
{
    original.push(other.top());
    other.pop();
}


问:
How do I write a named arrow function in ES2015?
I have a function that I am trying to convert to the new arrow syntax in ES6.  It is a named function:

```<code>function sayHello(name) {
    console.log(name + ' says hello');
}
</code>```

Is there a way to give it a name without a var statement:

```<code>var sayHello = (name) => {
    console.log(name + ' says hello');
}
</code>```

Obviously, I can only use this function after I have defined it.  Something like following:

```<code>sayHello = (name) => {
    console.log(name + ' says hello');
}
</code>```

Is there a new way to do this in ES6?

答:
You could skip the function part and the arrow part to create functions. Example:</p>

```<code> class YourClassNameHere{

   constructor(age) {
     this.age = age;
   }

   foo() {
     return "This is a function with name Foo";
   }

   bar() {
     return "This is a function with name bar";
   }

 }

let myVar = new YourClassNameHere(50);
myVar.foo();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a function that I am trying to convert to the new arrow syntax in ES6.  It is a named function:

function sayHello(name) {
    console.log(name + ' says hello');
}

Is there a way to give it a name without a var statement:

var sayHello = (name) => {
    console.log(name + ' says hello');
}

Obviously, I can only use this function after I have defined it.  Something like following:

sayHello = (name) => {
    console.log(name + ' says hello');
}

Is there a new way to do this in ES6?

Body:
You could skip the function part and the arrow part to create functions. Example:

 class YourClassNameHere{

   constructor(age) {
     this.age = age;
   }

   foo() {
     return "This is a function with name Foo";
   }

   bar() {
     return "This is a function with name bar";
   }

 }

let myVar = new YourClassNameHere(50);
myVar.foo();


问:
Animate different corners in CAShapeLayer
I am using the following code:

```<code>let MainLayer : CAShapeLayer = {
    let mainlayer = CAShapeLayer()
    mainlayer.fillColor = UIColor.white.cgColor
    mainlayer.shadowColor = UIColor.darkGray.cgColor
    mainlayer.shadowOffset = CGSize(width: 3.0, height: 3.0)
    mainlayer.shadowOpacity = 0.5
    mainlayer.shadowRadius = 7
    return mainlayer
}()
var LayerRect:CGRect!
var bezierPath:UIBezierPath!
let CellHeightMargin:CGFloat = 6.0
let CellWidthMargin:CGFloat = 15.0

override func viewDidLoad() {
    super.viewDidLoad()
    LayerRect = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y, width: UIScreen.main.bounds.width - CellWidthMargin * 2, height: self.bounds.height - CellHeightMargin * 2)
    bezierPath = UIBezierPath(roundedRect: LayerRect, byRoundingCorners: [.bottomRight,.topRight], cornerRadii: CGSize(width: 5, height: 5))
    MainLayer.path = bezierPath.cgPath
    self.mainView.layer.insertSublayer(MainLayer, at: 0)

}
</code>```

As you can see, byRoundingCorners is to bottom right and top right corners, now I want to replace it by the bottom left and bottom right with animation. How to do that?

答:
By the following:</p>

```<code>    let ToStatusLayerPath = UIBezierPath(roundedRect: CellView.statusView.bounds, byRoundingCorners: [.bottomRight,.bottomLeft], cornerRadii: CGSize(width: 5, height: 5))
    let animation = CABasicAnimation(keyPath: "path")
    animation.toValue   = ToStatusLayerPath.cgPath
    animation.duration  = 1.0;
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    statusLayer.add(animation, forKey: nil)
</code>```

Body:
I am using the following code:

let MainLayer : CAShapeLayer = {
    let mainlayer = CAShapeLayer()
    mainlayer.fillColor = UIColor.white.cgColor
    mainlayer.shadowColor = UIColor.darkGray.cgColor
    mainlayer.shadowOffset = CGSize(width: 3.0, height: 3.0)
    mainlayer.shadowOpacity = 0.5
    mainlayer.shadowRadius = 7
    return mainlayer
}()
var LayerRect:CGRect!
var bezierPath:UIBezierPath!
let CellHeightMargin:CGFloat = 6.0
let CellWidthMargin:CGFloat = 15.0

override func viewDidLoad() {
    super.viewDidLoad()
    LayerRect = CGRect(x: self.bounds.origin.x, y: self.bounds.origin.y, width: UIScreen.main.bounds.width - CellWidthMargin * 2, height: self.bounds.height - CellHeightMargin * 2)
    bezierPath = UIBezierPath(roundedRect: LayerRect, byRoundingCorners: [.bottomRight,.topRight], cornerRadii: CGSize(width: 5, height: 5))
    MainLayer.path = bezierPath.cgPath
    self.mainView.layer.insertSublayer(MainLayer, at: 0)

}

As you can see, byRoundingCorners is to bottom right and top right corners, now I want to replace it by the bottom left and bottom right with animation. How to do that?

Body:
By the following:

    let ToStatusLayerPath = UIBezierPath(roundedRect: CellView.statusView.bounds, byRoundingCorners: [.bottomRight,.bottomLeft], cornerRadii: CGSize(width: 5, height: 5))
    let animation = CABasicAnimation(keyPath: "path")
    animation.toValue   = ToStatusLayerPath.cgPath
    animation.duration  = 1.0;
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    statusLayer.add(animation, forKey: nil)


问:
Convert an UWP app to Unity for the HoloLens
I'm using the HoloLens and I need GPS on it. I succesfully connected my HoloLens to a Bluetooth GPS receiver and I found a project that I can use the read the GPS data in UWP (project).

I need my GPS data in Unity, so I'm trying to convert the UWP code to Unity, but Unity doesn't have for example C# StreamSockets, ... .

What is the best way to use specific UWP code in Unity?

答:
You simply put platform directive NETFX_CORE in your scripts:

```<code>#if NETFX_CORE
    using Windows.Networking.Sockets;
#endif

private void MyFunctionForHololens()
{
    #if NETFX_CORE
        // UWP code here using StreamSocket class
    #else
        // non-UWP core here (maybe some error message for platform not supported)
    #endif
}
</code>```

Unity's platform directives documentation: https://docs.unity3d.com/Manual/PlatformDependentCompilation.html

Body:
You simply put platform directive NETFX_CORE in your scripts:

#if NETFX_CORE
    using Windows.Networking.Sockets;
#endif

private void MyFunctionForHololens()
{
    #if NETFX_CORE
        // UWP code here using StreamSocket class
    #else
        // non-UWP core here (maybe some error message for platform not supported)
    #endif
}

Unity's platform directives documentation: https://docs.unity3d.com/Manual/PlatformDependentCompilation.html


问:
Allow anonymous users to create unpublished nodes in Drupal?
I'm creating a site for a client based on drupal, and the client wants an anonymous user (not logged in) to be able to create a new node, but only an unpublished one. Then an admin can review the node and alter it before publishing himself.

I have looked at using triggers and actions, but writing a custom trigger module seems a bit daunting, as I'm not very fluent with the Drupal API currently. Any ideas are appreciated.

答:
You can accomplish that without custom coding or triggers/actions.

You could use 2 different node types, one for each group, and then treat them the same when displaying. Alternatively you should be able to, in the "presave" op of nodeapi to publish or unpublish depending on role.

Just set the anonymous users content type's default 'status' to unpublished and set the permissions for the content type to allow anonymous users to create that type of content.


问:
How to select rows with information in a text file by using linux command
I just want to select certain info in separated rows in a text file. How do I deal with this?

For selecting row, which contains "SUBSCRIBERIDENTIFIER" and another row contains "LATEST_OFFLINE_TIME"

My output to look like following:

SUBSCRIBERIDENTIFIER=23481XXXXXX02

LATEST_OFFLINE_TIME=20170330191209

答:
```<code>$ awk '/'"SUBSCRIBERIDENTIFIER"'/,/'"LATEST_OFFLINE_TIME"'/' file.txt
SUBSCRIBERIDENTIFIER=1923UIO1U23I1O
LATEST_OFFLINE_TIME=128390812903810983019
</code>```


问:
How to use TimeUnit in java
I am trying to use TimeUnit in java but it just send me errors
That’s how I wrote it</p>
```<code>import java.util.concurrent.TimeUnit ;

public class Anything {
    public static void main( String[] args ) {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}
</code>```

答:
Try this as your code have many syntax errors as well as you are not handling Exception during the call of TimeUnit.SECONDS.sleep(6);, either use throws or surround this with try catch.

```<code>import java.util.concurrent.TimeUnit ;

public class Anything {
    public static void main( String[] args ) throws InterruptedException {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}
</code>```

Title: How to use TimeUnit in java

Body:
I am trying to use TimeUnit in java but it just send me errors
That’s how I wrote it

import java.util.concurrent.TimeUnit ;

public class Anything {
    public static void main( String[] args ) {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}

Body:
Try this as your code have many syntax errors as well as you are not handling Exception during the call of TimeUnit.SECONDS.sleep(6);, either use throws or surround this with try catch.

import java.util.concurrent.TimeUnit ;

public class Anything {
    public static void main( String[] args ) throws InterruptedException {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}


问:
Converting List<String[]> for use in ng-repeat
So Im a bit stuck on where to go with this. Im handling the upload of csv data.

If the data has 10 columns I am to filter out any columns which are not previous defined in the database. So far so good....

I end up with List<String[]> which looks something like this, where each array is a column of data.

```<code>["key", "11111", "222222", "33333", "44444", "55555", "66666", "777777"]

["Group", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852"]

["Types"Group", "Group", "Group", "Group", "Group", "Group", "Group", "Group", "Group"]

["Price", "0.625711406", "5.631402651", "3.441412731", "4.692835542", "6.014119336", "16.64599505"]
</code>```

How do I convert a List<String[]> so the first entry of every array would be a whole record as below, without knowing the number of columns

```<code>[{"11111", "9852", "Group", "0.625711406"},
{"222222", "9852", "Group", "0.62571140"}] etc
</code>```

I would be grateful for any ideas

答:
This question is too broad, but I will provide a few tips to get you started. Take a look upon this article:

Define the table in HTML. The ng-repeat can be used for trs:

Write the code to perform the data fetch from the server (Web.API or similar)

```<code>$http({
        url: "endpoint",
        dataType: 'json',
        method: 'GET',
        data: '',
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function (response) {
        debugger;
        $scope.entityList = response;
    })
       .error(function (error) {
           // error handling here
       });
</code>```

Write the API code (basically a controller action that should handle call from AngularJS).

NOTE: code provided in the article is just to get you started and you should refactor you application to have a clear separation between controller action code and data fetch code (thin controller).

Body:
So Im a bit stuck on where to go with this. Im handling the upload of csv data.

If the data has 10 columns I am to filter out any columns which are not previous defined in the database. So far so good....

I end up with List<String[]> which looks something like this, where each array is a column of data.

["key", "11111", "222222", "33333", "44444", "55555", "66666", "777777"]

["Group", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852", "9852"]

["Types"Group", "Group", "Group", "Group", "Group", "Group", "Group", "Group", "Group"]

["Price", "0.625711406", "5.631402651", "3.441412731", "4.692835542", "6.014119336", "16.64599505"]

How do I convert a List<String[]> so the first entry of every array would be a whole record as below, without knowing the number of columns

[{"11111", "9852", "Group", "0.625711406"},
{"222222", "9852", "Group", "0.62571140"}] etc

I would be grateful for any ideas

Body:
This question is too broad, but I will provide a few tips to get you started. Take a look upon this article:

Define the table in HTML. The ng-repeat can be used for trs:

Write the code to perform the data fetch from the server (Web.API or similar)

$http({
        url: "endpoint",
        dataType: 'json',
        method: 'GET',
        data: '',
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function (response) {
        debugger;
        $scope.entityList = response;
    })
       .error(function (error) {
           // error handling here
       });

Write the API code (basically a controller action that should handle call from AngularJS).

NOTE: code provided in the article is just to get you started and you should refactor you application to have a clear separation between controller action code and data fetch code (thin controller).


问:
Searching in XML using another XML data
I have those two tables:

Table1:

```<code>IDt1    |    XML
1123         xml
1457         xml
</code>```

Table2:

```<code>ID     |    Name    |    XML
01           A           xml
02           B           xml
</code>```

I want to search in table1 XML and if the data exist, then use the IDt1 and search with it in table2 XML if it exist, then return the ID and Name from table2
here is the XMLs for each table.

Table1 xml:

```<code><t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555/rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>
</code>```

Table2 xml:

```<code><t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>
</code>```

data I want like:

```<code>ID   |   Name
01        a
</code>```

I was able to retrieve the IDs from table 1 that contain what I'm looking for but then I was not able to use these IDs to search in the other xml.
Here is what I have:

```<code>SELECT IDt1 as table1IDs
  FROM [Table1]
  WHERE [XML].exist ('/t/ts/sc/am[contains(., "Name1")]') > 0
</code>```

it returns a table of IDs that contain the Name1 now the question how to use the IDs and search with them in the xml of table2 and then return Name and ID of table2
the issue is now I have to use xml.exist [contain table1IDs ] which cannot accept variables

Is there a way to do that?

答:
Your solution is quite close, although I would not use LIKE... You can try this:

```<code>DECLARE @dummy1 TABLE(IDt1 INT, xml1 XML);
INSERT INTO @dummy1 VALUES
 (1123,N'<t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555</rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>')
,(1457,N'<t />'); --you provided only one example...

DECLARE @dummy2 TABLE(ID INT, [Name] VARCHAR(100), [XML] XML);
INSERT INTO @dummy2 VALUES
 (1,'A',N'<t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>')
,(2,'B',N'<t />'); --you provided only one example...

DECLARE @searchFor NVARCHAR(100)=N'Name1'
SELECT *
FROM @dummy1 AS t1
INNER JOIN @dummy2 AS t2 ON t2.[XML].exist(N'/t/ts/d/n[text()[1]=sql:column("t1.IDt1")]')=1
WHERE t1.xml1.exist(N'/t/ts/sc/am[text()[1]=sql:variable("@searchFor")]')=1
</code>```

Title: Searching in XML using another XML data

Body:
I have those two tables:

Table1:

IDt1    |    XML
1123         xml
1457         xml

Table2:

ID     |    Name    |    XML
01           A           xml
02           B           xml

I want to search in table1 XML and if the data exist, then use the IDt1 and search with it in table2 XML if it exist, then return the ID and Name from table2
here is the XMLs for each table.

Table1 xml:

<t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555/rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>

Table2 xml:

<t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>

data I want like:

ID   |   Name
01        a

I was able to retrieve the IDs from table 1 that contain what I'm looking for but then I was not able to use these IDs to search in the other xml.
Here is what I have:

SELECT IDt1 as table1IDs
  FROM [Table1]
  WHERE [XML].exist ('/t/ts/sc/am[contains(., "Name1")]') > 0

it returns a table of IDs that contain the Name1 now the question how to use the IDs and search with them in the xml of table2 and then return Name and ID of table2
the issue is now I have to use xml.exist [contain table1IDs ] which cannot accept variables

Is there a way to do that?

Body:
Your solution is quite close, although I would not use LIKE... You can try this:

DECLARE @dummy1 TABLE(IDt1 INT, xml1 XML);
INSERT INTO @dummy1 VALUES
 (1123,N'<t>
  <ts>
    <sc>
      <rn>445</rn>
      <am>Name1</am>
    </sc>
    <sc>
      <rn>555</rn>
      <am>Name2</am>
    </sc>
  </ts>
</t>')
,(1457,N'<t />'); --you provided only one example...

DECLARE @dummy2 TABLE(ID INT, [Name] VARCHAR(100), [XML] XML);
INSERT INTO @dummy2 VALUES
 (1,'A',N'<t>
  <ts>
    <d>
      <n>01123</n>
    </d>
    <d>
      <n>04344</n>
    </d>
  </ts>
</t>')
,(2,'B',N'<t />'); --you provided only one example...

DECLARE @searchFor NVARCHAR(100)=N'Name1'
SELECT *
FROM @dummy1 AS t1
INNER JOIN @dummy2 AS t2 ON t2.[XML].exist(N'/t/ts/d/n[text()[1]=sql:column("t1.IDt1")]')=1
WHERE t1.xml1.exist(N'/t/ts/sc/am[text()[1]=sql:variable("@searchFor")]')=1


问:
OpenGL SOIL error
I'm working on a university project and it requires us to load up a cube model, texture it and do some other stuff with it.

We have been provided with a basic framework that uses SOIL to load up textures into OpenGL.

However, when I call the function:

```<code>SOIL_load_OGL_texture("Barren Reds.JPG", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS);
</code>```

I get the following error:

```<code>OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in GetString: (ID: 491340553) Generic error
OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in TexParameteri: (ID: 2102148481) Generic error
OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in TexParameteri: (ID: 2102148481) Generic error
</code>```

The thing is, I have another framework that uses SOIL too and when I run the same function with the same texture, it works fine. So I figured my SOIL build is not good, so I copied the working SOIL build to my project and still the same error.

I get these 3 lines of error whenever I call the function, so if I call it to create 3 textures I get it 3 times.

答:
If you're using a Core context be aware that SOIL's query_tex_rectangle_capability() unconditionally calls glGetString(GL_EXTENSIONS) (GL_EXTENSIONS is not a valid argument for glGetString() in Core contexts and will generate a GL_INVALID_ENUM) instead of using glGetStringi() to iterate over extension strings.

Your options are:

Fix SOIL, or

Use stb_image.h directly and handle texture upload yourself, or

Use a Compatibility context (where glGetString(GL_EXTENSIONS) is still valid usage)

Title: OpenGL SOIL error

Body:
I'm working on a university project and it requires us to load up a cube model, texture it and do some other stuff with it.

We have been provided with a basic framework that uses SOIL to load up textures into OpenGL.

However, when I call the function:

SOIL_load_OGL_texture("Barren Reds.JPG", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS);

I get the following error:

OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in GetString: (ID: 491340553) Generic error
OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in TexParameteri: (ID: 2102148481) Generic error
OpenGL Debug Output: Source(OpenGL), Type(Error), Priority(High), Error has been generated. GL error GL_INVALID_ENUM in TexParameteri: (ID: 2102148481) Generic error

The thing is, I have another framework that uses SOIL too and when I run the same function with the same texture, it works fine. So I figured my SOIL build is not good, so I copied the working SOIL build to my project and still the same error.

I get these 3 lines of error whenever I call the function, so if I call it to create 3 textures I get it 3 times.


问:
Is it ugly design that I overload a method depending on whether the argument is subtype or supertype?
Is it ugly design that I overload a method depending on whether the argument is subtype or supertype?

I intend to implent a super class A and a subclass B, and the objects can compare with each other.

compareTo is overloaded twice both in class A and class B, and the code seems a little messy.
It feels like ugly design. I'm not sure if there is a more elegant approach.

```<code>class A implements Comparable<A> {
    private Integer x;

    public A(Integer i) {
        x = i;
    }

    public Integer getX() {
        return x;
    }

    public int compareTo(A other) {
        return x.compareTo(other.getX());
    }

    public int compareTo(B other) {
        return x.compareTo(other.getX() + other.getY());
    }
}

class B extends A {
    private Integer y;

    public B(Integer a, Integer b) {
        super(a);
        y = b;
    }

    public Integer getY() {
        return y;
    }

    @Override
    public int compareTo(A other) {
        return Integer.compare(this.getX() + y, other.getX());
    }

    @Override
    public int compareTo(B other) {
        return Integer.compare(this.getX() + y, other.getX() + other.getY());
    }
}
</code>```

答:
Yes it is a bad design. Something like this would be better.</p>

```<code>class A implements Comparable<A> {
    private Integer x;

    public A(Integer i) {
        x = i;
    }

    public Integer getX() {
        return getX();
    }

    protected Integer compareValue() {
        return getX();
    }

    @Override
    public int compareTo(A other) {
        return compareValue().compareTo(other.compareValue());
    }
}

class B extends A {
    Integer y;

    public B(Integer a, Integer b) {
        super(a);
        y = b;
    }

    public Integer getY() {
        return y;
    }

    @Override
    protected Integer compareValue() {
        return getX() + getY();
    }
}
</code>```

Body:
Is it ugly design that I overload a method depending on whether the argument is subtype or supertype?

I intend to implent a super class A and a subclass B, and the objects can compare with each other.

compareTo is overloaded twice both in class A and class B, and the code seems a little messy.
It feels like ugly design. I'm not sure if there is a more elegant approach.

class A implements Comparable {
    private Integer x;

    public A(Integer i) {
        x = i;
    }

    public Integer getX() {
        return x;
    }

    public int compareTo(A other) {
        return x.compareTo(other.getX());
    }

    public int compareTo(B other) {
        return x.compareTo(other.getX() + other.getY());
    }
}

class B extends A {
    private Integer y;

    public B(Integer a, Integer b) {
        super(a);
        y = b;
    }

    public Integer getY() {
        return y;
    }

    @Override
    public int compareTo(A other) {
        return Integer.compare(this.getX() + y, other.getX());
    }

    @Override
    public int compareTo(B other) {
        return Integer.compare(this.getX() + y, other.getX() + other.getY());
    }
}

Body:
Yes it is a bad design. Something like this would be better.

class A implements Comparable<A> {
    private Integer x;

    public A(Integer i) {
        x = i;
    }

    public Integer getX() {
        return getX();
    }

    protected Integer compareValue() {
        return getX();
    }

    @Override
    public int compareTo(A other) {
        return compareValue().compareTo(other.compareValue());
    }
}

class B extends A {
    Integer y;

    public B(Integer a, Integer b) {
        super(a);
        y = b;
    }

    public Integer getY() {
        return y;
    }

    @Override
    protected Integer compareValue() {
        return getX() + getY();
    }
}


问:
Can't avoid io.realm.exceptions.RealmMigrationNeededException
I'm want to add new field in my model

```<code>public class NoteModel extends RealmObject {
    @PrimaryKey
    private int id; //new field
    private String note;
    private String header;
    private Date date;
    /*
     * few getters and setters
     */

}
</code>```

And I don't want to make any migrations so

```<code>public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        //if I'm right it's delete all data from db and change it's schema (that's OK for me)
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
    }
}
</code>```

But I still got exception  io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
                  - Primary Key for class 'NoteModel' has been added.
                  - Property 'NoteModel.id' has been added.

It's happens in onCreate method (MainActivity.java).

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm = Realm.getDefaultInstance();      //error right here
</code>```

What should I actually do?
Get information from here: "realm migration needed", exception in android while retrieving values from realm db

答:
You need to call Realm.setDefaultConfiguration(config) after creating said config.

```<code>public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
        Realm.setDefaultConfiguration(config); // <---
    }
}
</code>```

Body:
I'm want to add new field in my model

public class NoteModel extends RealmObject {
    @PrimaryKey
    private int id; //new field
    private String note;
    private String header;
    private Date date;
    /*
     * few getters and setters
     */

}

And I don't want to make any migrations so

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        //if I'm right it's delete all data from db and change it's schema (that's OK for me)
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
    }
}

But I still got exception  io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
                  - Primary Key for class 'NoteModel' has been added.
                  - Property 'NoteModel.id' has been added.

It's happens in onCreate method (MainActivity.java).

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm = Realm.getDefaultInstance();      //error right here

What should I actually do?
Get information from here: "realm migration needed", exception in android while retrieving values from realm db

Body:
You need to call Realm.setDefaultConfiguration(config) after creating said config.

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .deleteRealmIfMigrationNeeded()
                .build()
        Realm.setDefaultConfiguration(config); // <---
    }
}


问:
Visual Studio 2010 default zoom level
Is there a way to set the default zoom level in Visual Studio 2010?  The problem is that I find font size 10 to be too small, but font size 11 is too big.  It just so happens that 90% zoom level with font size 11 gives the perfect size I am looking for.  I would like to be able to have VS automatically always zoom the editor to 90%.</p>

答: As far as I am aware you cannot set a default value for the zoom level. Instead, consider setting the default font size for the text editor.</p>

Title: Visual Studio 2010 default zoom level


问:
Elastic aggregation to identify period A vs B percentage increases
I have some daily sales data indexed into Elasticsearch. I successfully run a number of aggregations to identify top sellers across a date range etc.

I am now trying to write a single query to do the following:

Identify Top n sellers over a date range (Period A)

Take the results of Period A and sum sales for these products over second date range (Period B)

Compare sales in period A to Period B and identify those with percentage increases above X%.

My attempt so far:

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "2017-10-01",
              "lte": "2017-10-14"
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "data_split": {
      "terms": {
        "size": 10,
        "field": "product_id"
      },
      "aggs": {
        "date_periods": {
          "date_range": {
            "field": "date",
            "format": "YYYY-MM-dd",
            "ranges": [
              {
                "from": "2017-10-01",
                "to": "2017-10-07"
              },
              {
                "from": "2017-10-08",
                "to": "2017-10-14"
              }
            ]
          },
          "aggs": {
            "product_id_split": {
              "terms": {
                "field": "product_id"
              },
              "aggs": {
                "unit_sum": {
                  "sum": {
                    "field": "units"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Although this outputs results for two periods, I don't think this is quite what I want as the initial filter is running from Period A start date to Period B end date and I think summing results for that range instead of Period A only. I also don't get the % comparison, I would probably do this at my application level, but I understand could be handled with a scripted Elastic query?

It would be especially awesome if instead of top n results in period A, I could set a sales threshold of say 1,000 sales.

Any pointers would be much appreciated. Thanks in advance!

Currently running Elastic 5.6

答:
```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "2017-10-01",
              "lte": "2017-10-14"
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "data_split": {
      "terms": {
        "size": 10,
        "field": "product_id"
      },
      "aggs": {
        "date_period1": {
          "filter": {
            "range": {
              "date": {
                "gte": "2017-10-01",
                "lte": "2017-10-07"
              }
            }
          },
          "aggs": {
            "unit_sum": {
              "sum": {
                "field": "units"
              }
            }
          }
        },
        "date_period2": {
          "filter": {
            "range": {
              "date": {
                "gte": "2017-10-08",
                "lte": "2017-10-14"
              }
            }
          },
          "aggs": {
            "unit_sum": {
              "sum": {
                "field": "units"
              }
            }
          }
        },
        "percentage_increase": {
          "bucket_script": {
            "buckets_path": {
              "firstPeriod": "date_period1>unit_sum",
              "secondPeriod": "date_period2>unit_sum"
            },
            "script": "(params.secondPeriod-params.firstPeriod)*100/params.firstPeriod"
          }
        },
        "retain_buckets": {
          "bucket_selector": {
            "buckets_path": {
              "percentage": "percentage_increase"
            },
            "script": "params.percentage > 5"
          }
        }
      }
    }
  }
}
</code>```

And a full test data in this gist.

The result of this aggregation is giving you this:

```<code>  "aggregations": {
    "data_split": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "A",
          "doc_count": 6,
          "date_period1": {
            "doc_count": 3,
            "unit_sum": {
              "value": 150
            }
          },
          "date_period2": {
            "doc_count": 3,
            "unit_sum": {
              "value": 160
            }
          },
          "percentage_increase": {
            "value": 6.666666666666667
          }
        },
        {
          "key": "C",
          "doc_count": 2,
          "date_period1": {
            "doc_count": 1,
            "unit_sum": {
              "value": 50
            }
          },
          "date_period2": {
            "doc_count": 1,
            "unit_sum": {
              "value": 70
            }
          },
          "percentage_increase": {
            "value": 40
          }
        }
      ]
    }
  }
</code>```

The idea is that you use two filter type of aggregations for the two date intervals. And for each you calculate a sum. Then, using a third aggregation of type bucket_script you calculate the percentage increase (note, though, that it will be a negative number of there is a decrease in sales for example).
Then, using yet another aggregation - of type bucket_selector - you keep the product_ids where the percentage is larger than 5%.

Body:
I have some daily sales data indexed into Elasticsearch. I successfully run a number of aggregations to identify top sellers across a date range etc.

I am now trying to write a single query to do the following:

Identify Top n sellers over a date range (Period A)

Take the results of Period A and sum sales for these products over second date range (Period B)

Compare sales in period A to Period B and identify those with percentage increases above X%.

My attempt so far:

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "2017-10-01",
              "lte": "2017-10-14"
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "data_split": {
      "terms": {
        "size": 10,
        "field": "product_id"
      },
      "aggs": {
        "date_periods": {
          "date_range": {
            "field": "date",
            "format": "YYYY-MM-dd",
            "ranges": [
              {
                "from": "2017-10-01",
                "to": "2017-10-07"
              },
              {
                "from": "2017-10-08",
                "to": "2017-10-14"
              }
            ]
          },
          "aggs": {
            "product_id_split": {
              "terms": {
                "field": "product_id"
              },
              "aggs": {
                "unit_sum": {
                  "sum": {
                    "field": "units"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Although this outputs results for two periods, I don't think this is quite what I want as the initial filter is running from Period A start date to Period B end date and I think summing results for that range instead of Period A only. I also don't get the % comparison, I would probably do this at my application level, but I understand could be handled with a scripted Elastic query?

It would be especially awesome if instead of top n results in period A, I could set a sales threshold of say 1,000 sales.

Any pointers would be much appreciated. Thanks in advance!

Currently running Elastic 5.6

Body:
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gte": "2017-10-01",
              "lte": "2017-10-14"
            }
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "data_split": {
      "terms": {
        "size": 10,
        "field": "product_id"
      },
      "aggs": {
        "date_period1": {
          "filter": {
            "range": {
              "date": {
                "gte": "2017-10-01",
                "lte": "2017-10-07"
              }
            }
          },
          "aggs": {
            "unit_sum": {
              "sum": {
                "field": "units"
              }
            }
          }
        },
        "date_period2": {
          "filter": {
            "range": {
              "date": {
                "gte": "2017-10-08",
                "lte": "2017-10-14"
              }
            }
          },
          "aggs": {
            "unit_sum": {
              "sum": {
                "field": "units"
              }
            }
          }
        },
        "percentage_increase": {
          "bucket_script": {
            "buckets_path": {
              "firstPeriod": "date_period1>unit_sum",
              "secondPeriod": "date_period2>unit_sum"
            },
            "script": "(params.secondPeriod-params.firstPeriod)*100/params.firstPeriod"
          }
        },
        "retain_buckets": {
          "bucket_selector": {
            "buckets_path": {
              "percentage": "percentage_increase"
            },
            "script": "params.percentage > 5"
          }
        }
      }
    }
  }
}

And a full test data in this gist.

The result of this aggregation is giving you this:

  "aggregations": {
    "data_split": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "A",
          "doc_count": 6,
          "date_period1": {
            "doc_count": 3,
            "unit_sum": {
              "value": 150
            }
          },
          "date_period2": {
            "doc_count": 3,
            "unit_sum": {
              "value": 160
            }
          },
          "percentage_increase": {
            "value": 6.666666666666667
          }
        },
        {
          "key": "C",
          "doc_count": 2,
          "date_period1": {
            "doc_count": 1,
            "unit_sum": {
              "value": 50
            }
          },
          "date_period2": {
            "doc_count": 1,
            "unit_sum": {
              "value": 70
            }
          },
          "percentage_increase": {
            "value": 40
          }
        }
      ]
    }
  }

The idea is that you use two filter type of aggregations for the two date intervals. And for each you calculate a sum. Then, using a third aggregation of type bucket_script you calculate the percentage increase (note, though, that it will be a negative number of there is a decrease in sales for example).
Then, using yet another aggregation - of type bucket_selector - you keep the product_ids where the percentage is larger than 5%.


问:
What's the difference between two usages of
 tag?
Consider below code :

```<code><?php
function a($txt) {
    b("Cleveland");
}
function b($txt) {
    var_dump(debug_backtrace());
}
echo '```';
a("Peter");
'```';
?>
</code>```

Output :

```<code>array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(40) "C:\xampp\htdocs\php_playground\hello.php"
    ["line"]=>
    int(6)
    ["function"]=>
    string(1) "b"
    ["args"]=>
    array(1) {
      [0]=>
      string(9) "Cleveland"
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(40) "C:\xampp\htdocs\php_playground\hello.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(1) "a"
    ["args"]=>
    array(1) {
      [0]=>
      string(5) "Peter"
    }
  }
}
</code>```

Now, consider below code :

```<code><?php
function a($txt) {
    b("Cleveland");
}
function b($txt) {
    var_dump(debug_backtrace());
}
echo '```'.a("Peter").'```';
?>
</code>```

Output :

```<code>array(2) { [0]=> array(4) { ["file"]=> string(40) "C:\xampp\htdocs\php_playground\hello.php" ["line"]=> int(3) ["function"]=> string(1) "b" ["args"]=> array(1) { [0]=> string(9) "Cleveland" } } [1]=> array(4) { ["file"]=> string(40) "C:\xampp\htdocs\php_playground\hello.php" ["line"]=> int(8) ["function"]=> string(1) "a" ["args"]=> array(1) { [0]=> string(5) "Peter" } } }
</code>```

Why I'm getting two different outputs for the two different usages of ```</code> tag?</p>

```echo '```';
a("Peter");
'```';
```

<p>AND</p>

```echo '```'.a("Peter").'```';
```

I think I'm doing nothing different in both of the statements. I'm doing almost the same thing then why I'm getting different outputs?

答:
echo outputs to STDOUT. var_dump outputs to STDOUT.

```<code>echo '```';
a("Peter");
'```';
</code>```

This outputs ```</code>.</p>

<p>Then it <strong>outputs</strong> the var_dump.</p>

<p>Then it waves the string literal <code>``` around in the air doing nothing with it.

```<code>echo '```'.a("Peter").'```';
</code>```

This starts building a string.

It starts with ```</code>.</p>

<p>Then it <strong>outputs</strong> the result of <code>var_dump</code>, and joins <strong>the return value</strong> of the <code>a</code> function (which doesn't have a <code>return</code> statement) to the string.</p>

<p>Then it joins <code>``` to the string.

Finally it outputs the string (``````)

Title: What's the difference between two usages of <pre> tag?

Body:
Consider below code :

<?php
function a($txt) {
    b("Cleveland");
}
function b($txt) {
    var_dump(debug_backtrace());
}
echo '
';
a("Peter");
'
';
?>

Output :

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(40) "C:\xampp\htdocs\php_playground\hello.php"
    ["line"]=>
    int(6)
    ["function"]=>
    string(1) "b"
    ["args"]=>
    array(1) {
      [0]=>
      string(9) "Cleveland"
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(40) "C:\xampp\htdocs\php_playground\hello.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(1) "a"
    ["args"]=>
    array(1) {
      [0]=>
      string(5) "Peter"
    }
  }
}

Now, consider below code :

<?php
function a($txt) {
    b("Cleveland");
}
function b($txt) {
    var_dump(debug_backtrace());
}
echo '
'.a("Peter").'
';
?>

Output :

array(2) { [0]=> array(4) { ["file"]=> string(40) "C:\xampp\htdocs\php_playground\hello.php" ["line"]=> int(3) ["function"]=> string(1) "b" ["args"]=> array(1) { [0]=> string(9) "Cleveland" } } [1]=> array(4) { ["file"]=> string(40) "C:\xampp\htdocs\php_playground\hello.php" ["line"]=> int(8) ["function"]=> string(1) "a" ["args"]=> array(1) { [0]=> string(5) "Peter" } } }

Why I'm getting two different outputs for the two different usages of
 tag?

echo '
';
a("Peter");
'
';

AND

echo '
'.a("Peter").'
';

I think I'm doing nothing different in both of the statements. I'm doing almost the same thing then why I'm getting different outputs?

Body:
echo outputs to STDOUT. var_dump outputs to STDOUT.

echo '<pre>';
a("Peter");
'</pre>';

This outputs <pre>.

Then it outputs the var_dump.

Then it waves the string literal </pre> around in the air doing nothing with it.

echo '<pre>'.a("Peter").'</pre>';

This starts building a string.

It starts with <pre>.

Then it outputs the result of var_dump, and joins the return value of the a function (which doesn't have a return statement) to the string.

Then it joins </pre> to the string.

Finally it outputs the string (<pre></pre>)


Title: How can we replace "./." with "-1"

Body:
Input:

7058    7067    7111    7186    7288    7322    7328    7373
./. ./. ./. ./. ./. 0|0 ./. 0|0
./. ./. 0|0 ./. ./. 0|0 ./. 0|0
./. ./. ./. ./. ./. 0|0 ./. 0|0
./. ./. ./. ./. ./. 0|0 ./. 1|1

Desired output:

7058    7067    7111    7186    7288    7322    7328    7373
-1  -1  -1  -1  -1  0|0 -1  0|0
-1  -1  0|0 -1  -1  0|0 -1  0|0
-1  -1  -1  -1  -1  0|0 -1  0|0
-1  -1  -1  -1  -1  0|0 -1  1|1

I have tried sed -i 's/././-1/g' File_name but it didn't work.

Body:
sed -r 's:./.:-1:g' File_name

=> 7058 7067 7111 7186 7288 7322 7328 7373 -1 -1 -1 -1 -1 0|0 -1 0|0 -1 -1 0|0 -1 -1 0|0 -1 0|0 -1 -1 -1 -1 -1 0|0 -1 0|0 -1 -1 -1 -1 -1 0|0 -1 1|1


问:
More elements in LinkedList<T> than COUNT property can return in C#
The count property of LinkedList<T>has return type of int. What if my LinkedList<T> has more elements than int can store and want to know the elements in it. Wont it cause an overflow ? I'm asking this because I am given to create a sequence whose upper bound is 10e15elements it means more elements than an int can store and I want to check that a certain value is less than total elements in my LinkedList<T> and that certain value can be greater than int but still less than the given upper bound.

答:
There is a longCount extension method for LinkedList in System.Linq namespace which return Int64.

Note:

As Hans Passant says in the comment that it traverses the whole list having O(n) complexity and its use must be avoided with LinkedLists


问:
jQuery hide / show content based on common parent
I've this repeated HTML code.

```<code><div id="id1" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Content</div>
</div>

<div id="id2" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>

<div id="id3" class="questio">
  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>
</div>
</code>```

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

```<code>if ($(".c1").is(":checked")) {
  $('.c2').show();
}
</code>```

I tried somethig like this but I can't go on :

```<code>$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});
</code>```

答:
Try this :</p>

```<code>var div1 = $("id1");
var c2OfDiv1 = div1.find(".c2");
c2OfDiv1.hide(); //or c2OfDiv1.show();
</code>```

Body:
I've this repeated HTML code.

  <input type="checkbox" class="c1">

Content

  <input type="checkbox" class="c1">

Another Content

  <input type="checkbox" class="c1">

Another Content

The wanted behaviour is to hide / show div c2 Content for each section independently based on input.c1 checked or not:

if ($(".c1").is(":checked")) {
  $('.c2').show();
}

I tried somethig like this but I can't go on :

$("input.c1").each(function() {
  var parent1 = $(this).closest('questio');
  if ($(this).is(":checked")) {
        /// ??
  }
});

Body:
Try this :

var div1 = $("id1");
var c2OfDiv1 = div1.find(".c2");
c2OfDiv1.hide(); //or c2OfDiv1.show();


答:
You need to use this to refer to the element being clicked on, otherwise you're targeting too many elements you don't need.

$('input.c1').click(function() {
  $(this).next('div.c2').toggle($(this).is(":checked"))
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.c2 {
  display: none;
}</code>```

  <input type="checkbox" class="c1">

Content

  <input type="checkbox" class="c1">

Another Content

  <input type="checkbox" class="c1">

Another Content

```

Title: jQuery hide / show content based on common parent

Body:
You need to use this to refer to the element being clicked on, otherwise you're targeting too many elements you don't need.

$('input.c1').click(function() {
  $(this).next('div.c2').toggle($(this).is(":checked"))
})

.c2 {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Content</div>

</div>

<div id="id2" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>

</div>

<div id="id3" class="questio">

  <input type="checkbox" class="c1">
  <div class="c2">Another Content</div>

</div>


问:
How to implement jvectormap in angular
I'm working on an Angular project (ng-version=4.4.6). I need to have a map which will work without connection. I'd like to try jvectormap. The documentation and every exemples I found are shown for Angular.js. As I am not very experimented in Angular, I have no idea of how to implement this library and use it in my project.

Did anybody ever use it in a project and could show me the way ?

Thanks

答:
You should include both jQuery and jVectorMap files just like described in the official documentation inside your index.html

Then inside your component you have to declare jQuery by doing this just @Component decorator.

```<code>declare var jQuery: any;
</code>```

Then you can inside by example ngAfterViewInit() add this code

```<code>ngAfterViewInit(){
  jQuery('#world-map').vectorMap();
}
</code>```

Inside you component html file you add this

```<code><div id="world-map" style="width: 600px; height: 400px"></div>
</code>```

In your index.html

```<code><link href="https://cdn.jsdelivr.net/npm/jvectormap@2.0.4/jquery-jvectormap.css"></link
<script src="https://cdn.jsdelivr.net/npm/jvectormap@2.0.4/jquery-jvectormap.min.js"></script>
</code>```

The thing is that with angular 2 due to typescript you can easily use jQuery or pure JS

Title: How to implement jvectormap in angular

Body:
You should include both jQuery and jVectorMap files just like described in the official documentation inside your index.html

Then inside your component you have to declare jQuery by doing this just @Component decorator.

declare var jQuery: any;

Then you can inside by example ngAfterViewInit() add this code

ngAfterViewInit(){
  jQuery('#world-map').vectorMap();
}

Inside you component html file you add this

<div id="world-map" style="width: 600px; height: 400px"></div>

In your index.html

<link href="https://cdn.jsdelivr.net/npm/jvectormap@2.0.4/jquery-jvectormap.css"></link
<script src="https://cdn.jsdelivr.net/npm/jvectormap@2.0.4/jquery-jvectormap.min.js"></script>

The thing is that with angular 2 due to typescript you can easily use jQuery or pure JS


问:
Debug a framework while developing
I am creating a statistical calculator app. It has various functions.
I am creating the functions in a cocoapod framework.
How can we test or debug a library framework while we develop it? That means every time without copying it to the demo/test project.</p>

答:
In your framework project, in Xcode add a target for testing. Press File > New > Target... > iOS Unit Testing Bundle.

This will create a test target for you. You can run this target at any time. Also, a swift file with a subclass of XCTestCase. This class has all functions necessary for testing, such as setUp(), testExample() or testPerformanceExample(). You can read how to use this in the XCTest framework reference.

Title: Debug a framework while developing


问:
Symfony2 cache directory permissions
Sorry, I'm new to Symfony.

I think I've tried everything here. I'm trying to install a Symfony v2.8 application on a new machine. When I'm trying to access the application I'm getting exceptions stating lack of permissions to access either cache or logs directory. Cache and logs directories are writeable though - mask 777 set for both.
Also there seems to be a process that creates entries in the cache directory as it fills in with files. The problem seems to be that the web server can't access them - but why?

getfacl for both cache and logs directories returns this:

```<code># owner: apache
# group: apache
user::rwx
user:apache:rwx
group::rwx
mask::rwx
other::rwx
default:user::rwx
default:user:apache:rwx
default:group::rwx
default:mask::rwx
default:other::rwx
</code>```

Any suggestions would be greatly appreciated. Thanks!

答: Check that you logs and cache are being put in the correct location. Symfony has "two" major development environments (dev and prod). They (env) write logs and caches in two separate folders. Check the getCacheDir() and getLogDir() methods in the app/AppKernel.php.

Title: Symfony2 cache directory permissions

Body:
Sorry, I'm new to Symfony.

I think I've tried everything here. I'm trying to install a Symfony v2.8 application on a new machine. When I'm trying to access the application I'm getting exceptions stating lack of permissions to access either cache or logs directory. Cache and logs directories are writeable though - mask 777 set for both.
Also there seems to be a process that creates entries in the cache directory as it fills in with files. The problem seems to be that the web server can't access them - but why?

getfacl for both cache and logs directories returns this:

# owner: apache
# group: apache
user::rwx
user:apache:rwx
group::rwx
mask::rwx
other::rwx
default:user::rwx
default:user:apache:rwx
default:group::rwx
default:mask::rwx
default:other::rwx

Any suggestions would be greatly appreciated. Thanks!


答:
It's bad design, yes. Specifically, it violates transitivity. From the Comparable Javadocs:

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

When you introduce inheritance, you lose transitivity. That's because your A.compareTo(B) method doesn't actually override anything, and so if you passed a List to Collections.sort() which contained both A and B, it would end up using the A.compareTo(A) method for the A instances and the B.compareTo(A) method for the B instances. As you've written them, they are not transitive, and therefore would result in unpredictable ordering since reversing the comparison can change the sort order.

I wrote a similar response w.r.t. Object.equals and why you can't overload it a while back, which you can find here.

Title: Is it ugly design that I overload a method depending on whether the argument is subtype or supertype?

Body:
It's bad design, yes. Specifically, it violates transitivity. From the Comparable Javadocs:

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

When you introduce inheritance, you lose transitivity. That's because your A.compareTo(B) method doesn't actually override anything, and so if you passed a List<A> to Collections.sort() which contained both A and B, it would end up using the A.compareTo(A) method for the A instances and the B.compareTo(A) method for the B instances. As you've written them, they are not transitive, and therefore would result in unpredictable ordering since reversing the comparison can change the sort order.

I wrote a similar response w.r.t. Object.equals and why you can't overload it a while back, which you can find here.