问:
Fill in a range of cells based on a column - VBA?
I want a range of cells to fill in with specified information but only if column A is "GFR"
I've been able to accomplish this very simply by recording a macro, searching for GFR in Column A, then pasting in information in Columns C and G

My problem is I can't get my macro to do this for me with new data.  It's go over the old data and copy in the information, but I can't replicate it, obviously.

Example data, with columns C and G already filled in with the correct information:

```<code>Test Name(O)    Result(R)   Units(R)    Result Interpretation Flag(R)   Reference Low(C)    Reference High(C)   Reference Alpha(C)
GFR     ML/MIN/1.73M2   L           >60
CREATININE
POTASSIUM
WHITE BLOOD COUNT
PLATELET COUNT
GLOBULIN
GFR     ML/MIN/1.73M2   L           >60
CREATININE
POTASSIUM
SGOT (AST)
</code>```

I need a hint on how to start this out.

If Column A = GFR, then Column C of the same row = ML/MIN/1.73M2, and column G of the same row = >60

答:
This should do it...</p>

```<code>Sub FillIn()

   Dim LR As Long

   With ActiveSheet
      LR = Cells(.Rows.Count, "A").End(xlUp).Row
      For i = LR To 1 Step -1
         If (.Range("A" & i).Value = "GFR") Then
            .Range("C" & i).Value = "ML/MIN/1.73M2"
            .Range("G" & i).Value = ">60"
         End If
      Next i
   End With

End Sub
</code>```

Body:
I want a range of cells to fill in with specified information but only if column A is "GFR"
I've been able to accomplish this very simply by recording a macro, searching for GFR in Column A, then pasting in information in Columns C and G

My problem is I can't get my macro to do this for me with new data.  It's go over the old data and copy in the information, but I can't replicate it, obviously.

Example data, with columns C and G already filled in with the correct information:

Test Name(O)    Result(R)   Units(R)    Result Interpretation Flag(R)   Reference Low(C)    Reference High(C)   Reference Alpha(C)
GFR     ML/MIN/1.73M2   L           >60
CREATININE
POTASSIUM
WHITE BLOOD COUNT
PLATELET COUNT
GLOBULIN
GFR     ML/MIN/1.73M2   L           >60
CREATININE
POTASSIUM
SGOT (AST)

I need a hint on how to start this out.

If Column A = GFR, then Column C of the same row = ML/MIN/1.73M2, and column G of the same row = >60

Body:
This should do it...

Sub FillIn()

   Dim LR As Long

   With ActiveSheet
      LR = Cells(.Rows.Count, "A").End(xlUp).Row
      For i = LR To 1 Step -1
         If (.Range("A" & i).Value = "GFR") Then
            .Range("C" & i).Value = "ML/MIN/1.73M2"
            .Range("G" & i).Value = ">60"
         End If
      Next i
   End With

End Sub


来源: stackexchange

问:
Automatic type Conversion in C#
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

```<code>public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}
</code>```

so that I could just call them like this:

```<code>eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();
</code>```

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

```<code>eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];
</code>```

The row is a DataRow if that matters.

答:
Forgive me if I'm stating the obvious but I got this impression after reading your question.

You know the basetype of every type in .NET is object right?
So the column in the datarow which you describe of type object could also just as well be of the same type as the member you're trying to assign to and then a simple cast is needed.

for instance

eventObject.EventId = (int)row["event_id"];

ContentLicense: CC BY-SA 2.5

Title: Automatic type Conversion in C#

Body:
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}

so that I could just call them like this:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];

The row is a DataRow if that matters.


问:
C# clearing sensitive data after communicating it to payment gateways.
I'm trying to find a solution for clearing sensitive credit card data from memory after communicating it to a payment gateway. Most payment gateways seem to expect the plain text card number as a string in the API. If I use a string in C# I cannot clear the memory as I do not have any control over when the memory is garbage collected. The below dto snippet from an SDK for Cybersource illustrates my problem.
Note I'm trying to fulfill PA-DSS version 3.2 requirement 5.1.6.1 Coding techniques include documentation of how PAN and/or SAD are handled in memory. Our auditor is indicating that plain text account numbers cannot be stored in a C# string variable.

We have integrations with other gateways that also have this PAN in string variable issue. How are others dealing with this problem?

```<code>namespace CyberSource.Clients.SoapServiceReference
{
    //
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [GeneratedCode("System.Xml", "4.0.30319.34234")]
    [XmlType(Namespace = "urn:schemas-cybersource-com:transaction-data-1.109")]
    public class Card : INotifyPropertyChanged
    {
        public Card();

        [XmlElement(Order = 6)]
        public string cardType { get; set; }
        //
        [XmlElement(Order = 5)]
        public string cvNumber { get; set; }
        //
        [XmlElement(Order = 4)]
        public string cvIndicator { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 3)]
        public string expirationYear { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 2)]
        public string expirationMonth { get; set; }
        //
        [XmlElement(Order = 1)]
        public string accountNumber { get; set; }
        //
        [XmlElement(Order = 0)]
        public string fullName { get; set; }
</code>```

答: Actually, you have such a control. GC.Collect().https://msdn.microsoft.com/en-us/library/xe0c2357(v=vs.110).aspx. The problem there that you should be aware of how GC works to ensure your object indeed gets collected. It heavily depends upon your implementation, so I can't help more that just pointing out such a possibility. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find a solution for clearing sensitive credit card data from memory after communicating it to a payment gateway. Most payment gateways seem to expect the plain text card number as a string in the API. If I use a string in C# I cannot clear the memory as I do not have any control over when the memory is garbage collected. The below dto snippet from an SDK for Cybersource illustrates my problem.
Note I'm trying to fulfill PA-DSS version 3.2 requirement 5.1.6.1 Coding techniques include documentation of how PAN and/or SAD are handled in memory. Our auditor is indicating that plain text account numbers cannot be stored in a C# string variable.

We have integrations with other gateways that also have this PAN in string variable issue. How are others dealing with this problem?

namespace CyberSource.Clients.SoapServiceReference
{
    //
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [GeneratedCode("System.Xml", "4.0.30319.34234")]
    [XmlType(Namespace = "urn:schemas-cybersource-com:transaction-data-1.109")]
    public class Card : INotifyPropertyChanged
    {
        public Card();

        [XmlElement(Order = 6)]
        public string cardType { get; set; }
        //
        [XmlElement(Order = 5)]
        public string cvNumber { get; set; }
        //
        [XmlElement(Order = 4)]
        public string cvIndicator { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 3)]
        public string expirationYear { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 2)]
        public string expirationMonth { get; set; }
        //
        [XmlElement(Order = 1)]
        public string accountNumber { get; set; }
        //
        [XmlElement(Order = 0)]
        public string fullName { get; set; }


问:
How do I iterate through an ansible registered value?
So, I had to run a command in ansible which will have multiple answers,
 for example : Run a command to list the names and other details of all the users. Result will have say,

```<code>Carry   2/10

Barry   19/7

Harry   7/7

Jerry   11/4

Terry   7/12

Marie   13/10
</code>```

I've saved this result to variable called names in the tasks of the playbook

```<code> register: names
</code>```

How do I iterate through each of these names one at a time and run specific commands when I'm iterating through them?

Will I have to convert this string to a json file as ansible accepts json?

答:
If you want to run the same command using the different inputs you have for the list variable you created with register, you can itterate using with_items:

```<code>- name: doing something cool
    cmd: my_awesome_cmd {{ item }}
  with_items:
    names
</code>```

You can take a look at the docs here.
https://docs.ansible.com/ansible/devel/plugins/lookup/items.html

If you want to do different stuff for each input, you can also rely on the fact that you can use register as a list:

```<code>- name: doing something cool with carry
    cmd: my_awesome_cmd {{ names[0] }}
- name: doing something cool with barry
    cmd: my_awesome_cmd {{ names[1] }}
- name: doing something cool with harry
    cmd: my_awesome_cmd {{ names[2] }}
...
</code>```

You can always use debug to print out the output of your variable, that way you can have a better look at the structure and grab exactelly what you're looking for.
http://docs.ansible.com/ansible/latest/debug_module.html

Body:
So, I had to run a command in ansible which will have multiple answers,
 for example : Run a command to list the names and other details of all the users. Result will have say,

Carry   2/10

Barry   19/7

Harry   7/7

Jerry   11/4

Terry   7/12

Marie   13/10

I've saved this result to variable called names in the tasks of the playbook

 register: names

How do I iterate through each of these names one at a time and run specific commands when I'm iterating through them?

Will I have to convert this string to a json file as ansible accepts json?

Body:
If you want to run the same command using the different inputs you have for the list variable you created with register, you can itterate using with_items:

- name: doing something cool
    cmd: my_awesome_cmd {{ item }}
  with_items:
    names

You can take a look at the docs here.
https://docs.ansible.com/ansible/devel/plugins/lookup/items.html

If you want to do different stuff for each input, you can also rely on the fact that you can use register as a list:

- name: doing something cool with carry
    cmd: my_awesome_cmd {{ names[0] }}
- name: doing something cool with barry
    cmd: my_awesome_cmd {{ names[1] }}
- name: doing something cool with harry
    cmd: my_awesome_cmd {{ names[2] }}
...

You can always use debug to print out the output of your variable, that way you can have a better look at the structure and grab exactelly what you're looking for.
http://docs.ansible.com/ansible/latest/debug_module.html


问:
Bootstrap Popover Element Inside A-Link; Prevent A-Link Click From Firing
I have a Bootstrap Popover Image which should display a popup. This IMG is inside an A-link which has its own Click Handler.

My goal is to prevent the Parent A-Click from firing; when you click the image, the only thing you see is the popup, but not the real A-Click action (the alert box).

I know that this is done via e.stopPropagation() but the problem is, how do I get access to Bootstrap Popover's Click Handler? Where would I put e.stopPropagation?

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function() {
    alert('Clicked main link');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Main Link

<img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</code>```

Let me show why the IMG has to be inside the A. The A's are Accordion Menu Bars, and they all have a fixed width. You can go to a page by selecting a menu (you don't have to click right on the text). Some menu items also have an INFO I icon that displays a popup. The action of the I-Icon should be to display the popover. The action of the A-link itself should be to go the page as normal.

答:
I finally solved it...

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function(e) {
    e.preventDefault();
    if (e.target.nodeName != "IMG") {
      alert('Clicked main link');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Main Link

<img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</code>```

Body:
I have a Bootstrap Popover Image which should display a popup. This IMG is inside an A-link which has its own Click Handler.

My goal is to prevent the Parent A-Click from firing; when you click the image, the only thing you see is the popup, but not the real A-Click action (the alert box).

I know that this is done via e.stopPropagation() but the problem is, how do I get access to Bootstrap Popover's Click Handler? Where would I put e.stopPropagation?

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function() {
    alert('Clicked main link');
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Main Link

Let me show why the IMG has to be inside the A. The A's are Accordion Menu Bars, and they all have a fixed width. You can go to a page by selecting a menu (you don't have to click right on the text). Some menu items also have an INFO I icon that displays a popup. The action of the I-Icon should be to display the popover. The action of the A-link itself should be to go the page as normal.

Body:
I finally solved it...

$('[data-toggle="popover"]').popover();

$('#link').off('click.link').on('click.link', function(e) {
    e.preventDefault();
    if (e.target.nodeName != "IMG") {
      alert('Clicked main link');
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<a id="link" href="#" style="width:300px; height:100px; border:1px solid black;">Main Link

<img src="abc.png" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="PopOver Tooltip" aria-describedby="tooltip">
</a>


问:
Xcode 6.4 quits unexpectedly in macOS Sierra?
I have many working projects built in Xcode 6.4(had OS X Yosemite).
Recently i updated to macOS Sierra.
And also i have installed Xcode version 7.3.1.
i.e. i have multiple Xcode versions installed following this link.
http://iosdevelopertips.com/xcode/install-multiple-versions-of-xcode.html

However i can open my projects in Xcode 7.3.1 but it shows too many errors. i want to open it in Xcode 6.4, which is giving me the error "Xcode quit unexpectedly." each time i reopen the project in Xcode 6.4

I tried this solutions, still no results

Xcode quits unexpectedly every time I open my project

Xcode 5 crashes -- Xcode quit unexpectedly

I understand there is some compatibility issue.
Is there any solution.SOMEONE PLEASE HELP ME.

答: What worked for me was to remove a recent file {PROJECT-FOLDER}/{YOUR-PROJECT-NAME}.entitlements.

ContentLicense: CC BY-SA 4.0


问:
Evaluating a constant anonymous function in MATLAB
In Matlab, I generally do things such as

```<code>f  = @(x) x.^2;
xx = 0:.1:1;
ff = f(xx);
</code>```

So that f is a function handle and both xx and ff are 1x11 vectors.

However, if for some reason I need to define my function handle f like this

```<code>f  = @(x) 1;
</code>```

and do not change the code for xx and ff, then xx will still be a vector but ff will NOT: it will be a double.

This is annoying of course, because the sequel of my code assumes that ff is a 11x1 vector, so I would need to change my code any time f happens to be constant.

So my first question is whether or not my code is sound to begin with.
If so, what should I do to make it work in the "constant f" case?
If not, how should I rewrite it?

This is admittedly similar to
matlab constant anonymous function returns only one value instead of an array
but I can't quite find an answer in that thread.

答:
I found a better way of doing this. This shows how stupid Matlab is:

```<code>f  = @(x) (x-x)+1
</code>```

Try it!

Body:
In Matlab, I generally do things such as

f  = @(x) x.^2;
xx = 0:.1:1;
ff = f(xx);

So that f is a function handle and both xx and ff are 1x11 vectors.

However, if for some reason I need to define my function handle f like this

f  = @(x) 1;

and do not change the code for xx and ff, then xx will still be a vector but ff will NOT: it will be a double.

This is annoying of course, because the sequel of my code assumes that ff is a 11x1 vector, so I would need to change my code any time f happens to be constant.

So my first question is whether or not my code is sound to begin with.
If so, what should I do to make it work in the "constant f" case?
If not, how should I rewrite it?

This is admittedly similar to
matlab constant anonymous function returns only one value instead of an array
but I can't quite find an answer in that thread.

Body:
I found a better way of doing this. This shows how stupid Matlab is:

f  = @(x) (x-x)+1

Try it!


问:
<column> is ambiguous in column comparison between two tables
I want this postgres function to work :

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

This stand alone query works just fine:

```<code>SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);
</code>```

But when I put it into this function and try to run it like this:

```<code>select *
from difference_of_match_ids_in_match_history_and_match_results();
</code>```

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

答:
The structure of the result set must match the function result type. If you want to get only match_ids:

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  RETURNS TABLE(m_id BIGINT)    -- !!
AS
$$
BEGIN
  RETURN QUERY
  SELECT match_id               -- !!
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

If you want to get whole rows as a result:

```<code>DROP FUNCTION difference_of_match_ids_in_match_history_and_match_results();
CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  RETURNS SETOF sports.match_history    -- !!
AS
$$
BEGIN
  RETURN QUERY
  SELECT *                              -- !!
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

Body:
I want this postgres function to work :

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

This stand alone query works just fine:

SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);

But when I put it into this function and try to run it like this:

select *
from difference_of_match_ids_in_match_history_and_match_results();

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

Body:
The structure of the result set must match the function result type. If you want to get only match_ids:

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  RETURNS TABLE(m_id BIGINT)    -- !!
AS
$$
BEGIN
  RETURN QUERY
  SELECT match_id               -- !!
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

If you want to get whole rows as a result:

DROP FUNCTION difference_of_match_ids_in_match_history_and_match_results();
CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  RETURNS SETOF sports.match_history    -- !!
AS
$$
BEGIN
  RETURN QUERY
  SELECT *                              -- !!
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';


问:
Why my application crash on applicationDidEnterBackground?
I have a static method called writeToServer that is called when application enter in background mode.

in my AppDelegate.m:

```<code>- (void)applicationDidEnterBackground:(UIApplication *) application {
    [LogZone writeToServer];
    NSLog(@"Log sended to server. Done.");
}
</code>```

in my LogZone.m:

```<code>+ (void) writeToServer {
    NSString *qStr = [[NSString alloc]
        initWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@",
            LOG_SERVER_URL,
            _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:qStr]];
    [request setHTTPMethod: @"POST"];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
</code>```

Uppercase vars are static strings created in this way:

.h

```<code>extern NSString* _LOG_UID;
</code>```

.m

```<code>NSString* _LOG_UID = @"-1";
</code>```

When I enter in background mode it crash with this "classic" error:

* -[CFString respondsToSelector:]: message sent to deallocated instance
  0x6a4c800

But why?

I don't release anything!=!

What's wrong?

答:
Why not just use the following:</p>

```<code>NSString *qStr = [NSString stringWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@", LOG_SERVER_URL, _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];
</code>```

Body:
I have a static method called writeToServer that is called when application enter in background mode.

in my AppDelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *) application {
    [LogZone writeToServer];
    NSLog(@"Log sended to server. Done.");
}

in my LogZone.m:

+ (void) writeToServer {
    NSString *qStr = [[NSString alloc]
        initWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@",
            LOG_SERVER_URL,
            _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:qStr]];
    [request setHTTPMethod: @"POST"];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

Uppercase vars are static strings created in this way:

.h

extern NSString* _LOG_UID;

.m

NSString* _LOG_UID = @"-1";

When I enter in background mode it crash with this "classic" error:

* -[CFString respondsToSelector:]: message sent to deallocated instance
  0x6a4c800

But why?

I don't release anything!=!

What's wrong?

Body:
Why not just use the following:

NSString *qStr = [NSString stringWithFormat:@"%@?ip=%@&uid=%@&platform=%@&model=%@&lat=%@&lon=%@", LOG_SERVER_URL, _LOG_IP, _LOG_UID, _LOG_PLAT, _LOG_MOD, _LOG_LAT, _LOG_LON];


问:
How can I iteratively partition the same string multiple times?
I have a string of unknown length that can repeat the pattern of interest any number of times.
The string looks like so:

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:18
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:19

SARAHJOHNSON has entered the above notes on 12/05/2017 17:45
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

SARAHJOHNSON has entered the above notes on 12/05/2017 17:46

I'm trying separate out the comment, username, and date to create a nicer looking comment box (with some css). The following is what I have to separate the user name

```<code>before_keyword, keyword, after_keyword = stringg.partition("has entered the above notes on ")
namedate = before_keyword.split()[-1] + "--" + after_keyword.split()[0] + after_keyword.split()[1]
comment = before_keyword.replace(before_keyword.split()[-1], '').rstrip()
print comment
print namedate
</code>```

This works for the first case of Username entered the above notes. How can I iterate through the string to collect all comments/usernames/dates in the string and print them out separately.

Thanks.

Edit: put in fake names instead of USERNAME2389 to show how the names appear for me.

答:
You can just iterate over the lines, create a text placeholder and when a username hits append it to a dataframe so at the end you have a nice, manipulatable dataset. You can also convert the datetime's directly so you can analyze more around the times, dates, etc. </p>

```<code>import re
import pandas as pd
from datetime import datetime

string = """
    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    blahblahblahblahblahblahblahblahblahblah

    USERNAME2398 has entered the above notes on 12/05/2017 14:18

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    USERNAME2839 has entered the above notes on 12/05/2017 14:19

    USERNAME7348 has entered the above notes on 12/05/2017 17:45

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    USERNAME857 has entered the above notes on 12/05/2017 17:46
    """

# define regex for username matching
username = re.compile('USERNAME.*?\s', re.IGNORECASE)
# define regex for datetime matching
datetime_re = re.compile('[0-9]{1,2}\/[0-9]{1,2}\/(20|19)[0-9]{2}\s[0-9]{1,2}\:[0-9]{1,2}')
# create placeholder datfarame
masterdf = pd.DataFrame()
# define text placeholder
cur_text = ''
for line in string.split('\n'):
    if datetime_re.search(line) and all([x.isupper() for x in line.split()[0]]):
        # pull out username
        cur_user = line.split()[0].strip()# username.search(line).group(0)
        # pull out datetime
        cur_datetime = datetime_re.search(line).group(0)
        # convert to datetime object
        cur_datetime = datetime.strptime(cur_datetime, '%m/%d/%Y %H:%M')
        # create row to append to dataframe
        row = pd.DataFrame({'user': cur_user,
                       'datetime': cur_datetime,
                       'text': cur_text}, index = [0])
        # append row to dataframe
        masterdf = masterdf.append(row)
        # reinit cur_text
        cur_text = ''

    else:
        # if not a username line, continue appending the commentary for the user
        cur_text += line
</code>```

Body:
I have a string of unknown length that can repeat the pattern of interest any number of times.
The string looks like so:

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:18
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:19

SARAHJOHNSON has entered the above notes on 12/05/2017 17:45
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

SARAHJOHNSON has entered the above notes on 12/05/2017 17:46

I'm trying separate out the comment, username, and date to create a nicer looking comment box (with some css). The following is what I have to separate the user name

before_keyword, keyword, after_keyword = stringg.partition("has entered the above notes on ")
namedate = before_keyword.split()[-1] + "--" + after_keyword.split()[0] + after_keyword.split()[1]
comment = before_keyword.replace(before_keyword.split()[-1], '').rstrip()
print comment
print namedate

This works for the first case of Username entered the above notes. How can I iterate through the string to collect all comments/usernames/dates in the string and print them out separately.

Thanks.

Edit: put in fake names instead of USERNAME2389 to show how the names appear for me.

Body:
You can just iterate over the lines, create a text placeholder and when a username hits append it to a dataframe so at the end you have a nice, manipulatable dataset. You can also convert the datetime's directly so you can analyze more around the times, dates, etc.

import re
import pandas as pd
from datetime import datetime

string = """
    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    blahblahblahblahblahblahblahblahblahblah

    USERNAME2398 has entered the above notes on 12/05/2017 14:18

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    USERNAME2839 has entered the above notes on 12/05/2017 14:19

    USERNAME7348 has entered the above notes on 12/05/2017 17:45

    blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

    USERNAME857 has entered the above notes on 12/05/2017 17:46
    """

# define regex for username matching
username = re.compile('USERNAME.*?\s', re.IGNORECASE)
# define regex for datetime matching
datetime_re = re.compile('[0-9]{1,2}\/[0-9]{1,2}\/(20|19)[0-9]{2}\s[0-9]{1,2}\:[0-9]{1,2}')
# create placeholder datfarame
masterdf = pd.DataFrame()
# define text placeholder
cur_text = ''
for line in string.split('\n'):
    if datetime_re.search(line) and all([x.isupper() for x in line.split()[0]]):
        # pull out username
        cur_user = line.split()[0].strip()# username.search(line).group(0)
        # pull out datetime
        cur_datetime = datetime_re.search(line).group(0)
        # convert to datetime object
        cur_datetime = datetime.strptime(cur_datetime, '%m/%d/%Y %H:%M')
        # create row to append to dataframe
        row = pd.DataFrame({'user': cur_user,
                       'datetime': cur_datetime,
                       'text': cur_text}, index = [0])
        # append row to dataframe
        masterdf = masterdf.append(row)
        # reinit cur_text
        cur_text = ''

    else:
        # if not a username line, continue appending the commentary for the user
        cur_text += line


问:
can't cast wrapper to object
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.</p>

```<code>private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}
</code>```

答:
There is no relationship between text and Long for that reason any attempts to cast from text to Long or vice versa will result in failure.

A cast is only possible where there is a relationship between the two given types.

Title: can't cast wrapper to object

Body:
I have two long variables and I wanted to cast them to an object type. I know that if I cast the long variables to Long wrapper, then cast the wrappers to an object it will work, but the compiler says "cannot cast from Long to text" text is an a object type.

private quantity start;
private quantity end;

public quantity(long s , long e) {
    Long e1 = (Long) e;
    Long s1 = (Long) s;
    start = (quantity) s1;
    end = (quantity) e1;
}


问:
Python: selectionsort algorithm with queues
I have come across an exercise in Python:

Read in some strings and put them into a queue

Sort the strings lexicographically into a new queue, but the original queue shouldn't be changed. I should write a function from scratch (e.g. the sorted function cannot be used)

The use of arrays is not allowed

I think I have managed to come up with a function for step 1, but I have been struggling with step 2 for hours. I would really appreciate any kind of help!

Here is my code snippet for step 1:

```<code>q1 = []

def DisplayQueue(queue):
    for Item in queue:
        print(Item)

def PushQueue(queue):
    x = True
    while x:
        user_input = input("Please enter a string (for exit type: exit): ")
        if user_input == "exit":
            x = False
        else:
           queue.append(user_input)
    return queue

queue = PushQueue(q1)
</code>```

答:
Sorting can be done in many ways (bubble sort, insert sort, quick sort radix sort), but I recommend you start with something simple, although not the fastest.

Create a queue (or list) to store the answer in.

Find the smallest element in the old data list. *

Remove that element from the old list. **

Add than element to the answer list.

Repeat from step 2 (if the data list is not empty).

The data list will get shorter and shorter for each turn,
and the elements will be added in increasing order to the answer list.

*) To find the smallest element in the data list (you could put that in a separate function),  keep the value of the currently smallest value in a variable called x or something, and go through the data items one by one.  If the data item is smaller than what you have in the variable x, then put the value of that data item into x.

Now, once you have gone through the whole data list, your variable x will contain the value of the smallest element in the list.

**) You can remove a value v from a list x with x.remove(v). It just removes the first occurence of that value.

Body:
I have come across an exercise in Python:

Read in some strings and put them into a queue

Sort the strings lexicographically into a new queue, but the original queue shouldn't be changed. I should write a function from scratch (e.g. the sorted function cannot be used)

The use of arrays is not allowed

I think I have managed to come up with a function for step 1, but I have been struggling with step 2 for hours. I would really appreciate any kind of help!

Here is my code snippet for step 1:

q1 = []

def DisplayQueue(queue):
    for Item in queue:
        print(Item)

def PushQueue(queue):
    x = True
    while x:
        user_input = input("Please enter a string (for exit type: exit): ")
        if user_input == "exit":
            x = False
        else:
           queue.append(user_input)
    return queue

queue = PushQueue(q1)


问:
SVN: forcing theirs-full
I have an svn local copy. I changed some files. Usually after svn checkout ... I got conflict message with options what to do with changed (in local copy) files. One of that option was theirs-full.

But this time after svn checkout I got G status on those files and no conflict message.

How can I get the server copy of those files?

Thanks.

答: Subversion only gives the conflict options (like theirs-full) if there is a conflict in the file: a change on the server that it can't merge into your local version.  In your second case, Subversion was able to merge your local changes and the server changes without any problems, so it didn't need your input on what to do.  If you want the server version, you can use svn revert to overwrite your local copy or svn cat to show the server copy or save it into a different file.

Title: SVN: forcing theirs-full


问:
My Java code is not running
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.</p>

```<code>public class Even {

    public static void main(String args[]) {

        int number = 1;
        int remainder = number % 2;

        while(number <= 100) {
            number++;
            if(remainder == 0) {
                System.out.println(number);
            }
        }

    }

}
</code>```

答:
```<code>    for(int i = 0;i<=100; i= i+2)
        System.out.println(i);
</code>```

You do not need remainder :)

Title: My Java code is not running

Body:
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.

public class Even {

    public static void main(String args[]) {

        int number = 1;
        int remainder = number % 2;

        while(number <= 100) {
            number++;
            if(remainder == 0) {
                System.out.println(number);
            }
        }

    }

}

Body:
    for(int i = 0;i<=100; i= i+2)
        System.out.println(i);

You do not need remainder :)


答:
I would use regular expressions to do this.

Simply loop through every line (FOREACH), then test the line for this expression:

```<code>(USERNAME\S*) has entered the above notes on (\d{1,2}/\d{1,2}/\d{4}) (\d{1,2}:\d{1,2})
</code>```

If this line matches, you have your 3 information (in parentheses): Username, Date and Time. Store the lines before that in an array (buffer) and you'll have your text.

Title: How can I iteratively partition the same string multiple times?

Body:
I would use regular expressions to do this.

Simply loop through every line (FOREACH), then test the line for this expression:

(USERNAME\S*) has entered the above notes on (\d{1,2}/\d{1,2}/\d{4}) (\d{1,2}:\d{1,2})

If this line matches, you have your 3 information (in parentheses): Username, Date and Time. Store the lines before that in an array (buffer) and you'll have your text.


问:
Spring Data JPA - How can I fetch data from a Date column using only month and day?
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

```<code>1935-12-08 00:00:00
</code>```

If I want to do this in a db level it works fine:

```<code>SELECT * FROM my_database.event where event_date LIKE '%-12-08%';
</code>```

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

```<code>List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);
</code>```

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

答:
If your JPA provider is Hibernate then you can use year and month (and other funcs) in your JPQL (HQL) query, for example like this:

```<code>@Query("select e from Event e where year(e.eventDate) = ?1 and month(e.eventDate) = ?2")
List<Entity> getByYearAndMonth(int year, int month);
</code>```

Body:
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

1935-12-08 00:00:00

If I want to do this in a db level it works fine:

SELECT * FROM my_database.event where event_date LIKE '%-12-08%';

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

Body:
If your JPA provider is Hibernate then you can use year and month (and other funcs) in your JPQL (HQL) query, for example like this:

@Query("select e from Event e where year(e.eventDate) = ?1 and month(e.eventDate) = ?2")
List<Entity> getByYearAndMonth(int year, int month);


问:
AJAX DELETE request in asp.net MVC
I've always thought that a delete request should be done using type: "DELETE". However, it seems not work in .NET

```<code>$.ajax({
    type: "GET",
    url: '/TestController/DeleteTest?id=10',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        if (data) {
            // Works
        }
    },
    error: function (erro) {
        console.debug(erro);
    }
});
</code>```

Controller:

```<code>[HttpGet]
    public JsonResult DeleteTest()
    {
        int id= Int32.Parse(Request["id"]);

        var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
        db.mytable.Remove(myTableTest);

        db.SaveChanges();
        return Json(true, JsonRequestBehavior.AllowGet);
    }
</code>```

This code works fine! But if I change to type: "DELETE", it won't work anymore. So, does asp.net have HttpDelete?

Thanks

答: You should be able to just decorate your action with the [HttpDelete] attribute instead of [HttpGet]. I would also have it set to return an ActionResult instead of JsonResult and return new HttpStatusCodeResult(200) on success in order to make sure your ajax call properly understands the returned result.

Title: AJAX DELETE request in asp.net MVC

Body:
I've always thought that a delete request should be done using type: "DELETE". However, it seems not work in .NET

$.ajax({
    type: "GET",
    url: '/TestController/DeleteTest?id=10',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        if (data) {
            // Works
        }
    },
    error: function (erro) {
        console.debug(erro);
    }
});

Controller:

[HttpGet]
    public JsonResult DeleteTest()
    {
        int id= Int32.Parse(Request["id"]);

        var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
        db.mytable.Remove(myTableTest);

        db.SaveChanges();
        return Json(true, JsonRequestBehavior.AllowGet);
    }

This code works fine! But if I change to type: "DELETE", it won't work anymore. So, does asp.net have HttpDelete?

Thanks


答:
Your method is decorated with the [HttpGet] attribute. This tells the framework that the method should only be considered if the GET verb is used.

If you want it to respond to DELETE you need to change the attribute to [HttpDelete] instead:

```<code>[HttpDelete]
public JsonResult DeleteTest()
{
    ...
}
</code>```

Title: AJAX DELETE request in asp.net MVC

Body:
Your method is decorated with the [HttpGet] attribute. This tells the framework that the method should only be considered if the GET verb is used.

If you want it to respond to DELETE you need to change the attribute to [HttpDelete] instead:

[HttpDelete]
public JsonResult DeleteTest()
{
    ...
}


问:
Pass ngModel in child component for common error handling
i am trying to pass ngModel in child component to displaying error from common component.

It giving error like.
Template parse errors:No provider for NgControl.

can any one please check the code and let me know what i am missing.

Plunker

Parent component

```<code>      <div>
  <h2>Hello {{name}}</h2>
  <form #countryForm="ngForm">
    <div class="form-group row">
      <label for="txtCountryName" class="col-sm-3 col-form-label">Country Name</label>
      <div class="col-sm-9">
        <input type="text" [(ngModel)]="name" ngModel #countryName="ngModel" name="name" class="form-control" id="txtCountryName" placeholder="Country Name"              required minlength="5" maxlength="15">
        <app-error-message [formControl]="countryName"></app-error-message>
      </div>
    </div>
  </form>
</div>
</code>```

Child component

```<code>@Component({
selector: 'app-error-message',
template: `<ng-container *ngIf="formControl">
            <div [hidden]="(formControl.valid || formControl.pristine) && (formControl.errors == null || formControl.errors.invalid == null)" class="alert alert-danger">
              {{GetValidationMessage()}}
            </div>
          </ng-container>`

  })

export class ErrorMessageComponent  {
@Input() public formControl: any = null;

public GetValidationMessage() {
    let errorMessage: string = "";
    if (this.formControl.errors) {
        if (this.formControl.dirty || this.formControl.touched) {
            if (this.formControl.errors.required != null) {
                errorMessage = "This field is required.";
            }
            if (this.formControl.errors.minlength != null) {
                errorMessage += "This field must be 8 characters long, we need another " + (this.formControl.errors.minlength.requiredLength - this.formControl.errors.minlength.actualLength) + " characters";
            }
        }
        if (this.formControl.errors.invalid != null) {
            errorMessage += this.formControl.errors.errorMessage;
        }
    }
    return errorMessage;
}
</code>```

}

答:
You should use another name for @Input to not intersect with built-in directive NgControlStatus that requires NgControl provider https://github.com/angular/angular/blob/3ce3b4d2afdc5198a9a5a9432db1f88e2e5d1972/packages/forms/src/directives/ng_control_status.ts#L56

To do so you can either completely replace property name

error-message.component.ts

```<code>@Input() public control: any = null;
</code>```

parent.html

```<code><app-error-message [control]="countryName"></app-error-message>
</code>```

Forked Plunker

or use alias for @Input

error-message.component.ts

```<code>@Input('control') public formControl: any = null;
</code>```

parent.html

```<code><app-error-message [control]="countryName"></app-error-message>
</code>```

Forked Plunker

Body:
i am trying to pass ngModel in child component to displaying error from common component.

It giving error like.
Template parse errors:No provider for NgControl.

can any one please check the code and let me know what i am missing.

Plunker

Parent component

Hello {{name}}

  <form #countryForm="ngForm">

      Country Name

        <input type="text" [(ngModel)]="name" ngModel #countryName="ngModel" name="name" class="form-control" id="txtCountryName" placeholder="Country Name"              required minlength="5" maxlength="15">
        <app-error-message [formControl]="countryName"></app-error-message>

  </form>

Child component

@Component({
selector: 'app-error-message',
template: `<ng-container *ngIf="formControl">

              {{GetValidationMessage()}}

          </ng-container>`

  })

export class ErrorMessageComponent  {
@Input() public formControl: any = null;

public GetValidationMessage() {
    let errorMessage: string = "";
    if (this.formControl.errors) {
        if (this.formControl.dirty || this.formControl.touched) {
            if (this.formControl.errors.required != null) {
                errorMessage = "This field is required.";
            }
            if (this.formControl.errors.minlength != null) {
                errorMessage += "This field must be 8 characters long, we need another " + (this.formControl.errors.minlength.requiredLength - this.formControl.errors.minlength.actualLength) + " characters";
            }
        }
        if (this.formControl.errors.invalid != null) {
            errorMessage += this.formControl.errors.errorMessage;
        }
    }
    return errorMessage;
}

}

Body:
You should use another name for @Input to not intersect with built-in directive NgControlStatus that requires NgControl provider https://github.com/angular/angular/blob/3ce3b4d2afdc5198a9a5a9432db1f88e2e5d1972/packages/forms/src/directives/ng_control_status.ts#L56

To do so you can either completely replace property name

error-message.component.ts

@Input() public control: any = null;

parent.html

<app-error-message [control]="countryName"></app-error-message>

Forked Plunker

or use alias for @Input

error-message.component.ts

@Input('control') public formControl: any = null;

parent.html

<app-error-message [control]="countryName"></app-error-message>

Forked Plunker


问:
Encoding::UndefinedConversionError when using open-uri
When I do this:

require 'open-uri'
response = open('some-html-page-url-here')
response.read
```

<p>On a certain url I get the following error (due to wrong encoding in the returned url?!):</p>

```Encoding::UndefinedConversionError: U+00A0 from UTF-8 to US-ASCII
```

Any way around this to still get the html content?

答:
Had the same issue, will add my solution here:

After reading the open-uri documentation further, it turns out you could set the encoding of the io before reading using the set_encoding method, like this:

```<code>result = open('some-page-uri') do |io|
  io.set_encoding(Encoding.default_external)
  io.read
end
</code>```

Hope it helps!

Body:
When I do this:

require 'open-uri'
response = open('some-html-page-url-here')
response.read

On a certain url I get the following error (due to wrong encoding in the returned url?!):

Encoding::UndefinedConversionError: U+00A0 from UTF-8 to US-ASCII

Any way around this to still get the html content?

Body:
Had the same issue, will add my solution here:

After reading the open-uri documentation further, it turns out you could set the encoding of the io before reading using the set_encoding method, like this:

result = open('some-page-uri') do |io|
  io.set_encoding(Encoding.default_external)
  io.read
end

Hope it helps!


问:
Is IntelliJ IDEA Ultimate slower than the Community edition?
The ultimate has many more features, so I imagine it loads slower, consumes more memory and is generally less responsive. Actually I don't care about the load time all that much, but memory and responsiveness (which are related) are of more importance.

Did you notice any difference between these editions?

答:
If you are working on the same project and using the same features, you should not notice any differences.

However, if your project uses several languages (like Ruby, Python, Groovy, Scala), load time will be longer since IDEA will have to load plug-ins for these languages.

Also, more features used in the project, means that IDEA will need more memory. If you don't hit your hardware limit and have a descent rig, you'll not notice it at all. If you are short on memory, IDEA may become slower because of the frequent garbage collections and operating system swapping.

So, generally it would require more memory since you are going to use more features, but if it doesn't swap and you have enough free RAM, you will not have performance problems. Also note that you can disable all the unused plug-ins to save resources.


问:
Get the supported "bitness" of an x86 CPU when booted in 16-bit mode
I am developing an x86 bootloader and have come across this problem (which I guess should be pretty straightforward, but so far I haven't been able to solve): I want to detect the bitness of the CPU host (e.g. if it's 16bit-only, or supports 32bit or 64bit).

I have used the CPUID instruction, but it was introduced with 486 so doesn't help for detecting 16-bit-only vs. a 386-compatible CPU that supports 32-bit protected mode (or 32-bit operand-size in real mode with prefixes).

答:
Checking for 32-bits (see http://www.rcollins.org/ddj/Sep96/Sep96.html):

16-bit CPUs without protected mode (8088/8086/80186) will always have the upper 4 bits (15-12) of the flags register set when doing pushf

80286 will always have the upper 4 bits clear on pushf (when running in real mode)

CPUs supporting 32-bit allow modifying the upper 4 bits in real mode using popf (however all 4 bits should have the same value - all set or all clear)

By using pushf, popf and modifying the data on the stack you check if it is possible to modify the upper 4 bits; if yes, it must be a 32-bit CPU.

Checking for CPUID:

Ensure the CPU supports 32-bit (see above)

Switch to 32-bits mode

Check if bit 21 of EFLAGS can be modified (set and cleared); if the value of that bit is not fixed (it can be changed from 0 to 1 or vice versa) the cpuid instruction is supported.


问:
Libgdx masking with image
I have a framebuffer, where some shapes are drawn using ShapeRenderer. And now I want to mask this framebuffer with mask from image. Before that I got it working with simple circle mask drawn by ShapeRenderer. But I need to use more complex mask so I have to use an image. Mask is a png with black mask and transparent background. Here's my code:

```<code>   @Override
   public void draw(Batch batch, float parentAlpha) {

      //disable RGB color, only enable ALPHA to the frame buffer
      Gdx.gl.glColorMask(false, false, false, true);

      //change the blending function for our alpha map
      batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_ALPHA);

      //draw alpha mask sprite(s)
      batch.draw(maskTexture, MASK_OFFSET_X + getX(), MASK_OFFSET_Y + getY());

      //flush the batch to the GPU
      batch.flush();

      Gdx.gl.glColorMask(true, true, true, true);
      batch.setBlendFunction(GL20.GL_DST_ALPHA, GL20.GL_ONE_MINUS_DST_ALPHA);

      //The scissor test is optional, but it depends
      Gdx.gl.glEnable(GL20.GL_SCISSOR_TEST);
      Gdx.gl.glScissor(MASK_OFFSET_X + (int) getX(), MASK_OFFSET_Y + (int) getY(), maskTexture.getWidth(), maskTexture.getHeight());

      //draw framebuffer to be masked
      batch.draw(frm, getX(), getY(), frmSizeX, frmSizeY);

      //remember to flush before changing GL states again
      batch.flush();

      //disable scissor before continuing
      Gdx.gl.glDisable(GL20.GL_SCISSOR_TEST);

      //set default blend function
      batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
   }
</code>```

My image is masked indeed, but there's a black background from mask image (it should be transparent).
It's looking like this now:

And it should look for example like this (except this example is without mask so ofc paint shoudn't go outside head):

Also take a note that paint is half-transparent. (I don't know if it will change some code).

Ofc I'm using RGBA8888 format, here's initialization code:

```<code>frmBuff = new FrameBuffer(Format.RGBA8888, frmSizeX, frmSizeY, false);
frm = new TextureRegion(frmBuff.getColorBufferTexture());
frmCam = new OrthographicCamera(frmSizeX, frmSizeY);
frmCam.translate(frmSizeX / 2, frmSizeY / 2);

maskTexture = game.manager.get("my_mask.png", Texture.class);
maskTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
</code>```

I was messing around setBlendFunction and achieved very different results, but none of them was actually right.

How can I fix this?

Btw my code is based on this example:
https://gist.github.com/mattdesl/6076846

I've also already read this:
https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Masking

答:
I know this is an old post. But all my research on this issue only lead me here. I read the post on https://gist.github.com/mattdesl/6076846 and realized that the issue is that you are only taking into consideration the alpha of the mask, but really you want the alpha of the product of the mask and the foreground (the purple paint).</p>

```<code>//disable RGB color, only enable ALPHA to the frame buffer
Gdx.gl.glColorMask(false, false, false, true);

//change the blending function for our alpha map
batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_ALPHA);

//draw alpha mask sprite(s)
batch.draw(maskTexture, MASK_OFFSET_X + getX(), MASK_OFFSET_Y + getY());

//change the function for our source
batch.setBlendFunction(GL20.GL_ONE_MINUS_SRC_ALPHA, GL20.GL_SRC_ALPHA);

//draw the source alpha
river_sprite.draw(batch);

//flush the batch to the GPU
batch.flush();
</code>```

Title: Libgdx masking with image

Body:
I have a framebuffer, where some shapes are drawn using ShapeRenderer. And now I want to mask this framebuffer with mask from image. Before that I got it working with simple circle mask drawn by ShapeRenderer. But I need to use more complex mask so I have to use an image. Mask is a png with black mask and transparent background. Here's my code:

   @Override
   public void draw(Batch batch, float parentAlpha) {

      //disable RGB color, only enable ALPHA to the frame buffer
      Gdx.gl.glColorMask(false, false, false, true);

      //change the blending function for our alpha map
      batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_ALPHA);

      //draw alpha mask sprite(s)
      batch.draw(maskTexture, MASK_OFFSET_X + getX(), MASK_OFFSET_Y + getY());

      //flush the batch to the GPU
      batch.flush();

      Gdx.gl.glColorMask(true, true, true, true);
      batch.setBlendFunction(GL20.GL_DST_ALPHA, GL20.GL_ONE_MINUS_DST_ALPHA);

      //The scissor test is optional, but it depends
      Gdx.gl.glEnable(GL20.GL_SCISSOR_TEST);
      Gdx.gl.glScissor(MASK_OFFSET_X + (int) getX(), MASK_OFFSET_Y + (int) getY(), maskTexture.getWidth(), maskTexture.getHeight());

      //draw framebuffer to be masked
      batch.draw(frm, getX(), getY(), frmSizeX, frmSizeY);

      //remember to flush before changing GL states again
      batch.flush();

      //disable scissor before continuing
      Gdx.gl.glDisable(GL20.GL_SCISSOR_TEST);

      //set default blend function
      batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
   }

My image is masked indeed, but there's a black background from mask image (it should be transparent).
It's looking like this now:

And it should look for example like this (except this example is without mask so ofc paint shoudn't go outside head):

Also take a note that paint is half-transparent. (I don't know if it will change some code).

Ofc I'm using RGBA8888 format, here's initialization code:

frmBuff = new FrameBuffer(Format.RGBA8888, frmSizeX, frmSizeY, false);
frm = new TextureRegion(frmBuff.getColorBufferTexture());
frmCam = new OrthographicCamera(frmSizeX, frmSizeY);
frmCam.translate(frmSizeX / 2, frmSizeY / 2);

maskTexture = game.manager.get("my_mask.png", Texture.class);
maskTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

I was messing around setBlendFunction and achieved very different results, but none of them was actually right.

How can I fix this?

Btw my code is based on this example:
https://gist.github.com/mattdesl/6076846

I've also already read this:
https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Masking

Body:
I know this is an old post. But all my research on this issue only lead me here. I read the post on https://gist.github.com/mattdesl/6076846 and realized that the issue is that you are only taking into consideration the alpha of the mask, but really you want the alpha of the product of the mask and the foreground (the purple paint).

//disable RGB color, only enable ALPHA to the frame buffer
Gdx.gl.glColorMask(false, false, false, true);

//change the blending function for our alpha map
batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_ALPHA);

//draw alpha mask sprite(s)
batch.draw(maskTexture, MASK_OFFSET_X + getX(), MASK_OFFSET_Y + getY());

//change the function for our source
batch.setBlendFunction(GL20.GL_ONE_MINUS_SRC_ALPHA, GL20.GL_SRC_ALPHA);

//draw the source alpha
river_sprite.draw(batch);

//flush the batch to the GPU
batch.flush();


问:
Connecting to an Azure Webjob from an application within the same App Service
I've been using the Microsoft Orleans framework within my application, and am now trying to deploy it to Azure.  If you're not familiar, Orleans is a Virtual Actor framework that exposes servers called Silos where code is instantiated, held in memory until it's been idle for a set amount of time, and then unloaded.  My WebApi application then acts as a client and will connect to the Orleans silos.

I have deployed the WebApi application in an Azure App Service, and within that same App Service have created a continuous webjob that runs the Silo.  However, when the WebApi client tries to connect to the Silo, I'm seeing "Unable to connect" errors in the log (trying via TCP).

That made me think that maybe I needed to attach a Virtual Network to the Application Service, but that did not fix the issue (same log message) and I don't see anything that indicates that I would need to also add the webjobs to the Virtual Network.

Should I be able to connect these two applications together via the network?

答:
The main site runs in a different sandbox from the WebJobs, which run in the 'scm site'. They're set up so that the scm site can talk to the Main site, but not vice versa. This may be what's blocking you here.

Try setting WEBSITE_DISABLE_SCM_SEPARATION=true if your Azure App Settings to make them run in the same sandbox (see doc). Though note that technically it is no longer an officially supported mode. Still, it would be interesting to test whether that helps.


问:
Rails application to interface with local machine running Ubuntu
What im trying to do:

service-hosted rails app ( heroku or something )

user logs into application and wants to " DO THINGS "

" DO THINGS " entails running commands to the local machine i have here in my apartment

I've SSHed into a server before ... but i think this would be best setup if the server initiates the connection

I'm FAIRLY running a permanent SSH isnt the best idea

I'm not 100% sure on the process .. i just need information transfer between my hosted application .. and my local machine.

ruby socket set of commands which could possibly work?

any particular gem that would handle this?

Thanks ahead of time!

答:
so far it looks like NetSSH is the answer im looking for

at command prompt:

```<code>$ gem install net-ssh
</code>```

Next we create a new controller file:

```<code>app/controllers/ssh_connections_controller.rb
</code>```

and inside ssh_connections_controller.rb file place:

```<code>  def conn

  Net::SSH.start( '127.0.0.1','wonton' ) do |session|
    session.open_channel do |channel|
      channel.on_close do |ch|
        puts "channel closed successfully."
        render :text => 'hits'
      end
      puts "closing channel..."
      channel.close
    end

    session.loop
  end

  end
</code>```

... and substitute your local settings...
'wonton' would be the name of whatever user you want to SSH in as

more to be updated!

Body:
so far it looks like NetSSH is the answer im looking for

at command prompt:

$ gem install net-ssh

Next we create a new controller file:

app/controllers/ssh_connections_controller.rb

and inside ssh_connections_controller.rb file place:

  def conn

  Net::SSH.start( '127.0.0.1','wonton' ) do |session|
    session.open_channel do |channel|
      channel.on_close do |ch|
        puts "channel closed successfully."
        render :text => 'hits'
      end
      puts "closing channel..."
      channel.close
    end

    session.loop
  end

  end

... and substitute your local settings...
'wonton' would be the name of whatever user you want to SSH in as

more to be updated!


问:
Add an iteration variable in a nested for-loop on every iteration
I'm trying to write a program that prints every possible alphabetical combination between two and four characters. The program as I have it now works just fine, but the implementation is far from ideal. This is what it is now:

```<code># make a list that contains ascii characters A to z
ascii = list(range(65, 123))
del ascii[91 - 65 : 97 - 65] # values 91-97 aren't letters

for c1, c2 in product(ascii, repeat=2):
    word = chr(c1) + chr(c2)
    print(word)

for c1, c2, c3 in product(ascii, repeat=3):
    word = chr(c1) + chr(c2) + chr(c3)
    print(word)

for c1, c2, c3, c4 in product(ascii, repeat=4):
    word = chr(c1) + chr(c2) + chr(c3) + chr(c4)
    print(word)
</code>```

I'd much rather have something in the spirit of the following. Forgive me that the following code is totally wrong, I'm trying to convey the spirit of what I thought would be a nicer implementation.

```<code>iterationvars = [c1, c2, c3, c4]

for i in range(2,5):
    for iterationvars[0:i] in product(ascii, repeat=i):
        word = ??
        print(word)
</code>```

So I have two questions:

1) how can I change the number of iteration variables of a nested for loop on every iteration of the 'mother loop'?

2) how can word be implemented such that it dynamically adds up all iteration variables, no matter how many there are on that particular iteration.

Of course, very different implementations from what I suggest are also more than welcome. Thanks a lot!

答:
there's no need to change the number of iteration variables, just keep it all in one tuple then use a joined list comprehension. Something like this would work:</p>

```<code>for iter_tuple in product(ascii, repeat = i):
    word = ''.join(chr(x) for x in iter_tuple)
    print(word)
</code>```

Body:
I'm trying to write a program that prints every possible alphabetical combination between two and four characters. The program as I have it now works just fine, but the implementation is far from ideal. This is what it is now:

# make a list that contains ascii characters A to z
ascii = list(range(65, 123))
del ascii[91 - 65 : 97 - 65] # values 91-97 aren't letters

for c1, c2 in product(ascii, repeat=2):
    word = chr(c1) + chr(c2)
    print(word)

for c1, c2, c3 in product(ascii, repeat=3):
    word = chr(c1) + chr(c2) + chr(c3)
    print(word)

for c1, c2, c3, c4 in product(ascii, repeat=4):
    word = chr(c1) + chr(c2) + chr(c3) + chr(c4)
    print(word)

I'd much rather have something in the spirit of the following. Forgive me that the following code is totally wrong, I'm trying to convey the spirit of what I thought would be a nicer implementation.

iterationvars = [c1, c2, c3, c4]

for i in range(2,5):
    for iterationvars[0:i] in product(ascii, repeat=i):
        word = ??
        print(word)

So I have two questions:

1) how can I change the number of iteration variables of a nested for loop on every iteration of the 'mother loop'?

2) how can word be implemented such that it dynamically adds up all iteration variables, no matter how many there are on that particular iteration.

Of course, very different implementations from what I suggest are also more than welcome. Thanks a lot!

Body:
there's no need to change the number of iteration variables, just keep it all in one tuple then use a joined list comprehension. Something like this would work:

for iter_tuple in product(ascii, repeat = i):
    word = ''.join(chr(x) for x in iter_tuple)
    print(word)


问:
Hosting MusicBot on Heroku
I'm trying to insall this Music Bot application. It works as an application for Discord that plays music upon request. I've been trying to figure out any way of putting those files into a Heroku account so that it would run on my Discord server forever. I want to get a better understanding on how Heroku works with Python files like these.

答:
You should checkout the Heroku docs for Python, it's really not that hard

That you will need:

A fork/clone of above mentioned discord bot

A requirements.txt file which states your pip requirements (already present at the mentioned discord bot)

A runtime.txt file which states which interpreter on which version you want to use, i.e. python-3.6.1

A Procfile file which states which Heroku worker should start which script file

After you've done that, you can push your changes via git to your Heroku git repository

Title: Hosting MusicBot on Heroku


问:
in operator, float("NaN") and np.nan
I used to believe that in operator in Python checks the presence of element in some collection using equality checking ==, so element in some_list is roughly equivalent to any(x == element for x in some_list). For example:

```<code>True in [1, 2, 3]
# True because True == 1
</code>```

or

```<code>1 in [1., 2., 3.]
# also True because 1 == 1.
</code>```

However, it is well-known that NaN is not equal to itself. So I expected that float("NaN") in [float("NaN")] is False. And it is False indeed.

However, if we use numpy.nan instead of float("NaN"), the situation is quite different:

```<code>import numpy as np
np.nan in [np.nan, 1, 2]
# True
</code>```

But np.nan == np.nan still gives False!

How is it possible? What's the difference between np.nan and float("NaN")? How does in deal with np.nan?

答:
One thing worth mentioning is that numpy arrays do behave as expected:

```<code>a = np.array((np.nan,))
a[0] in a
# False
</code>```

Variations of the theme:

```<code>[np.nan]==[np.nan]
# True
[float('nan')]==[float('nan')]
# False
{np.nan: 0}[np.nan]
# 0
{float('nan'): 0}[float('nan')]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: nan
</code>```

Everything else is covered in @AlexRiley's excellent answer.

Title: in operator, float("NaN") and np.nan

Body:
I used to believe that in operator in Python checks the presence of element in some collection using equality checking ==, so element in some_list is roughly equivalent to any(x == element for x in some_list). For example:

True in [1, 2, 3]
# True because True == 1

or

1 in [1., 2., 3.]
# also True because 1 == 1.

However, it is well-known that NaN is not equal to itself. So I expected that float("NaN") in [float("NaN")] is False. And it is False indeed.

However, if we use numpy.nan instead of float("NaN"), the situation is quite different:

import numpy as np
np.nan in [np.nan, 1, 2]
# True

But np.nan == np.nan still gives False!

How is it possible? What's the difference between np.nan and float("NaN")? How does in deal with np.nan?

Body:
One thing worth mentioning is that numpy arrays do behave as expected:

a = np.array((np.nan,))
a[0] in a
# False

Variations of the theme:

[np.nan]==[np.nan]
# True
[float('nan')]==[float('nan')]
# False
{np.nan: 0}[np.nan]
# 0
{float('nan'): 0}[float('nan')]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: nan

Everything else is covered in @AlexRiley's excellent answer.


问:
Writing to a file in c, garbage value gets populated
The code is supposed to append whatever data it gets in fileReceived to a.txt file but instead it gets populated with random values.(well not so random also but definitely not the correct values). Am i missing out on something?</p>

```<code>File *fp;
fp = fopen("a.txt",+a);
while(1)
{
    fileReceived =...// getting char array of 1024 size
    fwrite(fileReceived,1,sizeof(fileReceived),fp);

    if(padding!=0)
    {
      fclose(fp);
      break;
    }
}
</code>```

答:
Guessing (but can't be otherwise) even if you're not showing the right part:

```<code>fileReceived =...// getting char array of 1024 size
fwrite(fileReceived,1,sizeof(fileReceived),fp);
</code>```

fileReceived has to be a pointer on data, so sizeof(fileReceived) isn't 1024 but 4 or 8 depending on your architecture (since it's not possible to assign an array to another array)

You're writing too few data in your loop and your file gets the first values but not the last ones. Since you know the size, fix it like this:

```<code>int size = 1024;
...
fwrite(fileReceived,1,size,fp);
</code>```

if the data size varies, you have to get the size information from whatever function provides the pointer to you, or you'll get undefined behaviour

Body:
The code is supposed to append whatever data it gets in fileReceived to a.txt file but instead it gets populated with random values.(well not so random also but definitely not the correct values). Am i missing out on something?

File *fp;
fp = fopen("a.txt",+a);
while(1)
{
    fileReceived =...// getting char array of 1024 size
    fwrite(fileReceived,1,sizeof(fileReceived),fp);

    if(padding!=0)
    {
      fclose(fp);
      break;
    }
}

Body:
Guessing (but can't be otherwise) even if you're not showing the right part:

fileReceived =...// getting char array of 1024 size
fwrite(fileReceived,1,sizeof(fileReceived),fp);

fileReceived has to be a pointer on data, so sizeof(fileReceived) isn't 1024 but 4 or 8 depending on your architecture (since it's not possible to assign an array to another array)

You're writing too few data in your loop and your file gets the first values but not the last ones. Since you know the size, fix it like this:

int size = 1024;
...
fwrite(fileReceived,1,size,fp);

if the data size varies, you have to get the size information from whatever function provides the pointer to you, or you'll get undefined behaviour


问:
EC2 instance store volumes issue
I have created an c3.2xlarge EC2 instance with the store volume specified as 2 x 80 GB (160 GB). But when I use df -H command, this is what i see, and there is not enough storage as specified.

```<code>Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        7.9G   62k  7.9G   1% /dev
tmpfs           7.9G     0  7.9G   0% /dev/shm
/dev/xvda1      8.4G  1.1G  7.2G  14% /
</code>```

I need an EC2 instance to have at least 80 gigs of storage, which instance should I choose?

答:
Thanks for the points in the comments.

The problem was; I used EC2 Management Console and didn't add the volumes when I created the cluster, I terminated that cluster, created a new one, on Storage page Added New Volume, chose the volume type as Instance Store 0.

```<code>[]$ lsblk
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
xvdb    202:16   0  75G  0 disk /media/ephemeral0
</code>```

Now the 80 Gig volume is there.

Title: EC2 instance store volumes issue

Body:
I have created an c3.2xlarge EC2 instance with the store volume specified as 2 x 80 GB (160 GB). But when I use df -H command, this is what i see, and there is not enough storage as specified.

Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        7.9G   62k  7.9G   1% /dev
tmpfs           7.9G     0  7.9G   0% /dev/shm
/dev/xvda1      8.4G  1.1G  7.2G  14% /

I need an EC2 instance to have at least 80 gigs of storage, which instance should I choose?

Body:
Thanks for the points in the comments.

The problem was; I used EC2 Management Console and didn't add the volumes when I created the cluster, I terminated that cluster, created a new one, on Storage page Added New Volume, chose the volume type as Instance Store 0.

[]$ lsblk
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
xvdb    202:16   0  75G  0 disk /media/ephemeral0

Now the 80 Gig volume is there.


问:
Laravel stop events propagation
I have registered two queued event handlers on an event :

```<code>// in app/Providers/EventServiceProvider.php
//...

'App\Events\UserWasCreated' => [
    'App\Handlers\Events\RegisterInSalesForce',
    'App\Handlers\Events\SendMailToAdmin',
],
</code>```

I want to run SendMailToAdmin only if RegisterInSalesForce is OK. I tried to return false in RegisterInSalesForce on failure and true on success but it does not work.

What should I do ? Did I miss something ?

答:
In Laravel 5.5 you can just return false to stop propagation of an event.

From Laravel 5.5 documentation

Stopping The Propagation Of An Event

https://laravel.com/docs/5.5/events#defining-listeners

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.

Title: Laravel stop events propagation

Body:
I have registered two queued event handlers on an event :

// in app/Providers/EventServiceProvider.php
//...

'App\Events\UserWasCreated' => [
    'App\Handlers\Events\RegisterInSalesForce',
    'App\Handlers\Events\SendMailToAdmin',
],

I want to run SendMailToAdmin only if RegisterInSalesForce is OK. I tried to return false in RegisterInSalesForce on failure and true on success but it does not work.

What should I do ? Did I miss something ?