问:
Get instance function from header file
I am currently testing private frameworks for IOS and currently I'm trying to figure out how to check if Night Shift is enabled. For reference, the header file I am working with is located here.

And here is the code I am using below:

```<code>  if (!(NSClassFromString(@"CCUINightShiftSectionController"))) {
            dlopen("System/Library/PrivateFrameworks/ControlCenterUI.framework/ControlCenterUI", RTLD_LOCAL);
}

     NSObject *manager = [NSClassFromString(@"CCUINightShiftSectionController") performSelector:NSSelectorFromString(@"_defaultFontTight")];

            NSLog(@" ok= %@", manager);

        }
</code>```

From that file, I got the data for _defaultFontTight to print in the NSLog just fine, but what I'm struggling with is how do I get the instance functions? More specifically, everything below that start with a -  symbol. I can only get info from a +
 symbol.

If I were to switch out _defaultFontTight with enabled then I get the following:

```<code>2017-07-02 18:09:35.382109-0400 Testing[809:96270] +[CCUINightShiftSectionController enabled]: unrecognized selector sent to class 0x1b7d5e420
</code>```

Any help would be greatly appreciated!

EDIT:

I tried this code below:

```<code>id myInstance =[NSClassFromString(@"CCUINightShiftSectionController") new];
[myInstance performSelector:NSSelectorFromString(@"enabled")];
</code>```

For some frameworks, it gets the instance variable values sucessfully, while for most it just returns null or errors such as [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""

答:
Make sure private headers match the iOS version of your device. Otherwise you might get errors when trying to instantiate non-existing classes or call methods they don't implement.

Link to frameworks you want to use. You can't just allocate a class. You need to link your application to the framework that contains the class. Otherwise NSClassFromString will return nil. They're various ways you can do that but for now dlopen("/System/Library/PrivateFrameworks/ControlCenterUI.framework/ControlCenterUI", RTLD_LAZY) would be the simplest.

With that out of the way you will be able to call anything you want from private frameworks. But it doesn't mean it will actually work. Most private APIs are protected by entitlements and wouldn't work without jailbreak. And there's always a problem with figuring how to actually use them. You can't just call a random method and expect it to work. You might need to do some initialization. The only way to figure that out is to disassemble the methods and applications that call these methods.

Title: Get instance function from header file

Body:
I am currently testing private frameworks for IOS and currently I'm trying to figure out how to check if Night Shift is enabled. For reference, the header file I am working with is located here.

And here is the code I am using below:

  if (!(NSClassFromString(@"CCUINightShiftSectionController"))) {
            dlopen("System/Library/PrivateFrameworks/ControlCenterUI.framework/ControlCenterUI", RTLD_LOCAL);
}

     NSObject *manager = [NSClassFromString(@"CCUINightShiftSectionController") performSelector:NSSelectorFromString(@"_defaultFontTight")];

            NSLog(@" ok= %@", manager);

        }

From that file, I got the data for _defaultFontTight to print in the NSLog just fine, but what I'm struggling with is how do I get the instance functions? More specifically, everything below that start with a -  symbol. I can only get info from a +
 symbol.

If I were to switch out _defaultFontTight with enabled then I get the following:

2017-07-02 18:09:35.382109-0400 Testing[809:96270] +[CCUINightShiftSectionController enabled]: unrecognized selector sent to class 0x1b7d5e420

Any help would be greatly appreciated!

EDIT:

I tried this code below:

id myInstance =[NSClassFromString(@"CCUINightShiftSectionController") new];
[myInstance performSelector:NSSelectorFromString(@"enabled")];

For some frameworks, it gets the instance variable values sucessfully, while for most it just returns null or errors such as [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""


来源: stackexchange

问:
Parsing String by pattern of substrings
I need to parse a formula and get all the variables that were used. The list of variables is available. For example, the formula looks like this:

```<code>String f = "(Min(trees, round(Apples1+Pears1,1)==1&&universe==big)*number";
</code>```

I know that possible variables are:

```<code>String[] vars = {"trees","rivers","Apples1","Pears1","Apricots2","universe","galaxy","big","number"};
</code>```

I need to get the following array:

```<code>String[] varsInF = {"trees", "Apples1","Pears1", "universe", "big","number"};
</code>```

I believe that split method is good here but can’t figure the regexp required for this.

答:
Assuming "variable" is represented by one alphanumeric character or sequential sequence of multiple such characters, you should split by not-alphanumeric characters, i. e. [^\w]+, then collect result by iteration or filter:

```<code>Set<String> varSet = new HashSet<>(Arrays.asList(vars));
List<String> result = new ArrayList<>();
for (String s : f.split("[^\\w]+")) {
    if (varSet.contains(s)) {
        result.add(s);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parsing String by pattern of substrings

Body:
I need to parse a formula and get all the variables that were used. The list of variables is available. For example, the formula looks like this:

String f = "(Min(trees, round(Apples1+Pears1,1)==1&&universe==big)*number";

I know that possible variables are:

String[] vars = {"trees","rivers","Apples1","Pears1","Apricots2","universe","galaxy","big","number"};

I need to get the following array:

String[] varsInF = {"trees", "Apples1","Pears1", "universe", "big","number"};

I believe that split method is good here but can’t figure the regexp required for this.

Body:
Assuming "variable" is represented by one alphanumeric character or sequential sequence of multiple such characters, you should split by not-alphanumeric characters, i. e. [^\w]+, then collect result by iteration or filter:

Set<String> varSet = new HashSet<>(Arrays.asList(vars));
List<String> result = new ArrayList<>();
for (String s : f.split("[^\\w]+")) {
    if (varSet.contains(s)) {
        result.add(s);
    }
}


问:
How to trigger browser's find (ctrl+F) on button click.
That is when i click on a button
 it should fire browser's find event
 and browser's find pop up should appear. </p>

答:
You can set your button to call Javascripts window.find function. Works in Chrome and Firefox and possibly Edge.

Javascript

```<code>findString = function findText(text) {
  window.find(text);
  alert("String \x22" + text + "\x22 found? " + window.find(text));
}
</code>```

HTML

```<code><p>Apples, Bananas, and Oranges.</p>
<button type="button" onClick='findString("Apples")'>Search for Apples</button>
<button type="button" onClick='findString("Banana")'>Search for Banana</button>
<button type="button" onClick='findString("Borange")'>Search for Borange</button>
</code>```

Here is a website for reference.

https://developer.mozilla.org/en-US/docs/Web/API/Window/find

Body:
You can set your button to call Javascripts window.find function. Works in Chrome and Firefox and possibly Edge.

Javascript

findString = function findText(text) {
  window.find(text);
  alert("String \x22" + text + "\x22 found? " + window.find(text));
}

HTML

<p>Apples, Bananas, and Oranges.</p>
<button type="button" onClick='findString("Apples")'>Search for Apples</button>
<button type="button" onClick='findString("Banana")'>Search for Banana</button>
<button type="button" onClick='findString("Borange")'>Search for Borange</button>

Here is a website for reference.

https://developer.mozilla.org/en-US/docs/Web/API/Window/find


问:
How to create numerical indexed array to XML?
I am working on array to XML conversion using PHP. I am using the following code:

```<code>function array_to_xml($template_info, &$xml_template_info) {
            foreach($template_info as $key => $value) {
                if(is_array($value)) {
                    if(!is_numeric($key)){

                        $subnode = $xml_template_info->addChild("$key");

                        if(count($value) >1 && is_array($value)){
                            $jump = false;
                            $count = 1;
                            foreach($value as $k => $v) {
                                if(is_array($v)){
                                    if($count++ > 1)
                                        $subnode = $xml_template_info->addChild("$key");

                                    array_to_xml($v, $subnode);
                                    $jump = true;
                                }
                            }
                            if($jump) {
                                goto LE;
                            }
                            array_to_xml($value, $subnode);
                        }
                        else
                            array_to_xml($value, $subnode);
                    }
                    else{
                        array_to_xml($value, $xml_template_info);
                    }
                }
                else {
                    $xml_template_info->addChild("$key","$value");
                }

                LE: ;
            }
        }
</code>```

but the problem is I can't able to create numerical standard value for sub node which is having numerical array value,

I am trying to achieve the following method.

```<code>Array
(
    [DateTimeStamp] => 06/30/2017 08:11:23
    [Sender] => Array
        (
            [SenderID] => TRN
            [SenderName] => Transportation Reservation System,Inc.
        )

    [Recipient] => Array
        (
            [RecipientID] => DATA1
            [RecipientName] =>
        )
    [Payload] => Array
        (
            [RateProduct] => Array
                (
                    [0] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 13
                            [RentalLocationID] => 262
                            [RateCompanyID] => RCR
                            [TotalPricing] => Array
                            (
                                [RentalDays] => 1
                                [RateCharge] => 127.50
                            )
                            [Taxes] => Array
                                    (
                                        [Tax2Amount] => 154.04
                                        [Tax2Rate] => 0.13
                                    )
                            [0] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )

                              [1] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )
                       )
                    [1] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 13
                            [RentalLocationID] => 262
                            [RateCompanyID] => RCR
                            [TotalPricing] => Array
                            (
                                [RentalDays] => 1
                                [RateCharge] => 127.50
                            )
                            [Taxes] => Array
                                    (
                                        [Tax2Amount] => 154.04
                                        [Tax2Rate] => 0.13
                                    )
                            [0] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )

                              [1] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )
                       )
                 )
          )
)
</code>```

this array value need to be changed to the following format

```<code><?xml version="1.0" encoding="UTF-8"?>
<PRE>
    <TRNXML Version="1.0.0" TimeZone="ET" />
    <DateTimeStamp>06/30/2017 04:36:04</DateTimeStamp>
    <Sender>
        <SenderID>TRN</SenderID>
        <SenderName>Transportation Reservation System,Inc.</SenderName>
    </Sender>
    <Recipient>
        <RecipientID>ROUTES</RecipientID>
        <RecipientName />
    </Recipient>
    <Payload>
        <RateProduct>
            <RateVendor>FCAR</RateVendor>
            <RateID />
            <RentalLocationID>FCAR</RentalLocationID>
            <RateCompanyID>FCAR</RateCompanyID>
            <TotalPricing>
                <RentalDays>FCAR</RentalDays>
                <RateCharge>FCAR</RateCharge>
            </TotalPricing>
            <Taxes>
                <Tax2Amount>FCAR</Tax2Amount>
                <Tax2Rate>FCAR</Tax2Rate>
            </Taxes>
            ///this has to come in following format
            <DailyExtra>
                <ExtraCode>FCAR</ExtraCode>
                <ExtraDesc>FCAR</ExtraDesc>
            </DailyExtra>
            <DailyExtra>
                <ExtraCode>FCAR</ExtraCode>
                <ExtraDesc>FCAR</ExtraDesc>
            </DailyExtra>
        </RateProduct>
    </Payload>
</PRE>
</code>```

How to make it work in the XML code?

答:
check it:

```<code>#declare
/**
 * $array - IN array
 * $dom - DOMDocument object
 * $node - DomElement
 *
 * */
function array_to_xml($array, &$dom, &$node){
    foreach($array as $key=>$value){
        if( is_array( $value ) ){
            if ( is_numeric($key) ){
                array_to_xml($value, $dom, $node);
            }
            elseif( is_string($key) ){
                $el = $dom->createElement($key);
                array_to_xml($value, $dom, $el);
                $node->appendChild($el);
            }
        }
        elseif ( empty($value) ){
            $el = $dom->createElement($key);
            $node->appendChild($el);
        }
        elseif( is_string($key) && is_string($value)){
            $el = $dom->createElement($key, $value);
            $node->appendChild($el);
        }
    }
}

#implementation

    $doc = new DOMDocument('1.0', 'UTF-8');

    $doc->formatOutput = true;

    $pre = $doc->createElement('PRE');

    #<TRNXML Version="1.0.0" TimeZone="ET" />
    $TRNXML = $doc->createElement('TRNXML');
    $TRNXML->setAttribute('Version', '1.0.0');
    $TRNXML->setAttribute('TimeZone', 'ET');
    $pre->appendChild($TRNXML);

    $array = array (
            'DateTimeStamp' => '06/30/2017 08:11:23',
            'Sender' => array   (
                    'SenderID' => 'TRN',
                    'SenderName' => 'Transportation Reservation System,Inc.'),
            'Recipient' => array(
                    'RecipientID' => 'DATA1',
                    'RecipientName' => ''   ),
            'Payload' => array (
                    'RateProduct' => array(
                            0 => array(
                                    'RateVendor' => 42074,
                                    'RateId' => 13,
                                    'RentalLocationID' => 262,
                                    'RateCompanyID' => 'RCR',
                                    'TotalPricing' => array(
                                            'RentalDays' => 1,
                                            'RateCharge' => 127.50
                                            ),
                                    'Taxes' => array(
                                            'Tax2Amount' => 154.04,
                                            'Tax2Rate' => 0.13
                                            ),
                                    0 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                          ),
                                    1 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                            )
                                    ),
                            1 => array(
                                    'RateVendor' => 42074,
                                    'RateId' => 13,
                                    'RentalLocationID' => 262,
                                    'RateCompanyID' => 'RCR',
                                    'TotalPricing' => array(
                                            'RentalDays' => 1,
                                            'RateCharge' => 127.50
                                            ),
                                    'Taxes' => array(
                                            'Tax2Amount' => 154.04,
                                            'Tax2Rate' => 0.13
                                            ),
                                    0 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )

                                            ),

                                    1 => array(
                                            'DailyExtra' => array (
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                            )
                                    )
                            )
                    )
            );

    array_to_xml($array, $doc, $pre);

    $doc->appendChild($pre);

echo $doc->saveXML() . "\n";
</code>```

Body:
I am working on array to XML conversion using PHP. I am using the following code:

function array_to_xml($template_info, &$xml_template_info) {
            foreach($template_info as $key => $value) {
                if(is_array($value)) {
                    if(!is_numeric($key)){

                        $subnode = $xml_template_info->addChild("$key");

                        if(count($value) >1 && is_array($value)){
                            $jump = false;
                            $count = 1;
                            foreach($value as $k => $v) {
                                if(is_array($v)){
                                    if($count++ > 1)
                                        $subnode = $xml_template_info->addChild("$key");

                                    array_to_xml($v, $subnode);
                                    $jump = true;
                                }
                            }
                            if($jump) {
                                goto LE;
                            }
                            array_to_xml($value, $subnode);
                        }
                        else
                            array_to_xml($value, $subnode);
                    }
                    else{
                        array_to_xml($value, $xml_template_info);
                    }
                }
                else {
                    $xml_template_info->addChild("$key","$value");
                }

                LE: ;
            }
        }

but the problem is I can't able to create numerical standard value for sub node which is having numerical array value,

I am trying to achieve the following method.

Array
(
    [DateTimeStamp] => 06/30/2017 08:11:23
    [Sender] => Array
        (
            [SenderID] => TRN
            [SenderName] => Transportation Reservation System,Inc.
        )

    [Recipient] => Array
        (
            [RecipientID] => DATA1
            [RecipientName] =>
        )
    [Payload] => Array
        (
            [RateProduct] => Array
                (
                    [0] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 13
                            [RentalLocationID] => 262
                            [RateCompanyID] => RCR
                            [TotalPricing] => Array
                            (
                                [RentalDays] => 1
                                [RateCharge] => 127.50
                            )
                            [Taxes] => Array
                                    (
                                        [Tax2Amount] => 154.04
                                        [Tax2Rate] => 0.13
                                    )
                            [0] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )

                              [1] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )
                       )
                    [1] => Array
                        (
                            [RateVendor] => 42074
                            [RateId] => 13
                            [RentalLocationID] => 262
                            [RateCompanyID] => RCR
                            [TotalPricing] => Array
                            (
                                [RentalDays] => 1
                                [RateCharge] => 127.50
                            )
                            [Taxes] => Array
                                    (
                                        [Tax2Amount] => 154.04
                                        [Tax2Rate] => 0.13
                                    )
                            [0] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )

                              [1] => Array
                                    (
                                        [DailyExtra] => Array
                                            (
                                                [ExtraCode] => ERF
                                                [ExtraDesc] => ENERGY RECOVERY FEES
                                            )

                                    )
                       )
                 )
          )
)

this array value need to be changed to the following format

<?xml version="1.0" encoding="UTF-8"?>

    <TRNXML Version="1.0.0" TimeZone="ET" />
    <DateTimeStamp>06/30/2017 04:36:04</DateTimeStamp>
    <Sender>
        <SenderID>TRN</SenderID>
        <SenderName>Transportation Reservation System,Inc.</SenderName>
    </Sender>
    <Recipient>
        <RecipientID>ROUTES</RecipientID>
        <RecipientName />
    </Recipient>
    <Payload>
        <RateProduct>
            <RateVendor>FCAR</RateVendor>
            <RateID />
            <RentalLocationID>FCAR</RentalLocationID>
            <RateCompanyID>FCAR</RateCompanyID>
            <TotalPricing>
                <RentalDays>FCAR</RentalDays>
                <RateCharge>FCAR</RateCharge>
            </TotalPricing>
            <Taxes>
                <Tax2Amount>FCAR</Tax2Amount>
                <Tax2Rate>FCAR</Tax2Rate>
            </Taxes>
            ///this has to come in following format
            <DailyExtra>
                <ExtraCode>FCAR</ExtraCode>
                <ExtraDesc>FCAR</ExtraDesc>
            </DailyExtra>
            <DailyExtra>
                <ExtraCode>FCAR</ExtraCode>
                <ExtraDesc>FCAR</ExtraDesc>
            </DailyExtra>
        </RateProduct>
    </Payload>

How to make it work in the XML code?

Body:
check it:

#declare
/**
 * $array - IN array
 * $dom - DOMDocument object
 * $node - DomElement
 *
 * */
function array_to_xml($array, &$dom, &$node){
    foreach($array as $key=>$value){
        if( is_array( $value ) ){
            if ( is_numeric($key) ){
                array_to_xml($value, $dom, $node);
            }
            elseif( is_string($key) ){
                $el = $dom->createElement($key);
                array_to_xml($value, $dom, $el);
                $node->appendChild($el);
            }
        }
        elseif ( empty($value) ){
            $el = $dom->createElement($key);
            $node->appendChild($el);
        }
        elseif( is_string($key) && is_string($value)){
            $el = $dom->createElement($key, $value);
            $node->appendChild($el);
        }
    }
}

#implementation

    $doc = new DOMDocument('1.0', 'UTF-8');

    $doc->formatOutput = true;

    $pre = $doc->createElement('PRE');

    #<TRNXML Version="1.0.0" TimeZone="ET" />
    $TRNXML = $doc->createElement('TRNXML');
    $TRNXML->setAttribute('Version', '1.0.0');
    $TRNXML->setAttribute('TimeZone', 'ET');
    $pre->appendChild($TRNXML);

    $array = array (
            'DateTimeStamp' => '06/30/2017 08:11:23',
            'Sender' => array   (
                    'SenderID' => 'TRN',
                    'SenderName' => 'Transportation Reservation System,Inc.'),
            'Recipient' => array(
                    'RecipientID' => 'DATA1',
                    'RecipientName' => ''   ),
            'Payload' => array (
                    'RateProduct' => array(
                            0 => array(
                                    'RateVendor' => 42074,
                                    'RateId' => 13,
                                    'RentalLocationID' => 262,
                                    'RateCompanyID' => 'RCR',
                                    'TotalPricing' => array(
                                            'RentalDays' => 1,
                                            'RateCharge' => 127.50
                                            ),
                                    'Taxes' => array(
                                            'Tax2Amount' => 154.04,
                                            'Tax2Rate' => 0.13
                                            ),
                                    0 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                          ),
                                    1 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                            )
                                    ),
                            1 => array(
                                    'RateVendor' => 42074,
                                    'RateId' => 13,
                                    'RentalLocationID' => 262,
                                    'RateCompanyID' => 'RCR',
                                    'TotalPricing' => array(
                                            'RentalDays' => 1,
                                            'RateCharge' => 127.50
                                            ),
                                    'Taxes' => array(
                                            'Tax2Amount' => 154.04,
                                            'Tax2Rate' => 0.13
                                            ),
                                    0 => array(
                                            'DailyExtra' => array(
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )

                                            ),

                                    1 => array(
                                            'DailyExtra' => array (
                                                    'ExtraCode' => 'ERF',
                                                    'ExtraDesc' => 'ENERGY RECOVERY FEES'
                                                    )
                                            )
                                    )
                            )
                    )
            );

    array_to_xml($array, $doc, $pre);

    $doc->appendChild($pre);

echo $doc->saveXML() . "\n";


问:
Joining CSV fields
I need to convert

```<code>Name | Org
a    | 5
a    | 6
b    | 5
c    | 7
</code>```

into

```<code>Name | Org
a    | 5,6
b    |  5
c    |  7
</code>```

my first attempt was with this code

```<code>    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1
</code>```

which just ends up with the result

```<code>Name | Org
a    |
b    |
c    |
</code>```

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

答:
The solution using itertools.groupby() function:

```<code>import csv, itertools

with open('yourfile.csv', 'r') as f:
    reader = csv.reader(f, delimiter='|', skipinitialspace=True)
    head = next(reader)   # header line
    items = [list(g) for k,g in itertools.groupby(sorted(reader), key=lambda x: x[0])]

    fmt = '{0[0]:<5} | {0[1]:^5}'  # format spec
    print(fmt.format(head))
    for item in items:
        print(fmt.format([item[0][0], ','.join(i[1] for i in item)] if len(item) > 1 else item[0]))
</code>```

The output:

```<code>Name  |  Org
a     |  5,6
b     |   5
c     |   7
</code>```

Title: Joining CSV fields

Body:
I need to convert

Name | Org
a    | 5
a    | 6
b    | 5
c    | 7

into

Name | Org
a    | 5,6
b    |  5
c    |  7

my first attempt was with this code

    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1

which just ends up with the result

Name | Org
a    |
b    |
c    |

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

Body:
The solution using itertools.groupby() function:

import csv, itertools

with open('yourfile.csv', 'r') as f:
    reader = csv.reader(f, delimiter='|', skipinitialspace=True)
    head = next(reader)   # header line
    items = [list(g) for k,g in itertools.groupby(sorted(reader), key=lambda x: x[0])]

    fmt = '{0[0]:<5} | {0[1]:^5}'  # format spec
    print(fmt.format(head))
    for item in items:
        print(fmt.format([item[0][0], ','.join(i[1] for i in item)] if len(item) > 1 else item[0]))

The output:

Name  |  Org
a     |  5,6
b     |   5
c     |   7


问:
Does overriding in swift replace or modify the current implementation of the properties and methods of the superclass? Swift
Does overriding in swift replace or modify the current implementation of the properties and methods of the superclass? After experimenting with code I observed that overriden methods in swift do not modify the existing methods in the superclass. I'm assuming it's similar to dynamic binding in java. computed properties that override stored properties on the other hand seem to modify the property of the superclass.From the code below you can see that the new value 87 is printed instead of 0.0 even though super is called, while this is not true when calling methods. I wanted to confirm if my observation is true or if there is another reason behind this.

```<code>class Vehicle {
var currentSpeed: Double = 0.0
var cuc: Double = 0.0

var description: String {
    return "traveling at \(currentSpeed) miles per hour"
}

func makeNoise() {
    // do nothing - an arbitrary vehicle doesn't necessarily
   // make a noise
}
}

class Car: Vehicle {
var gear = 1
   override var currentSpeed: Double {
    didSet {
       print(super.currentSpeed)
    }
}
//override var currentSpeed: Double = 56
override var description: String {
    return super.description + " in gear \(gear)"
}
}
var car = Car()
car.currentSpeed = 87
print(car.description)
</code>```

This other segment of code does the opposite and produces 0 instead of 90 .

```<code>override var currentSpeed: Double {
set {
    super.cuc = 90
}
    get {
       return super.cuc
    }
    }
print(car.cuc)
</code>```

答:
It does not. Consider when the statement would be true. I don't see any reason why it should work as you describe. You took the bad example in variables. For instance take functions. (see the move() function)

```<code>class Vehicle {
var currentSpeed: Double = 0.0

var description: String {
    return "traveling at \(currentSpeed) miles per hour"
}

func move() {

    // Move, every vehicle should really move...

}
}

class Car: Vehicle {
var gear = 1
   override var currentSpeed: Double {
    didSet {
       print(super.currentSpeed)
    }
}

override func move(){
       //Call super.move to call method from superclass for moving (default implemented behavior)
       super.move()
    //Car should make noise or start spinning wheels (lol funny example)
       startSpinningWheels()
       makeNoise()
}

private func makeNoise(){
//Make noise...

}

private func startSpinningWheels(){
//Start spinning wheels on vehicle...
}

//override var currentSpeed: Double = 56
override var description: String {
    return super.description + " in gear \(gear)"
}
}
</code>```

Okay now. Wouldn't be strange if the method move() would modify the superclass behaviour? Because you know, then for example Plane would need to start spinning wheels, which is really obvious :D So the answer is BIG NO, that woud be fail to inheritance at all. You should read the whole idea about inheritance...

The thing is you can cast your current instance of object to superclass object (set Car as? Vehicle) and modify only the properties that are not declared in Car object...

let myCar = Car()

//No error here
let carAsVehicle = myCar as Vehicle

//neither here.
print(carAsVehicle.currentSpeed)

See inheritance in Apple docs:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html

wish happy coding and if you have any questions feel free to ask!

Body:
Does overriding in swift replace or modify the current implementation of the properties and methods of the superclass? After experimenting with code I observed that overriden methods in swift do not modify the existing methods in the superclass. I'm assuming it's similar to dynamic binding in java. computed properties that override stored properties on the other hand seem to modify the property of the superclass.From the code below you can see that the new value 87 is printed instead of 0.0 even though super is called, while this is not true when calling methods. I wanted to confirm if my observation is true or if there is another reason behind this.

class Vehicle {
var currentSpeed: Double = 0.0
var cuc: Double = 0.0

var description: String {
    return "traveling at \(currentSpeed) miles per hour"
}

func makeNoise() {
    // do nothing - an arbitrary vehicle doesn't necessarily
   // make a noise
}
}

class Car: Vehicle {
var gear = 1
   override var currentSpeed: Double {
    didSet {
       print(super.currentSpeed)
    }
}
//override var currentSpeed: Double = 56
override var description: String {
    return super.description + " in gear \(gear)"
}
}
var car = Car()
car.currentSpeed = 87
print(car.description)

This other segment of code does the opposite and produces 0 instead of 90 .

override var currentSpeed: Double {
set {
    super.cuc = 90
}
    get {
       return super.cuc
    }
    }
print(car.cuc)

Body:
It does not. Consider when the statement would be true. I don't see any reason why it should work as you describe. You took the bad example in variables. For instance take functions. (see the move() function)

class Vehicle {
var currentSpeed: Double = 0.0

var description: String {
    return "traveling at \(currentSpeed) miles per hour"
}

func move() {

    // Move, every vehicle should really move...

}
}

class Car: Vehicle {
var gear = 1
   override var currentSpeed: Double {
    didSet {
       print(super.currentSpeed)
    }
}

override func move(){
       //Call super.move to call method from superclass for moving (default implemented behavior)
       super.move()
    //Car should make noise or start spinning wheels (lol funny example)
       startSpinningWheels()
       makeNoise()
}

private func makeNoise(){
//Make noise...

}

private func startSpinningWheels(){
//Start spinning wheels on vehicle...
}

//override var currentSpeed: Double = 56
override var description: String {
    return super.description + " in gear \(gear)"
}
}

Okay now. Wouldn't be strange if the method move() would modify the superclass behaviour? Because you know, then for example Plane would need to start spinning wheels, which is really obvious :D So the answer is BIG NO, that woud be fail to inheritance at all. You should read the whole idea about inheritance...

The thing is you can cast your current instance of object to superclass object (set Car as? Vehicle) and modify only the properties that are not declared in Car object...

let myCar = Car()

//No error here
let carAsVehicle = myCar as Vehicle

//neither here.
print(carAsVehicle.currentSpeed)

See inheritance in Apple docs:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html

wish happy coding and if you have any questions feel free to ask!


问:
Is there a better way to set a gcloud project in a directory?
I work on multiple appengine projects in any given week. i.e. assume multiple clients. Earlier I could set application in app.yaml. So whenever I did appcfg.py update.... it would ensure deployment to the right project.

When deploying, the application variable throws an error with gcloud deploy. I had to use
gcloud app deploy --project [YOUR_PROJECT_ID]. So what used to be a directory level setting for a project, is now going into our build tooling. And missing out that simple detail can push a project code to the wrong customer.
i.e. if I did gcloud config set project proj1 and then somehow did a gcloud app deploy in proj2, it would deploy to proj1. Production deployments are done after detailed verification on the build tools and hence it is less of an issue there because we still use the --project flag.

But its hard to do similar stuff on the development environment. dev_appserver.py doesn't have a --project flag.
When starting dev_appserver.py I've to do gcloud config set project <project-id> before I start the server. This is important when I using stuff like PubSub or GCS (in dev topics or dev buckets).

Unfortunately, missing out a simple configuration like setting a project ID in a dev environment can result into uploading blobs/messages/etc into the wrong dev gcs bucket or wrong dev pubsub topic (not using emulators). And this has happened quite a few times especially when starting new projects.

I find the above solutions as hackish-workarounds. Is there a good way to ensure that we do not deploy or develop in a wrong project when working from a certain directory?

答:
TL;DR - Not supported based on the current working directory, but there are workarounds.

Available workarounds

gcloud does not directly let you set up a configuration per working directory. Instead, you could use one of these 3 options to achieve something similar:

Specify --project, --region, --zone or the config of interest per command. This is painful but gets the job done.

Specify a different gcloud configuration directory per command (gcloud uses ~/.config/gcloud on *nix by default):

```<code>CLOUDSDK_CONFIG=/path/to/config/dir1 gcloud COMMAND
CLOUDSDK_CONFIG=/path/to/config/dir2 gcloud COMMAND
</code>```

Create multiple configurations and switch between them as needed.

```<code>gcloud config configurations activate config-1 && gcloud COMMAND
</code>```

Shell helpers

As all of the above options are ways to customize on the command line, aliases and/or functions in your favorite shell will also help make things easier.

For example in bash, option 2 can be implemented as follows:

```<code>function gcloud_proj1() {
  CLOUDSDK_CONFIG=CLOUDSDK_CONFIG=/path/to/config/dir1 $@
}

function gcloud_proj2() {
  CLOUDSDK_CONFIG=CLOUDSDK_CONFIG=/path/to/config/dir2 $@
}

gcloud_proj1 COMMAND
gcloud_proj2 COMMAND
</code>```

Body:
TL;DR - Not supported based on the current working directory, but there are workarounds.

Available workarounds

gcloud does not directly let you set up a configuration per working directory. Instead, you could use one of these 3 options to achieve something similar:

Specify --project, --region, --zone or the config of interest per command. This is painful but gets the job done.

Specify a different gcloud configuration directory per command (gcloud uses ~/.config/gcloud on *nix by default):

CLOUDSDK_CONFIG=/path/to/config/dir1 gcloud COMMAND
CLOUDSDK_CONFIG=/path/to/config/dir2 gcloud COMMAND

Create multiple configurations and switch between them as needed.

gcloud config configurations activate config-1 && gcloud COMMAND

Shell helpers

As all of the above options are ways to customize on the command line, aliases and/or functions in your favorite shell will also help make things easier.

For example in bash, option 2 can be implemented as follows:

function gcloud_proj1() {
  CLOUDSDK_CONFIG=CLOUDSDK_CONFIG=/path/to/config/dir1 $@
}

function gcloud_proj2() {
  CLOUDSDK_CONFIG=CLOUDSDK_CONFIG=/path/to/config/dir2 $@
}

gcloud_proj1 COMMAND
gcloud_proj2 COMMAND


问:
Java Swing - How to sound beep before any JOptionPane?
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

```<code>Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );
</code>```

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?

答:
void showMessageDialog(Component pC, Object m, String t, int mT)
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( pC, m,t,mT);
}

ContentLicense: CC BY-SA 2.5

Body:
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?


问:
ROBLOX.Lua Infinite Yeild Possible Fix?
I am making this tool Wait For "PlaceEvent", but I keep getting this error:

```<code>21:58:52.024 - Infinite yield possible on 'ReplicatedStorage:WaitForChild("PlaceEvent")'
21:58:52.026 - Stack Begin
21:58:52.026 - Script 'Players.rohanskywalker.Backpack.Grass.Main', Line 7
21:58:52.026 - Stack End
</code>```

Here is the script:

```<code>-- Local Script
local tool = script.Parent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local clickEvent = tool.ClickEvent
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlaceEvent = ReplicatedStorage:WaitForChild("PlaceEvent")

local function onActivate()
local clickLocation = mouse.hit
clickEvent:FireServer(clickLocation)
PlaceEvent:FireServer()
end

tool.Activated:connect(onActivate)
</code>```

答:
The output you are getting is not an error, but a warning. It is informing you that it is taking a long time for it to find "PlaceEvent" in ReplicatedStorage. There could be a couple causes for this.

Object isn't created yet

If you are creating the object in another script or moving the object into ReplicatedStorage, check that it doesn't have a separate error, causing it to abort before creating 'PlaceEvent'

Object is named Improperly

If it is being created properly, or it is in ReplicatedStorage from the beginning, check the name to make sure that it is EXACTLY 'PlaceEvent', otherwise your script will yield forever, never finding 'PlaceEvent'.

Those are the two possibilities for that warning, but remember it's only a warning and as soon as it finds that object the script will resume.

Title: ROBLOX.Lua Infinite Yeild Possible Fix?

Body:
I am making this tool Wait For "PlaceEvent", but I keep getting this error:

21:58:52.024 - Infinite yield possible on 'ReplicatedStorage:WaitForChild("PlaceEvent")'
21:58:52.026 - Stack Begin
21:58:52.026 - Script 'Players.rohanskywalker.Backpack.Grass.Main', Line 7
21:58:52.026 - Stack End

Here is the script:

-- Local Script
local tool = script.Parent
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local clickEvent = tool.ClickEvent
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlaceEvent = ReplicatedStorage:WaitForChild("PlaceEvent")

local function onActivate()
local clickLocation = mouse.hit
clickEvent:FireServer(clickLocation)
PlaceEvent:FireServer()
end

tool.Activated:connect(onActivate)


问:
how to setup Thingworx 7.0 for high availability?
I am currently trying to instantiate 2 or more instances of thingworx on a single machine for trying Thingworx for high availability.Can you specify the different software along with their version that are required to setup  Thingworx 7.0 for high availability?.Are their any tutorials that can help me with the setup?</p>

答:
To decrease the duration of outage for critical internet of things systems ,you can configure thingwrox core for high availability .This requires a complex setup which you can configure by this guide
http://support.ptc.com/WCMS/files/171336/en/ThingWorx_7.0_High_Availability_Administrators_Guide.pdf</p>


问:
Regular expression - text between multiple occurences of the same pattern
I need to parse a large number of files and process some content based on certain tokens. In order to do this I have to take each token and the text after it, until the next token (with extra new lines).

```<code>A ---
some text of many lines
B ---

other text with some lines

C ---
more text and tokens and text
</code>```

I've been using regex101 and made it up to splitting them

```<code>(?<token>^([a-zA-Z].--.*))|(?<content>.*)
</code>```

However, I can't get the second match in a single group.
The desired result is to get the token and text following pairs.

Is this possible to accomplish this using a single regex expression ? and how ?

Thanks

答:
Let's assume your token pattern is correct and matches all you need. Then, the content is everything after the token pattern up to the first occurrence of the token pattern, that is ^[a-zA-Z].--.*: start of the line (^), an ASCII letter ([a-zA-Z]), any char but a newline (.), two hyphens (--) and then any 0+ chars, as many as possible, up to the end of the line (note, in .NET regex, . also matches CR "\r" symbol).

If your files are not that big, you could use

```<code>@"(?m)^(?<token>[a-zA-Z].--.*)(?<content>(?:\r?\n(?![a-zA-Z].---).*)*)"
</code>```

See the regex demo. This regex accounts for the cases when the token has no content, and also excludes matching the token in the middle of some content.

From the structural point of view, the pattern is equal to (?m)^(?<token>[a-zA-Z].--.*)(?<content>(?s:.*?))(?=^[a-zA-Z].---|\z), but is a more efficient version, since the lazy dot matching pattern constrained with a lookahead having two alternatives makes the regex engine work hard when matching each char in the input string. An unrolled pattern like the one I suggest will grab whole lines that do not start with the token at once, and thus it will work much quicker.

Details:

(?m) - same as RegexOptions.Multiline, the ^ matches line start now (and $ matches the end of the line, not whole string)

^ - start of the line

(?<token>[a-zA-Z].--.*) - "token" group:

[a-zA-Z] - an ASCII letter

. - any char but a newline (also, matches CR, use [^\n\r] to only match a char that is not a part of the CRLF ending)

-- - two hyphens

.* - any 0+ chars other than a newline, as many as possible, up to the end of the line (note the . matches CR in .NET regex)

(?<content>(?:\r?\n(?![a-zA-Z].---).*)*) - "content" group:

(?:\r?\n(?![a-zA-Z].---).*)* - zero or more sequences of:

\r?\n(?![a-zA-Z].---)  - a CRLF or an LF line end not followed with the token pattern

.* - any 0+ chars other than a newline, as many as possible, up to the end of the line

C# demo (note I am trimming both the group values to get rid of leading/trailing whitespace):

```<code>var s = "A ---\r\nsome text of many lines\r\nB ---\r\n\r\nother text with some lines\r\nand text and\r\ntext \r\n\r\nC --- \r\nmore text and tokens and text\r\n\r\nQQ--- \r\n\r\nmore text more text\r\n\r\nHH---\r\nJJ---\r\n";
var pat = @"^(?<token>[a-zA-Z].--.*)(?<content>(?:\r?\n(?![a-zA-Z].---).*)*)";
var result = Regex.Matches(s, pat, RegexOptions.Multiline)
        .Cast<Match>()
        .Select(m => new[] {m.Groups["token"].Value.Trim(), m.Groups["content"].Value.Trim()});
foreach (var pair in result)
    Console.WriteLine($"--- New match ---\nToken: {pair[0]}\nContent: {pair[1]}");
</code>```

Output:

```<code>--- New match ---
Token: A ---
Content: some text of many lines
--- New match ---
Token: B ---
Content: other text with some lines
and text and
text
--- New match ---
Token: C ---
Content: more text and tokens and text
--- New match ---
Token: QQ---
Content: more text more text
--- New match ---
Token: HH---
Content:
--- New match ---
Token: JJ---
Content:
</code>```

Body:
I need to parse a large number of files and process some content based on certain tokens. In order to do this I have to take each token and the text after it, until the next token (with extra new lines).

A ---
some text of many lines
B ---

other text with some lines

C ---
more text and tokens and text

I've been using regex101 and made it up to splitting them

(?<token>^([a-zA-Z].--.*))|(?<content>.*)

However, I can't get the second match in a single group.
The desired result is to get the token and text following pairs.

Is this possible to accomplish this using a single regex expression ? and how ?

Thanks

Body:
Let's assume your token pattern is correct and matches all you need. Then, the content is everything after the token pattern up to the first occurrence of the token pattern, that is ^[a-zA-Z].--.*: start of the line (^), an ASCII letter ([a-zA-Z]), any char but a newline (.), two hyphens (--) and then any 0+ chars, as many as possible, up to the end of the line (note, in .NET regex, . also matches CR "\r" symbol).

If your files are not that big, you could use

@"(?m)^(?<token>[a-zA-Z].--.*)(?<content>(?:\r?\n(?![a-zA-Z].---).*)*)"

See the regex demo. This regex accounts for the cases when the token has no content, and also excludes matching the token in the middle of some content.

From the structural point of view, the pattern is equal to (?m)^(?<token>[a-zA-Z].--.*)(?<content>(?s:.*?))(?=^[a-zA-Z].---|\z), but is a more efficient version, since the lazy dot matching pattern constrained with a lookahead having two alternatives makes the regex engine work hard when matching each char in the input string. An unrolled pattern like the one I suggest will grab whole lines that do not start with the token at once, and thus it will work much quicker.

Details:

(?m) - same as RegexOptions.Multiline, the ^ matches line start now (and $ matches the end of the line, not whole string)

^ - start of the line

(?<token>[a-zA-Z].--.*) - "token" group:

[a-zA-Z] - an ASCII letter

. - any char but a newline (also, matches CR, use [^\n\r] to only match a char that is not a part of the CRLF ending)

-- - two hyphens

.* - any 0+ chars other than a newline, as many as possible, up to the end of the line (note the . matches CR in .NET regex)

(?<content>(?:\r?\n(?![a-zA-Z].---).*)*) - "content" group:

(?:\r?\n(?![a-zA-Z].---).*)* - zero or more sequences of:

\r?\n(?![a-zA-Z].---)  - a CRLF or an LF line end not followed with the token pattern

.* - any 0+ chars other than a newline, as many as possible, up to the end of the line

C# demo (note I am trimming both the group values to get rid of leading/trailing whitespace):

var s = "A ---\r\nsome text of many lines\r\nB ---\r\n\r\nother text with some lines\r\nand text and\r\ntext \r\n\r\nC --- \r\nmore text and tokens and text\r\n\r\nQQ--- \r\n\r\nmore text more text\r\n\r\nHH---\r\nJJ---\r\n";
var pat = @"^(?<token>[a-zA-Z].--.*)(?<content>(?:\r?\n(?![a-zA-Z].---).*)*)";
var result = Regex.Matches(s, pat, RegexOptions.Multiline)
        .Cast<Match>()
        .Select(m => new[] {m.Groups["token"].Value.Trim(), m.Groups["content"].Value.Trim()});
foreach (var pair in result)
    Console.WriteLine($"--- New match ---\nToken: {pair[0]}\nContent: {pair[1]}");

Output:

--- New match ---
Token: A ---
Content: some text of many lines
--- New match ---
Token: B ---
Content: other text with some lines
and text and
text
--- New match ---
Token: C ---
Content: more text and tokens and text
--- New match ---
Token: QQ---
Content: more text more text
--- New match ---
Token: HH---
Content:
--- New match ---
Token: JJ---
Content:


问:
IBM BPM create a Task when action is called
How we can create a manuall Task (adhoc Task) and assign it to a User when some actions are triggered (e.g. when the Service is called)?</p>

答:
Ad-hoc tasks run in the context of a BPD.  What is the connection between the service you are calling and the Ad-Hoc task?  Generally the ad-hoc events are meant to be triggered by a participant in the process selecting the item they want to launch.

If what you want is that an external system triggers an event in a running instance when certain things happen you might want to look at Intermediate Message Events (IMEs).  To really provide the correct full answer we likely need to have a better understanding of the underlying use case in order to guide you well.


问:
before_save except on new record if field value changes
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

```<code>  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

and I'm pretty sure this works...

```<code>  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

答:
You can use multiple conditions in your callback, like this:

```<code>before_save :reset_confirmation, if: :email_changed?, unless: :new_record?

def reset_confirmation
  self.confirmed_at = nil
  self.confirmation_sent_at = nil
end
</code>```

Or, you could add another method to check both conditions, for example:

```<code>before_save :reset_confirmation, if: :email_changed_and_its_not_new_record?

def reset_confirmation
  self.confirmed_at = nil
  self.confirmation_sent_at = nil
end

def email_changed_and_its_not_new_record?
  email_changed? && !new_record?
end
</code>```

You can find more information for conditional callbacks here.

Body:
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

and I'm pretty sure this works...

  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

Body:
You can use multiple conditions in your callback, like this:

before_save :reset_confirmation, if: :email_changed?, unless: :new_record?

def reset_confirmation
  self.confirmed_at = nil
  self.confirmation_sent_at = nil
end

Or, you could add another method to check both conditions, for example:

before_save :reset_confirmation, if: :email_changed_and_its_not_new_record?

def reset_confirmation
  self.confirmed_at = nil
  self.confirmation_sent_at = nil
end

def email_changed_and_its_not_new_record?
  email_changed? && !new_record?
end

You can find more information for conditional callbacks here.


问:
"var d = document;" Is it really useful?
I regularly see JavaScript code with variables like this:

```<code>var w = window,
    d = document,
    e = d.documentElement,
    g = d.body;

w.addEventListener('resize', function () {
    ...
    d.querySelectorAll(...);
    ...
});
</code>```

I just wonder if there is an interest in using these kinds of variables? (Other than decreasing the amount of code if there are many calls to "document" or "window")
I think the answer is no, but just in case ...

答:
The answer is yes and no. The way you are using them, no, there is no benefit because your code doesn't make use of g or e.

Your code makes these variables global and globals should be avoided. We can do this by wrapping our code in an Immediately Invoked Function Expression (IIFE) which creates a wrapper scope around your variables. But, because there is now a layer of indirection, references to elements in a higher scope will have to be resolved by going up the "scope chain" to find their definitions.

If you were to pass references to your global (or higher scoped) objects into the smaller scope, you can increase performance slightly because you will have local references to higher scoped objects and avoid having to go up the scope chain. So, if you did this:

```<code>(function(w, d){
  // Within this function w and d are local references to global objects
  w.addEventListener('resize', function () {
    ...
    d.querySelectorAll(...);
    ...
  });

}(window, document));
</code>```

then, having these declarations (actually arguments here) would make sense.

Additionally, any time you have to "resolve" an object reference, the less steps you take to resolve them, the better the performance, so while:

```<code>var w = window;
var d = document;
</code>```

aren't particularly useful since both are always globally available, these

```<code>var g = document.body;
var e = document.documentElement;
</code>```

are useful because you do have to look up the object stored in the body and documentElement properties and you've taken the "hit" in resolving the body and documentElement DOM objects just once, but later you can directly access them without having to resolve them again and again.

Body:
I regularly see JavaScript code with variables like this:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.body;

w.addEventListener('resize', function () {
    ...
    d.querySelectorAll(...);
    ...
});

I just wonder if there is an interest in using these kinds of variables? (Other than decreasing the amount of code if there are many calls to "document" or "window")
I think the answer is no, but just in case ...

Body:
The answer is yes and no. The way you are using them, no, there is no benefit because your code doesn't make use of g or e.

Your code makes these variables global and globals should be avoided. We can do this by wrapping our code in an Immediately Invoked Function Expression (IIFE) which creates a wrapper scope around your variables. But, because there is now a layer of indirection, references to elements in a higher scope will have to be resolved by going up the "scope chain" to find their definitions.

If you were to pass references to your global (or higher scoped) objects into the smaller scope, you can increase performance slightly because you will have local references to higher scoped objects and avoid having to go up the scope chain. So, if you did this:

(function(w, d){
  // Within this function w and d are local references to global objects
  w.addEventListener('resize', function () {
    ...
    d.querySelectorAll(...);
    ...
  });

}(window, document));

then, having these declarations (actually arguments here) would make sense.

Additionally, any time you have to "resolve" an object reference, the less steps you take to resolve them, the better the performance, so while:

var w = window;
var d = document;

aren't particularly useful since both are always globally available, these

var g = document.body;
var e = document.documentElement;

are useful because you do have to look up the object stored in the body and documentElement properties and you've taken the "hit" in resolving the body and documentElement DOM objects just once, but later you can directly access them without having to resolve them again and again.


答:
Yes it is useful, when you write var d=document, you are storing the document inside this variable which makes it easier if you want to use this variable with a
method

Example:

```<code>var d = new Date()
document.write(d.getHours())
</code>```

Here you store the new Date() inside the d variable that way it will be easier to use it somewhere else.

Title: "var d = document;" Is it really useful?

Body:
Yes it is useful, when you write var d=document, you are storing the document inside this variable which makes it easier if you want to use this variable with a
method

Example:

var d = new Date()
document.write(d.getHours())

Here you store the new Date() inside the d variable that way it will be easier to use it somewhere else.


问:
Change Browser URL without actually loading anything on the UI
I have seen a lot of questions related to this where actually user wanted to change the URL (I want to change Hash) without reloading the page. But for my case, none of them seems to be working.

First here is my requirement:
A user selects some filters on the UI and data refreshes automatically. I want my URL Hash to change along with that without reloading any content of the UI.

I tried following options available on Stack Overflow:

Change the document hash to the new hash URL:

document.location.hash = new_hash_value;

Manipulate the Browser History:

window.history.replaceState('test', 'title' , new_url);

But in both of the cases, page actually reloads (Though it doesn't reloads the data) due to this, for every selection in the drop down filter, it closes the filter options.

Can any one please help me here, how I can trick the browser to change the URL only without doing this.

(NS: Itried passing parameter reload: true, but that also do not seems to be working.)

答:
This has been answered before i believe.

```<code>window.history.pushState("object or string", "PageTitle", "/url");
</code>```

For more check: https://developer.mozilla.org/en-US/docs/Web/API/History_API

Body:
This has been answered before i believe.

window.history.pushState("object or string", "PageTitle", "/url");

For more check: https://developer.mozilla.org/en-US/docs/Web/API/History_API


问:
How to find the 404 error cause, when I am using a webview based application and the server fails in iphone sdk
I am implementing a webview based application, in that I need to find out a way when the 404 error occurred.

Anyone's help will be much appreciated.

Thanks to all,
Monish.

答:
Here you just need to check the status of the request when it finishes or fails in webview delegate method.`

```<code>     - (void)webViewDidFinishLoad:(UIWebView *)webView
{
    int status = [[[webView request] valueForHTTPHeaderField:@"Status"] intValue];
    if (status == 404) {

    }
}
</code>```

If this doesn't help you out. Check this one.
Create an NSURLRequest with the URL you want to load. Then make the connection using NSURLConnection.

NSURLConnection has a delegate method

```<code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
</code>```

which will give the the response from the server. Please note that if you are making the connection over HTTP, the response will actually be of class NSHTTPURLResponse. The NSHTTPURLResponse can be used to get the status using the following instance method

```<code>- (NSInteger)statusCode
</code>```

Then check if status = 404 or not and if yes then show your alert view. In this way you will be able to show the html page and the alert view both.

Body:
Here you just need to check the status of the request when it finishes or fails in webview delegate method.`

     - (void)webViewDidFinishLoad:(UIWebView *)webView
{
    int status = [[[webView request] valueForHTTPHeaderField:@"Status"] intValue];
    if (status == 404) {

    }
}

If this doesn't help you out. Check this one.
Create an NSURLRequest with the URL you want to load. Then make the connection using NSURLConnection.

NSURLConnection has a delegate method

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

which will give the the response from the server. Please note that if you are making the connection over HTTP, the response will actually be of class NSHTTPURLResponse. The NSHTTPURLResponse can be used to get the status using the following instance method

- (NSInteger)statusCode

Then check if status = 404 or not and if yes then show your alert view. In this way you will be able to show the html page and the alert view both.


问:
javascript bitwise xor producing inconsistent result
I am using bitwise operations in javascript but I have noticed something that appears inconsistent.

Right now, I'm using the XOR (^) operation. When I do '0101'^'0001', I get 4, which makes sense since 4 = 0100 in binary.
But when I do '10001'^'01111', I get 9030, when I think I should get 11110.
The format is, to best that I can tell, the same; only the strings are different.

```<code>console.log(5^1); //4
console.log('0101'^'0001'); // 100 = 4

console.log(17^15); //30
console.log('10001'^'01111'); //9030...why? shouldn't it be '11110'?
</code>```

Why is this code producing this result?

Now, If I do this:

```<code>console.log(('0b'+'10001')^('0b' + '01111')); //30
</code>```

Why did I have to add '0b' to specify that the strings were binary sequences when doing bitwise ops on 17 and 15, but not with 5 and 1?

答:
As has been pointed out already, you are not using binary numbers. Use the 0b prefix for binary numbers and toString(2) to convert back:

```<code>console.log((0b10001 ^ 0b01111).toString(2));
11110
</code>```

The first example just works because 1 in decimal is the same as 1 in binary. The result is 100 (decimal) though, not 4. Javascript doesn't store the number format internally.

Body:
I am using bitwise operations in javascript but I have noticed something that appears inconsistent.

Right now, I'm using the XOR (^) operation. When I do '0101'^'0001', I get 4, which makes sense since 4 = 0100 in binary.
But when I do '10001'^'01111', I get 9030, when I think I should get 11110.
The format is, to best that I can tell, the same; only the strings are different.

console.log(5^1); //4
console.log('0101'^'0001'); // 100 = 4

console.log(17^15); //30
console.log('10001'^'01111'); //9030...why? shouldn't it be '11110'?

Why is this code producing this result?

Now, If I do this:

console.log(('0b'+'10001')^('0b' + '01111')); //30

Why did I have to add '0b' to specify that the strings were binary sequences when doing bitwise ops on 17 and 15, but not with 5 and 1?

Body:
As has been pointed out already, you are not using binary numbers. Use the 0b prefix for binary numbers and toString(2) to convert back:

console.log((0b10001 ^ 0b01111).toString(2));
11110

The first example just works because 1 in decimal is the same as 1 in binary. The result is 100 (decimal) though, not 4. Javascript doesn't store the number format internally.


答:
It is useful if you feel that it helps you.

Some people are using it as a shortcut to reduce the number of characters when writing a program.

To me it reduces readability and adding variables to global scope can cause some unpredicted issues.


问:
C# WPF - Get data from a web page via button click and paste into text box
I am stuck at trying to get a specific set of data from a web page via a button click, and then paste that value into a separate text box. I haven't found much on the topic that was of much use and was wondering if anyone could steer me in the right direction.

```<code>    private void refresh_goblin_Click(object sender, RoutedEventArgs e)
    {
        WebClient client = new WebClient();
        string downloadString = client.DownloadString("http://services.runescape.com/m=itemdb_oldschool/Ensouled_goblin_head/viewitem?obj=13448");
</code>```

Above is a code excerpt from one of the buttons I'm working on. As a simple test, I have taken the URL of the website I want and stored it to a variable. If anyone could help show me how to paste this value into one of my text boxes so I can see how it's done that would be great. Thanks!

答:
You'll need to have a TextBox or TextBlock or similar control on your form. Then, in your method, set the Text property of the control to downloadString.

For example, if you've created a TextBox and named it "myTextbox", the code would look like this:

```<code>private void refresh_goblin_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    string downloadString = client.DownloadString("http://services.runescape.com/m=itemdb_oldschool/Ensouled_goblin_head/viewitem?obj=13448");
    this.myTextbox.Text = downloadString;
}
</code>```

Body:
I am stuck at trying to get a specific set of data from a web page via a button click, and then paste that value into a separate text box. I haven't found much on the topic that was of much use and was wondering if anyone could steer me in the right direction.

    private void refresh_goblin_Click(object sender, RoutedEventArgs e)
    {
        WebClient client = new WebClient();
        string downloadString = client.DownloadString("http://services.runescape.com/m=itemdb_oldschool/Ensouled_goblin_head/viewitem?obj=13448");

Above is a code excerpt from one of the buttons I'm working on. As a simple test, I have taken the URL of the website I want and stored it to a variable. If anyone could help show me how to paste this value into one of my text boxes so I can see how it's done that would be great. Thanks!

Body:
You'll need to have a TextBox or TextBlock or similar control on your form. Then, in your method, set the Text property of the control to downloadString.

For example, if you've created a TextBox and named it "myTextbox", the code would look like this:

private void refresh_goblin_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    string downloadString = client.DownloadString("http://services.runescape.com/m=itemdb_oldschool/Ensouled_goblin_head/viewitem?obj=13448");
    this.myTextbox.Text = downloadString;
}


问:
How to go back one page at a time (Go back to the referring page, not itself)
The history back function records requests. A page may request itself many times. So when pressing the back button, you might return to the previous request to the same page.

Here is a very simplified example:

Alice.html:

```<code><h1>This is Alice</h1>
<a href="charlie.php">Go to Charlie</a>
</code>```

Bob.html:

```<code><h1>This is Bob</h1>
<a href="charlie.php">Go to Charlie</a>
</code>```

Charlie.php:

```<code><h1>This is Charlie</h1>
<p id="output">Here goes the server output</p>
<form method="post">
<input type="hidden" id="somevalue" name="somevalue" value="0">
<button type="button" onclick="window.history.go(-1);">Back</button>
<button type="submit">Calculate</button>
</form>
<script>
// Simulate some server side action
document.getElementById("output").innerHTML = document.getElementById("somevalue").value = "Value = " + Math.random();
</script>
</code>```

Alice.html and Bob.html both links to Charlie.php.
Charlie.php has a form and call itself any number of times, to do some server manipulation of data.

The history back function steps one request back, not one page. To get back to Alice or Bob, the user has to hit the back button the same number of times that she hid the calculate button.

Question: How to step one page back, regardless of the number of requests to Charlie?

Edit: I'm looking for a generic solution for a simple "back up one page" button, without using server side variables.

A HTML5 only solutions is ok.

答:
The best solution for the information given is to create back links or what they call breadcrumbs linking that person directly to where you want them to go. You can just add a link anywhere guiding them back.

If my answer does not suffice then please explain a little more and it would help to provide a link to your site :). The more detailed you are then the answer will be what you need.

CODE BELOW

Home / Bob / This is Charlie

This is Charlie

Here comes the server some output

    <form method="post">
    <input type="hidden" id="somevalue" name="somevalue" value="0">
    <button type="button" onclick="window.history.go(-1);">Back</button>
    <button type="submit">Calculate</button>
    </form>
```

Body:
The history back function records requests. A page may request itself many times. So when pressing the back button, you might return to the previous request to the same page.

Here is a very simplified example:

Alice.html:

This is Alice

Go to Charlie

Bob.html:

This is Bob

Go to Charlie

Charlie.php:

This is Charlie

Here goes the server output

<form method="post">
<input type="hidden" id="somevalue" name="somevalue" value="0">
<button type="button" onclick="window.history.go(-1);">Back</button>
<button type="submit">Calculate</button>
</form>

Alice.html and Bob.html both links to Charlie.php.
Charlie.php has a form and call itself any number of times, to do some server manipulation of data.

The history back function steps one request back, not one page. To get back to Alice or Bob, the user has to hit the back button the same number of times that she hid the calculate button.

Question: How to step one page back, regardless of the number of requests to Charlie?

Edit: I'm looking for a generic solution for a simple "back up one page" button, without using server side variables.

A HTML5 only solutions is ok.

Body:
The best solution for the information given is to create back links or what they call breadcrumbs linking that person directly to where you want them to go. You can just add a link anywhere guiding them back.

If my answer does not suffice then please explain a little more and it would help to provide a link to your site :). The more detailed you are then the answer will be what you need.

CODE BELOW

<div>
<a href="index.php">Home</a> / <a href="bob.php">Bob</a> / This is Charlie </div>
<h1>This is Charlie</h1>
    <p id="output">Here comes the server some output</p>
    <form method="post">
    <input type="hidden" id="somevalue" name="somevalue" value="0">
    <button type="button" onclick="window.history.go(-1);">Back</button>
    <button type="submit">Calculate</button>
    </form>
<script>
    // Simulate some server side action
    document.getElementById("output").innerHTML =     document.getElementById("somevalue").value = "Value = " + Math.random();
    </script>


问:
Displaying JSON data in Chartjs
I am trying to use Chart JS to create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:

```<code>var datapart;
for (i = 0; i < jsonfile.jsonarray.length; i++){
     datapart += {
          label: jsonfile.jsonarray[i].name,
          data: [jsonfile.jsonarray[i].age]
     };
}

var config = {
   type: 'line',
   data: {
      labels: ["Graph Line"],
      datasets: [datapart]
   }
}
</code>```

My JSON file meanwhile looks something like so:

```<code>{
"jsonarray": [
    {
      "name": "Joe",
      "age": 12
    },
    {
      "name": "Tom",
      "age": 14
    }
]
}
</code>```

The config variable houses the configuration settings for ChartJS, including setting datapoints. When loaded into ChartJS, config provides information needed to display my chart.

Anyhow, my thinking was to use the variable datapart as a means of appending the datasets using my for loop. Unfortunately the code produces no results. I understand that my method for appending variables is faulty, but am unsure how to proceed.

How might I go about adding these JSON values to Chart.js?

答:
Your approach on constructing the chart is completely inappropriate. Here is the proper way, that you should follow :

var jsonfile = {
   "jsonarray": [{
      "name": "Joe",
      "age": 12
   }, {
      "name": "Tom",
      "age": 14
   }]
};

var labels = jsonfile.jsonarray.map(function(e) {
   return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
   return e.age;
});

var ctx = canvas.getContext('2d');
var config = {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Graph Line',
         data: data,
         backgroundColor: 'rgba(0, 119, 204, 0.3)'
      }]
   }
};

var chart = new Chart(ctx, config);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas></code>```

Title: Displaying JSON data in Chartjs

Body:
I am trying to use Chart JS to create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:

var datapart;
for (i = 0; i < jsonfile.jsonarray.length; i++){
     datapart += {
          label: jsonfile.jsonarray[i].name,
          data: [jsonfile.jsonarray[i].age]
     };
}

var config = {
   type: 'line',
   data: {
      labels: ["Graph Line"],
      datasets: [datapart]
   }
}

My JSON file meanwhile looks something like so:

{
"jsonarray": [
    {
      "name": "Joe",
      "age": 12
    },
    {
      "name": "Tom",
      "age": 14
    }
]
}

The config variable houses the configuration settings for ChartJS, including setting datapoints. When loaded into ChartJS, config provides information needed to display my chart.

Anyhow, my thinking was to use the variable datapart as a means of appending the datasets using my for loop. Unfortunately the code produces no results. I understand that my method for appending variables is faulty, but am unsure how to proceed.

How might I go about adding these JSON values to Chart.js?

Body:
Your approach on constructing the chart is completely inappropriate. Here is the proper way, that you should follow :

var jsonfile = {
   "jsonarray": [{
      "name": "Joe",
      "age": 12
   }, {
      "name": "Tom",
      "age": 14
   }]
};

var labels = jsonfile.jsonarray.map(function(e) {
   return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
   return e.age;
});

var ctx = canvas.getContext('2d');
var config = {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Graph Line',
         data: data,
         backgroundColor: 'rgba(0, 119, 204, 0.3)'
      }]
   }
};

var chart = new Chart(ctx, config);

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

ContentLicense: CC BY-SA 4.0


问:
issue with singleton method in calling WCF using JQuery
I created a bare simple method, that just increments a number by 1 and returns the value.

```<code>    [ServiceContract]
public interface ICalc
{
    [OperationContract]
    [WebGet(UriTemplate = "getnumber")]
    int GetNextNumber();
</code>```

service class:

```<code> [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Calculator : ICalc
{
    int i = 1;

    public int GetNextNumber()
    {return i++; }
}
</code>```

The service is hosted using WebHttpBinding and works well when opened from browser. For example, when I browse http://localhost:8083/Calc/getnumber , I get

```<code>  <int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1</int>
</code>```

Every time I refresh, value keeps incrementing by 1 in xml response (as expected due to singleton behavior)

PROBLEM

When I call the same service using JQuery as:

```<code>$.ajax(
            {
                type: "GET",
                url: "http://localhost:8083/Calc/getnumber",
                data: "",
                contentType: "application/html",
                processData: true,
                success: function (msg) { alertResult(alert(msg.childNodes[0].xml)) }
            }

        );
</code>```

I keep getting the same (latest) number and debugger too is not invoked at service.

What I am not understanding is: If method is not getting called using JQuery, how am I getting valid output and if method is called then why increment is not taking place (which works properly if I invoke service just by hitting service url directly from browse)r???

thanks!

答: Try adding cache: false to the properties of the ajax request to force the browser to really request the URL everytime as otherwise every sane browser will cache the response for your GET request as your URL doesn't change.

Body:
I created a bare simple method, that just increments a number by 1 and returns the value.

    [ServiceContract]
public interface ICalc
{
    [OperationContract]
    [WebGet(UriTemplate = "getnumber")]
    int GetNextNumber();

service class:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Calculator : ICalc
{
    int i = 1;

    public int GetNextNumber()
    {return i++; }
}

The service is hosted using WebHttpBinding and works well when opened from browser. For example, when I browse http://localhost:8083/Calc/getnumber , I get

  <int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1</int>

Every time I refresh, value keeps incrementing by 1 in xml response (as expected due to singleton behavior)

PROBLEM

When I call the same service using JQuery as:

$.ajax(
            {
                type: "GET",
                url: "http://localhost:8083/Calc/getnumber",
                data: "",
                contentType: "application/html",
                processData: true,
                success: function (msg) { alertResult(alert(msg.childNodes[0].xml)) }
            }

        );

I keep getting the same (latest) number and debugger too is not invoked at service.

What I am not understanding is: If method is not getting called using JQuery, how am I getting valid output and if method is called then why increment is not taking place (which works properly if I invoke service just by hitting service url directly from browse)r???

thanks!


问:
Currency conversion based on location and Paypal payments
In a Prestashop 1.6 based store I want to accept payments via Paypal in only one currency (Euros). However, I want to show prices in other currencies based on the location of the customer (probably using it's IP address?). How can I do that?</p>

答:
In Modules and services > payment you have a tab CURRENCY RESTRICTIONS, you can check in which currency you would like Paypal to be available

For currecy selection by IP:
First, you should get the user IP after, you should set the curency of the Prestashop context

```<code>$this->context->currency->id = $id_currency
</code>```

To get $id_currency, follow this steps

You should get the country of the the user IP with this script

Then get the currency code by country code (you can get if from a csv file or you you should use an API or database)

Body:
In Modules and services > payment you have a tab CURRENCY RESTRICTIONS, you can check in which currency you would like Paypal to be available

For currecy selection by IP:
First, you should get the user IP after, you should set the curency of the Prestashop context

$this->context->currency->id = $id_currency

To get $id_currency, follow this steps

You should get the country of the the user IP with this script

Then get the currency code by country code (you can get if from a csv file or you you should use an API or database)


问:
Calling client side human service from another client side human service
I have created two client side human services.
Now i want to call one client side human service from the second client side human service.
Is it possible to do so?</p>

答: Generally moving between CSHS is handled by simply putting both CSHS in a wrapper service.  Basically service 1 can either set a variable or use multiple end points to indicate where to go next. At least one of these options is to go to CSHS 2.  We expose the wrapper service to the end user, and when they run it, they will wind up running CSHS 1, which is the first sub-service in the wrapper service.  Then some interaction with the presented Coach has them go to CSHS 2.</p>


问:
Setting variables in addEventListener
In the following code, I attempted to set an input variable in a function called by addEventListener. The issue that I encountered is that the input variable 'input_left' is never set to true. The code under the if statement is not run, but the code that should set the variable is run. I tried messing around with the bind() function, but it changed nothing.

```<code>//Player
var Player = function() {
    this.input_left = false;
}

Player.prototype.update = function() {
    this.input_left = false;

    window.addEventListener('keydown', this.keyPressed.bind(this));

    if (this.input_left) {
        alert('2'); //It doesn't show this
    }
}

Player.prototype.keyPressed = function(e) {
    switch(e.keyCode) {
        case 65:
            this.input_left = true;
            alert('1'); //It shows this
        break;
    }
}

//Initialize the object
var player = new Player();

//Game loop
var gameLoop = function() {
    player.update();
    window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);
</code>```

I suspect that the this.input_left variable of the player is never set properly, even though the code that sets it is run, I am wondering how to ensure that the variable is set correctly so that also alert('2'); runs.

答:
You should move your event listener into your constructor (or some init function) so that you don't create it over-and-over again.

You're also setting input_left to false right before you check it in your update function, so how about checking it before you reset it?

//Player
var Player = function() {
    this.input_left = false;
    window.addEventListener('keydown', this.keyPressed.bind(this));
}

Player.prototype.update = function() {
    if (this.input_left) {
        console.log('2'); //It shows this
    }
    this.input_left = false;
}

Player.prototype.keyPressed = function(e) {
    switch(e.keyCode) {
        case 65:
            this.input_left = true;
            console.log('1'); //It shows this
        break;
    }
}

//Initialize the object
var player = new Player();

//Game loop
var gameLoop = function() {
    player.update();
    window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);```

Title: Setting variables in addEventListener

Body:
In the following code, I attempted to set an input variable in a function called by addEventListener. The issue that I encountered is that the input variable 'input_left' is never set to true. The code under the if statement is not run, but the code that should set the variable is run. I tried messing around with the bind() function, but it changed nothing.

//Player
var Player = function() {
    this.input_left = false;
}

Player.prototype.update = function() {
    this.input_left = false;

    window.addEventListener('keydown', this.keyPressed.bind(this));

    if (this.input_left) {
        alert('2'); //It doesn't show this
    }
}

Player.prototype.keyPressed = function(e) {
    switch(e.keyCode) {
        case 65:
            this.input_left = true;
            alert('1'); //It shows this
        break;
    }
}

//Initialize the object
var player = new Player();

//Game loop
var gameLoop = function() {
    player.update();
    window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);

I suspect that the this.input_left variable of the player is never set properly, even though the code that sets it is run, I am wondering how to ensure that the variable is set correctly so that also alert('2'); runs.


问:
Using $window in http interceptor service
I am trying to use the $window object in an http interceptor so I can reference to the localStorage.

The problem is that whenever I remove the following line, my web app works. But when I add it, no page loads, just a white screen, but there are no errors either.

```<code>let {$window} = this;
</code>```

My main module config:

```<code>$httpProvider.interceptors.push('authInterceptor');
</code>```

My authInterceptor service class:

```<code>export class authInterceptor {
  constructor($window) {
    this.$window = $window;
  }

  request(config) {
    let {$window} = this;

    return config;
  }

  responseError(response) {
    return response;
  }

}
authInterceptor.$inject = ['$window'];
</code>```

答:
Considering that ES6 is supported by the browser (and it's supported, since interceptor service is a class that is likely being transpiled), the only possibility when let {$window} = this can cause a problem is that this isn't class instance or even an object.

Interceptor functions are functions that are used as callbacks and pushed to the stack. This means that this will be undefined in strict mode inside them.

As any other class methods that are used as callbacks, these ones should be bound to proper context in order to keep it and be able to use injected services:

```<code>  constructor($window) {
    this.$window = $window;
    this.request = this.request.bind(this);
    this.responseError = this.responseError.bind(this);
  }
</code>```

Body:
I am trying to use the $window object in an http interceptor so I can reference to the localStorage.

The problem is that whenever I remove the following line, my web app works. But when I add it, no page loads, just a white screen, but there are no errors either.

let {$window} = this;

My main module config:

$httpProvider.interceptors.push('authInterceptor');

My authInterceptor service class:

export class authInterceptor {
  constructor($window) {
    this.$window = $window;
  }

  request(config) {
    let {$window} = this;

    return config;
  }

  responseError(response) {
    return response;
  }

}
authInterceptor.$inject = ['$window'];

Body:
Considering that ES6 is supported by the browser (and it's supported, since interceptor service is a class that is likely being transpiled), the only possibility when let {$window} = this can cause a problem is that this isn't class instance or even an object.

Interceptor functions are functions that are used as callbacks and pushed to the stack. This means that this will be undefined in strict mode inside them.

As any other class methods that are used as callbacks, these ones should be bound to proper context in order to keep it and be able to use injected services:

  constructor($window) {
    this.$window = $window;
    this.request = this.request.bind(this);
    this.responseError = this.responseError.bind(this);
  }


问:
R click position for matrix plot
My algorithm calculates a symmetric matrix m. What I need to do is to create a plot similar to image for instance and make this plot clickable, so that a click callback would print out the positions indeces for the clicked matrix entry. How can I do this with R?

```<code>m = createMatrix(data);
image(1:matrixSize,1:matrixSize,m);
</code>```

答:
Try this solution based on the plotly package.

Hope it can help you.

```<code># A symmetrix matrix
mtx <- cor(matrix(rnorm(1000),ncol=5))

# From wide to long format
library(reshape)
mtx.long <- melt(mtx)

# Create an image plot of the matrix
library(ggplot2)
p <- ggplot(data=mtx.long, aes(x=X1, y=X2, fill=value))+geom_raster()

# Create an interactive plot
library(plotly)
ggplotly(p)
</code>```

Title: R click position for matrix plot

Body:
My algorithm calculates a symmetric matrix m. What I need to do is to create a plot similar to image for instance and make this plot clickable, so that a click callback would print out the positions indeces for the clicked matrix entry. How can I do this with R?

m = createMatrix(data);
image(1:matrixSize,1:matrixSize,m);

Body:
Try this solution based on the plotly package.

Hope it can help you.

# A symmetrix matrix
mtx <- cor(matrix(rnorm(1000),ncol=5))

# From wide to long format
library(reshape)
mtx.long <- melt(mtx)

# Create an image plot of the matrix
library(ggplot2)
p <- ggplot(data=mtx.long, aes(x=X1, y=X2, fill=value))+geom_raster()

# Create an interactive plot
library(plotly)
ggplotly(p)


问:
UIView doesn't appear as subview
I have a cell with subviews.

I can't figure out why the UIView boom isn't visible.  Here is my code:

```<code>let separator: UIView = {
    let view = UIView()
    view.backgroundColor = .yellow
    return view
}()

let boom: UIView = {
    let b = UIView()
    b.backgroundColor = .red
    return b
}()

override func setupViews() {
    super.setupViews()

    addSubview(separator)
    addSubview(setNumberView)
    addSubview(boom)

    backgroundColor = .orange

    addConstraintsWithFormat("H:|-20-[v0]", views: boom)
    addConstraintsWithFormat("V:|-20-[v0]", views: boom)

    addConstraintsWithFormat("H:|[v0]|", views: separator)
    addConstraintsWithFormat("V:[v0(10)]|", views: separator)
</code>```

separator shows up as it is supposed to.  Is there a bug in my xcode or something?  I have tried restarting xcode, putting the view into a frame, and changing the cell size.

答:
You are not setting any width or height to your view.

To properly setup the position of a view, you have to specify the horizontal position, the vertical position, the width and height.

The separator correctly specifies all of them, the view is missing constraints for width and height.

A way to fix that could be for example:

```<code>addConstraintsWithFormat("H:|-20-[v0]-20-|", views: boom)
addConstraintsWithFormat("V:|-20-[v0(100)]", views: boom)
</code>```

Title: UIView doesn't appear as subview

Body:
I have a cell with subviews.

I can't figure out why the UIView boom isn't visible.  Here is my code:

let separator: UIView = {
    let view = UIView()
    view.backgroundColor = .yellow
    return view
}()

let boom: UIView = {
    let b = UIView()
    b.backgroundColor = .red
    return b
}()

override func setupViews() {
    super.setupViews()

    addSubview(separator)
    addSubview(setNumberView)
    addSubview(boom)

    backgroundColor = .orange

    addConstraintsWithFormat("H:|-20-[v0]", views: boom)
    addConstraintsWithFormat("V:|-20-[v0]", views: boom)

    addConstraintsWithFormat("H:|[v0]|", views: separator)
    addConstraintsWithFormat("V:[v0(10)]|", views: separator)

separator shows up as it is supposed to.  Is there a bug in my xcode or something?  I have tried restarting xcode, putting the view into a frame, and changing the cell size.

Body:
You are not setting any width or height to your view.

To properly setup the position of a view, you have to specify the horizontal position, the vertical position, the width and height.

The separator correctly specifies all of them, the view is missing constraints for width and height.

A way to fix that could be for example:

addConstraintsWithFormat("H:|-20-[v0]-20-|", views: boom)
addConstraintsWithFormat("V:|-20-[v0(100)]", views: boom)