问:
GNU Make wildcard to compile each file separately into a build directory
I am trying to create the following directory structure for a C++ project.

```<code>├── Project
├── Makefile
│   ├── build/
│   ├── src
│   │   ├── include/
│   │   ├── cpp/
│   │   loader.s
│   │   linker.ld
</code>```

I also want to compile each .cpp file separately into the build directory and link in a different target.

I am having trouble with the wildcard to do this:

```<code>BUILD    = ./build/
OBJS     = $(patsubst src/cpp/%.cpp,build/%.o,$(wildcard src/cpp/*.cpp))
CPPFLAGS = -I ./src/include -Wfatal-errors -fno-use-cxa-atexit -nostdlib -fno-builtin -fno-rtti -fno-exceptions -fno-leading-underscore

$(BUILD)kernel.elf: $(BUILD)loader.o $(OBJS)
    $(ARMGNU)-ld -T ./src/linker.ld -o $@ $^
    $(ARMGNU)-objdump -D $(BUILD)kernel.elf > $(BUILD)kernel.list

$(BUILD)%.o: ./src/%.s
    $(ARMGNU)-as $(AFLAGS) -c -o $@ $^

$(BUILD)%.o: ./src/cpp/%.cpp
    $(ARMGNU)-gcc $(CPPFLAGS) -c -o $@ $^
</code>```

The build/%.o's are never built so the link step gets an empty $(OBJS). What's the correct syntax for this?

答:
Your BUILD variable is set to ./build/, while object files in OBJ start with build/.  After expansion rules look like:

```<code>./build/kernel.elf: ./build/loader.o build/...
./build/%.o: ./src/%.s
</code>```

That additional ./ prefix affects rule matching by make, because paths aren't normalized.

The fix is as simple as making prefixes in target goals and prerequisites match by setting:

```<code>BUILD = build/
</code>```

Body:
I am trying to create the following directory structure for a C++ project.

├── Project
├── Makefile
│   ├── build/
│   ├── src
│   │   ├── include/
│   │   ├── cpp/
│   │   loader.s
│   │   linker.ld

I also want to compile each .cpp file separately into the build directory and link in a different target.

I am having trouble with the wildcard to do this:

BUILD    = ./build/
OBJS     = $(patsubst src/cpp/%.cpp,build/%.o,$(wildcard src/cpp/*.cpp))
CPPFLAGS = -I ./src/include -Wfatal-errors -fno-use-cxa-atexit -nostdlib -fno-builtin -fno-rtti -fno-exceptions -fno-leading-underscore

$(BUILD)kernel.elf: $(BUILD)loader.o $(OBJS)
    $(ARMGNU)-ld -T ./src/linker.ld -o $@ $^
    $(ARMGNU)-objdump -D $(BUILD)kernel.elf > $(BUILD)kernel.list

$(BUILD)%.o: ./src/%.s
    $(ARMGNU)-as $(AFLAGS) -c -o $@ $^

$(BUILD)%.o: ./src/cpp/%.cpp
    $(ARMGNU)-gcc $(CPPFLAGS) -c -o $@ $^

The build/%.o's are never built so the link step gets an empty $(OBJS). What's the correct syntax for this?

Body:
Your BUILD variable is set to ./build/, while object files in OBJ start with build/.  After expansion rules look like:

./build/kernel.elf: ./build/loader.o build/...
./build/%.o: ./src/%.s

That additional ./ prefix affects rule matching by make, because paths aren't normalized.

The fix is as simple as making prefixes in target goals and prerequisites match by setting:

BUILD = build/


来源: stackexchange

问:
Image galley with Jquery (click on "next" button)
first of all sorry for my bad grammar as English is not my first language.

Anyway, I'm totally new to Jquery / Javascript.

I'm trying to create an image gallery with image swap effect using Jquery.

What I want to achieve is, when I click on a thumbnail (let's say No. 4), the main image would display image No. 4. Well, I've already successfully written a code for this matter.

Now, there's another thing I want to achieve:

I have a "next"-button. If the main image is displaying image No. 4, clicking on the "next"-button should result in the main image displaying image No. 5. Or, if the main image is displaying image No. 7, clicking on "next"-button would show image No. 8 and so on.

Using the code I've written, clicking on the "next"-button will cause the main image showing the 2nd image. Clicking it again then it shows the 3rd image, but not the next No. from where I clicked the thumbnail.

This is my Array:

```<code>var bilder = ["../../images/galerie/assassin_2_01.jpg",
              "../../images/galerie/assassin_2_02.jpg",
              "../../images/galerie/assassin_2_03.jpg",
              "../../images/galerie/assassin_2_04.jpg",
              "../../images/galerie/assassin_2_05.jpg",
              "../../images/galerie/assassin_2_06.jpg",
              "../../images/galerie/assassin_2_07.jpg",
              "../../images/galerie/assassin_2_08.jpg",
              "../../images/galerie/assassin_2_09.jpg",
              "../../images/galerie/assassin_2_10.jpg",
              "../../images/galerie/assassin_2_11.jpg",
              "../../images/galerie/assassin_2_12.jpg",
              "../../images/galerie/assassin_2_13.jpg",
              "../../images/galerie/assassin_2_14.jpg",
              "../../images/galerie/assassin_2_15.jpg"];
</code>```

This is my Jquery:

```<code>function mainimage(nr) {
    $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
        $(this).attr("src",bilder[nr]).fadeIn(500);
    }});
}
function next() {
    if (index < bilder.length) {
        index++;
        mainimage(index);
    }
}
</code>```

And this is my HTML-structure:

```<code><div class="mainimg">
    <ul>
        <li><div><img class="img1" src="../../images/galerie/assassin_2_01.jpg" /></div></li>
    </ul>
        <div class="caption">
            <div>Assassin's Creed 2</div>
            <div><a href="#">back/a>  |  <a onclick="next();">next</a></div>
        </div>
</div>

<div class="thumbsrow">
    <div class="galeriethumbs"><img onclick="mainimage(0);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(1);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(2);" /></div>
</div>
<div class="thumbsrow">
    <div class="galeriethumbs"><img onclick="mainimage(3);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(4);" /></div>
    <div class="galeriethumbs"><img onclick="mainimage(5);" /></div>
</div>
</code>```

I'm thankful for any help!

答:
As stated above you just need to set the index variable when on your mainimage function.</p>

```<code>function mainimage(nr) {
        $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
            $(this).attr("src",bilder[nr]).fadeIn(500);
            index = nr; //this will set the index of the currently selected image.
        }});
    }
    function next() {
        if (index < bilder.length) {
            index++;
            mainimage(index);
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
first of all sorry for my bad grammar as English is not my first language.

Anyway, I'm totally new to Jquery / Javascript.

I'm trying to create an image gallery with image swap effect using Jquery.

What I want to achieve is, when I click on a thumbnail (let's say No. 4), the main image would display image No. 4. Well, I've already successfully written a code for this matter.

Now, there's another thing I want to achieve:

I have a "next"-button. If the main image is displaying image No. 4, clicking on the "next"-button should result in the main image displaying image No. 5. Or, if the main image is displaying image No. 7, clicking on "next"-button would show image No. 8 and so on.

Using the code I've written, clicking on the "next"-button will cause the main image showing the 2nd image. Clicking it again then it shows the 3rd image, but not the next No. from where I clicked the thumbnail.

This is my Array:

var bilder = ["../../images/galerie/assassin_2_01.jpg",
              "../../images/galerie/assassin_2_02.jpg",
              "../../images/galerie/assassin_2_03.jpg",
              "../../images/galerie/assassin_2_04.jpg",
              "../../images/galerie/assassin_2_05.jpg",
              "../../images/galerie/assassin_2_06.jpg",
              "../../images/galerie/assassin_2_07.jpg",
              "../../images/galerie/assassin_2_08.jpg",
              "../../images/galerie/assassin_2_09.jpg",
              "../../images/galerie/assassin_2_10.jpg",
              "../../images/galerie/assassin_2_11.jpg",
              "../../images/galerie/assassin_2_12.jpg",
              "../../images/galerie/assassin_2_13.jpg",
              "../../images/galerie/assassin_2_14.jpg",
              "../../images/galerie/assassin_2_15.jpg"];

This is my Jquery:

function mainimage(nr) {
    $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
        $(this).attr("src",bilder[nr]).fadeIn(500);
    }});
}
function next() {
    if (index < bilder.length) {
        index++;
        mainimage(index);
    }
}

And this is my HTML-structure:

Assassin's Creed 2

back/a>  |  next

I'm thankful for any help!

Body:
As stated above you just need to set the index variable when on your mainimage function.

function mainimage(nr) {
        $("div.mainimg ul li:eq(0) div img").fadeOut({"duration":300, complete:function() {
            $(this).attr("src",bilder[nr]).fadeIn(500);
            index = nr; //this will set the index of the currently selected image.
        }});
    }
    function next() {
        if (index < bilder.length) {
            index++;
            mainimage(index);
        }
    }


问:
Is there way to use interpolation inside *ngFor
```<code><div *ngFor="let t of {{randomName}}"></div>
</code>```

I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

```<code><div formArrayName="{{obj.key}}">
 <div *ngFor="let t of formGrp.controls.{{obj.key}}.controls"></div>
</div>
</code>```

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

答:
```<code><div *ngFor="let t of dynamicArr"></div>
</code>```

What you can do is set the Array dynamically in your component. Rather than using string interpolation.

```<code>export class SomeClass {
   dynamicArr:[];
   updateArr(){
     // some logic
   return this.dynamicArr = dynamic Array
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

Body:
<div *ngFor="let t of dynamicArr"></div>

What you can do is set the Array dynamically in your component. Rather than using string interpolation.

export class SomeClass {
   dynamicArr:[];
   updateArr(){
     // some logic
   return this.dynamicArr = dynamic Array
   }
}


问:
Python - iterate through a list
I'm trying to automate email reporting using python. My problem is that i cant pull the subject from the data that my email client outputs.

Abbreviated dataset:

```<code>[(messageObject){
   id = "0bd503eb00000000000000000000000d0f67"
   name = "11.26.17 AM [TXT-CAT]{Shoppers:2}"
   status = "active"
   messageFolderId = "0bd503ef0000000000000000000000007296"
   content[] =
      (messageContentObject){
         type = "html"
         subject = "Early Cyber Monday – 60% Off Sitewide "
         }
         }
         ]
</code>```

I can pull the other fields like this:

```<code>messageId = []
messageName = []
subject = []

for info in messages:
    messageId.append(str(info['id']))
    messageName.append(str(info['name']))
    subject.append(str(info[content['subject']]))

data = pd.DataFrame({
    'id': messageId,
    'name': messageName,
    'subject': subject
})
data.head()
</code>```

I've been trying to iterate though content[] using a for loop, but i can't get it to work. Let me know if you have any suggestions.

答:
@FamousJameous gave the correct answer:

That format is called SOAP. My guess for the syntax would be info['content']['subject'] or maybe info['content'][0]['subject']

info['content'][0]['subject'] worked with my data.

Title: Python - iterate through a list

Body:
I'm trying to automate email reporting using python. My problem is that i cant pull the subject from the data that my email client outputs.

Abbreviated dataset:

[(messageObject){
   id = "0bd503eb00000000000000000000000d0f67"
   name = "11.26.17 AM [TXT-CAT]{Shoppers:2}"
   status = "active"
   messageFolderId = "0bd503ef0000000000000000000000007296"
   content[] =
      (messageContentObject){
         type = "html"
         subject = "Early Cyber Monday – 60% Off Sitewide "
         }
         }
         ]

I can pull the other fields like this:

messageId = []
messageName = []
subject = []

for info in messages:
    messageId.append(str(info['id']))
    messageName.append(str(info['name']))
    subject.append(str(info[content['subject']]))

data = pd.DataFrame({
    'id': messageId,
    'name': messageName,
    'subject': subject
})
data.head()

I've been trying to iterate though content[] using a for loop, but i can't get it to work. Let me know if you have any suggestions.


问:
Inheriting from a template class using the inheriting class
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

```<code>#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}
</code>```

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.

答:
With this definition of template class IFoo, the compiler does not need to know the size of Foo to lay out IFoo<Foo>.

Foo will be an incomplete class in this context (not "undefined" or "undeclared") and usable in ways that any incomplete type can be used.  Appearing in a member function parameter list is fine.  Declaring a member variable as Foo* is fine.  Declaring a member variable as Foo is forbidden (complete type required).

Body:
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.


问:
Unable to locate element with in selenium using xpath written in python
I am trying to automate an iCal download from this website: webuntis.dk using python and selenium. So far I have managed to get get python to enter the credentials of au_health on the login site. Next I need it to press the small calendar icon in the top right corner. It keeps returning:

```<code>NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/a[@id="Timetable_toolbar_icalButton"]"}
</code>```

My code is as follow:

```<code>from selenium import webdriver

browser = webdriver.Chrome('/Users/juliushvidt/Desktop/chromedriver')

browser.get('https://webuntis.dk/WebUntis/login.do')

username = browser.find_element_by_id("school")

username.send_keys("au_health")

NEXT_BUTTON_XPATH = '//input[@type="submit"]'
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

browser.get('https://webuntis.dk/WebUntis/index.do#Timetable?type=3&id=1140')

driver = browser

time.sleep(5.5) #this did the trick

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]' #using the current button notation was definitely also contributing :)
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()
</code>```

The inspecting the element im trying to reach on the website I get the following source code:

Hope you can point me in the right direction as I'm at a loss.

Code exert from the source of the website:

```<code><div data-dojo-type="dijit/layout/ContentPane" data-dojo-attach-point="_toolbarContainer" class="dijitContentPane toolbarContainer dijitBorderContainerNoGutter-child dijitBorderContainerNoGutter-dijitContentPane dijitBorderContainerNoGutterPane dijitAlignTop" data-dojo-props="region: 'top'" id="dijit_layout_ContentPane_0" widgetid="dijit_layout_ContentPane_0" style="left: 0px; top: 0px; position: absolute; width: 31px;"><div class="grupetWidgetToolbar" id="Timetable_toolbar" widgetid="Timetable_toolbar"><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_0" widgetid="grupet_widget_LabelPanel_0" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Fag</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft dijitTextBox dijitComboBox dijitValidationTextBox" id="widget_Timetable_toolbar_elementSelect" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="Timetable_toolbar_elementSelect"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementSelect" aria-required="false" value="1. sem. Medicinsk filosofi forelæsning" aria-invalid="false"><span class="dijitPlaceHolder dijitInputField" style="display: none;">Vælg her</span><input type="hidden" value="1140"></div></div></div>
</div><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_1" widgetid="grupet_widget_LabelPanel_1" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Afdeling</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft grupetWidgetHasResetButton dijitTextBox dijitComboBox dijitValidationTextBox" id="widget_Timetable_toolbar_elementFilter_IDC_ABTEILUNG" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="Timetable_toolbar_elementFilter_IDC_ABTEILUNG"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><div class="dijitReset dijitRight dijitButtonNode grupetWidgetResetButton grupetWidgetResetButtonContainer grupetDisplayNone">
    <input type="text" role="presentation" readonly="readonly" tabindex="-1" value=" " title="Nulstil" class="dijitReset dijitInputField grupetWidgetResetButtonInner">
</div><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementFilter_IDC_ABTEILUNG" aria-required="false" value="" aria-invalid="false"><span class="dijitPlaceHolder dijitInputField">Vælg her</span><input type="hidden" value=""></div></div></div>
</div><div class="grupetWidgetLabelPanel" id="grupet_widget_LabelPanel_2" widgetid="grupet_widget_LabelPanel_2" style="display: inline-block; vertical-align: middle;">
    <div class="grupetWidgetLabelPanelText_ABOVE" data-dojo-attach-point="textNode">Aktuel uge</div>
    <div class="grupetWidgetLabelPanelContainer_ABOVE" data-dojo-attach-point="containerNode"><div class="dijit dijitReset dijitInline dijitLeft date-week-select dijitTextBox dijitComboBox dijitDateTextBox dijitValidationTextBox" id="widget_timetablePageToolbar_dateWeekSelect" role="combobox" aria-haspopup="true" data-dojo-attach-point="_popupStateNode" widgetid="timetablePageToolbar_dateWeekSelect"><div class="dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer" data-dojo-attach-point="_buttonNode" role="presentation"><input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true"></div><div class="dijitReset dijitValidationContainer"><input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation"></div><span role="button" class="fa fa-caret-right"></span><span role="button" class="fa fa-caret-left"></span><div class="dijitReset dijitInputField dijitInputContainer"><input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" tabindex="0" id="timetablePageToolbar_dateWeekSelect" value="04/12/2017" aria-invalid="false"><input type="hidden" value="2017-12-04"></div></div></div>
</div><span class="dijit dijitReset dijitInline gp-iconfont-button dijitDropDownButton" widgetid="Timetable_toolbar_settingsButton" style="display: inline-block; vertical-align: middle; float: right;"><span class="dijitReset dijitInline dijitButtonNode" data-dojo-attach-event="ondijitclick:__onClick" data-dojo-attach-point="_buttonNode"><span class="dijitReset dijitStretch dijitButtonContents dijitDownArrowButton" data-dojo-attach-point="focusNode,titleNode,_arrowWrapperNode,_popupStateNode" role="button" aria-haspopup="true" aria-labelledby="Timetable_toolbar_settingsButton_label" tabindex="0" id="Timetable_toolbar_settingsButton" aria-disabled="false" style="user-select: none;"><span class="dijitReset dijitInline dijitIcon fa fa-2x fa-cog" data-dojo-attach-point="iconNode"></span><span class="dijitReset dijitInline dijitButtonText" data-dojo-attach-point="containerNode" id="Timetable_toolbar_settingsButton_label"></span><span class="dijitReset dijitInline dijitArrowButtonInner"></span><span class="dijitReset dijitInline dijitArrowButtonChar">▼</span></span></span><input type="button" value="" class="dijitOffScreen" tabindex="-1" data-dojo-attach-event="onclick:_onClick" data-dojo-attach-point="valueNode" role="presentation" aria-hidden="true"></span><button type="button" class="gp-iconfont-button fa fa-2x fa-print" id="Timetable_toolbar_printButton" title="Udskriftsversion" aria-label="Udskriftsversion" widgetid="Timetable_toolbar_printButton" style="display: inline-block; vertical-align: middle; float: right;"></button><button type="button" class="icon-ical-24 imageButton imageButtonFocused dijitFocused" title="ICS kalender" aria-label="ICS kalender" id="Timetable_toolbar_icalButton" widgetid="Timetable_toolbar_icalButton" style="display: inline-block; vertical-align: middle; float: right;"><div class="icon icon-ical-24"></div></button></div></div>
</code>```

答:
Turns out it was a timing issue. Testing this with a:

time.sleep(5.5)

and it downloaded the file correctly. Thank you for all the help I received. Without it I am certain I couldn't have figured it out. Cheers :).

ContentLicense: CC BY-SA 4.0

Body:
I am trying to automate an iCal download from this website: webuntis.dk using python and selenium. So far I have managed to get get python to enter the credentials of au_health on the login site. Next I need it to press the small calendar icon in the top right corner. It keeps returning:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/a[@id="Timetable_toolbar_icalButton"]"}

My code is as follow:

from selenium import webdriver

browser = webdriver.Chrome('/Users/juliushvidt/Desktop/chromedriver')

browser.get('https://webuntis.dk/WebUntis/login.do')

username = browser.find_element_by_id("school")

username.send_keys("au_health")

NEXT_BUTTON_XPATH = '//input[@type="submit"]'
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

browser.get('https://webuntis.dk/WebUntis/index.do#Timetable?type=3&id=1140')

driver = browser

time.sleep(5.5) #this did the trick

NEXT_BUTTON_XPATH = '//button[@id="Timetable_toolbar_icalButton"]' #using the current button notation was definitely also contributing :)
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

The inspecting the element im trying to reach on the website I get the following source code:

Hope you can point me in the right direction as I'm at a loss.

Code exert from the source of the website:

Fag

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementSelect" aria-required="false" value="1. sem. Medicinsk filosofi forelæsning" aria-invalid="false">Vælg her<input type="hidden" value="1140">

Afdeling

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

    <input type="text" role="presentation" readonly="readonly" tabindex="-1" value=" " title="Nulstil" class="dijitReset dijitInputField grupetWidgetResetButtonInner">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="list" tabindex="0" id="Timetable_toolbar_elementFilter_IDC_ABTEILUNG" aria-required="false" value="" aria-invalid="false">Vælg her<input type="hidden" value="">

Aktuel uge

<input class="dijitReset dijitInputField dijitArrowButtonInner" value="▼ " type="text" tabindex="-1" readonly="readonly" role="button presentation" aria-hidden="true">

<input class="dijitReset dijitInputField dijitValidationIcon dijitValidationInner" value="Χ " type="text" tabindex="-1" readonly="readonly" role="presentation">

<input class="dijitReset dijitInputInner" type="text" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" tabindex="0" id="timetablePageToolbar_dateWeekSelect" value="04/12/2017" aria-invalid="false"><input type="hidden" value="2017-12-04">

▼<input type="button" value="" class="dijitOffScreen" tabindex="-1" data-dojo-attach-event="onclick:_onClick" data-dojo-attach-point="valueNode" role="presentation" aria-hidden="true"><button type="button" class="gp-iconfont-button fa fa-2x fa-print" id="Timetable_toolbar_printButton" title="Udskriftsversion" aria-label="Udskriftsversion" widgetid="Timetable_toolbar_printButton" style="display: inline-block; vertical-align: middle; float: right;"></button><button type="button" class="icon-ical-24 imageButton imageButtonFocused dijitFocused" title="ICS kalender" aria-label="ICS kalender" id="Timetable_toolbar_icalButton" widgetid="Timetable_toolbar_icalButton" style="display: inline-block; vertical-align: middle; float: right;">

</button>


问:
how to get DB id only after clicking imageButton in listView item with kotlin
i have a customAdapter class and a listView. i made the single_row layout with 3 textviews and one imageButton.
now my question is how can i get the DB id field, only from clicking on the imageButton and ignore clicks on the entire row?
I know i can get the id with:

```<code>mListView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, position, id ->
               view.delete.setOnClickListener(){
                   Toast.makeText(context,""+id,Toast.LENGTH_SHORT).show()
              }
</code>```

but this is working only if i click the entire row.
I tried android:descendantFocusability="blocksDescendants" in the root of the xml and android:focusable="false" in the imageButton node, and the imageButton is not recognized anyway while the entire row is recognized. only if i using button.onClickListener()...
the click is recognized. but that way i don't know how to get the id.

my adapter class code:

```<code>class MyAdapter(activity: Activity, context: Context, cursor: Cursor) : CursorAdapter(context, cursor, true) {

    var inflater: LayoutInflater
    lateinit var mListView: ListView

    init {
        this.inflater = LayoutInflater.from(context)
        mListView = activity.listView
    }

    override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
        val view = LayoutInflater.from(context).inflate(R.layout.single_row, parent, false)

        return view;
    }
override fun bindView(view: View, context: Context, cursor: Cursor) {
        val latitude = view.findViewById(R.id.latitude) as TextView
        val longtitude = view.findViewById(R.id.longtitude) as TextView
        val date = view.findViewById(R.id.date) as TextView
        val asu = view.findViewById(R.id.asu) as TextView

        latitude.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.LATITUDE)))
        longtitude.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.LONGTITUDE)))
        date.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.DATE)))
        asu.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.ASU)))

    }
}
</code>```

my single_row layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:id="@+id/list_item"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/latitude"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:text="latitude"
        android:gravity="center" />

    <TextView
        android:id="@+id/longtitude"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:text="longtitude"
        android:gravity="center" />

    <TextView
        android:id="@+id/date"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:gravity="center"
        android:text="date" />

    <TextView
        android:id="@+id/asu"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:gravity="center"
        android:focusable="false"
        android:text="asu"/>

    <ImageButton
        android:id="@+id/delete"
        android:layout_width="0.23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:focusable="false"
        android:src="@android:drawable/ic_menu_delete" />
</LinearLayout>
</code>```

答:
You are using cursor adapter, you should use ArrayAdapter.  Here is why custom-cursoradapter-and-why-not-use
and example of ArrayAdapter</p>

Body:
i have a customAdapter class and a listView. i made the single_row layout with 3 textviews and one imageButton.
now my question is how can i get the DB id field, only from clicking on the imageButton and ignore clicks on the entire row?
I know i can get the id with:

mListView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, position, id ->
               view.delete.setOnClickListener(){
                   Toast.makeText(context,""+id,Toast.LENGTH_SHORT).show()
              }

but this is working only if i click the entire row.
I tried android:descendantFocusability="blocksDescendants" in the root of the xml and android:focusable="false" in the imageButton node, and the imageButton is not recognized anyway while the entire row is recognized. only if i using button.onClickListener()...
the click is recognized. but that way i don't know how to get the id.

my adapter class code:

class MyAdapter(activity: Activity, context: Context, cursor: Cursor) : CursorAdapter(context, cursor, true) {

    var inflater: LayoutInflater
    lateinit var mListView: ListView

    init {
        this.inflater = LayoutInflater.from(context)
        mListView = activity.listView
    }

    override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
        val view = LayoutInflater.from(context).inflate(R.layout.single_row, parent, false)

        return view;
    }
override fun bindView(view: View, context: Context, cursor: Cursor) {
        val latitude = view.findViewById(R.id.latitude) as TextView
        val longtitude = view.findViewById(R.id.longtitude) as TextView
        val date = view.findViewById(R.id.date) as TextView
        val asu = view.findViewById(R.id.asu) as TextView

        latitude.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.LATITUDE)))
        longtitude.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.LONGTITUDE)))
        date.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.DATE)))
        asu.setText(cursor.getString(cursor.getColumnIndex(Constants.Signal.ASU)))

    }
}

my single_row layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:id="@+id/list_item"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/latitude"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:text="latitude"
        android:gravity="center" />

    <TextView
        android:id="@+id/longtitude"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:text="longtitude"
        android:gravity="center" />

    <TextView
        android:id="@+id/date"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:gravity="center"
        android:text="date" />

    <TextView
        android:id="@+id/asu"
        android:layout_width="23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:gravity="center"
        android:focusable="false"
        android:text="asu"/>

    <ImageButton
        android:id="@+id/delete"
        android:layout_width="0.23dp"
        android:layout_height="53dp"
        android:layout_weight="0.20"
        android:focusable="false"
        android:src="@android:drawable/ic_menu_delete" />
</LinearLayout>


问:
zend form decorators
Having (more) issues with zend form decorators. I've got this so far:

Reset overall form decorator:

```<code>    $this->clearDecorators();
    $this->setDecorators(array('FormElements', 'Form'));
</code>```

I'm adding all my elements to a display group that i want to be inside a fieldset, within a DL

```<code>    $group->setDecorators(array(
           'FormElements',
            array('HtmlTag', array('tag' => 'dl')),
           'Fieldset'
    ));
</code>```

all working so far, now i want to place an image tag immediately before the fieldset. on its own this would work:

```<code>        $group->setDecorators(array(
            'FormElements',
            'Fieldset',
            array('HtmlTag',array('tag'=>'img','placement'=>'prepend','src'=>'/images/'.$imgs[$i-1]->im_name.'_main.jpg'))
        ));
</code>```

but this doesnt (it stops the DL being added inside the fieldset):

```<code>        $group->setDecorators(array(
            'FormElements',
            array('HtmlTag', array('tag' => 'dl')),
            'Fieldset',
            array('HtmlTag',array('tag'=>'img','placement'=>'prepend','src'=>'/images/'.$imgs[$i-1]->im_name.'_main.jpg'))
        ));
</code>```

Where am i going wrong?

答:
Thank you so much for this information! I got it working now as well.

This is the complete php code FYI:

```<code>    $generatePhraseVariations = new Zend_Form_Element_Checkbox('generatephrasevariations');
    $generatePhraseVariations->setLabel('Generate phrase variations')
        ->setCheckedValue('yes')
        ->setUncheckedValue('no')
        ->setChecked(TRUE)
        ->setDecorators($this->myCheckBoxElementDecorators);
    $generateSpellingMistakes = new Zend_Form_Element_Checkbox('generatespellingmistakes');
    $generateSpellingMistakes->setLabel('Generate Spelling Mistakes')
        ->setCheckedValue('yes')
        ->setUncheckedValue('no')
        ->setChecked(FALSE)
        ->setDecorators($this->myCheckBoxElementDecorators);
    $this->addElements(array($generatePhraseVariations,$generateSpellingMistakes));
    $this->addDisplayGroup(
        array('generatephrasevariations','generatespellingmistakes'),
        'rightpanel1');
    Zend_Registry::get('logger')->info($this->getDisplayGroup('rightpanel1')->getDecorators());
    $this->getDisplayGroup('rightpanel1')
        ->setLegend('Features')
        ->setDecorators(
            array(
                'FormElements',
                array(array('Mijn-OL-HtmlTag'=>'HtmlTag'),array('tag'=>'ol')),
                array('Fieldset'),
                array(array('Mijn-DIV-HtmlTag'=>'HtmlTag'),array('tag'=>'div','id'=>'rightpanel1')),
                )
        );
    Zend_Registry::get('logger')->info($this->getDisplayGroup('rightpanel1')->getDecorators());
</code>```

/

Title: zend form decorators

Body:
Having (more) issues with zend form decorators. I've got this so far:

Reset overall form decorator:

    $this->clearDecorators();
    $this->setDecorators(array('FormElements', 'Form'));

I'm adding all my elements to a display group that i want to be inside a fieldset, within a DL

    $group->setDecorators(array(
           'FormElements',
            array('HtmlTag', array('tag' => 'dl')),
           'Fieldset'
    ));

all working so far, now i want to place an image tag immediately before the fieldset. on its own this would work:

        $group->setDecorators(array(
            'FormElements',
            'Fieldset',
            array('HtmlTag',array('tag'=>'img','placement'=>'prepend','src'=>'/images/'.$imgs[$i-1]->im_name.'_main.jpg'))
        ));

but this doesnt (it stops the DL being added inside the fieldset):

        $group->setDecorators(array(
            'FormElements',
            array('HtmlTag', array('tag' => 'dl')),
            'Fieldset',
            array('HtmlTag',array('tag'=>'img','placement'=>'prepend','src'=>'/images/'.$imgs[$i-1]->im_name.'_main.jpg'))
        ));

Where am i going wrong?

Body:
Thank you so much for this information! I got it working now as well.

This is the complete php code FYI:

    $generatePhraseVariations = new Zend_Form_Element_Checkbox('generatephrasevariations');
    $generatePhraseVariations->setLabel('Generate phrase variations')
        ->setCheckedValue('yes')
        ->setUncheckedValue('no')
        ->setChecked(TRUE)
        ->setDecorators($this->myCheckBoxElementDecorators);
    $generateSpellingMistakes = new Zend_Form_Element_Checkbox('generatespellingmistakes');
    $generateSpellingMistakes->setLabel('Generate Spelling Mistakes')
        ->setCheckedValue('yes')
        ->setUncheckedValue('no')
        ->setChecked(FALSE)
        ->setDecorators($this->myCheckBoxElementDecorators);
    $this->addElements(array($generatePhraseVariations,$generateSpellingMistakes));
    $this->addDisplayGroup(
        array('generatephrasevariations','generatespellingmistakes'),
        'rightpanel1');
    Zend_Registry::get('logger')->info($this->getDisplayGroup('rightpanel1')->getDecorators());
    $this->getDisplayGroup('rightpanel1')
        ->setLegend('Features')
        ->setDecorators(
            array(
                'FormElements',
                array(array('Mijn-OL-HtmlTag'=>'HtmlTag'),array('tag'=>'ol')),
                array('Fieldset'),
                array(array('Mijn-DIV-HtmlTag'=>'HtmlTag'),array('tag'=>'div','id'=>'rightpanel1')),
                )
        );
    Zend_Registry::get('logger')->info($this->getDisplayGroup('rightpanel1')->getDecorators());

/


问:
Shortest unique substrings of a vector
Say I have a character vector of some length,

```<code>vec <- c("man lives to work", "man works to live")
</code>```

Starting from the beginning, I'd now like to find the shortest unique substrings (of complete words) in this vector.
In other words, I'm not looking for the shortest substring overall, but I'd like crop the string after the word where it becomes unique, in this case after work and lives, respectively.

So the result should be, in this case:

```<code>[1] "man lives" "man works"
</code>```

The strings should be cropped after lives/works because that's the earliest point at which they become unique (in this context).
Including to would be redundant, because they are already unique.
Including only man would not be enough, because c("man", "man") is not unique.

(I want to use this to automatically generate valid R names, and base::make.names() will do the rest).

How do I do this?

I figured, there has to be a package out there which already does this, but couldn't find it.

答:
As a general strategy I would a) check to see if the first word is unique,
b) if not, check if the first two words are unique,
c) continue until unique solutions have been found for each string.

You could implement this usit a while loop, or using recursion. Here is an example of the later (UPDATED to preserve order):

```<code>library(stringi) ## makes string processing easier

vec <- c("man lives to work", "man works to live")

(word.mat <- stri_split_boundaries(vec,
                                   type = "word",
                                   skip_word_none = TRUE,
                                   simplify = TRUE))
##      [,1]  [,2]    [,3] [,4]
## [1,] "man" "lives" "to" "work"
## [2,] "man" "works" "to" "live"

## function to extract unique words
unique_words <- function(x, # matrix of words
                         n = nrow(x), # number of original strings
                         nc=1 # number of columns (words) to use
                         ) {
    ## join the first nc words
    s <- stri_trim(apply(x[, 1:nc, drop = FALSE], 1, stri_join, collapse = " "))
    ## find non-duplicated word combinations, and store in column 1
    nodups <- !s %in% s[stri_duplicated(s)]
    x[nodups, 1] <- s[nodups]
    ## remove extra words from the matrix
    x[nodups, -1] <- ""
    ## if some strings are not unique, do it again, increasing nc by one
    if(any(x[, 2] != "")) {
        x <- unique_words(x = x, n = n, nc = nc + 1)
    ## otherwise, grab the unique sub-phrases from column 1
    } else {
        x <- x[, 1]
    }
    ## return the result
    x
}
## test it out
unique_words(word.mat)
## [1] "man lives" "man works"

## test it out with a more complicated example:
vec <- c("foo", "man lives to eat", "man eats to live",
         "woman lives to work", "woman works to live",
         "we like apples", "we like peaches",
         "they like plums", "they love peas", "bar")
unique_words(stri_split_boundaries(vec,
                                   type = "word",
                                   skip_word_none = TRUE,
                                   simplify = TRUE))
## [1] "foo"             "man lives"       "man eats"        "woman lives"
## [5] "woman works"     "we like apples"  "we like peaches" "they like"
## [9] "they love"       "bar"
</code>```

Title: Shortest unique substrings of a vector

Body:
Say I have a character vector of some length,

vec <- c("man lives to work", "man works to live")

Starting from the beginning, I'd now like to find the shortest unique substrings (of complete words) in this vector.
In other words, I'm not looking for the shortest substring overall, but I'd like crop the string after the word where it becomes unique, in this case after work and lives, respectively.

So the result should be, in this case:

[1] "man lives" "man works"

The strings should be cropped after lives/works because that's the earliest point at which they become unique (in this context).
Including to would be redundant, because they are already unique.
Including only man would not be enough, because c("man", "man") is not unique.

(I want to use this to automatically generate valid R names, and base::make.names() will do the rest).

How do I do this?

I figured, there has to be a package out there which already does this, but couldn't find it.

Body:
As a general strategy I would a) check to see if the first word is unique,
b) if not, check if the first two words are unique,
c) continue until unique solutions have been found for each string.

You could implement this usit a while loop, or using recursion. Here is an example of the later (UPDATED to preserve order):

library(stringi) ## makes string processing easier

vec <- c("man lives to work", "man works to live")

(word.mat <- stri_split_boundaries(vec,
                                   type = "word",
                                   skip_word_none = TRUE,
                                   simplify = TRUE))
##      [,1]  [,2]    [,3] [,4]
## [1,] "man" "lives" "to" "work"
## [2,] "man" "works" "to" "live"

## function to extract unique words
unique_words <- function(x, # matrix of words
                         n = nrow(x), # number of original strings
                         nc=1 # number of columns (words) to use
                         ) {
    ## join the first nc words
    s <- stri_trim(apply(x[, 1:nc, drop = FALSE], 1, stri_join, collapse = " "))
    ## find non-duplicated word combinations, and store in column 1
    nodups <- !s %in% s[stri_duplicated(s)]
    x[nodups, 1] <- s[nodups]
    ## remove extra words from the matrix
    x[nodups, -1] <- ""
    ## if some strings are not unique, do it again, increasing nc by one
    if(any(x[, 2] != "")) {
        x <- unique_words(x = x, n = n, nc = nc + 1)
    ## otherwise, grab the unique sub-phrases from column 1
    } else {
        x <- x[, 1]
    }
    ## return the result
    x
}
## test it out
unique_words(word.mat)
## [1] "man lives" "man works"

## test it out with a more complicated example:
vec <- c("foo", "man lives to eat", "man eats to live",
         "woman lives to work", "woman works to live",
         "we like apples", "we like peaches",
         "they like plums", "they love peas", "bar")
unique_words(stri_split_boundaries(vec,
                                   type = "word",
                                   skip_word_none = TRUE,
                                   simplify = TRUE))
## [1] "foo"             "man lives"       "man eats"        "woman lives"
## [5] "woman works"     "we like apples"  "we like peaches" "they like"
## [9] "they love"       "bar"


问:
PrimeNG datatable filter by column - External textbox input
PrimeNg datatable uses built in [filter]="true". This will create a input text box internally that is used to filter data. How can I place this textbox outside the datatable and get the filter done for a particular column?

答:
Below is the code with external dropdown to  filter the primeng datatable.

html page:

```<code><!-- Top of the page -->
<div>
<p-dropdown [options]="orgs" [(ngModel)]="selectedOrg"  (onChange)="updateOrgFilter(dt);getFilteredOutput($event,dt)" styleClass="ui-column-filter"></p-dropdown>
</div>

<!-- Pie Chart -->

<!-- Bar Chart -->

<!-- Datatable -->

<p-dataTable #dt [value]="itemslist"  [rows]="30" [paginator]="true" [rowsPerPageOptions]="[30,50,75]" sortMode="multiple" scrollable="true"   resizableColumns="true" scrollHeight="350px">
    <p-header>
        <div class="ui-helper-clearfix">
            List of Items
        </div>
    </p-header>

    <p-column [style]="{'width':'100px'}"field="wipJobNum" header ="Title" [sortable]="true" [filter]="true" ></p-column>
    <p-column [style]="{'width':'150px'}"field="partNum" header ="Part Number" [sortable]="true" [filter]="true" ></p-column>
    <p-column [style]="{'width':'90px'}" field="org" header ="Org" [sortable]="true" [filter]="true"  filterMatchMode="equals">
        <ng-template pTemplate="filter" let-col>
            <p-dropdown [options]="orgs" [(ngModel)]="selectedOrg" appendTo="body" [style]="{'width':'100%'}"  (onChange)="dt.filter($event.value,col.field,col.filterMatchMode);getFilteredOutput(event,dt)"  styleClass="ui-column-filter"></p-dropdown>
        </ng-template>
    </p-column>
</p-dataTable>
</code>```

component.ts:

```<code>updateOrgFilter(dt) {
    dt.filter(this.selectedOrg, 'org', 'equals');
}
</code>```

In this example if you change value of org drop down inside the datatable , then the external dropdown will change and my charts will be updated.
 if you change the external drop down value then primeng datatable filter will be updated and displays the filtered output + charts will be updated.

Body:
Below is the code with external dropdown to  filter the primeng datatable.

html page:

<!-- Top of the page -->
<div>
<p-dropdown [options]="orgs" [(ngModel)]="selectedOrg"  (onChange)="updateOrgFilter(dt);getFilteredOutput($event,dt)" styleClass="ui-column-filter"></p-dropdown>
</div>

<!-- Pie Chart -->

<!-- Bar Chart -->

<!-- Datatable -->

<p-dataTable #dt [value]="itemslist"  [rows]="30" [paginator]="true" [rowsPerPageOptions]="[30,50,75]" sortMode="multiple" scrollable="true"   resizableColumns="true" scrollHeight="350px">
    <p-header>
        <div class="ui-helper-clearfix">
            List of Items
        </div>
    </p-header>

    <p-column [style]="{'width':'100px'}"field="wipJobNum" header ="Title" [sortable]="true" [filter]="true" ></p-column>
    <p-column [style]="{'width':'150px'}"field="partNum" header ="Part Number" [sortable]="true" [filter]="true" ></p-column>
    <p-column [style]="{'width':'90px'}" field="org" header ="Org" [sortable]="true" [filter]="true"  filterMatchMode="equals">
        <ng-template pTemplate="filter" let-col>
            <p-dropdown [options]="orgs" [(ngModel)]="selectedOrg" appendTo="body" [style]="{'width':'100%'}"  (onChange)="dt.filter($event.value,col.field,col.filterMatchMode);getFilteredOutput(event,dt)"  styleClass="ui-column-filter"></p-dropdown>
        </ng-template>
    </p-column>
</p-dataTable>

component.ts:

updateOrgFilter(dt) {
    dt.filter(this.selectedOrg, 'org', 'equals');
}

In this example if you change value of org drop down inside the datatable , then the external dropdown will change and my charts will be updated.
 if you change the external drop down value then primeng datatable filter will be updated and displays the filtered output + charts will be updated.


问:
Can `mvn compile` be expected to work with multi-module Maven reactor builds?
Can mvn compile be expected to work with multi-module Maven reactor builds?

I am trying to work on a project that uses a reactor/multi-module Maven build.  When mvn compile failed*, I was told by persons familiar with the project that mvn install is needed, and not mvn compile, because it is  a reactor build.

While  mvn install indeed works because Maven can then pull the build dependency out of the local repository, it seems wrong to me that I must publish to the repository since doing so can create problems, especially in CI environments.

However, nearly every example I can find surrounding a multi-module project uses mvn clean install, including Maven by Example.  I have found no examples of mvn compile that I can attribute to multi-module projects, making me inclined to think there is a Maven limitation/requirement here.

I note that mvn compile did work for me with the example provided in Maven by Example, but that  is a relatively simple project so I know I cannot take that to  mean it should work in general.

* It failed because it could not find one of the dependencies that was built successfully earlier in the reactor build.

答:
You can use --also-make-dependents option. It configures Maven to build the project and its dependents. Actually, the command examines all of the projects in reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

```<code>$ mvn --projects your-sample-project --also-make-dependents install
</code>```

Resource Link: Maven Tips and Tricks: Advanced Reactor Options

Body:
You can use --also-make-dependents option. It configures Maven to build the project and its dependents. Actually, the command examines all of the projects in reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

$ mvn --projects your-sample-project --also-make-dependents install

Resource Link: Maven Tips and Tricks: Advanced Reactor Options


问:
How to create reverse dns lookup zone for Premium HDInsight?
I have created a DNS zone in the azure. For example, for the IP range 192.0.2.128/26,I have created 128-26.2.0.192.in-addr.arpa. Now how should I create PTR records for Hdinsight vm's to be created ?</p>

答: When creating a reverse zone to host records for hosts with IPs that are in the 192.0.2.128/26 prefix, the zone name would be created by isolating the network prefix of the address (192.0.2) and then reversing the order (2.0.192) and adding the suffix .in-addr.arpa.


问:
Custom Filter of Core Image and "sig abrt" in Xcode 9.x
I'm writing a code. Here is my full source code.

I confirmed that my code runs successfully in Xcode 8.3.3.

However, my code crashed in Xcode 9.x (9.1 and 9.2).

Exactly, my code crashed in "filter.setValue(inputCIImage, forKey: kCIInputImageKey)" with "NSException (sig abrt)"

I did not find the cause even though I used the debugger.

result of Xcode 8.3.3

```<code>import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!

let inputImage = UIImage(named: "testImage.png")

override func viewDidLoad() {
    super.viewDidLoad()
    let inputCIImage = CIImage(image: inputImage!)

    let filter = CustomFilter()
    filter.setValue(inputCIImage, forKey: kCIInputImageKey)
    let outputImage = filter.outputImage!
    let context = CIContext()
    let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent)
    imageView.image = UIImage(cgImage: outputCGImage!)
}
}

class CustomFilter: CIFilter {
var inputImage: CIImage?

override public var outputImage: CIImage! {
    get {
        if let inputImage = self.inputImage {
            let args = [inputImage as AnyObject]
            return createCustomKernel().apply(extent: inputImage.extent, arguments: args)
        } else {
            return nil
        }
    }
}

func createCustomKernel() -> CIColorKernel {
    let kernelString =
        "kernel vec4 chromaKey(__sample s){\n" +
            "vec4 newPixel = s.rgba;\n" +
            "newPixel[0] = 0.0;\n" +
            "newPixel[2] = newPixel[2] / 2.0;\n" +
            "return newPixel;\n" + "}"
    return CIColorKernel(source: kernelString)!
}
}
</code>```

答:
The only way I've been able to use setValue(forKey:) is to actually register my custom filter. Granted, I've only been doing this in a Swift 4 app, but I'm rather surprised this worked in Swift 3.

Keep in mind, while `setValue(forKey:) is syntactically valid - meaning it will build - it's when CoreImage tried to execute your filter that any errors will arise.

I think you have two options:

(1) The easy one is to change how you pass the input image in (this is how I've done things since Swift 2). Try replacing that line with this:

```<code>filter.inputImage = inputCIImage
</code>```

(2) Register your filter. In your CustomFilter class, add this:

```<code>var inputImage: CIImage!

override var attributes: [String : Any] {
    return [
        kCIAttributeFilterDisplayName: "My custom filter",

        "inputImage": [kCIAttributeIdentity: 0,
                       kCIAttributeClass: "CIImage",
                       kCIAttributeDisplayName: "Image",
                       kCIAttributeType: kCIAttributeTypeImage]
    ]
}
</code>```

Next, subclass CIFilterConstructor:

```<code>class CustomFilters: NSObject, CIFilterConstructor {
    static func registerFilters() {
        CIFilter.registerName(
            "My custom filter",
            constructor: CustomFilters(),
            classAttributes: [
                kCIAttributeFilterCategories: [CategoryCustom]
            ])
    }
    func filter(withName name: String) -> CIFilter? {
        switch name {
        case "My custom filter":
            return CustomFilter()
        default:
            return nil
        }
    }
}
</code>```

Finally, in your app code, do these two things:

(A) Register your filter. I typically do this in viewDidLoad:

```<code>CustomFilters.RegisterFilters()
</code>```

(B) Instantiate your filter, calling it by name:

```<code>let filter = CIFilter(name: "My custom filter")
</code>```

Body:
I'm writing a code. Here is my full source code.

I confirmed that my code runs successfully in Xcode 8.3.3.

However, my code crashed in Xcode 9.x (9.1 and 9.2).

Exactly, my code crashed in "filter.setValue(inputCIImage, forKey: kCIInputImageKey)" with "NSException (sig abrt)"

I did not find the cause even though I used the debugger.

result of Xcode 8.3.3

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!

let inputImage = UIImage(named: "testImage.png")

override func viewDidLoad() {
    super.viewDidLoad()
    let inputCIImage = CIImage(image: inputImage!)

    let filter = CustomFilter()
    filter.setValue(inputCIImage, forKey: kCIInputImageKey)
    let outputImage = filter.outputImage!
    let context = CIContext()
    let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent)
    imageView.image = UIImage(cgImage: outputCGImage!)
}
}

class CustomFilter: CIFilter {
var inputImage: CIImage?

override public var outputImage: CIImage! {
    get {
        if let inputImage = self.inputImage {
            let args = [inputImage as AnyObject]
            return createCustomKernel().apply(extent: inputImage.extent, arguments: args)
        } else {
            return nil
        }
    }
}

func createCustomKernel() -> CIColorKernel {
    let kernelString =
        "kernel vec4 chromaKey(__sample s){\n" +
            "vec4 newPixel = s.rgba;\n" +
            "newPixel[0] = 0.0;\n" +
            "newPixel[2] = newPixel[2] / 2.0;\n" +
            "return newPixel;\n" + "}"
    return CIColorKernel(source: kernelString)!
}
}

Body:
The only way I've been able to use setValue(forKey:) is to actually register my custom filter. Granted, I've only been doing this in a Swift 4 app, but I'm rather surprised this worked in Swift 3.

Keep in mind, while `setValue(forKey:) is syntactically valid - meaning it will build - it's when CoreImage tried to execute your filter that any errors will arise.

I think you have two options:

(1) The easy one is to change how you pass the input image in (this is how I've done things since Swift 2). Try replacing that line with this:

filter.inputImage = inputCIImage

(2) Register your filter. In your CustomFilter class, add this:

var inputImage: CIImage!

override var attributes: [String : Any] {
    return [
        kCIAttributeFilterDisplayName: "My custom filter",

        "inputImage": [kCIAttributeIdentity: 0,
                       kCIAttributeClass: "CIImage",
                       kCIAttributeDisplayName: "Image",
                       kCIAttributeType: kCIAttributeTypeImage]
    ]
}

Next, subclass CIFilterConstructor:

class CustomFilters: NSObject, CIFilterConstructor {
    static func registerFilters() {
        CIFilter.registerName(
            "My custom filter",
            constructor: CustomFilters(),
            classAttributes: [
                kCIAttributeFilterCategories: [CategoryCustom]
            ])
    }
    func filter(withName name: String) -> CIFilter? {
        switch name {
        case "My custom filter":
            return CustomFilter()
        default:
            return nil
        }
    }
}

Finally, in your app code, do these two things:

(A) Register your filter. I typically do this in viewDidLoad:

CustomFilters.RegisterFilters()

(B) Instantiate your filter, calling it by name:

let filter = CIFilter(name: "My custom filter")


问:
Logback logs kept open by application and not deleting from disk
I have an Spring-Boot application on Linux that writes to service logs using Logback. Logback is setup to write to a file (account-service.log) and rotate the file at 10.5MB and finally delete the file on the 8th rotate. This is the default configuration.

The issue I'm having is the first log file created is written to past the 10.5MB size limit (it does rotate at the 10.5MB mark). So it's increasing in size until it becomes the 8th file and then it tries to get deleted. At this point the file is 84MB (10.5MB * 8) size. You can see here the file increasing in size

The main problem with that is that the OS tries to delete the file but since the application, because of Logback, still keeps it open then the filesystem doesn't show the deleted file (like with command find or du) and the system still keeps the space allocated on the disk. Also the file is still written to so it's taking up more and more disk space. I ran sudo lsof | grep deleted to find out that this file isn't being fully deleted.

Also interestingly the group that that first file belongs to is different than the rest. The first file has group root while the rest have the correct group name of account-service. This might be why the application can't close the file but I'm not sure.

The Logback dependency comes from my Spring-Boot pom:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Dalston.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

The subsequent log files do get deleted ok and don't get written to past the 10.5 MB limit.

Has anyone seen this issue or found a way to fix it?

答:
So I was able to solve most of my problems but one issue still remains.

The main issue was that I was using the built in logback xml for logging (base.xml). There it was configured for both console and file logging to be enabled.

```<code><root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
</root>
</code>```

So when I run it locally I get my logs written to my terminal and service log file which is good but the issue occurs on deployed instances. What happened was that both "CONSOLE" and "FILE" loggers where writing to the file which is why even after the first file rotated, it was still being written too. The "CONSOLE" logger was writing to the first file even though it rotated because from its point of view that file is the terminal. This also helped fix a double logging issue we were seeing.

My fix was to add my own logback xml (logback-spring.xml) to override the base.xml one.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<springProfile name="default">
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
</springProfile>
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<root level="INFO">
    <appender-ref ref="FILE" />
</root>
</code>```

This stops console logging on deployed instances and thus keeps the first file from logging past the 10.5MB limit. This fix fixed the disk space issue we experienced too.

The only issue I was not able to solve yet it why the file is kept open by the application and thus not allowing it to be fully deleted from the disk space.

Body:
I have an Spring-Boot application on Linux that writes to service logs using Logback. Logback is setup to write to a file (account-service.log) and rotate the file at 10.5MB and finally delete the file on the 8th rotate. This is the default configuration.

The issue I'm having is the first log file created is written to past the 10.5MB size limit (it does rotate at the 10.5MB mark). So it's increasing in size until it becomes the 8th file and then it tries to get deleted. At this point the file is 84MB (10.5MB * 8) size. You can see here the file increasing in size

The main problem with that is that the OS tries to delete the file but since the application, because of Logback, still keeps it open then the filesystem doesn't show the deleted file (like with command find or du) and the system still keeps the space allocated on the disk. Also the file is still written to so it's taking up more and more disk space. I ran sudo lsof | grep deleted to find out that this file isn't being fully deleted.

Also interestingly the group that that first file belongs to is different than the rest. The first file has group root while the rest have the correct group name of account-service. This might be why the application can't close the file but I'm not sure.

The Logback dependency comes from my Spring-Boot pom:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Dalston.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

The subsequent log files do get deleted ok and don't get written to past the 10.5 MB limit.

Has anyone seen this issue or found a way to fix it?

Body:
So I was able to solve most of my problems but one issue still remains.

The main issue was that I was using the built in logback xml for logging (base.xml). There it was configured for both console and file logging to be enabled.

<root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
</root>

So when I run it locally I get my logs written to my terminal and service log file which is good but the issue occurs on deployed instances. What happened was that both "CONSOLE" and "FILE" loggers where writing to the file which is why even after the first file rotated, it was still being written too. The "CONSOLE" logger was writing to the first file even though it rotated because from its point of view that file is the terminal. This also helped fix a double logging issue we were seeing.

My fix was to add my own logback xml (logback-spring.xml) to override the base.xml one.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<springProfile name="default">
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
</springProfile>
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<root level="INFO">
    <appender-ref ref="FILE" />
</root>

This stops console logging on deployed instances and thus keeps the first file from logging past the 10.5MB limit. This fix fixed the disk space issue we experienced too.

The only issue I was not able to solve yet it why the file is kept open by the application and thus not allowing it to be fully deleted from the disk space.


问:
Valgrind not showing line numbers when compiled with cmake
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

```<code>==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
</code>```

Not sure if this is helpful but here is my main CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)
</code>```

答: So, I don't know why but randomly valgrind started to show the line numbers... I didn't really do anything different, but either way it works... </p>

Body:
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)

Not sure if this is helpful but here is my main CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)


问:
Failing Android JUnit tests, not breaking my Ant script like I expect?
Failing JUnit tests, not breaking my Ant script like I expect?

My continuous integration server runs an Ant script, which calls something like:
/tests/ant run-tests

My JUnit tests run, but with errors:
run-tests:
     [echo] run-tests-helper.
     [echo] Running tests ...
     [exec]
     [exec] com.zedray.stuff.FooBarTest:....
     [exec] com.zedray.stuff.FooBarTest:.....INSTRUMENTATION_RESULT: shortMsg=Some error in your code.
     [exec] INSTRUMENTATION_RESULT: longMsg=java.security.InvalidParameterException: Some error in your code
     [exec] INSTRUMENTATION_CODE: 0

The errors are OK, but my build script keeps going (eventually publishing my broken app to my testers - bad!).  What I would expect is for the instrimentaiton to throw a build error, so my continuous integration server (TeamCity in this case) realises that something has gone wrong and reports a broken build.  The "failonerror" is already set in the relevant macrodef, so I'm not sure what else I can do?

/tests/build.xml

        Running tests ...

Any ideas/suggestions on how to fix this?

Regards
Mark

答:
Also was looking for some kind of standard solution for this. I wonder how do android guys develop, or they dont use teamcity and continuous integration? heard hudson has some plugin for android but I dont like hudson. anyway here is quick and dirty solution

replace  contents in android-sdk-windows\tools\ant\test_rules.xml  with:

```<code>        <attribute name="emma.enabled" default="false" />
    <element name="extra-instrument-args" optional="yes" />
    <sequential>
        <echo>Running tests ...</echo>
        <exec executable="${adb}" failonerror="true" outputproperty="tests.output">
            <arg line="${adb.device.arg}" />
            <arg value="shell" />
            <arg value="am" />
               <arg value="instrument" />
            <arg value="-w" />
            <arg value="-e" />
               <arg value="coverage" />
               <arg value="@{emma.enabled}" />
            <extra-instrument-args />
            <arg value="${manifest.package}/${test.runner}" />
    </exec>
    <echo message="${tests.output}"/>
    <fail message="Tests failed!!!">
            <condition>
                    <contains string="${tests.output}" substring="FAILURES" />
            </condition>
    </fail>
    </sequential>
</code>```

there are two drawbacks
1) you dont see test output while tests are running until they failed (and the output is crippled somewhow)
2) its better to override this macro in your project

Body:
Also was looking for some kind of standard solution for this. I wonder how do android guys develop, or they dont use teamcity and continuous integration? heard hudson has some plugin for android but I dont like hudson. anyway here is quick and dirty solution

replace  contents in android-sdk-windows\tools\ant\test_rules.xml  with:

        <attribute name="emma.enabled" default="false" />
    <element name="extra-instrument-args" optional="yes" />
    <sequential>
        <echo>Running tests ...</echo>
        <exec executable="${adb}" failonerror="true" outputproperty="tests.output">
            <arg line="${adb.device.arg}" />
            <arg value="shell" />
            <arg value="am" />
               <arg value="instrument" />
            <arg value="-w" />
            <arg value="-e" />
               <arg value="coverage" />
               <arg value="@{emma.enabled}" />
            <extra-instrument-args />
            <arg value="${manifest.package}/${test.runner}" />
    </exec>
    <echo message="${tests.output}"/>
    <fail message="Tests failed!!!">
            <condition>
                    <contains string="${tests.output}" substring="FAILURES" />
            </condition>
    </fail>
    </sequential>

there are two drawbacks
1) you dont see test output while tests are running until they failed (and the output is crippled somewhow)
2) its better to override this macro in your project


问:
Autofac InstancePerRequest scope - reuse the scope instance to other places
I am using Autofac as a dependency injection container in my project. I would like to make use of InstancePerRequest scope as I don't want those objects to outlive a request.

Below is the code I am using in the gateway class where I know each of my request will pass through it.

```<code>        using (var scope = _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
        {
            var service = scope.Resolve<MyTestService>();
            ...
        }
</code>```

Now in my code I locate several other classes where I need to resolve the MyTestService which at the moment is causing an exception with a message No scope with a Tag matching 'AutofacWebRequest'. The exception is because I am calling the resolve on a container instance, whereas I should call resolve on the same scope instance, as shown above.

Can someone please help me to know how do I access the same scope instance at those places in my code? I can't keep calling the BeingLifetimeScope in all the classes.

答:
Unfortunately I'm stuck on a phone and my house is being remodeled so I have no computer access. As such you'll get a shorter answer with no code but it should unstick you.

You say you've read the docs, so you should know:

When you create a scope in those using blocks it's not the same as the current request scope.

If your service is used inside an existing request then you should just be injecting what the service needs right into the constructor, not doing service location with a scope.

If your service is not used inside an existing request then you're on your own to figure out how to mimic a request around your service. There's no fixed way to deal with that since it's app specific.

If the whole point in needing a request scope is to get dependencies registered per request to resolve outside a request then you should switch to instance per lifetime scope.

If you must - and it's an anti-pattern, but if you must - you can put a constructor parameter in your service that is an ILifetimeScope. That will get the current scope injected.

It's not really possible from your question to tell why you need the scope. I'm guessing there may be better ways to do what you're trying to do but being stuck on my phone I can't really expand on the million possibilities and ways to work around doing what you say you need to do. In future questions consider explaining more about the context - why your service needs to pass through a "gateway" and why you're in the situation and not just injecting constructor parameters and letting Autofac integration do the heavy lifting.

Regardless, this should get you unstuck. If not, you'll need to clarify your question with additional context and maybe someone else can hop in.

Body:
I am using Autofac as a dependency injection container in my project. I would like to make use of InstancePerRequest scope as I don't want those objects to outlive a request.

Below is the code I am using in the gateway class where I know each of my request will pass through it.

        using (var scope = _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
        {
            var service = scope.Resolve<MyTestService>();
            ...
        }

Now in my code I locate several other classes where I need to resolve the MyTestService which at the moment is causing an exception with a message No scope with a Tag matching 'AutofacWebRequest'. The exception is because I am calling the resolve on a container instance, whereas I should call resolve on the same scope instance, as shown above.

Can someone please help me to know how do I access the same scope instance at those places in my code? I can't keep calling the BeingLifetimeScope in all the classes.


问:
how to convert Layout view to Bitmap excluding some components
in my layout I have a background, button and a textView, the button here serves to convert my view to bitmap and save it

I managed to do that but my png Image contains the save button as well,

I'm using this line  to get the drawing from my layout :

```<code>Bitmap cache = vw.getDrawingCache();
</code>```

What I want to achieve is that before getting the screen from the view , I want it to not consider my button.

Thanks in advance.

答:
Have you looked at setting the component to visibility gone?

```<code>Button saveButton = (Button) findViewById(R.id.save_button);
saveButton.setVisibility(View.GONE);
</code>```

Then after you get your snapshot make sure you do

```<code>saveButton.setVisibility(View.VISIBLE);
</code>```

The problem with this solution is that the screenshot will still contain the gap where the button was. The view does not get redrawn before the bitmap is saved. I have tried calling invalidate() and requestLayout() with no success (which is why I found your question).

Also, another alternative is to do something like what Anand said by drawing it to a Canvas. This is useful if your view is larger than the screen. By drawing it to a Canvas you can get the entire view. By going this route, you can have a container with your background and TextView and have the button outside that container. You can then get just the view with the container. (I can't use this solution since my button is in the middle of my desired data)

```<code>View v = findViewById(R.id.my_view); // the view containing your text view
// not needed since it is outside your my_view now
// v.findViewById(R.id.save_button).setVisibility(View.GONE);
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
// not needed since it is outside your my_view now
// v.findViewById(R.id.save_button).setVisibility(View.VISIBLE);

// your Bitmap "b" now contains the image you want
</code>```

Body:
in my layout I have a background, button and a textView, the button here serves to convert my view to bitmap and save it

I managed to do that but my png Image contains the save button as well,

I'm using this line  to get the drawing from my layout :

Bitmap cache = vw.getDrawingCache();

What I want to achieve is that before getting the screen from the view , I want it to not consider my button.

Thanks in advance.

Body:
Have you looked at setting the component to visibility gone?

Button saveButton = (Button) findViewById(R.id.save_button);
saveButton.setVisibility(View.GONE);

Then after you get your snapshot make sure you do

saveButton.setVisibility(View.VISIBLE);

The problem with this solution is that the screenshot will still contain the gap where the button was. The view does not get redrawn before the bitmap is saved. I have tried calling invalidate() and requestLayout() with no success (which is why I found your question).

Also, another alternative is to do something like what Anand said by drawing it to a Canvas. This is useful if your view is larger than the screen. By drawing it to a Canvas you can get the entire view. By going this route, you can have a container with your background and TextView and have the button outside that container. You can then get just the view with the container. (I can't use this solution since my button is in the middle of my desired data)

View v = findViewById(R.id.my_view); // the view containing your text view
// not needed since it is outside your my_view now
// v.findViewById(R.id.save_button).setVisibility(View.GONE);
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
// not needed since it is outside your my_view now
// v.findViewById(R.id.save_button).setVisibility(View.VISIBLE);

// your Bitmap "b" now contains the image you want


问:
Apply CountVectorizer to column with list of words in rows in Python
I made a preprocessing part for text analysis and after removing stopwords and stemming like this:

```<code>test[col] = test[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

train[col] = train[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])
</code>```

I've got a column with list of "cleaned words". Here are 3 rows in a column:

```<code>['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']
</code>```

I now want to apply CountVectorizer to this column:

```<code>from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) # will leave only 1500 words
X_train = cv.fit_transform(train[col])
</code>```

But I got an Error:

```<code>TypeError: expected string or bytes-like object
</code>```

It would be a bit strange to create string from list and than separate by CountVectorizer again.

答:
As I found no other way to avoid an error, I joined the lists in column

```<code>train[col]=train[col].apply(lambda x: " ".join(x) )
test[col]=test[col].apply(lambda x: " ".join(x) )
</code>```

Only after that I started to get the result

```<code>X_train = cv.fit_transform(train[col])
X_train=pd.DataFrame(X_train.toarray(), columns=cv.get_feature_names())
</code>```

Body:
I made a preprocessing part for text analysis and after removing stopwords and stemming like this:

test[col] = test[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

train[col] = train[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

I've got a column with list of "cleaned words". Here are 3 rows in a column:

['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']

I now want to apply CountVectorizer to this column:

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) # will leave only 1500 words
X_train = cv.fit_transform(train[col])

But I got an Error:

TypeError: expected string or bytes-like object

It would be a bit strange to create string from list and than separate by CountVectorizer again.

Body:
As I found no other way to avoid an error, I joined the lists in column

train[col]=train[col].apply(lambda x: " ".join(x) )
test[col]=test[col].apply(lambda x: " ".join(x) )

Only after that I started to get the result

X_train = cv.fit_transform(train[col])
X_train=pd.DataFrame(X_train.toarray(), columns=cv.get_feature_names())


问:
How important is it to follow web standards?
I recently found out that most of the major websites fail W3C's markup and CSS validation tests. Therefore, how important is it really to follow web standards?</p>

答:
Does anyone here use Hotmail?  Have you ever noticed that with each major Firefox release, Microsoft has to go back and make changes to their Hotmail website so that they won't be left behind in the latest Firefox release?

Would they have needed to do that if the developers respected standards?  How much time/money would they save?  How much of that time/money would they then be able to invest in newer technologies or new features?

You say that most of the major websites fail W3C's markup and CSS validation tests.  Look at most of the websites.  Do they look modern?  Do they look like the ones that do validate?  Are they the first to implement the latest and greatest features or are they stuck maintaining old and outdated technologies, feverishly and tirelessly trying to maintain a house of cards and hoping the winds of change won't knock it down?

There is an opportunity cost for every decision we make.  Sometimes the opportunity cost of skipping a standard can forge a profitable business partnership.  Other times, especially when standards aren't followed because of ignorance, the cost is being left behind because of bugs, random behavior, and guessing games.  Sometimes, following standards can create a platform of extensibility where new features can be added for years to come.


问:
Chrome Extension Injected Javascript Button Changes Page
So, I am working on an extension that will scoop up the values in some text fields on a page, and search them on another site to make sure they are not trademarked.

I have injected a button in the page, and when I click it, it works, but it also boots me out to the main page of the site, as though I were not logged in. However, I am still logged in and can hit "back" to get back to where I was, but then all my text fields are no longer filled in. This is obviously a problem for the end user.

Any ideas?

Here is my Content Script:

```<code>window.addEventListener("load", function load(event){

    var amz = document.getElementById("draft-field");
    var TMbutton = document.createElement("button");
    var text = document.createTextNode("TMHunt Your Product");
    TMbutton.className = "a-button a-button-primary scripter-button  button-fill"
    TMbutton.appendChild(text);
    amz.appendChild(TMbutton);

},false);

TMbutton.onclick = function() {
            chrome.runtime.sendMessage("test");
}
</code>```

This does create the button and has the desired effect, except for this side-effect of popping us into a different page. Would this be something to do with the host page receiving a message to do something from my Javascript somehow that I am not seeing?

答:
The button default type is submit. You should set the type to button so it won't trigger the form submit action.

```<code>window.addEventListener("load", function load(event){

    var amz = document.getElementById("draft-field");
    var TMbutton = document.createElement("button");
    var text = document.createTextNode("TMHunt Your Product");
    TMbutton.className = "a-button a-button-primary scripter-button  button-fill";
    TMbutton.type = "button";
    TMbutton.appendChild(text);
    amz.appendChild(TMbutton);

},false);

TMbutton.onclick = function() {
    chrome.runtime.sendMessage("test");
}
</code>```

Body:
So, I am working on an extension that will scoop up the values in some text fields on a page, and search them on another site to make sure they are not trademarked.

I have injected a button in the page, and when I click it, it works, but it also boots me out to the main page of the site, as though I were not logged in. However, I am still logged in and can hit "back" to get back to where I was, but then all my text fields are no longer filled in. This is obviously a problem for the end user.

Any ideas?

Here is my Content Script:

window.addEventListener("load", function load(event){

    var amz = document.getElementById("draft-field");
    var TMbutton = document.createElement("button");
    var text = document.createTextNode("TMHunt Your Product");
    TMbutton.className = "a-button a-button-primary scripter-button  button-fill"
    TMbutton.appendChild(text);
    amz.appendChild(TMbutton);

},false);

TMbutton.onclick = function() {
            chrome.runtime.sendMessage("test");
}

This does create the button and has the desired effect, except for this side-effect of popping us into a different page. Would this be something to do with the host page receiving a message to do something from my Javascript somehow that I am not seeing?

Body:
The button default type is submit. You should set the type to button so it won't trigger the form submit action.

window.addEventListener("load", function load(event){

    var amz = document.getElementById("draft-field");
    var TMbutton = document.createElement("button");
    var text = document.createTextNode("TMHunt Your Product");
    TMbutton.className = "a-button a-button-primary scripter-button  button-fill";
    TMbutton.type = "button";
    TMbutton.appendChild(text);
    amz.appendChild(TMbutton);

},false);

TMbutton.onclick = function() {
    chrome.runtime.sendMessage("test");
}


问:
How do I break out of this if?
I need to break out of the if statement when one of the for loops is used. But when I compile and run it, all three for loops give back info when I only need one. I know the answer is staring me in the face, but I just can't figure out what it is.</p>

```<code>if (filestat == 'S' || filestat == 's')
{

  for ( a = 0; a < 5000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .15;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 5000; a <= 20000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .22;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 20001; a >= 20001; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .31;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

}
</code>```

答:
I need to break out of the if statement when one of the for loops is used.

That doesn't make sense at all. Since inside the if statement all loops run unconditionally at least once (regardless of the break statement which does not make sense either), you cannot expect Java to magically "choose" one of the loops.

If you don't want the two latter to be run, why don't you just delete them?

Title: How do I break out of this if?

Body:
I need to break out of the if statement when one of the for loops is used. But when I compile and run it, all three for loops give back info when I only need one. I know the answer is staring me in the face, but I just can't figure out what it is.

if (filestat == 'S' || filestat == 's')
{

  for ( a = 0; a < 5000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .15;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 5000; a <= 20000; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .22;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

  for (a = 20001; a >= 20001; a++)
  {
     taxableincome = grossincome - 5000 - (1000 * exemptions);
     taxrate = .31;
     taxAmount = taxableincome * taxrate;
     System.out.println("Your Taxpayer ID is " + taxid);
     System.out.println("Your taxable income is $" + taxableincome);
     System.out.println("Your tax rate is %" + taxrate);
     System.out.println("Your tax amount is $" + taxAmount);

     break;
  }

}