问:
Error including file (include_path='.:/usr/share/pear:/usr/share/php')
I just uploaded my project to my server in var/www made using slim framework the project has a folder structure like:

include
  -Functions.php
controller
  -weeklysummary.php(Script I want to run)

vendor
  -autoload.php

When I try to call a function in the Functions.php script On my local machine the project worked fine but on the server it keeps telling me `

```<code> Warning: require(../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/project/include/Functions.php on line 11

 Fatal error: require(): Failed opening required '../vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/innov8alert/include/Functions.php on line 11`
</code>```

This is how Functions.php Looks like

```<code>class Functions {

private $conn;

function __construct() {
    require_once 'Connect.php';
    require '../vendor/autoload.php';
    require '../mailer/class.phpmailer.php';
    $db = new Connect();
    $this->conn = $db->connect();
}

function __destruct() {

}
</code>```

I looked up this and this but none seemed to help.

答:
This is due to your current working directory (CWD), which matches the one where you've started the script from. If this is a website, it should be safe to assume that CWD is where the index.php file is located.

There's 2 ways around the issue:

1) As suggested in the comments, declare a BASEPATH constant from inside index.php and always use it to prefix include paths:

```<code>// index.php:
define('BASEPATH', __DIR__.'/');

// other files:
// require BASEPATH.'path/relative/to/index.php/directory
</code>```

2) Use the __DIR__ magic constant itself to prefix includes on files, but relative to where you include them from (this will immediately work in your case without other changes):

```<code>require __DIR__.'/../vendor/autoload.php';
</code>```

Body:
I just uploaded my project to my server in var/www made using slim framework the project has a folder structure like:

include
  -Functions.php
controller
  -weeklysummary.php(Script I want to run)

vendor
  -autoload.php

When I try to call a function in the Functions.php script On my local machine the project worked fine but on the server it keeps telling me `

 Warning: require(../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/project/include/Functions.php on line 11

 Fatal error: require(): Failed opening required '../vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/innov8alert/include/Functions.php on line 11`

This is how Functions.php Looks like

class Functions {

private $conn;

function __construct() {
    require_once 'Connect.php';
    require '../vendor/autoload.php';
    require '../mailer/class.phpmailer.php';
    $db = new Connect();
    $this->conn = $db->connect();
}

function __destruct() {

}

I looked up this and this but none seemed to help.

Body:
This is due to your current working directory (CWD), which matches the one where you've started the script from. If this is a website, it should be safe to assume that CWD is where the index.php file is located.

There's 2 ways around the issue:

1) As suggested in the comments, declare a BASEPATH constant from inside index.php and always use it to prefix include paths:

// index.php:
define('BASEPATH', __DIR__.'/');

// other files:
// require BASEPATH.'path/relative/to/index.php/directory

2) Use the __DIR__ magic constant itself to prefix includes on files, but relative to where you include them from (this will immediately work in your case without other changes):

require __DIR__.'/../vendor/autoload.php';


来源: stackexchange

问:
Signed URLs on GAE with Python for GCS PUT request
I'm trying to create a signed URL to be used for uploading files directly to Google Cloud Storage (GCS).  I had this working using POST using this Github example, which makes use of a policy.  Per best practice, I'm refactoring to use PUT and getting a SignatureDoesNotMatch error:

```<code><?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>PUT

123456789
/mybucket/mycat.jpg</StringToSign></Error>
</code>```

Per the docs on creating a signed URL with a program and the GCP example Python code, I am doing this process:

building my Signature string

signing it

base64 encoding it

url encoding the result (the python example doesn't do this though...

Since this is running on a Google App Engine (GAE) App, I shouldn't need to get a JSON key file for my service account user, but rather use App Identity Services to sign it.  Here's my code within a Flask project:

```<code>google_access_id = app_identity.get_service_account_name()
expires = arrow.utcnow().replace(minutes=+10).replace(microseconds=0).timestamp
resource = '/mybucket/mycat.jpg'

args = self.get_parser.parse_args()
signature_string = 'PUT\n'
# take MD5 of file being uploaded and its content type, if provided
content_md5 = args.get('md5') or ''
content_type = args.get('contenttype') or ''
signature_string = ('PUT\n'
                    '{md5}\n'
                    '{content_type}\n'
                    '{expires}\n'
                    '{resource}\n').format(
                    md5=content_md5,
                    content_type=content_type,
                    expires=expires,
                    resource=resource)
log.debug('signature string:\n{}'.format(signature_string))
_, signature_bytes = app_identity.sign_blob(signature_string)
signature = base64.b64encode(signature_bytes)
# URL encode signature
signature = urllib.quote(signature)
media_url = 'https://storage.googleapis.com{}'.format(resource)
return dict(GoogleAccessId=google_access_id,
            Expires=expires,
            Signature=signature,
            bucket='mybucket',
            media_url='{}?GoogleAccessId={}&Expires={}&Signature={}'.format(media_url, google_access_id, expires, signature))
</code>```

The log.debug statement prints a signature file which perfectly matches the signature in the GCS XML error response  above.  If they match, then why can't I upload?

Using gsutil, I can create a signed URL using the same GAE service account, and it works fine in Postman.  I see gsutil URL-encodes the signature, but when creating my own signed URL, it doesn't seem to matter either way: GCS gets my PUT request and complains that the signature doesn't match, even though the signature it shows me matches my logged debug message.  I've also tried with and without a trailing \n in the original signature string.

EDIT:  The POST example I followed Base64 encodes the Policy before it sings, and again after it signs it.  I tried this approach with the PUT signature creation and it made no difference

答:
The answer was very close to other answers found on SO and elsewhere noting that a Content-Type header needs to be used.  This is partly true, but overshadowed by my main problem:  I was relying on the Default GAE Service Account which has permissions of "Editor" which I assumed could read and write to GCS.  I made a keyfile from that account and used it with gsutil which then gave me this clue:

```<code>myDefaultGAEserviceaccount@appspot.gserviceaccount.com does not have permissions on gs://mybucket/cat.jpg, using this link will likely result in a 403 error until at least READ permissions are granted
</code>```

It was right that I'd get an error from GCS when trying to PUT a file there, but it wasn't a 404 error, rather it was the SignatureDoesNotMatch error shown in the question.

The solution was 2 part:

Give the Default GAE service account more permission from the "Storage" set of permissions:

Storage Object Creator

Storage Object Viewer

Be sure to use Content-Type Header when PUTting the file to GCS because even I don't specify it in the Signature string to be signed, it will default to text/plain and require that in  the Header.

One final observation: Even after I added the correct permissions to my account, I still got the warning with gsutil until I created a new JSON key file from the IAM console.  Furthermore, signed URLs made with gsutil and the old key file failed to work (SignatureDoesNotMatch error) even if the permissions were set on the IAM console.  The Python code running on GAE worked fine without any updates - it only needed the permissions set in IAM and then the Content-Headers to match.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a signed URL to be used for uploading files directly to Google Cloud Storage (GCS).  I had this working using POST using this Github example, which makes use of a policy.  Per best practice, I'm refactoring to use PUT and getting a SignatureDoesNotMatch error:

<?xml version='1.0' encoding='UTF-8'?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>PUT

123456789
/mybucket/mycat.jpg</StringToSign></Error>

Per the docs on creating a signed URL with a program and the GCP example Python code, I am doing this process:

building my Signature string

signing it

base64 encoding it

url encoding the result (the python example doesn't do this though...

Since this is running on a Google App Engine (GAE) App, I shouldn't need to get a JSON key file for my service account user, but rather use App Identity Services to sign it.  Here's my code within a Flask project:

google_access_id = app_identity.get_service_account_name()
expires = arrow.utcnow().replace(minutes=+10).replace(microseconds=0).timestamp
resource = '/mybucket/mycat.jpg'

args = self.get_parser.parse_args()
signature_string = 'PUT\n'
# take MD5 of file being uploaded and its content type, if provided
content_md5 = args.get('md5') or ''
content_type = args.get('contenttype') or ''
signature_string = ('PUT\n'
                    '{md5}\n'
                    '{content_type}\n'
                    '{expires}\n'
                    '{resource}\n').format(
                    md5=content_md5,
                    content_type=content_type,
                    expires=expires,
                    resource=resource)
log.debug('signature string:\n{}'.format(signature_string))
_, signature_bytes = app_identity.sign_blob(signature_string)
signature = base64.b64encode(signature_bytes)
# URL encode signature
signature = urllib.quote(signature)
media_url = 'https://storage.googleapis.com{}'.format(resource)
return dict(GoogleAccessId=google_access_id,
            Expires=expires,
            Signature=signature,
            bucket='mybucket',
            media_url='{}?GoogleAccessId={}&Expires={}&Signature={}'.format(media_url, google_access_id, expires, signature))

The log.debug statement prints a signature file which perfectly matches the signature in the GCS XML error response  above.  If they match, then why can't I upload?

Using gsutil, I can create a signed URL using the same GAE service account, and it works fine in Postman.  I see gsutil URL-encodes the signature, but when creating my own signed URL, it doesn't seem to matter either way: GCS gets my PUT request and complains that the signature doesn't match, even though the signature it shows me matches my logged debug message.  I've also tried with and without a trailing \n in the original signature string.

EDIT:  The POST example I followed Base64 encodes the Policy before it sings, and again after it signs it.  I tried this approach with the PUT signature creation and it made no difference

Body:
The answer was very close to other answers found on SO and elsewhere noting that a Content-Type header needs to be used.  This is partly true, but overshadowed by my main problem:  I was relying on the Default GAE Service Account which has permissions of "Editor" which I assumed could read and write to GCS.  I made a keyfile from that account and used it with gsutil which then gave me this clue:

myDefaultGAEserviceaccount@appspot.gserviceaccount.com does not have permissions on gs://mybucket/cat.jpg, using this link will likely result in a 403 error until at least READ permissions are granted

It was right that I'd get an error from GCS when trying to PUT a file there, but it wasn't a 404 error, rather it was the SignatureDoesNotMatch error shown in the question.

The solution was 2 part:

Give the Default GAE service account more permission from the "Storage" set of permissions:

Storage Object Creator

Storage Object Viewer

Be sure to use Content-Type Header when PUTting the file to GCS because even I don't specify it in the Signature string to be signed, it will default to text/plain and require that in  the Header.

One final observation: Even after I added the correct permissions to my account, I still got the warning with gsutil until I created a new JSON key file from the IAM console.  Furthermore, signed URLs made with gsutil and the old key file failed to work (SignatureDoesNotMatch error) even if the permissions were set on the IAM console.  The Python code running on GAE worked fine without any updates - it only needed the permissions set in IAM and then the Content-Headers to match.


问:
Finding the count of  Jquery
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

```<code><table class="PrintTable">
    <tr>
      **<td>**
        <table>
            <thead>
                <tr><th>Type Of Transaction</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Name</td>
                </tr>
                <tr>
                    <td>Age</td>
                </tr>
            </tbody>
        </table>
      </td>
      **<td>**
        <table>
            <thead>
                <tr><th>2006</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Andi</td>
                </tr>
                <tr>
                    <td>25</td>
                </tr>
            </tbody>
        </table>
      </td>

    </tr>
</table>
</code>```

The function that I am using to find out the length of td is

```<code>function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}
</code>```

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

答:
I removed the asterisks out of your HTML and made some assumptions about how you're invoking getBody, so if I did anything that wasn't right, let me know.

Code: http://jsfiddle.net/27ygP/

```<code>function getBody(element) {
    var divider = 2;
    var originalTable = element.clone();
    var tds = $(originalTable).children('tbody').children('tr').children('td').length;
    alert(tds);
}

getBody($('table.PrintTable'));
</code>```

The big change was the add a .children('tbody'). The HTML interpreter wraps the trs in tbody. Traverse down into that, and you'll be fine.

ContentLicense: CC BY-SA 2.5

Title: Finding the count of <td> Jquery

Body:
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

      ****

Type Of Transaction

                    Name

                    Age

      ****

2006

                    Andi

                    25

The function that I am using to find out the length of td is

function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

Body:
I removed the asterisks out of your HTML and made some assumptions about how you're invoking getBody, so if I did anything that wasn't right, let me know.

Code: http://jsfiddle.net/27ygP/

function getBody(element) {
    var divider = 2;
    var originalTable = element.clone();
    var tds = $(originalTable).children('tbody').children('tr').children('td').length;
    alert(tds);
}

getBody($('table.PrintTable'));

The big change was the add a .children('tbody'). The HTML interpreter wraps the trs in tbody. Traverse down into that, and you'll be fine.


问:
How to refactor checkout process into service
I have e-commerce site that I am currently decoupling so it serves as pure backend.

For shopping cart to become an order there is a workflow(checkout) in place that the customer has to go through to place an order. With the checkout now being a backend service I wonder how should I approach it.

Specifically, each new order has to have: items, billing address, delivery address, payment method and shipping method. Admin can create additional fields, alter the flow(order of steps) and so on. With API-centric architecture, I am not sure how to communicate the flow with frontend.

Sure, the frontend will handle the flow, basically, on its own. But for example in the backend logic, the shipping method depends on the provided delivery address and payment method depends on the billing address - to prevent use of cash payment method for customer form different country or to use local bicycle carrier for international destination... for example.

How should I communicate to the client what data are needed, in which order(dependencies), what data I already have and what additional data has to be provided?

答:
You basically handle this with exceptions if the front-end does something out-of-order.  The statefulness of it means that you need to create something, then modify it multiple times.  If you want to enforce this, you would basically create an order (with items),

```<code>POST /orders <new order>
POST /orders/<ordernum>/items
POST /orders/<ordernum>/billingaddress
POST /orders/<ordernum>/shippingaddress
GET /orders/<ordernum>/availableshippingmethods (throws an error code if billing address not set)
GET /orders/<ordernum>/availablepaymentmethods (throws an error if shipping address not set)
POST /orders/<ordernum>/shippingmethod (throws an error if billing address not set)
</code>```

etc...  Just set up your step dependencies, and throw errors if they do it wrong.

This way the business logic stays on the front-end, and the API requirements for the flow are fairly self-describing (trying to get the shipping method tells you what you forgot to do).

Body:
You basically handle this with exceptions if the front-end does something out-of-order.  The statefulness of it means that you need to create something, then modify it multiple times.  If you want to enforce this, you would basically create an order (with items),

POST /orders <new order>
POST /orders/<ordernum>/items
POST /orders/<ordernum>/billingaddress
POST /orders/<ordernum>/shippingaddress
GET /orders/<ordernum>/availableshippingmethods (throws an error code if billing address not set)
GET /orders/<ordernum>/availablepaymentmethods (throws an error if shipping address not set)
POST /orders/<ordernum>/shippingmethod (throws an error if billing address not set)

etc...  Just set up your step dependencies, and throw errors if they do it wrong.

This way the business logic stays on the front-end, and the API requirements for the flow are fairly self-describing (trying to get the shipping method tells you what you forgot to do).


问:
make timeline-slider looping
I am wondering how to loop this auto-slide function? Its for this timeline here: https://bm-translations.de/#sprachrichtungen

I tried with if condition to check if next slide has items, but maybe because I am a beginner, its not working.

```<code>function timeLineAutoPlay() {
  var current = 0;

  setInterval(function() {
    current++;
    var current_elem = $($('.events a')[current - 1]);

    if (current == 11) {
      timeLineAutoPlay();
    }

    $($('.events a')[current]).trigger('click');

    if ((current + 1) % 4 == 0) {
      $('.next').trigger('click');
    }
  }, 8000);
}

timeLineAutoPlay();
</code>```

Slider is frome here: https://codyhouse.co/gem/horizontal-timeline/

2nd problem:
If I click on a date, the next autoslide isnt the date after. Do you know how to adjust this code?

Tried this, but its not working:

```<code>timelineComponents['eventsWrapper'].on('click', 'a', function(event){
    current = items.length;
}
</code>```

答:
Something like the following:</p>

```<code>setInterval(function(){
    var current_elem = $($('.events a')[current]);

    if(!current_elem.hasClass("selected")){
        $(".events a").each( function(index, elem) {
            if($(this).hasClass("selected")){
                current = index;
            }
        });
    }

    current++;

    if(current >= $('.events a').length) {
        current = 0;
    }

    $($('.events a')[current]).trigger('click');
}, 7000);
</code>```

Title: make timeline-slider looping

Body:
I am wondering how to loop this auto-slide function? Its for this timeline here: https://bm-translations.de/#sprachrichtungen

I tried with if condition to check if next slide has items, but maybe because I am a beginner, its not working.

function timeLineAutoPlay() {
  var current = 0;

  setInterval(function() {
    current++;
    var current_elem = $($('.events a')[current - 1]);

    if (current == 11) {
      timeLineAutoPlay();
    }

    $($('.events a')[current]).trigger('click');

    if ((current + 1) % 4 == 0) {
      $('.next').trigger('click');
    }
  }, 8000);
}

timeLineAutoPlay();

Slider is frome here: https://codyhouse.co/gem/horizontal-timeline/

2nd problem:
If I click on a date, the next autoslide isnt the date after. Do you know how to adjust this code?

Tried this, but its not working:

timelineComponents['eventsWrapper'].on('click', 'a', function(event){
    current = items.length;
}

Body:
Something like the following:

setInterval(function(){
    var current_elem = $($('.events a')[current]);

    if(!current_elem.hasClass("selected")){
        $(".events a").each( function(index, elem) {
            if($(this).hasClass("selected")){
                current = index;
            }
        });
    }

    current++;

    if(current >= $('.events a').length) {
        current = 0;
    }

    $($('.events a')[current]).trigger('click');
}, 7000);


问:
Unable to profile MySQL with MiniProfiler on .NET Core
I'm playing with .net core and trying to get asp.net core + mysql + dapper + mini-mvc-profiler to work on Linux. Having problem with mini-mvc-profiler.

I'm using:

```<code><PackageReference Include="Dapper" Version="1.50.2" />
<PackageReference Include="MiniProfiler.AspNetCore" Version="4.0.0-alpha6-79" />
<PackageReference Include="MiniProfiler.Shared" Version="4.0.0-alpha6-79" />
<PackageReference Include="MySql.Data.Core" Version="7.0.4-IR-191" />
</code>```

I have SQLProfiler class:

```<code>public class SQLProfiler
{
    public static DbConnection GetOpenConnection(string connectionString)
    {
        //return new MySqlConnection(connectionString); // that works OK
        return new StackExchange.Profiling.Data.ProfiledDbConnection(
            new MySqlConnection(connectionString), MiniProfiler.Current
        );
    }
}
</code>```

And calling it from repository class:

```<code>using (var connection = SQLProfiler.GetOpenConnection(_connectionString))
{
    return connection.Query<UserIdentityDTO>(sql,
        new {
            myemail = email,
            mypassword = password,
            myprovider = PROVIDER_LOCAL
        }
    ).FirstOrDefault();
}
</code>```

I get:

```<code>NullReferenceException: Object reference not set to an instance of an object.
MySql.Data.MySqlClient.MySqlConnection.set_Reader(MySqlDataReader value)
</code>```

StackTrace:

```<code>MySql.Data.MySqlClient.MySqlConnection.set_Reader(MySqlDataReader value)
MySql.Data.MySqlClient.MySqlCommand.ResetReader()
MySql.Data.MySqlClient.MySqlCommand.Dispose(bool disposing)
StackExchange.Profiling.Data.ProfiledDbCommand.Dispose(bool disposing) in ProfiledDbCommand.cs
System.Data.Common.DbCommand.Dispose()
Dapper.SqlMapper+<QueryImpl>d__124.MoveNext()
System.Collections.Generic.List..ctor(IEnumerable<T> collection)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
Dapper.SqlMapper.Query<T>(IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, Nullable<int> commandTimeout, Nullable<CommandType> commandType)
persistance.dapper.repository.UserQueries.Get(string email, string password) in UserQueries.cs
</code>```

答:
As suggested by Nick Craver, </p>

```<code> <ItemGroup>
    <PackageReference Include="Dapper" Version="1.50.2" />
    <PackageReference Include="DapperExtensions.DotnetCore" Version="1.0.1" />
    <PackageReference Include="MiniProfiler.AspNetCore" Version="4.0.0-alpha6-79" />
    <PackageReference Include="MiniProfiler.Shared" Version="4.0.0-alpha6-79" />
    <PackageReference Include="MySqlConnector" Version="0.30.0" />
  </ItemGroup>
</code>```

<p>...it's alive  :-)</p>

Body:
I'm playing with .net core and trying to get asp.net core + mysql + dapper + mini-mvc-profiler to work on Linux. Having problem with mini-mvc-profiler.

I'm using:

<PackageReference Include="Dapper" Version="1.50.2" />
<PackageReference Include="MiniProfiler.AspNetCore" Version="4.0.0-alpha6-79" />
<PackageReference Include="MiniProfiler.Shared" Version="4.0.0-alpha6-79" />
<PackageReference Include="MySql.Data.Core" Version="7.0.4-IR-191" />

I have SQLProfiler class:

public class SQLProfiler
{
    public static DbConnection GetOpenConnection(string connectionString)
    {
        //return new MySqlConnection(connectionString); // that works OK
        return new StackExchange.Profiling.Data.ProfiledDbConnection(
            new MySqlConnection(connectionString), MiniProfiler.Current
        );
    }
}

And calling it from repository class:

using (var connection = SQLProfiler.GetOpenConnection(_connectionString))
{
    return connection.Query<UserIdentityDTO>(sql,
        new {
            myemail = email,
            mypassword = password,
            myprovider = PROVIDER_LOCAL
        }
    ).FirstOrDefault();
}

I get:

NullReferenceException: Object reference not set to an instance of an object.
MySql.Data.MySqlClient.MySqlConnection.set_Reader(MySqlDataReader value)

StackTrace:

MySql.Data.MySqlClient.MySqlConnection.set_Reader(MySqlDataReader value)
MySql.Data.MySqlClient.MySqlCommand.ResetReader()
MySql.Data.MySqlClient.MySqlCommand.Dispose(bool disposing)
StackExchange.Profiling.Data.ProfiledDbCommand.Dispose(bool disposing) in ProfiledDbCommand.cs
System.Data.Common.DbCommand.Dispose()
Dapper.SqlMapper+<QueryImpl>d__124.MoveNext()
System.Collections.Generic.List..ctor(IEnumerable<T> collection)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
Dapper.SqlMapper.Query<T>(IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, Nullable<int> commandTimeout, Nullable<CommandType> commandType)
persistance.dapper.repository.UserQueries.Get(string email, string password) in UserQueries.cs

Body:
As suggested by Nick Craver,

 <ItemGroup>
    <PackageReference Include="Dapper" Version="1.50.2" />
    <PackageReference Include="DapperExtensions.DotnetCore" Version="1.0.1" />
    <PackageReference Include="MiniProfiler.AspNetCore" Version="4.0.0-alpha6-79" />
    <PackageReference Include="MiniProfiler.Shared" Version="4.0.0-alpha6-79" />
    <PackageReference Include="MySqlConnector" Version="0.30.0" />
  </ItemGroup>

...it's alive  :-)


问:
CDI in backend?
I've been tasked to refactor an old application, which used to create DAO's all over the place, by using the new keyword, and local managed entitymanager.

Now I'm supposed to use JTA to manage the connections. For what I can understand, I should use CDI for that. So far it haven't been a problems. My views are CDI views, and i @Inject all my DAO's, or in other cases whole controllers that use the DAO's, like the following example.

```<code>@CDIView(value = TestView.VIEW_ID)
public class TestView extends Test implements View {
public static final String VIEW_ID = "testviewer";

@Inject
private
TestInterface testInterface;

public void viewLogic() {

    ...
}
</code>```

While all this works fine, I'm starting to get worry. Because behind the scenes there is a lot of threads, running simultaneously. These threads would need their own instances of objects, and therefore just cannot be injected - or can they? An example would be:

```<code>@Stateless
public class TestInterface {

@Inject
TestDAO testDAO;

private List<TestRunner> getTestRunners(Test test, ToplevelTest tlt){
    List<TestRunner> runners = new ArrayList<>();
    for(SomeThing st : getTestSomethings()){
        if(st.condition())
            runners.add(new AbstractTestRunner());
        else runners.add(new FancyTestRunner());

    }
}

private SomeDataAccess(){
    testDAO.save(new Test());
}
</code>```

This example code would the execute within a managed bean, which is fine (I think!), but these testrunners would also need to have access to the dataccesslayer. But I need (a variable) multiple instances of these.

I've read that you can use CDI.current().get(MySingletonClass.class)
Is it a good idea (and possible?) to obtain a singleton repository to use as dataccess within these testrunners, and then just "new" the testrunners as before?

Or is there a better way to handle all this?

All suggestions are warmly received. I'm rather new to CDI.

Best regards

答: You could use the more "primitive" method of dependency injection, pass an instance of MySingletonClass into the TestRunners constructor.

Title: CDI in backend?

Body:
I've been tasked to refactor an old application, which used to create DAO's all over the place, by using the new keyword, and local managed entitymanager.

Now I'm supposed to use JTA to manage the connections. For what I can understand, I should use CDI for that. So far it haven't been a problems. My views are CDI views, and i @Inject all my DAO's, or in other cases whole controllers that use the DAO's, like the following example.

@CDIView(value = TestView.VIEW_ID)
public class TestView extends Test implements View {
public static final String VIEW_ID = "testviewer";

@Inject
private
TestInterface testInterface;

public void viewLogic() {

    ...
}

While all this works fine, I'm starting to get worry. Because behind the scenes there is a lot of threads, running simultaneously. These threads would need their own instances of objects, and therefore just cannot be injected - or can they? An example would be:

@Stateless
public class TestInterface {

@Inject
TestDAO testDAO;

private List<TestRunner> getTestRunners(Test test, ToplevelTest tlt){
    List<TestRunner> runners = new ArrayList<>();
    for(SomeThing st : getTestSomethings()){
        if(st.condition())
            runners.add(new AbstractTestRunner());
        else runners.add(new FancyTestRunner());

    }
}

private SomeDataAccess(){
    testDAO.save(new Test());
}

This example code would the execute within a managed bean, which is fine (I think!), but these testrunners would also need to have access to the dataccesslayer. But I need (a variable) multiple instances of these.

I've read that you can use CDI.current().get(MySingletonClass.class)
Is it a good idea (and possible?) to obtain a singleton repository to use as dataccess within these testrunners, and then just "new" the testrunners as before?

Or is there a better way to handle all this?

All suggestions are warmly received. I'm rather new to CDI.

Best regards


问:
Case within a Select returning "missing expression ORA-00905"
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

```<code>select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual
</code>```

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

答:
Why are you trying to embed dbms_output in a query?  Just write:

```<code>select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then 'M'
    when mod(round(dbms_random.value(1,100)),2) = 1 then 'W'
  end
from dual
</code>```

Also you know, since you are calling dbms_random two different times, you get two different values in the same query.  If you want one value to be compared, then use a WITH clause

```<code>with rand_value as
( select round(dbms_random.value(1,100)) val from dual
)
select
  case
    when mod(val,2) = 0 then 'M'
    when mod(val,2) = 1 then 'W'
  end
from rand_value
</code>```

Body:
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

Body:
Why are you trying to embed dbms_output in a query?  Just write:

select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then 'M'
    when mod(round(dbms_random.value(1,100)),2) = 1 then 'W'
  end
from dual

Also you know, since you are calling dbms_random two different times, you get two different values in the same query.  If you want one value to be compared, then use a WITH clause

with rand_value as
( select round(dbms_random.value(1,100)) val from dual
)
select
  case
    when mod(val,2) = 0 then 'M'
    when mod(val,2) = 1 then 'W'
  end
from rand_value


问:
Select of 2 related tables in MySQL
I have these 2 tables:

Table Users:

```<code>id | name
---------
1  | Joe
2  | Sara
3  | Michael
</code>```

Table Sales:

```<code>id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3
</code>```

I want the following:

```<code>User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0
</code>```

Any help would be appreciated

答:
```<code>SELECT
    name as UserName ,
    SUM(product= 'Car')AS Car,
    SUM(product= 'Truck')AS Truck,
    SUM(product= 'motorcycle') AS motorcycle
FROM Users join Sales
on Users.id = Sales.user_id
GROUP BY name
</code>```

hope it helps but still this is a standard solution you should check pivot Tables.

Title: Select of 2 related tables in MySQL

Body:
I have these 2 tables:

Table Users:

id | name
---------
1  | Joe
2  | Sara
3  | Michael

Table Sales:

id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3

I want the following:

User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0

Any help would be appreciated

Body:
SELECT
    name as UserName ,
    SUM(product= 'Car')AS Car,
    SUM(product= 'Truck')AS Truck,
    SUM(product= 'motorcycle') AS motorcycle
FROM Users join Sales
on Users.id = Sales.user_id
GROUP BY name

hope it helps but still this is a standard solution you should check pivot Tables.


问:
Excluding query result with in and not in
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

```<code>SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate
</code>```

Results:

```<code>CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000
</code>```

答:
having COUNT(CustomerID)>1 mean that you have more that 1 order (2,3,4...).

In the first subquery, use having COUNT(CustomerID)>0

and in the second, use:

```<code>s.CustomerID
not in(select CustomerID from Sales.SalesOrderHeader where YEAR(OrderDate)
in(2012,2013))
</code>```

without group by and having

Body:
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate

Results:

CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000

Body:
having COUNT(CustomerID)>1 mean that you have more that 1 order (2,3,4...).

In the first subquery, use having COUNT(CustomerID)>0

and in the second, use:

s.CustomerID
not in(select CustomerID from Sales.SalesOrderHeader where YEAR(OrderDate)
in(2012,2013))

without group by and having


问:
Angular 2 redirect from child router
I have appRoutes in my Angular 2 app

```<code>const appRoutes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    {
        path: 'component-two', component: AppComponent2,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
        ]
    },
];
</code>```

How I can redirect from my LoginComponent to HomeComponent?

答:
you should use redirectTo for default redirect

```<code>const appRoutes: Routes = [
  { path: '/login', component: LoginComponent },
  { path: '/home', component: LoginComponent },
  { path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];
</code>```

from Html you can redirect like

```<code><nav>
    <a routerLink="/login" routerLinkActive="active">Login</a>
    <a routerLink="/home" routerLinkActive="active">Home</a>
  </nav>
</code>```

inject Router to your HomeComponent's constructor

```<code>constructor(
  private router: Router,
  private service: HeroService
) {}
</code>```

Then use  this.router.navigate(['/login']); in your event function

for more details refer angular guide

Title: Angular 2 redirect from child router

Body:
I have appRoutes in my Angular 2 app

const appRoutes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    {
        path: 'component-two', component: AppComponent2,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
        ]
    },
];

How I can redirect from my LoginComponent to HomeComponent?

Body:
you should use redirectTo for default redirect

const appRoutes: Routes = [
  { path: '/login', component: LoginComponent },
  { path: '/home', component: LoginComponent },
  { path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

from Html you can redirect like

<nav>
    <a routerLink="/login" routerLinkActive="active">Login</a>
    <a routerLink="/home" routerLinkActive="active">Home</a>
  </nav>

inject Router to your HomeComponent's constructor

constructor(
  private router: Router,
  private service: HeroService
) {}

Then use  this.router.navigate(['/login']); in your event function

for more details refer angular guide


问:
Calculate Max from set of Calculated Measure in powerPivot
I have created a model in PowerPivot, and have many calculated measure to get the share value (%).
EX:

```<code> 1. Brand 1   15%
 2. Brand 2   34%
 3. Brand 3   51%
</code>```

To get each brand Share value i have written a Dax formula as below:

```<code> =(Sum(Column A)/Sum(Column b)).
</code>```

Now i need to get the max of the share value (%) from the list of Brands we have. Can someone help me write another formula to get the max of share Value among all the brands.
i.e. Brand 3 51%.

答:
Without knowing more about your model I can only propose to try measure below (if measure for brand shares is called ValueShare).

```<code>MaxShare = MAXX(ALL('Product'[Brands]),[ValueShare])
</code>```

Body:
I have created a model in PowerPivot, and have many calculated measure to get the share value (%).
EX:

 1. Brand 1   15%
 2. Brand 2   34%
 3. Brand 3   51%

To get each brand Share value i have written a Dax formula as below:

 =(Sum(Column A)/Sum(Column b)).

Now i need to get the max of the share value (%) from the list of Brands we have. Can someone help me write another formula to get the max of share Value among all the brands.
i.e. Brand 3 51%.

Body:
Without knowing more about your model I can only propose to try measure below (if measure for brand shares is called ValueShare).

MaxShare = MAXX(ALL('Product'[Brands]),[ValueShare])


问:
Jersey ModelValidationException - No Injection source found
I got a weird problem, that I absolutely doesn't understand, with Jersey 2.6.

I can't explain why, but one of the query parameter make jersey throw a ModelValidationException

```<code>    @ApiOperation("Save")
    @PUT
    public Response save(
            @HeaderParam("token") final String token,
            @QueryParam("someValue") final SomeValueDTO someValue,
            @QueryParam("anotherParam") final int anotherParam) throws TechnicalException {

        return Response.ok().build();
    }
</code>```

the queryParam 'someValue' make jersey throw:

```<code>org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.|[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response ch.rodano.studies.api.resources.PagesResource.save(java.lang.String,ch.rodano.studies.api.dto.JSONValueDTO,int) throws ch.rodano.studies.exceptions.RightException,ch.rodano.studies.configuration.exceptions.NoNodeException at index 1.; source='ResourceMethod{httpMethod=PUT, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class ch.rodano.studies.api.resources.PagesResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@41ed3918]}, definitionMethod=public javax.ws.rs.core.Response ch.rodano.studies.api.resources.PagesResource.save(java.lang.String,ch.rodano.studies.api.dto.JSONValueDTO,int) throws ch.rodano.studies.exceptions.RightException,ch.rodano.studies.configuration.exceptions.NoNodeException, parameters=[Parameter [type=class java.lang.String, source=token, defaultValue=null], Parameter [type=class ch.rodano.studies.api.dto.JSONValueDTO, source=valuesASD, defaultValue=null], Parameter [type=int, source=visitPk, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']
</code>```

If I use String instead of SomeValueDTO everything's okay.
SomeValueDTO is a quite classic POJO with an empty constructor and getters/setters.

If someone has an idiea !!

答:
From Jersey 2.0, you can use @BeanParam as input but you must set all @QueryParam in the DTO variables:

```<code>@ApiOperation("Save")
@PUT
public Response save(@BeanParam SomeValueDTO inputValue)
{
   String prop1 = inputValue.prop1;
   String prop2 = inputValue.prop2;
   String prop3 = inputValue.prop3;
}
</code>```

SomeValueDTO.java will be:

```<code>public class SomeValueDTO{
 @QueryParam("prop1")
 public String prop1;

 @QueryParam("prop2")
 public String prop2;

 @QueryParam("prop3")
 public String prop3;
}
</code>```

The http call can be:

```<code>$http.get('insert-path', {
    params: {
         prop1: "prop1value",
         prop2: "prop2value",
         prop3: "prop3value"
 }});
</code>```

Source answer:  https://stackoverflow.com/a/17309823/3410465

Body:
I got a weird problem, that I absolutely doesn't understand, with Jersey 2.6.

I can't explain why, but one of the query parameter make jersey throw a ModelValidationException

    @ApiOperation("Save")
    @PUT
    public Response save(
            @HeaderParam("token") final String token,
            @QueryParam("someValue") final SomeValueDTO someValue,
            @QueryParam("anotherParam") final int anotherParam) throws TechnicalException {

        return Response.ok().build();
    }

the queryParam 'someValue' make jersey throw:

org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.|[[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response ch.rodano.studies.api.resources.PagesResource.save(java.lang.String,ch.rodano.studies.api.dto.JSONValueDTO,int) throws ch.rodano.studies.exceptions.RightException,ch.rodano.studies.configuration.exceptions.NoNodeException at index 1.; source='ResourceMethod{httpMethod=PUT, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class ch.rodano.studies.api.resources.PagesResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@41ed3918]}, definitionMethod=public javax.ws.rs.core.Response ch.rodano.studies.api.resources.PagesResource.save(java.lang.String,ch.rodano.studies.api.dto.JSONValueDTO,int) throws ch.rodano.studies.exceptions.RightException,ch.rodano.studies.configuration.exceptions.NoNodeException, parameters=[Parameter [type=class java.lang.String, source=token, defaultValue=null], Parameter [type=class ch.rodano.studies.api.dto.JSONValueDTO, source=valuesASD, defaultValue=null], Parameter [type=int, source=visitPk, defaultValue=null]], responseType=class javax.ws.rs.core.Response}, nameBindings=[]}']

If I use String instead of SomeValueDTO everything's okay.
SomeValueDTO is a quite classic POJO with an empty constructor and getters/setters.

If someone has an idiea !!

Body:
From Jersey 2.0, you can use @BeanParam as input but you must set all @QueryParam in the DTO variables:

@ApiOperation("Save")
@PUT
public Response save(@BeanParam SomeValueDTO inputValue)
{
   String prop1 = inputValue.prop1;
   String prop2 = inputValue.prop2;
   String prop3 = inputValue.prop3;
}

SomeValueDTO.java will be:

public class SomeValueDTO{
 @QueryParam("prop1")
 public String prop1;

 @QueryParam("prop2")
 public String prop2;

 @QueryParam("prop3")
 public String prop3;
}

The http call can be:

$http.get('insert-path', {
    params: {
         prop1: "prop1value",
         prop2: "prop2value",
         prop3: "prop3value"
 }});

Source answer:  https://stackoverflow.com/a/17309823/3410465

ContentLicense: CC BY-SA 4.0


问:
How do I create email with css and images from Rails?
How do you create and send emails from Rails application, that contain images and proper formatting? like the ones you get from facebook and like.</p>

答:
Assuming you know how to send normal plain-text emails from Rails using ActionMailer, to get HTML emails working you need to set a content type for your email.

For example, your notifer might look like this:

```<code>class MyMailer < ActionMailer::Base
  def signup_notification(recipient)
    recipients   recipient.email_address_with_name
    subject      "New account information"
    from         "system@example.com"
    body         :user => recipient
    content_type "text/html"
  end
end
</code>```

Note the content_type "text/html" line. This tells ActionMailer to send an email with a content type of text/html instead of the default text/plain.

Next you have to make your mailer views output HTML. For example, your view file app/views/my_mailer/signup_notification.html.erb might look like the following:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css" media="screen">
      h3 { color: #f00; }
      ul { list-style: none; }
    </style>
</head>
<body>
  <h3>Your account signup details are below</h3>
  <ul>
    <li>Name: <%= @user.name %></li>
    <li>Login: <%= @user.login %></li>
    <li>E-mail: <%= @user.email_address %></li>
  </ul>
</body>
</html>
</code>```

As you can see the HTML view can include a

OwnerDisplayName: Akshay

LastEditorDisplayName: Mike Woodhouse

Body:
Assuming you know how to send normal plain-text emails from Rails using ActionMailer, to get HTML emails working you need to set a content type for your email.

For example, your notifer might look like this:

class MyMailer < ActionMailer::Base
  def signup_notification(recipient)
    recipients   recipient.email_address_with_name
    subject      "New account information"
    from         "system@example.com"
    body         :user => recipient
    content_type "text/html"
  end
end

Note the content_type "text/html" line. This tells ActionMailer to send an email with a content type of text/html instead of the default text/plain.

Next you have to make your mailer views output HTML. For example, your view file app/views/my_mailer/signup_notification.html.erb might look like the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css" media="screen">
      h3 { color: #f00; }
      ul { list-style: none; }
    </style>
</head>
<body>
  <h3>Your account signup details are below</h3>
  <ul>
    <li>Name: <%= @user.name %></li>
    <li>Login: <%= @user.login %></li>
    <li>E-mail: <%= @user.email_address %></li>
  </ul>
</body>
</html>

As you can see the HTML view can include a <style> tag to define basic styles. Not all HTML and CSS is supported, especially across all mail clients, but you should definitely have sufficient formatting control over text styles.

Embedding images is a bit tricker if you plan to display attached emails. If you are simply including emails from external sites, you can use an <img /> tag as you usually would in HTML. However, many mail clients will block these images from being displayed until the user authorises it. If you need to display attached images, the Rails plug-in Inline Attachments might be worth a look.

For more information on Rails mailing support, the ActionMailer documentation is a great resource

OwnerDisplayName: bjeanes


问:
Python converting a string of KB into a string of Bytes
I have a field on my web application that requires a KB. This is then reflected in the URL of the web app in Bytes form. </p>

<p>Can I convert a string of "500" KB to a string of Bytes in Python (expecting to get around "500000")? </p>

答:
From Wikipedia:

The kilobyte is a multiple of the unit byte for digital information.
The International System of Units (SI) defines the prefix kilo as 1000
(103); therefore one kilobyte is 1000 bytes.

You can simply cast it to an integer,multiply it by 1000, and return it to a string like this:

```<code>>>> size_in_kb = "500"
>>> bytes = str(int(size_in_kb) * 1000)
>>> bytes
'500000'
</code>```

Note: you can multiply it with 1024 instead of 1000, depends on your exact
needs

Body:
I have a field on my web application that requires a KB. This is then reflected in the URL of the web app in Bytes form.

Can I convert a string of "500" KB to a string of Bytes in Python (expecting to get around "500000")?

Body:
From Wikipedia:

The kilobyte is a multiple of the unit byte for digital information.
The International System of Units (SI) defines the prefix kilo as 1000
(103); therefore one kilobyte is 1000 bytes.

You can simply cast it to an integer,multiply it by 1000, and return it to a string like this:

>>> size_in_kb = "500"
>>> bytes = str(int(size_in_kb) * 1000)
>>> bytes
'500000'

Note: you can multiply it with 1024 instead of 1000, depends on your exact
needs


问:
How to trigger a touch event?
Lets start with some event listeners:

```<code>window.addEventListener('scroll', function (e) {
    console.log('scroll', e);
});
window.addEventListener('touchstart', function (e) {
    console.log('touchstart', e);
});
window.addEventListener('touchmove', function (e) {
    console.log('touchmove', e);
});
window.addEventListener('touchend', function (e) {
    console.log('touchend', e);
});
</code>```

I need to programmatically touch the document in position {pageX: 0, pageY: 0}, move it to {pageX: 0, pageY: 100} and end the touch event.

To do this, I am going to build a helper function TouchEvent that will trigger the touch event on the specified element.

```<code>/**
 * @see https://gist.github.com/sstephenson/448808
 * @see https://developer.apple.com/library/iad/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html
 * @see http://stackoverflow.com/questions/18059860/manually-trigger-touch-event
 */
function touchEvent (element, type, identifier, pageX, pageY) {
    var e,
        touch,
        touches,
        targetTouches,
        changedTouches;

    touch = document.createTouch(window, element, identifier, pageX, pageY, pageX, pageY);

    if (type == 'touchend') {
        touches = document.createTouchList();
        targetTouches = document.createTouchList();
        changedTouches = document.createTouchList(touch);
    } else {
        touches = document.createTouchList(touch);
        targetTouches = document.createTouchList(touch);
        changedTouches = document.createTouchList(touch);
    }

    e = document.createEvent('TouchEvent');
    e.initTouchEvent(type, true, true, window, null, 0, 0, 0, 0, false, false, false, false, touches, targetTouches, changedTouches, 1, 0);

    window.dispatchEvent(e);
};
</code>```

I am going to make sure that the document is loaded and dispatch the touch events representing earlier agreed scenario.

```<code>document.addEventListener('DOMContentLoaded', function() {
    var identifier = new Date().getTime(),
        element = document,
        i = 0;

    touchEvent(element, 'touchstart', identifier, 0, 0);
    while (i++ < 100) {
        touchEvent(element, 'touchmove', identifier, 0, i);
    }
    touchEvent(element, 'touchend', identifier, 0, i);
});
</code>```

The expected is that touchstart, touchmove and touchend events have been triggered. The unexpected is that scroll event has not been triggered and the actual "touching" of the document is not reflected in the current document.

window.addEventListener('scroll', function (e) {
    console.log('scroll', e);
});
window.addEventListener('resize', function (e) {
    console.log('resize', e);
});
window.addEventListener('touchstart', function (e) {
    console.log('touchstart', e);
});
window.addEventListener('touchmove', function (e) {
    console.log('touchmove', e);
});
window.addEventListener('touchend', function (e) {
    console.log('touchend', e);
});

/**
 * @see https://gist.github.com/sstephenson/448808
 * @see https://developer.apple.com/library/iad/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html
 * @see http://stackoverflow.com/questions/18059860/manually-trigger-touch-event
 */
function touchEvent (element, type, identifier, pageX, pageY) {
    var e,
        touch,
        touches,
        targetTouches,
        changedTouches;

    if (!document.createTouch) {
        throw new Error('This will work only in Safari browser.');
    }

    touch = document.createTouch(window, element, identifier, pageX, pageY, pageX, pageY);

    if (type == 'touchend') {
        touches = document.createTouchList();
        targetTouches = document.createTouchList();
        changedTouches = document.createTouchList(touch);
    } else {
        touches = document.createTouchList(touch);
        targetTouches = document.createTouchList(touch);
        changedTouches = document.createTouchList(touch);
    }

    e = document.createEvent('TouchEvent');
    e.initTouchEvent(type, true, true, window, null, 0, 0, 0, 0, false, false, false, false, touches, targetTouches, changedTouches, 1, 0);

    window.dispatchEvent(e);
};

document.addEventListener('DOMContentLoaded', function() {
    var identifier = new Date().getTime(),
        element = document,
        i = 0;

    touchEvent(element, 'touchstart', identifier, 0, 0);
    while (i++ < 100) {
        touchEvent(element, 'touchmove', identifier, 0, i);
    }
    touchEvent(element, 'touchend', identifier, 0, i);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#playground {
    background: #999; height: 5000px;
}</code>```

```

What is my setup missing to make the browser interpret the touch events as if those were issued by the end user? In essence, I am expecting the browser to scroll in response to the series of programmatically triggered touch start, move and end events.

答: I'm not sure if I understood your question correctly, but if you start touch at the top of page and drag down you're trying to scroll page to top and it's already there so why should the scroll trigger. Perhaps start at position {pageX: 0, pageY: 100} and end at {pageX: 0, pageY: 0} and then see if it's still not working.

Title: How to trigger a touch event?

Body:
Lets start with some event listeners:

window.addEventListener('scroll', function (e) {
    console.log('scroll', e);
});
window.addEventListener('touchstart', function (e) {
    console.log('touchstart', e);
});
window.addEventListener('touchmove', function (e) {
    console.log('touchmove', e);
});
window.addEventListener('touchend', function (e) {
    console.log('touchend', e);
});

I need to programmatically touch the document in position {pageX: 0, pageY: 0}, move it to {pageX: 0, pageY: 100} and end the touch event.

To do this, I am going to build a helper function TouchEvent that will trigger the touch event on the specified element.

/**
 * @see https://gist.github.com/sstephenson/448808
 * @see https://developer.apple.com/library/iad/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html
 * @see http://stackoverflow.com/questions/18059860/manually-trigger-touch-event
 */
function touchEvent (element, type, identifier, pageX, pageY) {
    var e,
        touch,
        touches,
        targetTouches,
        changedTouches;

    touch = document.createTouch(window, element, identifier, pageX, pageY, pageX, pageY);

    if (type == 'touchend') {
        touches = document.createTouchList();
        targetTouches = document.createTouchList();
        changedTouches = document.createTouchList(touch);
    } else {
        touches = document.createTouchList(touch);
        targetTouches = document.createTouchList(touch);
        changedTouches = document.createTouchList(touch);
    }

    e = document.createEvent('TouchEvent');
    e.initTouchEvent(type, true, true, window, null, 0, 0, 0, 0, false, false, false, false, touches, targetTouches, changedTouches, 1, 0);

    window.dispatchEvent(e);
};

I am going to make sure that the document is loaded and dispatch the touch events representing earlier agreed scenario.

document.addEventListener('DOMContentLoaded', function() {
    var identifier = new Date().getTime(),
        element = document,
        i = 0;

    touchEvent(element, 'touchstart', identifier, 0, 0);
    while (i++ < 100) {
        touchEvent(element, 'touchmove', identifier, 0, i);
    }
    touchEvent(element, 'touchend', identifier, 0, i);
});

The expected is that touchstart, touchmove and touchend events have been triggered. The unexpected is that scroll event has not been triggered and the actual "touching" of the document is not reflected in the current document.

window.addEventListener('scroll', function (e) {
    console.log('scroll', e);
});
window.addEventListener('resize', function (e) {
    console.log('resize', e);
});
window.addEventListener('touchstart', function (e) {
    console.log('touchstart', e);
});
window.addEventListener('touchmove', function (e) {
    console.log('touchmove', e);
});
window.addEventListener('touchend', function (e) {
    console.log('touchend', e);
});

/**
 * @see https://gist.github.com/sstephenson/448808
 * @see https://developer.apple.com/library/iad/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html
 * @see http://stackoverflow.com/questions/18059860/manually-trigger-touch-event
 */
function touchEvent (element, type, identifier, pageX, pageY) {
    var e,
        touch,
        touches,
        targetTouches,
        changedTouches;

    if (!document.createTouch) {
        throw new Error('This will work only in Safari browser.');
    }

    touch = document.createTouch(window, element, identifier, pageX, pageY, pageX, pageY);

    if (type == 'touchend') {
        touches = document.createTouchList();
        targetTouches = document.createTouchList();
        changedTouches = document.createTouchList(touch);
    } else {
        touches = document.createTouchList(touch);
        targetTouches = document.createTouchList(touch);
        changedTouches = document.createTouchList(touch);
    }

    e = document.createEvent('TouchEvent');
    e.initTouchEvent(type, true, true, window, null, 0, 0, 0, 0, false, false, false, false, touches, targetTouches, changedTouches, 1, 0);

    window.dispatchEvent(e);
};

document.addEventListener('DOMContentLoaded', function() {
    var identifier = new Date().getTime(),
        element = document,
        i = 0;

    touchEvent(element, 'touchstart', identifier, 0, 0);
    while (i++ < 100) {
        touchEvent(element, 'touchmove', identifier, 0, i);
    }
    touchEvent(element, 'touchend', identifier, 0, i);
});

#playground {
    background: #999; height: 5000px;
}

What is my setup missing to make the browser interpret the touch events as if those were issued by the end user? In essence, I am expecting the browser to scroll in response to the series of programmatically triggered touch start, move and end events.


答:
Use Conditional COUNT()

```<code>  SELECT BussinessEntityID, FirstName, LastName
  FROM Person P
  JOIN Sales S
    ON P.BussinessEntityID = S.CustomerID
  GROUP BY BussinessEntityID, FirstName, LastName
  HAVING COUNT(DISTINCT CASE WHEN YEAR(OrderDate) IN (2011,2014)
                             THEN YEAR(OrderDate)
                        END)  = 2
     AND COUNT(DISTINCT CASE WHEN YEAR(OrderDate) IN (2012,2013)
                             THEN YEAR(OrderDate)
                        END) = 0
</code>```

Title: Excluding query result with in and not in

Body:
Use Conditional COUNT()

  SELECT BussinessEntityID, FirstName, LastName
  FROM Person P
  JOIN Sales S
    ON P.BussinessEntityID = S.CustomerID
  GROUP BY BussinessEntityID, FirstName, LastName
  HAVING COUNT(DISTINCT CASE WHEN YEAR(OrderDate) IN (2011,2014)
                             THEN YEAR(OrderDate)
                        END)  = 2
     AND COUNT(DISTINCT CASE WHEN YEAR(OrderDate) IN (2012,2013)
                             THEN YEAR(OrderDate)
                        END) = 0


问:
How to force www, SSL and trailing slash in SilverStripe 4?
With the latest versions of SilverStripe they encourage you to use server side rules for URL re-writing and not Director::forceSSL(); and/or Director::forceWWW(); in your _config.php file as it is considered unreliable.

On an Apache server this would logically seem to suggest that it should be managed via an .htaccess file. Unfortunately the snippets shown below can fire a rewrite independently however chaining or combining in a single file seems to skip either the www or https case.

```<code>### SILVERSTRIPE START ###
### TRIMMED ROBOT/ERROR CODE ###

<IfModule mod_rewrite.c>

    # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
    <IfModule mod_dir.c>
        DirectoryIndex disabled
        DirectorySlash On
    </IfModule>

    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On
    RewriteBase '/'

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Deny access to potentially sensitive files and folders
    RewriteRule ^vendor(/|$) - [F,L,NC]
    RewriteRule ^\.env - [F,L,NC]
    RewriteRule silverstripe-cache(/|$) - [F,L,NC]
    RewriteRule composer\.(json|lock) - [F,L,NC]
    RewriteRule (error|silverstripe|debug)\.log - [F,L,NC]

    # Process through SilverStripe if no file with the requested name exists.
    # Pass through the original path as a query parameter, and retain the existing parameters.
    # Try finding framework in the vendor folder first
    RewriteCond %{REQUEST_URI} ^(.*)$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* index.php

</IfModule>
### SILVERSTRIPE END ###

<IfModule mod_rewrite.c>
    ### FORCE TRAILING SLASH ###
    ### Source - https://paulund.co.uk/using-htaccess-to-force-trailing-slash ###
    RewriteCond %{REQUEST_URI} /+[^\.]+$
    RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

    ### FORCE WWW ###
    #### Modified from source https://paulund.co.uk/add-www-subdomain-to-all-urls-using-htaccess ###
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    ### FORCE SSL ###
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com/$1 [R=301,L]

</IfModule>
</code>```

答:
You probably want to start with moving your rewrite rules above the SilverStripe ones - they can be last.

Secondly, the [L] flag on your rules means "Last" and will stop any further processing, you may want to try removing them.

Thirdly, from your code you could potentially see 2 redirects (3 requests in totla) for a URL here which (IMO) is a worse experience (thus SEO impact) than a single redirect that doesn't enforce the www and/or the trailing slash.

It looks to me like you could have the following set of redirects just to hit a page:

```<code>http://example.com/contact-us
http://example.com/contact-us/
https://www.example.com/contact-us/
</code>```

The alternative is SS4 is to use a HTTPMiddleware that could enforce this for you in PHP. Whilst not recommended it could be a bit more "transportable"

Body:
With the latest versions of SilverStripe they encourage you to use server side rules for URL re-writing and not Director::forceSSL(); and/or Director::forceWWW(); in your _config.php file as it is considered unreliable.

On an Apache server this would logically seem to suggest that it should be managed via an .htaccess file. Unfortunately the snippets shown below can fire a rewrite independently however chaining or combining in a single file seems to skip either the www or https case.

### SILVERSTRIPE START ###
### TRIMMED ROBOT/ERROR CODE ###

<IfModule mod_rewrite.c>

    # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
    <IfModule mod_dir.c>
        DirectoryIndex disabled
        DirectorySlash On
    </IfModule>

    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On
    RewriteBase '/'

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Deny access to potentially sensitive files and folders
    RewriteRule ^vendor(/|$) - [F,L,NC]
    RewriteRule ^\.env - [F,L,NC]
    RewriteRule silverstripe-cache(/|$) - [F,L,NC]
    RewriteRule composer\.(json|lock) - [F,L,NC]
    RewriteRule (error|silverstripe|debug)\.log - [F,L,NC]

    # Process through SilverStripe if no file with the requested name exists.
    # Pass through the original path as a query parameter, and retain the existing parameters.
    # Try finding framework in the vendor folder first
    RewriteCond %{REQUEST_URI} ^(.*)$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule .* index.php

</IfModule>
### SILVERSTRIPE END ###

<IfModule mod_rewrite.c>
    ### FORCE TRAILING SLASH ###
    ### Source - https://paulund.co.uk/using-htaccess-to-force-trailing-slash ###
    RewriteCond %{REQUEST_URI} /+[^\.]+$
    RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

    ### FORCE WWW ###
    #### Modified from source https://paulund.co.uk/add-www-subdomain-to-all-urls-using-htaccess ###
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    ### FORCE SSL ###
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com/$1 [R=301,L]

</IfModule>

Body:
You probably want to start with moving your rewrite rules above the SilverStripe ones - they can be last.

Secondly, the [L] flag on your rules means "Last" and will stop any further processing, you may want to try removing them.

Thirdly, from your code you could potentially see 2 redirects (3 requests in totla) for a URL here which (IMO) is a worse experience (thus SEO impact) than a single redirect that doesn't enforce the www and/or the trailing slash.

It looks to me like you could have the following set of redirects just to hit a page:

http://example.com/contact-us
http://example.com/contact-us/
https://www.example.com/contact-us/

The alternative is SS4 is to use a HTTPMiddleware that could enforce this for you in PHP. Whilst not recommended it could be a bit more "transportable"


问:
Java Recognize specific objects in image
I need to classify bolt, nut, and washer from the image,

but I don't know how to detect those objects from the image.

(This is the part of the image)

I copied every color (used java.awt.Color) value from the image to 2D array,

but I have no idea what I have to do with this.

If I want to classify them, program have to recognize which part is not a background at least.

Does java has library for this?

答:
The way to do it in Java is use the OpenCV library which has a Java native interface. Please refer to the link below in order to learn how to use OpenCV and Java together:

http://opencv-java-tutorials.readthedocs.io/en/latest/

Of course know how to use Java and OpenCV is not enough to solve your needs. So, you should to learn about image processing topics as well. See this motivating presentation:

https://pt.slideshare.net/luigidr/introduction-to-open-cv-28728435

Be aware that you must be ready to learn lots of things as image segmentation, color spaces, structural analysis and so on. Have a fun!


问:
Checkerboard CSS pattern bug (diagonal unaesthetic line)
I've created a checkerboard pattern with the following css code:

```<code>.testcheckerboard{
  width: 200px;
  height: 100px;

  background-color: white;
  background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%), linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%);
  background-position: 0 0, 20px 20px;
  background-size: 40px 40px;
}
</code>```

The result is the checkerboard pattern that I wanted, but is also shown an unaesthetic diagonal white line!

The strangeness is that, in some cases, the problem disappears.

There is a way to remove this line?
I think that is only an antialiasing bug, but i couldn't find a method to control, or remove, antialiasing...

I couldn't find any solutions on the Internet.

答:
I've found a workaround by using inline-svg into css.

Works with all Windows browsers, and Android browsers, but i'm not secure that this works with OSX (MAC).

.testcheckerboard{
  width: 200px;
  height: 100px;
  background-size: 40px 40px;

  background-color: white;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 2'%3E%3Cpath fill='rgb(0,0,0)' fill-rule='evenodd' d='M0 0h1v1H0V0zm1 1h1v1H1V1z'/%3E%3C/svg%3E");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="testcheckerboard"></div></code>```

Body:
I've created a checkerboard pattern with the following css code:

.testcheckerboard{
  width: 200px;
  height: 100px;

  background-color: white;
  background-image: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%), linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%);
  background-position: 0 0, 20px 20px;
  background-size: 40px 40px;
}

The result is the checkerboard pattern that I wanted, but is also shown an unaesthetic diagonal white line!

The strangeness is that, in some cases, the problem disappears.

There is a way to remove this line?
I think that is only an antialiasing bug, but i couldn't find a method to control, or remove, antialiasing...

I couldn't find any solutions on the Internet.

Body:
I've found a workaround by using inline-svg into css.

Works with all Windows browsers, and Android browsers, but i'm not secure that this works with OSX (MAC).

.testcheckerboard{
  width: 200px;
  height: 100px;
  background-size: 40px 40px;

  background-color: white;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 2'%3E%3Cpath fill='rgb(0,0,0)' fill-rule='evenodd' d='M0 0h1v1H0V0zm1 1h1v1H1V1z'/%3E%3C/svg%3E");
}

<div class="testcheckerboard"></div>


问:
Excel VBA copy cell formatting to range
I am creating a macro using conditional formatting. Purpose of the macro is to change the formatting (cell color and text font (bold/italic/...) and size) of cells in columns A to M, depending on the value of column M.

I defined 5 conditions and changed the conditional formatting of the cells of column M, so far so good, but I don't seem to be able to copy those formats using the PasteSpecial command.

In short: cells A3 to M3 should have the same formatting as N3, A4 to M4 the same as N4, and so on.

VBA included below, thanks in advance!

```<code>Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

'clear any existing conditional formatting
rg.FormatConditions.Delete

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlEqual, "1")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "2")
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlEqual, "3")
Set cond4 = rg.FormatConditions.Add(xlCellValue, xlEqual, "4")
Set cond5 = rg.FormatConditions.Add(xlCellValue, xlEqual, "5")

'define the format applied for each conditional format
With cond1
.Font.Color = RGB(0, 0, 0)
.Font.Bold = True
End With

With cond2
.Font.Color = RGB(128, 0, 0)
.Font.Bold = True
End With

With cond3
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End With

With cond4
.Font.Color = RGB(0, 176, 80)
.Font.Bold = True
End With

With cond5
.Font.Color = RGB(31, 73, 125)
.Font.Bold = True
End With

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub
</code>```

答:
```<code>Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

For Each cell In rg

If cell.Value = "1" Then
cell.Font.Color = RGB(128, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "2" Then
cell.Font.Color = RGB(128, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "3" Then
cell.Font.Color = RGB(255, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "4" Then
cell.Font.Color = RGB(0, 176, 80)
cell.Font.Bold = True

ElseIf cell.Value = "5" Then
cell.Font.Color = RGB(31, 73, 125)
cell.Font.Bold = True

End If

Next

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub
</code>```

Can't you just get rid of conditional formatting?

Title: Excel VBA copy cell formatting to range

Body:
I am creating a macro using conditional formatting. Purpose of the macro is to change the formatting (cell color and text font (bold/italic/...) and size) of cells in columns A to M, depending on the value of column M.

I defined 5 conditions and changed the conditional formatting of the cells of column M, so far so good, but I don't seem to be able to copy those formats using the PasteSpecial command.

In short: cells A3 to M3 should have the same formatting as N3, A4 to M4 the same as N4, and so on.

VBA included below, thanks in advance!

Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

'clear any existing conditional formatting
rg.FormatConditions.Delete

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlEqual, "1")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "2")
Set cond3 = rg.FormatConditions.Add(xlCellValue, xlEqual, "3")
Set cond4 = rg.FormatConditions.Add(xlCellValue, xlEqual, "4")
Set cond5 = rg.FormatConditions.Add(xlCellValue, xlEqual, "5")

'define the format applied for each conditional format
With cond1
.Font.Color = RGB(0, 0, 0)
.Font.Bold = True
End With

With cond2
.Font.Color = RGB(128, 0, 0)
.Font.Bold = True
End With

With cond3
.Font.Color = RGB(255, 0, 0)
.Font.Bold = True
End With

With cond4
.Font.Color = RGB(0, 176, 80)
.Font.Bold = True
End With

With cond5
.Font.Color = RGB(31, 73, 125)
.Font.Bold = True
End With

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub

Body:
Sub VoorwaardelijkeOpmaak()
'
' VoorwaardelijkeOpmaak Macro
'
' Sneltoets: Ctrl+Shift+Z
'
If ActiveSheet.Name <> "gedetailleerde meetstaat" Then
    MsgBox "Deze macro kan alleen in het werkblad 'gedetailleerde meetstaat' worden toegepast"
Else
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition, cond3 As FormatCondition, cond4 As FormatCondition, cond5 As FormatCondition
Set rg = Range("N3", Range("N3").End(xlDown))

For Each cell In rg

If cell.Value = "1" Then
cell.Font.Color = RGB(128, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "2" Then
cell.Font.Color = RGB(128, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "3" Then
cell.Font.Color = RGB(255, 0, 0)
cell.Font.Bold = True

ElseIf cell.Value = "4" Then
cell.Font.Color = RGB(0, 176, 80)
cell.Font.Bold = True

ElseIf cell.Value = "5" Then
cell.Font.Color = RGB(31, 73, 125)
cell.Font.Bold = True

End If

Next

Range("N3", Range("N3").End(xlDown)).Select
Selection.Copy
Range("A3:M3", Range("A3:M3").End(xlDown)).Select
Selection.PasteSpecial (xlPasteFormats)

End If

End Sub

Can't you just get rid of conditional formatting?


问:
Connect Jmeter to Redis with Beanshell
I want to connect Jmeter to Redis DB, I want to do it via java programming.
I added jedis-2.2.1.jar file to lib folder.
and create a test plan with only bean-shell preprocessor.
I can not understand what I can see, since nothing happened, and the response tree is blank,
Can someone please advise how to connect to redis via jmeter (please without the redis plugin)

Provided the Pic of the program, it is a simple program just want to connect.

** I am new in java scripting in Jmeter and the only jar I added is jedis.jar, the program is a script from the net.  not created thread group in the test plan

with void main it is not worked also

答:
Here is a JMeter file and beanShell Sampler script to fetch a set of keys from redis and put them into variables used by a looping HTTP GET request.

https://bitbucket.org/barryknapp/shared/src/d62f8ebb57ede1d15a3bd7683adfdd02cd039369/jmeter/?at=master

Title: Connect Jmeter to Redis with Beanshell


问:
Can't access Docker database using IP (only localhost)
I'm trying to setup Docker to allow connections from other devices on my network. Currently to access Docker I visit localhost on my computer. I'm trying to connect using my computer's local IP (192.168.0.140), which lets me see my files but not connect to my database.

I assume this is a problem with my configuration but I don't know enough about Docker to troubleshoot it.

```<code>version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    ports:
      - 3306
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - '8080:80'
</code>```

Any help would be greatly appreciated.

答:
Maybe you should try like this : </p>

```<code>version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '0.0.0.0:80:80'   # Map container port 80 on your "public" ip on port 80, it will be available on the network
      - '0.0.0.0:443:443' # Same for port 443
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    # ports:
    #  - 3306    # You don't need to map port 3306 because mysql already expose this port for others containers, unless you wan't to access to your mysql directly
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    #links:
    #  - db # Not necessary, with docker-compose v2 every containers are in the same network and see each other
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASS
      WORD: secret
    ports:
      - 'localhost:8080:80' # to keep your phpmyadmin only available from localhost.
</code>```

Body:
I'm trying to setup Docker to allow connections from other devices on my network. Currently to access Docker I visit localhost on my computer. I'm trying to connect using my computer's local IP (192.168.0.140), which lets me see my files but not connect to my database.

I assume this is a problem with my configuration but I don't know enough about Docker to troubleshoot it.

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    ports:
      - 3306
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - '8080:80'

Any help would be greatly appreciated.

Body:
Maybe you should try like this :

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '0.0.0.0:80:80'   # Map container port 80 on your "public" ip on port 80, it will be available on the network
      - '0.0.0.0:443:443' # Same for port 443
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    # ports:
    #  - 3306    # You don't need to map port 3306 because mysql already expose this port for others containers, unless you wan't to access to your mysql directly
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    #links:
    #  - db # Not necessary, with docker-compose v2 every containers are in the same network and see each other
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASS
      WORD: secret
    ports:
      - 'localhost:8080:80' # to keep your phpmyadmin only available from localhost.


问:
Response code 400 OKHTTP
Am getting a response code = 400 when i run my android app, but when i test the same URL in my browser and postman it has a response code of 200. What am I doing wrong. This is the get Request method

```<code>  public static String getRequest(String myUrl) throws IOException {

        InputStream is = null;

        try {

            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(30000 /*milliseconds*/);
            conn.setConnectTimeout(20000 /*milliseconds*/);
            conn.setRequestMethod("GET");

            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            if (response != HttpURLConnection.HTTP_OK)
                is = conn.getErrorStream();
            else
            is = conn.getInputStream();

            Log.i(TAG, String.valueOf(response));

            // Convert the InputStream into a string
            return readStream(is);

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
</code>```

Please i need help.

答:
so i found out the problem, since am using OData filter for the query and real devices devices cannot encode such URL I had to manually encode my URL.

This was what i was passing in before:

```<code>   String url = *Const.HOUSE_URL+"PropertyListings?$filter=Price ge "+ minPrice+" and Price le "+maxPrice*
</code>```

but when encoded:  String url = *Const.HOUSE_URL+"PropertyListings?$filter="+ **query** + minPrice+ **query1** + maxPrice;*

where

```<code>String query = URLEncoder.encode("Price ge ", "utf-8");

String query1 = URLEncoder.encode(" and Price le ","utf-8");
</code>```

Then the final url that is passed into my HTTP GET request is:

```<code> String url = Const.HOUSE_URL+"PropertyListings?$filter="+ query + minPrice+ query1 + maxPrice;
</code>```

where minPrice and maxPrice are String values from an EditText.

Hope this helps some one.

Title: Response code 400 OKHTTP

Body:
Am getting a response code = 400 when i run my android app, but when i test the same URL in my browser and postman it has a response code of 200. What am I doing wrong. This is the get Request method

  public static String getRequest(String myUrl) throws IOException {

        InputStream is = null;

        try {

            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(30000 /*milliseconds*/);
            conn.setConnectTimeout(20000 /*milliseconds*/);
            conn.setRequestMethod("GET");

            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            if (response != HttpURLConnection.HTTP_OK)
                is = conn.getErrorStream();
            else
            is = conn.getInputStream();

            Log.i(TAG, String.valueOf(response));

            // Convert the InputStream into a string
            return readStream(is);

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

Please i need help.

Body:
so i found out the problem, since am using OData filter for the query and real devices devices cannot encode such URL I had to manually encode my URL.

This was what i was passing in before:

   String url = *Const.HOUSE_URL+"PropertyListings?$filter=Price ge "+ minPrice+" and Price le "+maxPrice*

but when encoded:  String url = *Const.HOUSE_URL+"PropertyListings?$filter="+ **query** + minPrice+ **query1** + maxPrice;*

where

String query = URLEncoder.encode("Price ge ", "utf-8");

String query1 = URLEncoder.encode(" and Price le ","utf-8");

Then the final url that is passed into my HTTP GET request is:

 String url = Const.HOUSE_URL+"PropertyListings?$filter="+ query + minPrice+ query1 + maxPrice;

where minPrice and maxPrice are String values from an EditText.

Hope this helps some one.


问:
Getting Started with Unreal Engine
I am new to game development. I had recently worked with Unity 3D but its not free so I switched over to Unreal Engine. Documentation on Epic Games's website is not in detail and hard to understand for new game developers. </p>

答:
You may also want to check out this guy's channel on YouTube: TeslaDev

There are great tutorials there.

Title: Getting Started with Unreal Engine


问:
Using MapPath from a worker thread
I have a WCF service method that's running in a worker thread I spin from another method.
 I need to map a relative service app path ("~/Templates/a.template") to the physical path ("D:\Web\Templates\a.template"), but I can't use HttpContext.Current.Server.MapPath because HttpContext.Current is null in a worker thread. How else can I reach MapPath method?

答:
Use System.Web.Hosting.HostingEnvironment.MapPath().

No HttpContext required and it does the same work.

Title: Using MapPath from a worker thread


问:
How to get current time in jinja
What is the method to get current date time value in jinja tags ?

On my project I need to show current time in UTC at top right corner of site.

答:
I like @Assem's answer. I'm going to demo it in a Jinja2 template.

#!/bin/env python3
import datetime
from jinja2 import Template

template = Template("""
# Generation started on {{ now() }}
... this is the rest of my template...
# Completed generation.
""")

template.globals['now'] = datetime.datetime.utcnow

print(template.render())
```
<p>Output:</p>
```# Generation started on 2017-11-14 15:48:06.507123
... this is the rest of my template...
# Completed generation.
```

Note:

I rejected an edit from someone who stated "datetime.datetime.utcnow() is a method, not a property". While they are "correct", they misunderstood the intention of NOT including the (). Including () causes the method to be called at the time the object template.globals['now'] is defined. That would cause every use of now in your template to render the same value rather than getting a current result from datetime.datetime.utcnow.

Title: How to get current time in jinja

Body:
I like @Assem's answer. I'm going to demo it in a Jinja2 template.

#!/bin/env python3
import datetime
from jinja2 import Template

template = Template("""
# Generation started on {{ now() }}
... this is the rest of my template...
# Completed generation.
""")

template.globals['now'] = datetime.datetime.utcnow

print(template.render())

Output:

# Generation started on 2017-11-14 15:48:06.507123
... this is the rest of my template...
# Completed generation.

Note:

I rejected an edit from someone who stated "datetime.datetime.utcnow() is a method, not a property". While they are "correct", they misunderstood the intention of NOT including the (). Including () causes the method to be called at the time the object template.globals['now'] is defined. That would cause every use of now in your template to render the same value rather than getting a current result from datetime.datetime.utcnow.