问:
SQL strings added more than once for: tablename
I'm bootstrapping a database using hibernate-maven-plugin, using models that it scans in the maven module it's executed in.

Unfortunately, it stops when hibernate throws this:

```<code>org.hibernate.tool.schema.spi.SchemaManagementException: SQL strings added more than once for: reference_data_source.UK-UK_9ec6wdvyj3mjagiptcnrq2txv
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.checkExportIdentifier(SchemaCreatorImpl.java:299)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:255)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:128)
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:199)
</code>```

So, I have two persistence units, and some tables exists in both. Hibernate seems to interpret this like the same table though, so when it tries to store the same index, but for another schema, it fails thinking it is a duplicate. Their code can be found here.

I'm not sure how to approach this, anyway to configure hibernate hbm2ddl to keep track of these different peristence units?

This is the configuration for the hibernate-maven-plugin:

```<code><plugin>
    <groupId>de.juplo</groupId>
    <artifactId>hibernate-maven-plugin</artifactId>
    <version>2.0.0</version>
    <configuration>
        <detail>true</detail>
        <persistenceUnit>mainPersistenceUnit</persistenceUnit>
        <driver>com.mysql.jdbc.Driver</driver>
        <dialect>org.hibernate.dialect.MySQL5Dialect</dialect>
        <force>true</force>
        <url><![CDATA[jdbc:mysql://localhost/auto_bootstrap_schema]]></url>
        <username>user</username>
        <password>pass</password>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>create</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
    </dependencies>
</plugin>
</code>```

答:
Not sure if this is the same as what I ran into, but I had the same error issue with base class marked with @Entity annotation: changing to @MappedSuperclass removed the error.

Good Luck,
Ray

Body:
I'm bootstrapping a database using hibernate-maven-plugin, using models that it scans in the maven module it's executed in.

Unfortunately, it stops when hibernate throws this:

org.hibernate.tool.schema.spi.SchemaManagementException: SQL strings added more than once for: reference_data_source.UK-UK_9ec6wdvyj3mjagiptcnrq2txv
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.checkExportIdentifier(SchemaCreatorImpl.java:299)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:255)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:128)
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:199)

So, I have two persistence units, and some tables exists in both. Hibernate seems to interpret this like the same table though, so when it tries to store the same index, but for another schema, it fails thinking it is a duplicate. Their code can be found here.

I'm not sure how to approach this, anyway to configure hibernate hbm2ddl to keep track of these different peristence units?

This is the configuration for the hibernate-maven-plugin:

<plugin>
    <groupId>de.juplo</groupId>
    <artifactId>hibernate-maven-plugin</artifactId>
    <version>2.0.0</version>
    <configuration>
        <detail>true</detail>
        <persistenceUnit>mainPersistenceUnit</persistenceUnit>
        <driver>com.mysql.jdbc.Driver</driver>
        <dialect>org.hibernate.dialect.MySQL5Dialect</dialect>
        <force>true</force>
        <url><![CDATA[jdbc:mysql://localhost/auto_bootstrap_schema]]></url>
        <username>user</username>
        <password>pass</password>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>create</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
    </dependencies>
</plugin>


来源: stackexchange

问:
Split a file name and only take one part for use
I have a $value such as 22214-HAV.jpg or 22214 HAV.jpg (notice no dash)

I want to run a quick function to pull only the number from filename.

答:
A quick solution, which make use of PHPs type juggling</p>

```<code>$number = (int) $filename;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
A quick solution, which make use of PHPs type juggling

$number = (int) $filename;


问:
How to hide/show thumb drawable in a SeekBar
I have a SeekBar with a custom drawable for the Thumb, and I would like to be able to show/hide it based on another control I have.

I have tried loading the drawable from resources, and then using SeekBar.setThumb() with the drawable, or null.

That hides it (the set to null), but I can never get it back.

答:
You can hide the seekbar thumb by setting arbitrarily large thumb offset value, which will move the thumb out of view. For example,

```<code>mySeekBar.setThumbOffset(10000);    // moves the thumb out of view (to left)
</code>```

To show the thumb again, set the offset to zero or other conventional value:

```<code>mySeekBar.setThumbOffset(0);        // moves the thumb back to view
</code>```

This approach works in all API levels.

ContentLicense: CC BY-SA 3.0

Body:
You can hide the seekbar thumb by setting arbitrarily large thumb offset value, which will move the thumb out of view. For example,

mySeekBar.setThumbOffset(10000);    // moves the thumb out of view (to left)

To show the thumb again, set the offset to zero or other conventional value:

mySeekBar.setThumbOffset(0);        // moves the thumb back to view

This approach works in all API levels.


问:
Subscript out of range error with active column element
I am trying to write code which looks at whether a row in the active column in ("Input Sheet") matches the contents of a cell in a range which is in a different sheet ("Sheet2").

If the contents match, the code will take the contents of the cell directly to the right of the cell in ("Sheet2") & put it into row 39 of the active column in ("Input Sheet").

I know in all likelihood this is going to have something to do with the range part of the code, but am not really getting anywhere with a solution.

Any help would be appreciated.

```<code>Sub yellowgrey()

Dim y As Range

With y = Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))

If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets(“Sheet2”).Cells(y, 1) Then

Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(y, 2)

End If

End With

End Sub
</code>```

答:
Thanks guys, with your help I have fixed it below:

```<code>Sub yellowgrey()

Dim hh As Long

With Sheets("Sheet2")
    For hh = 2 To 131 Step 1
        If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets("Sheet2").Cells(hh, 1) Then
            Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(hh, 2)
        End If
    Next hh
End With

End Sub
</code>```

the goal was to loop through the data in column 1 of (Sheet2) & see if it matched the contents of a specific cell in (Input Sheet), & perform an action if it did.

Cheers

Body:
I am trying to write code which looks at whether a row in the active column in ("Input Sheet") matches the contents of a cell in a range which is in a different sheet ("Sheet2").

If the contents match, the code will take the contents of the cell directly to the right of the cell in ("Sheet2") & put it into row 39 of the active column in ("Input Sheet").

I know in all likelihood this is going to have something to do with the range part of the code, but am not really getting anywhere with a solution.

Any help would be appreciated.

Sub yellowgrey()

Dim y As Range

With y = Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))

If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets(“Sheet2”).Cells(y, 1) Then

Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(y, 2)

End If

End With

End Sub

Body:
Thanks guys, with your help I have fixed it below:

Sub yellowgrey()

Dim hh As Long

With Sheets("Sheet2")
    For hh = 2 To 131 Step 1
        If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets("Sheet2").Cells(hh, 1) Then
            Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(hh, 2)
        End If
    Next hh
End With

End Sub

the goal was to loop through the data in column 1 of (Sheet2) & see if it matched the contents of a specific cell in (Input Sheet), & perform an action if it did.

Cheers


问:
Condition Based Monitoring | CBM
Machine Learning (ML) can do two things from Vibration/ Acoustic Signal for Condition Based Monitoring (CBM):
1 . Feature Extraction (FT) and
2 . Classification

But if we look through the research/process, then why signal processing techniques are used for pre-processing and ML for rest of the part; I mean classification?
We can use only ML for all of these. But I have seen the merging model of the two techniques: conventional signal processing approach and ML.

I want to know the specific reason for that. Why researchers use these two; they could do with ML only; but they use both.

答:
Yes you can do so. However, the task becomes more complicated.
FFT for example transforms the input space into a more meaningful representation. If you have rotating equipment you would expect that the spectrum is mainly on the frequency of rotation. However, if there is a problem the spectrum changes. This can often be detected by for example SVMS.

If you don't do the FFT but only give the raw signal, SVMs have a hard time.

Nevertheless, i've seen recent practical examples using Deep Convolutional Networks which have learned to predict problems on raw vibration data. The disadvantage is, however, that you do need more data. More data is not a problem in general, but if you take for example a wind turbine more failure data is obviously -- or hopefully ;-) -- a problem.
The other thing is that the ConvNet learned the FFT all by itself. But why not use prior knowledge if you have that.....

Title: Condition Based Monitoring | CBM


问:
Set cookie after certain time delay (in PHP)
I'd like to set a cookie in PHP for my website visitors after they have been on my site for at least 2 minutes.

I guess the sleep() function could do just that, but I read that it might delay loading of the entire page.

Is there any other way to this?

答:
You can create an ajax request from the JavaScript which will load a PHP file after 2 minutes.

In JS:

```<code><script>
    setTimeout(function() {
        // create the AJAX request to set_the_cookie.php
    }, 120000);
</script>
</code>```

Information about AJAX requests.

In PHP (set_the_cookie.php):

```<code><?php
    $value = 'yours_value';
    setcookie('cookie_name', $value);
?>
</code>```

Body:
You can create an ajax request from the JavaScript which will load a PHP file after 2 minutes.

In JS:

<script>
    setTimeout(function() {
        // create the AJAX request to set_the_cookie.php
    }, 120000);
</script>

Information about AJAX requests.

In PHP (set_the_cookie.php):

<?php
    $value = 'yours_value';
    setcookie('cookie_name', $value);
?>


问:
How to delete from select in MySQL?
This code doesn't work for MySQL 5.0, how to re-write it to make it work

```<code>DELETE FROM posts where id=(SELECT id FROM posts GROUP BY id  HAVING ( COUNT(id) > 1 ))
</code>```

I want to delete columns that dont have unique id. I will add that most of the time its only one id(I tried the in syntax and it doesnt work as well).

答:
you can use inner join : </p>

```<code>DELETE
    ps
FROM
    posts ps INNER JOIN
         (SELECT
           distinct id
         FROM
             posts
         GROUP BY id
      HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id
</code>```

Title: How to delete from select in MySQL?

Body:
This code doesn't work for MySQL 5.0, how to re-write it to make it work

DELETE FROM posts where id=(SELECT id FROM posts GROUP BY id  HAVING ( COUNT(id) > 1 ))

I want to delete columns that dont have unique id. I will add that most of the time its only one id(I tried the in syntax and it doesnt work as well).

Body:
you can use inner join :

DELETE
    ps
FROM
    posts ps INNER JOIN
         (SELECT
           distinct id
         FROM
             posts
         GROUP BY id
      HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id


问:
Visual Studio 2017 mistakenly thinks EF 6 is installed
I upgraded my ASP.NET Core, EF Core class library solution to Visual Studio 2017.

However when I want to run migrations commands like Add-Migration I get the following warning.

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework\Update-Database' for Entity Framework 6.

However I don't have EF 6 installed

My csproj

```<code>    ...

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
    <PackageReference Include="System.Collections" Version="4.3.0" />
    <PackageReference Include="System.Linq" Version="4.3.0" />
    <PackageReference Include="System.Runtime" Version="4.3.0" />
    <PackageReference Include="System.Threading" Version="4.3.0" />
  </ItemGroup>

  <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Migrations\" />
  </ItemGroup>

</Project>
</code>```

答:
This can happen if you previously had an EF6 project open in VS. To unload EF6, you can use the following command.</p>

```<code>Remove-Module EntityFramework
</code>```

Body:
I upgraded my ASP.NET Core, EF Core class library solution to Visual Studio 2017.

However when I want to run migrations commands like Add-Migration I get the following warning.

Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework\Update-Database' for Entity Framework 6.

However I don't have EF 6 installed

My csproj

    ...

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
    <PackageReference Include="System.Collections" Version="4.3.0" />
    <PackageReference Include="System.Linq" Version="4.3.0" />
    <PackageReference Include="System.Runtime" Version="4.3.0" />
    <PackageReference Include="System.Threading" Version="4.3.0" />
  </ItemGroup>

  <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Migrations\" />
  </ItemGroup>

</Project>

Body:
This can happen if you previously had an EF6 project open in VS. To unload EF6, you can use the following command.

Remove-Module EntityFramework


问:
For loop for finding index in string
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.</p>

```<code>def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')
</code>```

答:
As mentioned in the comments, you don't increment correctly in your for loop. You want to loop through the word, incrementing each time and outputting the index when the letter is found:

```<code>def where_is(char, word):
    current_index = 0
    while current_index < len(word):
        if char == word[current_index]:
            print (current_index)
        current_index += 1

where_is('p', 'apple')
</code>```

Returning:

```<code>1
2
</code>```

Alternatively, by using enumerate and a list comprehension, you could reduce the whole thing down to:

```<code>def where_is(char, word):
    print [index for index, letter in enumerate(word) if letter == char]

where_is('p', 'apple')
</code>```

which will print:

```<code>[1,2]
</code>```

You then also have the option of return-ing the list you create, for further processing.

Title: For loop for finding index in string

Body:
I'm wondering why my function does not call the index of the character in the string. I used a for loop for this, and for some reason it's just listing all of the possible indices of the string. I made a specific if statement, but I don't get why it's not following the instructions.

def where_is(char,string):
  c=0
  for char in string:
    if char==(string[c]):
      print (c)
      c+=1
    else:
      print ("")
where_is('p','apple')

Body:
As mentioned in the comments, you don't increment correctly in your for loop. You want to loop through the word, incrementing each time and outputting the index when the letter is found:

def where_is(char, word):
    current_index = 0
    while current_index < len(word):
        if char == word[current_index]:
            print (current_index)
        current_index += 1

where_is('p', 'apple')

Returning:

1
2

Alternatively, by using enumerate and a list comprehension, you could reduce the whole thing down to:

def where_is(char, word):
    print [index for index, letter in enumerate(word) if letter == char]

where_is('p', 'apple')

which will print:

[1,2]

You then also have the option of return-ing the list you create, for further processing.


问:
How to add a:hover rule in js function?
I modified some jQuery slide gallery for my website. And I want to add .nav li a:hover{color:#00f;} in css, but it didn't work. I checked it in firebug, the css rule is be crossed off. I find something in the jquery slide galley's js file,like this:

```<code>function init(){
    g.find(".nav").children("li").css("margin","0").css("padding","5px");
    g.find(".nav").children("li").children("a").css("text-decoration","none").css("display","block");
}
</code>```

Is it should be add the a:hover css rule in the js files? How to add it? Thanks.

答:
It becomes a mess after a while, but you can give CSS directives precedence over subsequent directives using !important.

```<code>.nav li a:hover{ color:#00f !important; }
</code>```

Since you mention the property being crossed off in firebug, I suspect this is your issue.

Title: How to add a:hover rule in js function?

Body:
I modified some jQuery slide gallery for my website. And I want to add .nav li a:hover{color:#00f;} in css, but it didn't work. I checked it in firebug, the css rule is be crossed off. I find something in the jquery slide galley's js file,like this:

function init(){
    g.find(".nav").children("li").css("margin","0").css("padding","5px");
    g.find(".nav").children("li").children("a").css("text-decoration","none").css("display","block");
}

Is it should be add the a:hover css rule in the js files? How to add it? Thanks.

Body:
It becomes a mess after a while, but you can give CSS directives precedence over subsequent directives using !important.

.nav li a:hover{ color:#00f !important; }

Since you mention the property being crossed off in firebug, I suspect this is your issue.


问:
Suppressing SUCCESS alert boxes?
I have three functions that called as shown below (Functions not included):

Code:

```<code>$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
</code>```

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?

答:
You need to wait until all ajax requests are complete, like in this answer

So in your case you need to create functions for all $.ajax calls like this:

```<code>function ajax1() {
    var data = JSON.stringify(getAllSourcepData());
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
}
// add ajax2() and ajax3() ...
</code>```

And then use only one click handler like this:

```<code>$("#btnSubmit").click(function() {
    $.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
        // success, display message
    }, function(){
        // exception
    });
});
</code>```

Title: Suppressing SUCCESS alert boxes?

Body:
I have three functions that called as shown below (Functions not included):

Code:

$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?

Body:
You need to wait until all ajax requests are complete, like in this answer

So in your case you need to create functions for all $.ajax calls like this:

function ajax1() {
    var data = JSON.stringify(getAllSourcepData());
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
}
// add ajax2() and ajax3() ...

And then use only one click handler like this:

$("#btnSubmit").click(function() {
    $.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
        // success, display message
    }, function(){
        // exception
    });
});


问:
Nginx disable logging for certain user agents
Basically, I'm trying to remove search engine crawlers such as Google, Bing, and what not from my access logs. They really build up over time, eventually adding hundreds of thousands of useless access log entries to the logs, this is especially a pain if you ever have to search through them. The trouble I'm having is that in my blocks, I'm defining the access log, therefore Nginx is just looking at that and ignoring my 2nd one that I define in the location / block. If I comment out my access log for my site (not the crawler block) then it works fine. Here is the configuration:

```<code>server {
listen 80;
server_name example.com;
access_log  /home/domains/example.com/logs/access;
error_log /home/domains/example.com/logs/error;
root /home/domains/example.com/forums;
location / {
        index index.html index.htm;
        if ($http_user_agent ~* ("googlebot") ) {
        access_log off;
        }
}
</code>```

I've removed everything except that upon posting (php include, and what not), though I've checked that nothing is interfering it by commenting everything out everything except what is above. So to sum it up, I have a log defined in my virtual block to log all of the traffic (I have it defined for every block, to make it neater and what not. I'm trying to disable logging for certain user agents, unless I disable the main log for the site, it'll continue logging what I tell it not to for the user agents.

I've been at this for a few hours now, any help will be greatly appreciated.

答:
You should not use if statements in nginx - if is evil

Use conditional logging:

```<code>http {

     map $http_user_agent $excluded_ua {
         ~Googlebot  0;
         default     1;
     }
     .......
}

server {

     access_log  /home/domains/example.com/logs/access combined if=$excluded_ua;

}
</code>```

However be careful about excluding googlebot as some abusive bots disguise themselves.

Body:
Basically, I'm trying to remove search engine crawlers such as Google, Bing, and what not from my access logs. They really build up over time, eventually adding hundreds of thousands of useless access log entries to the logs, this is especially a pain if you ever have to search through them. The trouble I'm having is that in my blocks, I'm defining the access log, therefore Nginx is just looking at that and ignoring my 2nd one that I define in the location / block. If I comment out my access log for my site (not the crawler block) then it works fine. Here is the configuration:

server {
listen 80;
server_name example.com;
access_log  /home/domains/example.com/logs/access;
error_log /home/domains/example.com/logs/error;
root /home/domains/example.com/forums;
location / {
        index index.html index.htm;
        if ($http_user_agent ~* ("googlebot") ) {
        access_log off;
        }
}

I've removed everything except that upon posting (php include, and what not), though I've checked that nothing is interfering it by commenting everything out everything except what is above. So to sum it up, I have a log defined in my virtual block to log all of the traffic (I have it defined for every block, to make it neater and what not. I'm trying to disable logging for certain user agents, unless I disable the main log for the site, it'll continue logging what I tell it not to for the user agents.

I've been at this for a few hours now, any help will be greatly appreciated.

Body:
You should not use if statements in nginx - if is evil

Use conditional logging:

http {

     map $http_user_agent $excluded_ua {
         ~Googlebot  0;
         default     1;
     }
     .......
}

server {

     access_log  /home/domains/example.com/logs/access combined if=$excluded_ua;

}

However be careful about excluding googlebot as some abusive bots disguise themselves.


问:
Bootstrap 3 Datepicker Months View Only
I have an ASP.NET MVC web app and trying to use Bootstrap 3 Datepicker for my "month/year" field like the one in demo here:
https://eonasdan.github.io/bootstrap-datetimepicker/#min-view-mode

In that demo, it only allows users to select "year" and "month". Not "days". I want the same functionality in my app. However, in my app, it works the same on first click but on succeeding clicks it shows the "days" selection view. Setting the viewMode to 'years' doesn't fix the problem.

My model is as follows:

```<code>public class FilterViewModel
{
    public DateTime? StartMonthYear { get; set; }
    ...
</code>```

My view is as follows:

```<code><div class="col-sm-3">
    @Html.TextBoxFor(model => model.StartMonthYear, new { @class = "month-picker" })
    ...
<script type="text/javascript">
    $(function () {
        $('.month-picker').datetimepicker({
            viewMode: 'months',
            format: 'MM/YYYY',
            useCurrent: false
        });
    });
</script>
</code>```

答:
The problem is that viewMode only sets the initial view. However, it seems this particular library doesn't provide any way to actually restrict which views are available.

There's an alternate libary that I personally use, which does give you the ability. It's virtually a drop-in replacement, so you shouldn't have to change much to switch over. However, importantly, it provides minView/maxView options you can utilize:

```<code>$(function () {
    $('.month-picker').datetimepicker({
        startView: 'month',
        minView: 'month',
        format: 'mm/yyyy'
    });
});
</code>```

As you can see there's a few minor differences:

viewMode becomes startView. The view names are also singular month vs. months.

The formatting string is more similar to C# formatting, so you'd use lowercase mm and yyyy.

The default for this library is to use the current date/time, so there's no need for a separate useCurrent option. If you want to specify a different start date/time, you'd use initialDate.

Title: Bootstrap 3 Datepicker Months View Only

Body:
I have an ASP.NET MVC web app and trying to use Bootstrap 3 Datepicker for my "month/year" field like the one in demo here:
https://eonasdan.github.io/bootstrap-datetimepicker/#min-view-mode

In that demo, it only allows users to select "year" and "month". Not "days". I want the same functionality in my app. However, in my app, it works the same on first click but on succeeding clicks it shows the "days" selection view. Setting the viewMode to 'years' doesn't fix the problem.

My model is as follows:

public class FilterViewModel
{
    public DateTime? StartMonthYear { get; set; }
    ...

My view is as follows:

    @Html.TextBoxFor(model => model.StartMonthYear, new { @class = "month-picker" })
    ...

Body:
The problem is that viewMode only sets the initial view. However, it seems this particular library doesn't provide any way to actually restrict which views are available.

There's an alternate libary that I personally use, which does give you the ability. It's virtually a drop-in replacement, so you shouldn't have to change much to switch over. However, importantly, it provides minView/maxView options you can utilize:

$(function () {
    $('.month-picker').datetimepicker({
        startView: 'month',
        minView: 'month',
        format: 'mm/yyyy'
    });
});

As you can see there's a few minor differences:

viewMode becomes startView. The view names are also singular month vs. months.

The formatting string is more similar to C# formatting, so you'd use lowercase mm and yyyy.

The default for this library is to use the current date/time, so there's no need for a separate useCurrent option. If you want to specify a different start date/time, you'd use initialDate.


问:
C++ - Splitting Filename and File Extension
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.

答: The problem is indeed filenames like *.tar.gz, which can not be split consistently, due to the fact that (at least in Windows) the .tar part isn't part of the extension. You'll either have to keep a list for these special cases and use a one-dot string::rfind for the rest or find some pre-implemented way. Note that the .tar.* extensions aren't infinite, and very much standardized (there's about ten of them I think).

Body:
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.


问:
Update query with a third table involved in SQL Server 2016
I'm fairly new to SQL coding and am still learning some of the intricacies.
I've researched and couldn't find an example that related to what I'm trying (maybe I'm missing the right keywords).

I have three tables in SQL Server 2016 (an employee table - E1, an imported table with employee data - ED1 and a department table - D1)...pertinent structure for this question is:

E1 in DB1 contains columns

```<code>U_SysID - Identity,
UserID - VARCHAR,
FirstName - VARCHAR,
LastName - VARCHAR,
DepartmentID - VARCHAR
</code>```

ED1 in DB2 with schema of dbo contains columns

```<code>UserID - VARCHAR,
FirstName - VARCHAR,
LastName - VARCHAR,
DepartmentName - VARCHAR
</code>```

D1 in DB1 contains columns

```<code>DepartmentID - Identity and
DepartmentName - VARCHAR
</code>```

Code I came up with to try to accomplish this is:

```<code>USE DB1
GO

UPDATE E1
SET DepartmentID = (SELECT DepartmentID
                    FROM D1
                    WHERE E1.UserID IN (SELECT UserID
                                        FROM DB2.dbo.ED1)
                      AND D1.DepartmentName IN (SELECT DepartmentName
                                                FROM ED1)
                      AND E1.UserID = DB2.dbo.ED1.UserID)
</code>```

My problem is the last line.  The "DB2.dbo.ED1.UserID" produces a multi-part identifier could not be bound message.  There are no typos and there is no problem with the use of that database reference in the select statement above it, but if I remove the last line then I get the message that the sub query returned more than 1 value.

Any time spent reading this and providing suggestions is greatly appreciated.

I also apologize in advance if I didn't formulate this post correctly.

答:
This will do what you require. However, you should also check for missing or misspelled DepartmentNames, Missing Users, etc.</p>

```<code>USE DB1
GO

UPDATE E1
SET DepartmentID = D1.DepartmentID
FROM E1
INNER JOIN DB2.dbo.ED1 ED1
    ON E1.UserID = ED1.UserID
INNER JOIN D1
    ON ED1.DepartmentName = D1.DepartmentName
</code>```

Body:
I'm fairly new to SQL coding and am still learning some of the intricacies.
I've researched and couldn't find an example that related to what I'm trying (maybe I'm missing the right keywords).

I have three tables in SQL Server 2016 (an employee table - E1, an imported table with employee data - ED1 and a department table - D1)...pertinent structure for this question is:

E1 in DB1 contains columns

U_SysID - Identity,
UserID - VARCHAR,
FirstName - VARCHAR,
LastName - VARCHAR,
DepartmentID - VARCHAR

ED1 in DB2 with schema of dbo contains columns

UserID - VARCHAR,
FirstName - VARCHAR,
LastName - VARCHAR,
DepartmentName - VARCHAR

D1 in DB1 contains columns

DepartmentID - Identity and
DepartmentName - VARCHAR

Code I came up with to try to accomplish this is:

USE DB1
GO

UPDATE E1
SET DepartmentID = (SELECT DepartmentID
                    FROM D1
                    WHERE E1.UserID IN (SELECT UserID
                                        FROM DB2.dbo.ED1)
                      AND D1.DepartmentName IN (SELECT DepartmentName
                                                FROM ED1)
                      AND E1.UserID = DB2.dbo.ED1.UserID)

My problem is the last line.  The "DB2.dbo.ED1.UserID" produces a multi-part identifier could not be bound message.  There are no typos and there is no problem with the use of that database reference in the select statement above it, but if I remove the last line then I get the message that the sub query returned more than 1 value.

Any time spent reading this and providing suggestions is greatly appreciated.

I also apologize in advance if I didn't formulate this post correctly.

Body:
This will do what you require. However, you should also check for missing or misspelled DepartmentNames, Missing Users, etc.

USE DB1
GO

UPDATE E1
SET DepartmentID = D1.DepartmentID
FROM E1
INNER JOIN DB2.dbo.ED1 ED1
    ON E1.UserID = ED1.UserID
INNER JOIN D1
    ON ED1.DepartmentName = D1.DepartmentName


问:
Tool to Delambdafy Java code from Java 8 to Java 7 syntax?
Does anyone know of any tool to convert Java 8 code (at the source level) that uses lambdas and method references into Java 7 code that uses anonymous inner classes?
I know about Retrolambda, but that works at the bytecode level, not the source level.

For now, I have a version working that works as an IntelliJ plugin.
I extended the current IntelliJ code to convert all lambdas in a package at one go, instead of selecting each lambda individually and converting to anonymous inner class.
The problem with this approach though is that it cannot work as a standalone tool, say a maven plugin as it needs an IntelliJ context to work.

Edit: Note that the focus is on converting lamda/method references to anonymous inner classes. I am not concerned about API changes in Java 8 which would be caught by a Java 7 compiler and reported as compilation errors.

答:
You can try this. It's one person's proof-of-concept to do something close to what you are asking:

It can convert a variable declaration for a functional interface with
  a lambda initializer into a anonymous inner class.

e.g.:

```<code>Callable<String> callable = () -> "abc" ;

// Converted to:

Callable<String> callable = new Callable<String>() {
    public String call() throws java.lang.Exception {
        return "abc";
    }
};
</code>```

I don't know if it can convert anonymous lambdas (i.e. those not declared as a variable) or Method References (e.g. Person::compareByAge), or closures (local variable capture), but those might be features you can extend his code to do if you need them.

The author notes that "It's a long way from being feature complete, but it's usable..."

Body:
You can try this. It's one person's proof-of-concept to do something close to what you are asking:

It can convert a variable declaration for a functional interface with
  a lambda initializer into a anonymous inner class.

e.g.:

Callable<String> callable = () -> "abc" ;

// Converted to:

Callable<String> callable = new Callable<String>() {
    public String call() throws java.lang.Exception {
        return "abc";
    }
};

I don't know if it can convert anonymous lambdas (i.e. those not declared as a variable) or Method References (e.g. Person::compareByAge), or closures (local variable capture), but those might be features you can extend his code to do if you need them.

The author notes that "It's a long way from being feature complete, but it's usable..."


问:
Dispatcher has no subscribers error after upgrading spring-cloud version from Camden.SR4 to Camden.SR5
MyCode:
   1.ChannelInterface

```<code> public interface MessageChanelInterface {

        String DEVICE_SINK = "device-sink";

        @Input(DEVICE_SINK)
        SubscribableChannel receiveDeviceEvent();}
</code>```

2.Listener

```<code>@Service
public class SubscriberToDevice {

      @Autowired
      ParkingService parkingService;

      @StreamListener(MessageChanelInterface.DEVICE_SINK)
      public void receiveDeviceEvent(Object event) {
          //Some code what to do with event.
      }
}
</code>```

3.Chanell Binding

```<code>@Configuration

   @EnableBinding(MessageChanelInterface.class)

   public class MessageChanelConfiguration {

}
</code>```

4.Broker binding and channel configuration

```<code>spring.cloud.stream.binders.rabbit1.type=rabbit
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.addresses=${_rabbit.host}
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.port=5672
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.username=${_rabbit.username}
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.password=${_rabbit.password}
spring.cloud.stream.bindings.device-sink.binder=rabbit1
spring.cloud.stream.bindings.device-sink.destination=device
spring.cloud.stream.bindings.device-sink.group=group-${spring.application.name}
</code>```

While I use spring-cloud version Camden.SR4 no error message, when receive some message. After I upgrade to version Camden.SR5 after received message I got this error message. Publisher I have configured and he publish message without errors. By the way publisher configuration is:

```<code>spring.cloud.stream.bindings.device-source.binder=rabbit1
spring.cloud.stream.bindings.device-source.destination=device
</code>```

Is some big change in Brooklyn.SR2 (version spring.cloud.stream in spring cloud Camden.SR5) with subscriber configuration?  Because publisher work good. I didn't see any changes in subscriber configuration in description of spring.cloud.stream Brooklyn.SR2. Some solution how to fix it?

ERROR MESSAGE

```<code>org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:877)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:787)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:707)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:98)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:189)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.retry.interceptor.RetryOperationsInterceptor$1.doWithRetry(RetryOperationsInterceptor.java:74)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:276)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:172)
    at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy195.invokeListener(Unknown Source)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1236)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:688)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1190)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1174)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1200(SimpleMessageListenerContainer.java:98)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1363)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'parkingspace:default:8096.device-sink'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=EventOccupationDetected [parkingSpaceID=141AA061-86C4-8518-03EC-39C0F6F99AE0], headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedRoutingKey=device, amqp_receivedExchange=device, amqp_deliveryTag=1, correlation-id=85687a94-9bcd-48bb-bfc4-765546b32996, amqp_consumerQueue=device.group-parkingspace, amqp_redelivered=false, id=01d247a7-b37b-2d79-4b90-f59812d25f4b, amqp_consumerTag=amq.ctag-qSSn_-Zw481_KxEz-pbjUQ, contentType=application/x-java-object;type=sk.posam.sp.device.domain.event.EventOccupationDetected, timestamp=1490874431951}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:93)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:292)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:70)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:64)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:171)
    at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$400(AmqpInboundChannelAdapter.java:45)
    at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$1.onMessage(AmqpInboundChannelAdapter.java:95)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:784)
    ... 24 common frames omitted
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:154)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
    ... 43 common frames omitted
</code>```

答:
There's a known regression between Brooklyn.SR1 and Brooklyn.SR2 due to some internal refactoring.

https://github.com/spring-cloud/spring-cloud-stream/issues/844

One workaround ATM would be to use a different argument type than Object (we kind of recommend that anyway, in order to get the benefits of type coercion).

As this has been found after Brooklyn.SR3, probably it makes sense to wait until Brooklyn.S4 or a later version of Camden that picks that up. Alternatively, you can consider upgrading to Chelsea.RC1 which has just been released (planning a release for it on Monday, to be picked up in Dalston.RELEASE in Spring Cloud).

EDIT: Quick note on upgrading the version to Chelsea - it requires Boot 1.5 so YMMV there.

Body:
MyCode:
   1.ChannelInterface

 public interface MessageChanelInterface {

        String DEVICE_SINK = "device-sink";

        @Input(DEVICE_SINK)
        SubscribableChannel receiveDeviceEvent();}

2.Listener

@Service
public class SubscriberToDevice {

      @Autowired
      ParkingService parkingService;

      @StreamListener(MessageChanelInterface.DEVICE_SINK)
      public void receiveDeviceEvent(Object event) {
          //Some code what to do with event.
      }
}

3.Chanell Binding

@Configuration

   @EnableBinding(MessageChanelInterface.class)

   public class MessageChanelConfiguration {

}

4.Broker binding and channel configuration

spring.cloud.stream.binders.rabbit1.type=rabbit
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.addresses=${_rabbit.host}
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.port=5672
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.username=${_rabbit.username}
spring.cloud.stream.binders.rabbit1.environment.spring.rabbitmq.password=${_rabbit.password}
spring.cloud.stream.bindings.device-sink.binder=rabbit1
spring.cloud.stream.bindings.device-sink.destination=device
spring.cloud.stream.bindings.device-sink.group=group-${spring.application.name}

While I use spring-cloud version Camden.SR4 no error message, when receive some message. After I upgrade to version Camden.SR5 after received message I got this error message. Publisher I have configured and he publish message without errors. By the way publisher configuration is:

spring.cloud.stream.bindings.device-source.binder=rabbit1
spring.cloud.stream.bindings.device-source.destination=device

Is some big change in Brooklyn.SR2 (version spring.cloud.stream in spring cloud Camden.SR5) with subscriber configuration?  Because publisher work good. I didn't see any changes in subscriber configuration in description of spring.cloud.stream Brooklyn.SR2. Some solution how to fix it?

ERROR MESSAGE

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:877)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:787)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:707)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:98)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:189)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.retry.interceptor.RetryOperationsInterceptor$1.doWithRetry(RetryOperationsInterceptor.java:74)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:276)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:172)
    at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy195.invokeListener(Unknown Source)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1236)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:688)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1190)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1174)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1200(SimpleMessageListenerContainer.java:98)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1363)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'parkingspace:default:8096.device-sink'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=EventOccupationDetected [parkingSpaceID=141AA061-86C4-8518-03EC-39C0F6F99AE0], headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedRoutingKey=device, amqp_receivedExchange=device, amqp_deliveryTag=1, correlation-id=85687a94-9bcd-48bb-bfc4-765546b32996, amqp_consumerQueue=device.group-parkingspace, amqp_redelivered=false, id=01d247a7-b37b-2d79-4b90-f59812d25f4b, amqp_consumerTag=amq.ctag-qSSn_-Zw481_KxEz-pbjUQ, contentType=application/x-java-object;type=sk.posam.sp.device.domain.event.EventOccupationDetected, timestamp=1490874431951}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:93)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:292)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:70)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:64)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:171)
    at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$400(AmqpInboundChannelAdapter.java:45)
    at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$1.onMessage(AmqpInboundChannelAdapter.java:95)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:784)
    ... 24 common frames omitted
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:154)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
    ... 43 common frames omitted


问:
Razor variable inside string html helper parameter
Here's may Html helper:

```<code> @Html.ActionLink("CONTACT THE USER ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)
</code>```

What I would like to do is:

```<code> @Html.ActionLink("CONTACT " Model.UserName " ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)
</code>```

Can it be done?

答:
You can use the + operator to concatenate string values in C#:

```<code>"CONTACT " + Model.UserName + " ABOUT THIS LISTING"
</code>```

Or something like string.Format() instead:

```<code>string.Format("CONTACT {0} ABOUT THIS LISTING", Model.UserName)
</code>```

Body:
Here's may Html helper:

 @Html.ActionLink("CONTACT THE USER ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)

What I would like to do is:

 @Html.ActionLink("CONTACT " Model.UserName " ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)

Can it be done?

Body:
You can use the + operator to concatenate string values in C#:

"CONTACT " + Model.UserName + " ABOUT THIS LISTING"

Or something like string.Format() instead:

string.Format("CONTACT {0} ABOUT THIS LISTING", Model.UserName)


问:
IIS SMTP remote domain smart host never sends
I'm not a novice but sure feel like one,

Using IIS SMTP, I'm unable to get the smart host for a remote domain to send email.  Instead it always wants to send it from the IIS server unless I turn on smart host for entire SMTP IIS server in the properties.   No matter what settings I put in the remote domain settings, it never uses those settings to send email.  I've tried it on 2 servers and 1 server was a fresh install with defaults.  Here is my configuration:

Defined 1 local domain

Defined 1 remote domain (mydomain.com)

SMTP properties does not have smart host
configured

Configured remote domain
to use smarthost [10.124.100.20]

Disabled SMTP server from trying to
send email directly in the properties

Sending email to myself using from "test@mydomain.com"

The only way to have the email route to the other SMTP server using smarthost is to have all domains route to the same IP address by setting the overall smarthost setting in the SMTP properties dialog.  No matter what settings I put in the remote domain settings, it never uses those settings to send email.  Totally ingores them.

Any help would be appreciated.

答: I realize this is old but I just ran into the same problem.  After adding your remote domains you need to start and stop the smtp server before it will actually route the emails using them.  </p>

OwnerDisplayName: Blake


问:
How to have two instances of Jboss 5 running on the same machine?
I'm a little stuck since I want to have two instances of Jboss running on my machine, when I first raise the problem without any problems, it is important to note that I already configure my environment variable as well as my properties-service so that it points to my ip and port.

Now I have tried to raise a second instance on my machine, already configure my environment variable assigning a different port to the first one, so also my properties-service.xml and my server.xml

In my first instance in the properties-service.xml:

```<code>system.com.host=192.168.2.15
        system.com.port=8480
</code>```

In bindings-jboss-beans.xml

```<code><bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">Port</property>
               <property name="port">1099</property>
               <property name="description">The listening socket for the Naming service</property>
            </bean>

<bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">RmiPort</property>
               <property name="port">1098</property>
               <property name="description">Socket Naming service uses to receive RMI requests from client proxies</property>
            </bean>
</code>```

In my server.xml

```<code><Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
               connectionTimeout="20000" redirectPort="8543" />
</code>```

Now in my second instance I have it as follows:

Properties-service-xml:

```<code>system.com.host=192.168.2.15
            system.com.port=8383
</code>```

In the bindings-jboss-beans.xml:

```<code><bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">Port</property>
               <property name="port">1199</property>
               <property name="description">The listening socket for the Naming service</property>
            </bean>

            <bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">RmiPort</property>
               <property name="port">1195</property>
               <property name="description">Socket Naming service uses to receive RMI requests from client proxies</property>
            </bean>
</code>```

In my server.xml

```<code><Connector protocol="HTTP/1.1" port="8383" address="${jboss.bind.address}"
               connectionTimeout="20000" redirectPort="8543" />
</code>```

But when I want to raise my instance I get the following error:

```<code>[arjLoggerI18N] [com.arjuna.ats.arjuna.recovery.TransactionStatusManager_14] - Failed to create server socket on address 192.168.2.15 and port: 5,013
        [AbstractKernelController] Error installing to Create: name=TransactionManager state=Configured
com.arjuna.ats.arjuna.exceptions.FatalError: [com.arjuna.ats.arjuna.recovery.TransactionStatusManager_9] - Could not get unique port.
</code>```

Does anybody know what is it due to?

THANKS!

答:
JBoss AS 5 has Service Binding Manager that provide a centralized location where settings for all services that need to bind to ports can be configured.

You can start JBoss with the parameter jboss.service.binding.set set to either ports-default, ports-01, etc.

Eg:

```<code>run -Djboss.service.binding.set=ports-01
</code>```

The jboss.service.binding.set system property tells the ServiceBindingManager what set of ports to use.

To doing changes by hand check JBoss AS ConfigurePorts

Ref: https://developer.jboss.org/wiki/AS5ServiceBindingManager

Body:
I'm a little stuck since I want to have two instances of Jboss running on my machine, when I first raise the problem without any problems, it is important to note that I already configure my environment variable as well as my properties-service so that it points to my ip and port.

Now I have tried to raise a second instance on my machine, already configure my environment variable assigning a different port to the first one, so also my properties-service.xml and my server.xml

In my first instance in the properties-service.xml:

system.com.host=192.168.2.15
        system.com.port=8480

In bindings-jboss-beans.xml

<bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">Port</property>
               <property name="port">1099</property>
               <property name="description">The listening socket for the Naming service</property>
            </bean>

<bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">RmiPort</property>
               <property name="port">1098</property>
               <property name="description">Socket Naming service uses to receive RMI requests from client proxies</property>
            </bean>

In my server.xml

<Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
               connectionTimeout="20000" redirectPort="8543" />

Now in my second instance I have it as follows:

Properties-service-xml:

system.com.host=192.168.2.15
            system.com.port=8383

In the bindings-jboss-beans.xml:

<bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">Port</property>
               <property name="port">1199</property>
               <property name="description">The listening socket for the Naming service</property>
            </bean>

            <bean class="org.jboss.services.binding.ServiceBindingMetadata">
               <property name="serviceName">jboss:service=Naming</property>
               <property name="bindingName">RmiPort</property>
               <property name="port">1195</property>
               <property name="description">Socket Naming service uses to receive RMI requests from client proxies</property>
            </bean>

In my server.xml

<Connector protocol="HTTP/1.1" port="8383" address="${jboss.bind.address}"
               connectionTimeout="20000" redirectPort="8543" />

But when I want to raise my instance I get the following error:

[arjLoggerI18N] [com.arjuna.ats.arjuna.recovery.TransactionStatusManager_14] - Failed to create server socket on address 192.168.2.15 and port: 5,013
        [AbstractKernelController] Error installing to Create: name=TransactionManager state=Configured
com.arjuna.ats.arjuna.exceptions.FatalError: [com.arjuna.ats.arjuna.recovery.TransactionStatusManager_9] - Could not get unique port.

Does anybody know what is it due to?

THANKS!

Body:
JBoss AS 5 has Service Binding Manager that provide a centralized location where settings for all services that need to bind to ports can be configured.

You can start JBoss with the parameter jboss.service.binding.set set to either ports-default, ports-01, etc.

Eg:

run -Djboss.service.binding.set=ports-01

The jboss.service.binding.set system property tells the ServiceBindingManager what set of ports to use.

To doing changes by hand check JBoss AS ConfigurePorts

Ref: https://developer.jboss.org/wiki/AS5ServiceBindingManager


答:
Yes, just use standard string concantenation. </p>

```<code>@Html.ActionLink("CONTACT " + Model.UserName + " ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)
</code>```

Title: Razor variable inside string html helper parameter

Body:
Yes, just use standard string concantenation.

@Html.ActionLink("CONTACT " + Model.UserName + " ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)


问:
Mongoose - Append child documents to results that match a value
I have two collections - Assignments and Submissions - where a teacher gives an assignment and all students can upload a submission. I want to query the db so that I'll retrieve all the assignments that have been posted, and for each one, tag on the student's submission (if it exists) that goes with it.

```<code>AssignmentSchema = new Schema({
    teacher: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    course: {type: Schema.Types.ObjectId, ref: 'Course', required: true},
    name: {type: String},
    ...
});

SubmissionSchema = new Schema({
    assignment: {type: Schema.Types.ObjectId, ref: 'Assignment', required: true},
    student: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    ...
});
</code>```

Attempt using aggregation framework

```<code>Assignment.aggregate([
    {$match: {'course': new ObjectId(req.params.courseID)}},
    {$lookup: {
        from: 'submissions',
        localField: '_id',
        foreignField: 'assignment',
        as: 'submission'
    }},

    // Redact all submissions that aren't uploaded by the logged in user
    {$redact: {
        // This condition isn't working for some reason?
        $cond: {
            if: {
                $eq: ['$submission.user', new ObjectId(req.user._id)]
            },
            'then': '$$DESCEND',
            'else': '$$PRUNE' // Prune will remove the entire object. How can I only remove the assignments?
        }
    }},
    {$unwind: {
        path: '$submission',
        preserveNullAndEmptyArrays: true
    }}
]);
</code>```

The result that I need is this:

```<code>[{
    _id: '123456789',
    teacher: {teacher's id},
    course: '987654321',
    name: 'The assignment',
    submission: {
        assignment: '123456789',
        student: {authenticated user's id},
        ...
    },
    ...
}]
</code>```

答:
Replace your $eq expression with

[{$ifNull: ["$user", new ObjectId(req.user._id)]}, new ObjectId(req.user._id)]

$redact will go one document level at a time and look for user field recursively and perform $$DESCEND and $$PRUNE on the criteria.

Using $ifNull operator allows the $redact at the first document level, which doesn't have a $user field, to continue by comparing the replacement user id (new ObjectId(req.user._id)) value against new ObjectId(req.user._id)so that you can $$DESCEND to embedded document level for further processing.

Update:

$project with $filter seems more appropriate than $redact. Something like

```<code>{
    $project: {
    _id: 1,
    teacher: 1,
    course: 1,
    name: 1,
    submission: {
            $filter: {
                input: "$submission",
                as: "result",
                cond: {
                    $eq: ["$$result.user", new ObjectId(req.user._id)]
                }
            }
        }
    }
}
</code>```

Body:
I have two collections - Assignments and Submissions - where a teacher gives an assignment and all students can upload a submission. I want to query the db so that I'll retrieve all the assignments that have been posted, and for each one, tag on the student's submission (if it exists) that goes with it.

AssignmentSchema = new Schema({
    teacher: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    course: {type: Schema.Types.ObjectId, ref: 'Course', required: true},
    name: {type: String},
    ...
});

SubmissionSchema = new Schema({
    assignment: {type: Schema.Types.ObjectId, ref: 'Assignment', required: true},
    student: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    ...
});

Attempt using aggregation framework

Assignment.aggregate([
    {$match: {'course': new ObjectId(req.params.courseID)}},
    {$lookup: {
        from: 'submissions',
        localField: '_id',
        foreignField: 'assignment',
        as: 'submission'
    }},

    // Redact all submissions that aren't uploaded by the logged in user
    {$redact: {
        // This condition isn't working for some reason?
        $cond: {
            if: {
                $eq: ['$submission.user', new ObjectId(req.user._id)]
            },
            'then': '$$DESCEND',
            'else': '$$PRUNE' // Prune will remove the entire object. How can I only remove the assignments?
        }
    }},
    {$unwind: {
        path: '$submission',
        preserveNullAndEmptyArrays: true
    }}
]);

The result that I need is this:

[{
    _id: '123456789',
    teacher: {teacher's id},
    course: '987654321',
    name: 'The assignment',
    submission: {
        assignment: '123456789',
        student: {authenticated user's id},
        ...
    },
    ...
}]

Body:
Replace your $eq expression with

[{$ifNull: ["$user", new ObjectId(req.user._id)]}, new ObjectId(req.user._id)]

$redact will go one document level at a time and look for user field recursively and perform $$DESCEND and $$PRUNE on the criteria.

Using $ifNull operator allows the $redact at the first document level, which doesn't have a $user field, to continue by comparing the replacement user id (new ObjectId(req.user._id)) value against new ObjectId(req.user._id)so that you can $$DESCEND to embedded document level for further processing.

Update:

$project with $filter seems more appropriate than $redact. Something like

{
    $project: {
    _id: 1,
    teacher: 1,
    course: 1,
    name: 1,
    submission: {
            $filter: {
                input: "$submission",
                as: "result",
                cond: {
                    $eq: ["$$result.user", new ObjectId(req.user._id)]
                }
            }
        }
    }
}


答:
```<code>@Html.ActionLink($"CONTACT {Model.UserName} ABOUT THIS LISTING", "create", "contactform", new { recipientID = Model.User.Id, productid = Model.Product.ID }, null)
</code>```


问:
Rails 5 converts object to a string when passing on the params
In Rails 5 I have my sign up page using form_for helper to create a user, which is then directed to my custom confirm page.

```<code>  <%= form_for @user, url: {action: :confirm} do |f| %>
</code>```

In my confirm controller I can access parameters without any problem. This is how they are displayed in the console.

```<code> Parameters: {"utf8"=>"✓",
"authenticity_token"=>"<longBlaString>",
"user"=>{"name"=>"Railsmastanot",
         "email"=>"example@domain.com",
         "password"=>"[FILTERED]",
         "password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}
</code>```

I then use

<%= button_to "Yes", {controller: "users", action: "create",  params: params}, class: 'btn btn-success' %>

to redirect to the actual users#create method. Inside I am trying to access parameters, e.g. params[:user][:email] but get an error

no implicit conversion of Symbol into Integer

Examining console reveals than my parameters hash turned into this:

```<code>Parametes:
 {"authenticity_token"=>"longBlaString",
"commit"=>"Sign up",
"user"=>"email=example@domain.com&name=Railsmastanot&password=
<myActualPassword!>&password_confirmation=<myActualPassword!>",
"utf8"=>"✓"}
</code>```

So the user key no longer holds the hash, but a string. Is this supposed to happen or a bug? If not a bug, what is the correct way to handle this? Am I doing something wrong?

EDIT:

I figured out that params is not actually a hash in Rails 5. If I pass parameters like  params: params.to_unsafe_h it works, but I am not sure this is safe to do.

答:
This can be done like this

Add column confirmed in user table

Save user when form is submitted with confirmed => false and take id from it.

Then from confirmation page send user id with confirmation.

If information confirmed then update user with confirmed = true.

If information not confirmed then delete user.

Method you are using may not be safe because parameters are printed in confirmation page.

Body:
In Rails 5 I have my sign up page using form_for helper to create a user, which is then directed to my custom confirm page.

  <%= form_for @user, url: {action: :confirm} do |f| %>

In my confirm controller I can access parameters without any problem. This is how they are displayed in the console.

 Parameters: {"utf8"=>"✓",
"authenticity_token"=>"<longBlaString>",
"user"=>{"name"=>"Railsmastanot",
         "email"=>"example@domain.com",
         "password"=>"[FILTERED]",
         "password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}

I then use

<%= button_to "Yes", {controller: "users", action: "create",  params: params}, class: 'btn btn-success' %>

to redirect to the actual users#create method. Inside I am trying to access parameters, e.g. params[:user][:email] but get an error

no implicit conversion of Symbol into Integer

Examining console reveals than my parameters hash turned into this:

Parametes:
 {"authenticity_token"=>"longBlaString",
"commit"=>"Sign up",
"user"=>"email=example@domain.com&name=Railsmastanot&password=
<myActualPassword!>&password_confirmation=<myActualPassword!>",
"utf8"=>"✓"}

So the user key no longer holds the hash, but a string. Is this supposed to happen or a bug? If not a bug, what is the correct way to handle this? Am I doing something wrong?

EDIT:

I figured out that params is not actually a hash in Rails 5. If I pass parameters like  params: params.to_unsafe_h it works, but I am not sure this is safe to do.


问:
Is it possible to exclude links from tracking
I am building an app which is utilizing Sendgrid Marketing Email API, with the purpose of sending newsletters. It has a number of links to articles, but also banner ads and other service links. We would obviously like to keep tracking of article links, but exclude other links from affecting the click rate. Is it possible in any way to mark links which we don't wish to add to tracking?</p>

答:
Minor thread necromancy to let anyone who gets here via google know that they added an attribute to disable link tracking.

https://sendgrid.com/docs/Classroom/Track/Clicks/click_tracking_html_best_practices.html

Click tracking can be turned off for individual links by including the clicktracking=off attribute inside the anchor of an HTML link before the href. For example, link text would not be tracked.

Body:
Minor thread necromancy to let anyone who gets here via google know that they added an attribute to disable link tracking.

https://sendgrid.com/docs/Classroom/Track/Clicks/click_tracking_html_best_practices.html

Click tracking can be turned off for individual links by including the clicktracking=off attribute inside the anchor of an HTML link before the href. For example, <a clicktracking=off href="http://example.com">link text</a> would not be tracked.


答:
Why you want to call 3 times for button click?
Why not put them all together?
Any how you can use variable as isAlertToBeShown= false and after pushing data make it has true. finally check the variable is true or false. </p>

Title: Suppressing SUCCESS alert boxes?

Body:
I have three functions that called as shown below (Functions not included):

Code:

$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?


问:
Selecting a random value from a subsection of an enum
Given a Swift enum as such:

```<code>enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}
</code>```

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

```<code>private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}
</code>```

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

答:
If you have different subsets in your enum and you need to access them separately, I would recommend to identify the subsets somehow, consider:

```<code>enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute

    static let strings: [PerformerPosition] = [
        .String_Violin1, .String_Violin2, .String_Viola, .String_Cello, .String_CB
    ]

    static let winds: [PerformerPosition] = [
        .Wind_Oboe, .Wind_Clarinet, .String_Viola, .Wind_Flute
    ]
}
</code>```

Note that this will enable you several things:

You won't need the String_ and Wind_ prefixes. You can simply use .violin1, .oboe, etc.

You can simply generate random position from your array

You can directly check the type of your position:

```<code>let isString = PerformerPosition.strings.contains(.violin1)
</code>```

Body:
Given a Swift enum as such:

enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

Body:
If you have different subsets in your enum and you need to access them separately, I would recommend to identify the subsets somehow, consider:

enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute

    static let strings: [PerformerPosition] = [
        .String_Violin1, .String_Violin2, .String_Viola, .String_Cello, .String_CB
    ]

    static let winds: [PerformerPosition] = [
        .Wind_Oboe, .Wind_Clarinet, .String_Viola, .Wind_Flute
    ]
}

Note that this will enable you several things:

You won't need the String_ and Wind_ prefixes. You can simply use .violin1, .oboe, etc.

You can simply generate random position from your array

You can directly check the type of your position:

let isString = PerformerPosition.strings.contains(.violin1)


问:
HSQLDB: Memory table and data loss
Situation: memory table is created and database is used as file:.  As I understand this case all data must be contained in .script file. My question is what happens if hsqldb after some inserts is closed not in a proper way? For example someone pushes power button on server box.

The core of this question is when does hsqldb save data to file when memory tables are used.

答: There is also a .log file that records all the INSERT, UPDATE and DELETE statements. When the database is restarted, the .log file is read and the data is restored to the point of power loss.

Title: HSQLDB: Memory table and data loss


问:
How can I pass a list as a command-line argument with argparse?
I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?

```<code>parser.add_argument('-l', '--list',
                      type=list, action='store',
                      dest='list',
                      help='<Required> Set flag',
                      required=True)
</code>```

Script is called like below

```<code>python test.py -l "265340 268738 270774 270817"
</code>```

答:
If you are intending to make a single switch take multiple parameters, then you use nargs='+'. If your example '-l' is actually taking integers:

```<code>a = argparse.ArgumentParser()
a.add_argument(
    '-l', '--list',  # either of this switches
    nargs='+',       # one or more parameters to this switch
    type=int,        # /parameters/ are ints
    dest='lst',      # store in 'lst'.
    default=[],      # since we're not specifying required.
)

print a.parse_args("-l 123 234 345 456".split(' '))
print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))
</code>```

Produces

```<code>Namespace(lst=[123, 234, 345, 456])
Namespace(lst=[456])  # Attention!
</code>```

If you specify the same argument multiple times, the default action ('store') replaces the existing data.

The alternative is to use the append action:

```<code>a = argparse.ArgumentParser()
a.add_argument(
    '-l', '--list',  # either of this switches
    type=int,        # /parameters/ are ints
    dest='lst',      # store in 'lst'.
    default=[],      # since we're not specifying required.
    action='append', # add to the list instead of replacing it
)

print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))
</code>```

Which produces

```<code>Namespace(lst=[123, 234, 345, 456])
</code>```

Or you can write a custom handler/action to parse comma-separated values so that you could do

```<code>-l 123,234,345 -l 456
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option?

parser.add_argument('-l', '--list',
                      type=list, action='store',
                      dest='list',
                      help='<Required> Set flag',
                      required=True)

Script is called like below

python test.py -l "265340 268738 270774 270817"

Body:
If you are intending to make a single switch take multiple parameters, then you use nargs='+'. If your example '-l' is actually taking integers:

a = argparse.ArgumentParser()
a.add_argument(
    '-l', '--list',  # either of this switches
    nargs='+',       # one or more parameters to this switch
    type=int,        # /parameters/ are ints
    dest='lst',      # store in 'lst'.
    default=[],      # since we're not specifying required.
)

print a.parse_args("-l 123 234 345 456".split(' '))
print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))

Produces

Namespace(lst=[123, 234, 345, 456])
Namespace(lst=[456])  # Attention!

If you specify the same argument multiple times, the default action ('store') replaces the existing data.

The alternative is to use the append action:

a = argparse.ArgumentParser()
a.add_argument(
    '-l', '--list',  # either of this switches
    type=int,        # /parameters/ are ints
    dest='lst',      # store in 'lst'.
    default=[],      # since we're not specifying required.
    action='append', # add to the list instead of replacing it
)

print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))

Which produces

Namespace(lst=[123, 234, 345, 456])

Or you can write a custom handler/action to parse comma-separated values so that you could do

-l 123,234,345 -l 456


问:
Testing express passport application with mocha and chai
I'm trying to test my application with mocha, chai and chai-http. When I test the login, I can't seem to log in no matter what I try. I've tried in Postman and gotten the same result.

I've seen many answers along the lines of this one but I've had no success with them.

Is Passport doing something that's preventing successful login? I can log in from the browser with no problem.

答:
I found an answer in this post and from tinkering with the settings in Postman. Adding the content type x-www-form-urlencoded seemed to be the key.

```<code>it('should redirect to dashboard on successful login', function(done) {
    chai.request('http://localhost:3000')
      .post('/login')
      .set('Token', 'text/plain')
      .set('content-type', 'application/x-www-form-urlencoded')
      .type('form')
      .send('grant_type=password')
      .send('username=bobby')
      .send('password=abc123')
      .end(function(err, res) {
        res.should.have.status(200);
        expect(res).to.redirectTo('http://localhost:3000/user/dashboard');
        done();
      });
  });
</code>```

Body:
I found an answer in this post and from tinkering with the settings in Postman. Adding the content type x-www-form-urlencoded seemed to be the key.

it('should redirect to dashboard on successful login', function(done) {
    chai.request('http://localhost:3000')
      .post('/login')
      .set('Token', 'text/plain')
      .set('content-type', 'application/x-www-form-urlencoded')
      .type('form')
      .send('grant_type=password')
      .send('username=bobby')
      .send('password=abc123')
      .end(function(err, res) {
        res.should.have.status(200);
        expect(res).to.redirectTo('http://localhost:3000/user/dashboard');
        done();
      });
  });


问:
Splitting timespan and creating new fields in csv
The following csv structure and data is given:

```<code>timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...
</code>```

I would like to split up the timespan into begin and end. As you can see a timespan can be several days (first record) or only one day (second record). Splitting up the first record is pretty easy by replacing the delimiter but i don't know how to process the second record. There must be some logic to identify it as single day (begin and end should be same value).

All is done in SSIS but i would like to realize it in C#.

Result:

```<code>begin,end,someOtherField, ...
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...
</code>```

答: Check for the presence of a hyphen character in the timespan column.   If there is none, then use the same value for both begin and end.

Body:
The following csv structure and data is given:

timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...

I would like to split up the timespan into begin and end. As you can see a timespan can be several days (first record) or only one day (second record). Splitting up the first record is pretty easy by replacing the delimiter but i don't know how to process the second record. There must be some logic to identify it as single day (begin and end should be same value).

All is done in SSIS but i would like to realize it in C#.

Result:

begin,end,someOtherField, ...
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...


问:
Algorithm that finds similar words based on their letters
I am looking for a way to detect the similarity of words (textstrings) based on their shared letters.

I was looking into Hash functions and especially the Rabin-Karp algorithm to find similar words inside larger strings.

But it doesnt work on the case I want:
Three examples for words I consider "similar" in my case based on german banks:
There is the "Deutsche Bank", "Postbank", and "Landesbank". All three have the word "bank" inside their name but only the Deutsche Bank has it as a individual word.
So basically measure the similary of words based on their shared characters.
I think there should be a limit that only similarities of >=4 characters should be considered if thats possible.

And if I was just looking for the word "bank" I would hardcode something. But im looking for a way to find such similar names/strings without knowing about it in the first place.

答:
Sounds like a good use case for Levenshtein Distance. In brief, this calculates the number of "edits" you need to make to go from one string to another. You can get better by adding probabilities of edits occuring into the model too, but this may not be necessary. Usually I've found a 2-edit limit to be good for basic spell-correction.

Wiki Page: Levenshtein Distance