问:
iCAL DTSTART and DTEND format confusion. Should be easy to answer
I'm writing an iCAL file.  I work on a cruise ship and the file will basically be my itinerary for the next 6 months, which I want to share with other crew members, to be displayed on our phones (a mixture of iPhones and Android phones).  I want to included the name of the port we visit, and the arrival and departure times.  So far, so easy.

BUT, on a cruise ship we pass through different time zones on an almost daily basis.  Some people use local carrier info to set their phone timezones, others adjust the timezone manually, and some don't bother doing either.  I tried this once before, but got very confused with TIMEZONE formats: whether to use UTC with a 'Z' prefix, whether to specify the country codes, etc.

HOWEVER, a recent bit of googling turned up the 'floating' DTSTART and DTEND format, aka 'Local Time', which seems to do away with all the region and timezone specifications. So, am I right in thinking the following will work?

(Source data: 23 Nov, Rio De Janeiro, 8:00am to 6:00pm,

 and 25 Nov, A Different Port, 10:00am to 8:30pm)

```<code>    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID: MyNameHere
    BEGIN:VEVENT
    UID:milesmuso.mf@qwertyqwertyqwerty.com
    DTSTAMP:20171123T080000Z
    DTSTART:20171123T080000
    DTEND:20171123T180000
    SUMMARY:Rio De Janiero
    END:VEVENT
    .
    BEGIN:VEVENT
    UID:milesmuso.mf@qwertyqwertyqwerty.com
    DTSTAMP:20171125T100000Z
    DTSTART:20171125T100000
    DTEND:20171125T203000
    SUMMARY:Another Port
    END:VEVENT
    .
    .
    BEGIN: VEVENT
    (next event here)
    END VEVENT
    END:VCALENDAR
</code>```

And if that syntax IS correct, then do I still need to specify DTSTAMP:20171123T080000Z with the 'Z' suffix? (something I read on https://www.kanzaki.com/docs/ical/dtstamp.html said that the 'Z' suffix is mandatory, even though I don't WANT to use UTC - I just want floating start and end times.)

Also, should the DTSTAMP time be the same as the DTSTART time for each event, or do I use the same one for each event?

I hope you can help

Thanks

Miles,

Musician,

Celebrity Infinity

答:
Using floating time means that the timezone that's actually used, is actually in the timezone of the viewer of the event.

So if you schedule something at 8PM floating time, and: "User A" has their timezone set to Eastern, and it's 7:55pm, the event will occur 5 minutes from now, then user "B" who has their phone set to Central time will see that the event starts one hour + 5 minutes from now.

In other words, using floating time means that the actual time as viewed by the user is going to depend on the viewer of the event.

This is not what you want. Because you are going to arriving and departing at fixed points in time. You really have two options:

Use UTC.

Use local time + a timezone of the port

UTC might be simpler in your case, but there's a caveat. You mention Rio De Janairo, and Brazil's treatment of DST (daylight savings time) has not been stellar.

So it's possible that you plan to arrive your ship at 2PM localtime somewhere, but a few weeks before you do, the Brazilian government decides to postpone or scrap daylight savings time that year. The question is then, does the boat depart an hour later (still 2PM local time) or does it depart at the exact same time from a UTC perspective?

You might consider this an edge case and make adjustments if needed, when they do but I thought it was worth talking about this scenario.

Anyway, ignoring that, both "local time + TZ" or "UTC" will probably be good enough for you. If you use "America/Sao_Paulo" for a departure time, and people:

Automatically got a time and timezone from a carrier, it will "just work"

Manually changed their timezone, it will "just work"

I think I would prefer the local time + TZ because it's the most 'accurate' representation of the event.

Body:
I'm writing an iCAL file.  I work on a cruise ship and the file will basically be my itinerary for the next 6 months, which I want to share with other crew members, to be displayed on our phones (a mixture of iPhones and Android phones).  I want to included the name of the port we visit, and the arrival and departure times.  So far, so easy.

BUT, on a cruise ship we pass through different time zones on an almost daily basis.  Some people use local carrier info to set their phone timezones, others adjust the timezone manually, and some don't bother doing either.  I tried this once before, but got very confused with TIMEZONE formats: whether to use UTC with a 'Z' prefix, whether to specify the country codes, etc.

HOWEVER, a recent bit of googling turned up the 'floating' DTSTART and DTEND format, aka 'Local Time', which seems to do away with all the region and timezone specifications. So, am I right in thinking the following will work?

(Source data: 23 Nov, Rio De Janeiro, 8:00am to 6:00pm,

 and 25 Nov, A Different Port, 10:00am to 8:30pm)

    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID: MyNameHere
    BEGIN:VEVENT
    UID:milesmuso.mf@qwertyqwertyqwerty.com
    DTSTAMP:20171123T080000Z
    DTSTART:20171123T080000
    DTEND:20171123T180000
    SUMMARY:Rio De Janiero
    END:VEVENT
    .
    BEGIN:VEVENT
    UID:milesmuso.mf@qwertyqwertyqwerty.com
    DTSTAMP:20171125T100000Z
    DTSTART:20171125T100000
    DTEND:20171125T203000
    SUMMARY:Another Port
    END:VEVENT
    .
    .
    BEGIN: VEVENT
    (next event here)
    END VEVENT
    END:VCALENDAR

And if that syntax IS correct, then do I still need to specify DTSTAMP:20171123T080000Z with the 'Z' suffix? (something I read on https://www.kanzaki.com/docs/ical/dtstamp.html said that the 'Z' suffix is mandatory, even though I don't WANT to use UTC - I just want floating start and end times.)

Also, should the DTSTAMP time be the same as the DTSTART time for each event, or do I use the same one for each event?

I hope you can help

Thanks

Miles,

Musician,

Celebrity Infinity


来源: stackexchange

问:
SQL Returning remaining rows
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

```<code>Name   Qty-Have
A      10
B      10
C      5
</code>```

Table 2, Next two months of future orders for parts A, B, and C:

```<code>Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7
</code>```

Result, the earliest order date for when we will have insufficient inventory:

```<code>Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2
</code>```

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

答:
This approach involves creating a view in MySQL. The view contains a rolling cumulative sum of the future inventory.  The current Qty-have inventory is subtracted from the sum.  Some rows will therefore have a negative value, and they are eliminated with the HAVING clause:

```<code>CREATE OR REPLACE VIEW future_orders AS
(SELECT
  t2.name,
  t2.due,
  t1.qty_have as qty_have,
  t2.qty_need,
  (SELECT SUM(fo.qty_need) FROM table_2 fo WHERE fo.name = t2.name AND fo.due <= t2.due)-qty_have as qty_want
FROM table_2 t2
LEFT JOIN table_1 t1 ON t1.name = t2.name
HAVING qty_want > 0);
</code>```

Once the view is created, query for the earliest date and the latest date, for both 'Next Due' and 'Qty-Want' respectively:

```<code>SELECT
  t1.name,
  (SELECT fo.due FROM future_orders fo WHERE fo.name = t1.name ORDER BY fo.due ASC LIMIT 1) as 'Next Due',
  (SELECT fo.qty_want FROM future_orders fo WHERE fo.name = t1.name ORDER BY fo.due DESC LIMIT 1) as 'Qty-Want'
FROM table_1 t1
WHERE 1;
</code>```

This gives you the result you were looking for: next shipment date for the next order that will be uncovered, plus the quantity required to fulfill all the remaining demand.  'C' is returned as NULL because it actually does not require any inventory to be ordered.

ContentLicense: CC BY-SA 3.0

Title: SQL Returning remaining rows

Body:
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

Name   Qty-Have
A      10
B      10
C      5

Table 2, Next two months of future orders for parts A, B, and C:

Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7

Result, the earliest order date for when we will have insufficient inventory:

Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

Body:
This approach involves creating a view in MySQL. The view contains a rolling cumulative sum of the future inventory.  The current Qty-have inventory is subtracted from the sum.  Some rows will therefore have a negative value, and they are eliminated with the HAVING clause:

CREATE OR REPLACE VIEW future_orders AS
(SELECT
  t2.name,
  t2.due,
  t1.qty_have as qty_have,
  t2.qty_need,
  (SELECT SUM(fo.qty_need) FROM table_2 fo WHERE fo.name = t2.name AND fo.due <= t2.due)-qty_have as qty_want
FROM table_2 t2
LEFT JOIN table_1 t1 ON t1.name = t2.name
HAVING qty_want > 0);

Once the view is created, query for the earliest date and the latest date, for both 'Next Due' and 'Qty-Want' respectively:

SELECT
  t1.name,
  (SELECT fo.due FROM future_orders fo WHERE fo.name = t1.name ORDER BY fo.due ASC LIMIT 1) as 'Next Due',
  (SELECT fo.qty_want FROM future_orders fo WHERE fo.name = t1.name ORDER BY fo.due DESC LIMIT 1) as 'Qty-Want'
FROM table_1 t1
WHERE 1;

This gives you the result you were looking for: next shipment date for the next order that will be uncovered, plus the quantity required to fulfill all the remaining demand.  'C' is returned as NULL because it actually does not require any inventory to be ordered.


问:
Trying to use jQuery to trigger an anchor click after the page loads
So this has been asked a number of times on here, and while I've read all of the threads I can find, this still isn't working for me.

A little background: I'm working on a Wordpress site with a grid plugin, and I'm trying to trigger a filter when the page loads, depending on a url parameter. For the purpose of this thread I've just hardcoded a url parameter (the category variable) as an example because that functionality is working fine.

The anchor tag I'm trying to trigger:

```<code><a href="javascript:;" class="ladda-button" data-category="55" data-style="zoom-in">Tarps and Covers</a>
</code>```

The broken code I'm trying to use to trigger the click event:

```<code><script type="text/javascript">
    $(document).ready(function() {
        var hash = window.location.hash;
        var category = '55';
        var anchor = $("[data-category=" + category + "]");
        anchor.click();
    });
</script>
</code>```

A console log returning the anchor variable confirms that I'm selecting the correct jQuery object, and I've also tried anchor[0].click() to trigger it with no success. Does anyone see any problems that I'm overlooking?

答:
I tried it :

```<code>  $(document).ready(function() {
        var hash = window.location.hash;
        var category = '55';
        var anchor = $("[data-category=" + category + "]");
        anchor.click();
      anchor.on('click',()=>{
             alert();
       })
    });
</code>```

Everything is working

Body:
So this has been asked a number of times on here, and while I've read all of the threads I can find, this still isn't working for me.

A little background: I'm working on a Wordpress site with a grid plugin, and I'm trying to trigger a filter when the page loads, depending on a url parameter. For the purpose of this thread I've just hardcoded a url parameter (the category variable) as an example because that functionality is working fine.

The anchor tag I'm trying to trigger:

Tarps and Covers

The broken code I'm trying to use to trigger the click event:

A console log returning the anchor variable confirms that I'm selecting the correct jQuery object, and I've also tried anchor[0].click() to trigger it with no success. Does anyone see any problems that I'm overlooking?

Body:
I tried it :

  $(document).ready(function() {
        var hash = window.location.hash;
        var category = '55';
        var anchor = $("[data-category=" + category + "]");
        anchor.click();
      anchor.on('click',()=>{
             alert();
       })
    });

Everything is working


问:
R accumulating memory in each iteration with large input files
I am reading around 20,000 text files in a for loop for sentiment analysis. Each file is of around 20-40 MB size. In each loop, I am taking out some sentiment counts (just a 2 numbers) out of my input text and storing it in a dataframe. The issue is, in each iteration, I can see R is cumulatively accumulating memory. After 10,000 files I see around 13GB memory allocation for R in my task manager. I tried gc() and rm() to delete objects after each iteration, but still it does not work. The logic is as I am using the same objects iteratively R is not releasing memory used in the previous iterations.</p>

```<code>for(i in 1:20,000){
 filename <- paste0("file_", i, ".txt")
 text <- readLines(filename)

 # Doing sentiment analysis based on dictionary based approach

 # Storing sentiment counts in dataframe

 # Removing used objects
 rm(filename, text)
 gc()
}
</code>```

答:
You could try to check which objects are taking memory and that you do not use anymore:

```<code>print(sapply(ls(), function(x) pryr::object_size(get(x))/1024/1024))
</code>```

(EDIT: just saw the comment with this almost identical advice)

this line will give you the size in Megabytes of every object present in the environment (in RAM).

Alternatively if nothing appears, you can call gc() several times instead of once like:

```<code>rm(filename, text)
for (i in 1:3) gc()
</code>```

It is usually more effective...
If nothing works, that could mean the memory is fragmented and thus RAM is free but unavailable to use as misplaced between data you still use.
The solution could be to run your scripts by chunks of files say 1000 by 1000.

Body:
I am reading around 20,000 text files in a for loop for sentiment analysis. Each file is of around 20-40 MB size. In each loop, I am taking out some sentiment counts (just a 2 numbers) out of my input text and storing it in a dataframe. The issue is, in each iteration, I can see R is cumulatively accumulating memory. After 10,000 files I see around 13GB memory allocation for R in my task manager. I tried gc() and rm() to delete objects after each iteration, but still it does not work. The logic is as I am using the same objects iteratively R is not releasing memory used in the previous iterations.

for(i in 1:20,000){
 filename <- paste0("file_", i, ".txt")
 text <- readLines(filename)

 # Doing sentiment analysis based on dictionary based approach

 # Storing sentiment counts in dataframe

 # Removing used objects
 rm(filename, text)
 gc()
}

Body:
You could try to check which objects are taking memory and that you do not use anymore:

print(sapply(ls(), function(x) pryr::object_size(get(x))/1024/1024))

(EDIT: just saw the comment with this almost identical advice)

this line will give you the size in Megabytes of every object present in the environment (in RAM).

Alternatively if nothing appears, you can call gc() several times instead of once like:

rm(filename, text)
for (i in 1:3) gc()

It is usually more effective...
If nothing works, that could mean the memory is fragmented and thus RAM is free but unavailable to use as misplaced between data you still use.
The solution could be to run your scripts by chunks of files say 1000 by 1000.


问:
Visual Studio Debugger - Visualising Intel Quadruple precision (_Quad)
I'm using Intel C++ Compiler from within Visual Studio 2008. I was experimenting with the Intel quadruple precision type (_Quad). Everything seems to be working fine, except for the debugging. Visual Studio visualiser is unable to peek into _Quad values.

What's worse, the visualiser is unable to provide the type information about the _Quad value, giving enigmatic three question marks: ??? (as on the attached screenshot)

The value is 0 while it should be something else.

Would appreciate some hints on how to attack this puzzle. To work with autoexp.dat I need the VS to pickup the type, don't I?

答: _Quad is a keyword for Intel C++ compiler, which means it's type info is proprietary and not understandable by Microsoft tools.  To display it in VisualStudio Debugger/IDE, you'll need VisualStudio extensions that can interpret this type for the debugger/IDE.  You might want just contact Intel and see if they have any extensions for you to use in VisualStudio.</p>

ContentLicense: CC BY-SA 2.5


问:
Full-width image with aspect ratio in React Native
I want to require() a static image in a Home screen component I've written, and I want that image to be the full width of the display (which here happens to also be the full width of the container) while maintaining the aspect ratio.

Here is what I have so far. The Home component:

```<code>import React, { Component } from "react";
import {
    StatusBar,
} from "react-native";

import Container from "../components/Container/Container";
import Header from "../components/Header/Header";
import FullWidthImage from "../components/Images/FullWidthImage";

export default class Home extends Component {
    render() {
        return (
            <Container>
                <FullWidthImage source={require("./lifting.jpg")}/>
                <Header/>
                <StatusBar translucent={false}/>
            </Container>
        );
    }
}
</code>```

And the FullWidthImage component:

```<code>import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";

import Proptypes from "prop-types";

export default class FullWidthImage extends Component {
    render() {
        return (
            <Image source={this.props.source} style={style.image} resizeMode="contain"/>
        );
    }
}

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
    }
});
</code>```

I've been trying for a while and looking around on SO for a good answer but I can't find one (for an example some of them assume you have an uri and are not using require()). Greatly appreciate the help!

答:
Use resizeMode (https://facebook.github.io/react-native/docs/image.html#style)

```<code>resizeMode: "cover"
</code>```

In your code:

```<code>...

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
        resizeMode: "cover"
    },
    container: {flex:1}
});
</code>```

Or try with other types:  contain, cover, stretch, center, repeat.

Body:
I want to require() a static image in a Home screen component I've written, and I want that image to be the full width of the display (which here happens to also be the full width of the container) while maintaining the aspect ratio.

Here is what I have so far. The Home component:

import React, { Component } from "react";
import {
    StatusBar,
} from "react-native";

import Container from "../components/Container/Container";
import Header from "../components/Header/Header";
import FullWidthImage from "../components/Images/FullWidthImage";

export default class Home extends Component {
    render() {
        return (
            <Container>
                <FullWidthImage source={require("./lifting.jpg")}/>

                <StatusBar translucent={false}/>
            </Container>
        );
    }
}

And the FullWidthImage component:

import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";

import Proptypes from "prop-types";

export default class FullWidthImage extends Component {
    render() {
        return (
            <Image source={this.props.source} style={style.image} resizeMode="contain"/>
        );
    }
}

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
    }
});

I've been trying for a while and looking around on SO for a good answer but I can't find one (for an example some of them assume you have an uri and are not using require()). Greatly appreciate the help!

Body:
Use resizeMode (https://facebook.github.io/react-native/docs/image.html#style)

resizeMode: "cover"

In your code:

...

const style = StyleSheet.create({
    image: {
        flex: 1,
        width: "100%",
        borderColor: "red", borderWidth: 2,
        resizeMode: "cover"
    },
    container: {flex:1}
});

Or try with other types:  contain, cover, stretch, center, repeat.


问:
Maximizing window and layout pass
So goal here is to use custom ScrollBar for ScrollPane without having trouble with layout when maximizing/minimizing window.

Consider example program:

```<code>import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Layout extends Application
{
    @Override
    public void start(Stage stage)
    {
        BorderPane main = new BorderPane();
        main.setPrefSize(800, 600);

        BorderPane center = new BorderPane(); // begin center
        center.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
        main.setCenter(center); // end center

        BorderPane left = new BorderPane(); // begin left

        ScrollPane pane = new ScrollPane();
        pane.setFitToWidth(true);

        Pane p1 = new Pane(); // child 1
        p1.setPrefSize(200, 100);
        p1.setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
        this.makeResizable(p1);
        Pane p2 = new Pane(); // child 2
        p2.setPrefSize(200, 100);
        p2.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
        this.makeResizable(p2);
        VBox content = new VBox(10, p1, p2); // content in scroll pane
        pane.setContent(content);

        // replace normal bars
        pane.setHbarPolicy(ScrollBarPolicy.NEVER);
        pane.setVbarPolicy(ScrollBarPolicy.NEVER);

        // with custom
        ScrollBar sb = new ScrollBar();
        sb.setOrientation(Orientation.VERTICAL);
        sb.minProperty().bind(pane.vminProperty());
        sb.maxProperty().bind(pane.vmaxProperty());
        sb.visibleAmountProperty().bind(pane.heightProperty().divide(content.heightProperty()));
        sb.managedProperty().bind(sb.visibleAmountProperty().lessThan(1.0)); // bar should be managed when it is needed (content too long)
        sb.visibleProperty().bind(sb.managedProperty()); // and also visible only when managed
        sb.valueProperty().bindBidirectional(pane.vvalueProperty());

        left.setCenter(pane); // content
        left.setRight(sb); // scroll bar
        main.setLeft(left); //end left

        Scene scene = new Scene(main);
        stage.setScene(scene);
        stage.show();
    }

    // Simple for testing
    double prevY;
    boolean dragging;

    // Makes node resizable on drag.
    private void makeResizable(Region region)
    {
        region.addEventFilter(MouseEvent.MOUSE_PRESSED, e ->
        {
            this.dragging = true;
            region.setPrefHeight(region.getHeight());
            this.prevY = e.getSceneY();
        });
        region.addEventFilter(MouseEvent.MOUSE_DRAGGED, e ->
        {
            if (!this.dragging) return;
            region.setPrefHeight(region.getPrefHeight() + (e.getSceneY() - this.prevY));
            this.prevY = e.getSceneY();
        });
        region.addEventFilter(MouseEvent.MOUSE_RELEASED, e -> this.dragging = false);
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}
</code>```

It will produce GUI with ScrollPane on the left with a custom ScrollBar that appears when content (2 nodes p1 and p2) exceed bounds. In order to make it easy to test - both p1 and p2 are made resizable when dragging them with mouse (try it). While the ScrollBar appears and works as expected, there is a flaw in layout if we would start maximizing and minimizing window.

For example:

Start program

Resize content so ScrollBar appears, but not too
much (make it so that when you maximize it, it will be in bounds)

Maximize window - you will notice that bar might have disappeard, but "empty space" appears.

Now, if you would somehow make refresh (e.g by resizing content again), bar would disappear due to layout pass update.

Other bug:

Start program and maximize.

Resize content so it is still contained in maximized window, but is big enough that when you minimize, it will exceed bounds.

Minimize

Notice how ScrollBar is misplaced.

There are few other bugs if you would try other stuff, but all originate from the fact that when you maximize/minimize this happens (using 1st example):

ScrollBar is managed and visible (considering content exceeds).

Maximize

Window is resized layout is calculated (using old values - managed=true && visible=true)

Layout happens, everything is in place, all properties receive update, including sb.visibleAmountProperty() making ScrollBar set managed and visible to false (since they are bound, see code).

ScrollBar becomes invisible and unmanaged, but layout already happened, and will not re-run.

How do I make it work with window maximizing? How else could I bind ScrollBar so it doesn't break when maximizing? Please note that we talk about maximizing, not resizing (which works).

答:
I found one workaround, but it doesn't seem like absolutely best thing to do, if there is more proper one - please share.

```<code>sb.managedProperty().addListener(e -> Platform.runLater(() -> content.requestLayout()));
</code>```

Since this will be ran "later" (and since also on main thread which 1st should finish previous layout), this will cause relayout to happen.

Why is it not best? Well for one it would be called also when not really needed (while not maximizing) causing double layout (and we can't really resove this with some if statement).

Title: Maximizing window and layout pass

Body:
So goal here is to use custom ScrollBar for ScrollPane without having trouble with layout when maximizing/minimizing window.

Consider example program:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Layout extends Application
{
    @Override
    public void start(Stage stage)
    {
        BorderPane main = new BorderPane();
        main.setPrefSize(800, 600);

        BorderPane center = new BorderPane(); // begin center
        center.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
        main.setCenter(center); // end center

        BorderPane left = new BorderPane(); // begin left

        ScrollPane pane = new ScrollPane();
        pane.setFitToWidth(true);

        Pane p1 = new Pane(); // child 1
        p1.setPrefSize(200, 100);
        p1.setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
        this.makeResizable(p1);
        Pane p2 = new Pane(); // child 2
        p2.setPrefSize(200, 100);
        p2.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
        this.makeResizable(p2);
        VBox content = new VBox(10, p1, p2); // content in scroll pane
        pane.setContent(content);

        // replace normal bars
        pane.setHbarPolicy(ScrollBarPolicy.NEVER);
        pane.setVbarPolicy(ScrollBarPolicy.NEVER);

        // with custom
        ScrollBar sb = new ScrollBar();
        sb.setOrientation(Orientation.VERTICAL);
        sb.minProperty().bind(pane.vminProperty());
        sb.maxProperty().bind(pane.vmaxProperty());
        sb.visibleAmountProperty().bind(pane.heightProperty().divide(content.heightProperty()));
        sb.managedProperty().bind(sb.visibleAmountProperty().lessThan(1.0)); // bar should be managed when it is needed (content too long)
        sb.visibleProperty().bind(sb.managedProperty()); // and also visible only when managed
        sb.valueProperty().bindBidirectional(pane.vvalueProperty());

        left.setCenter(pane); // content
        left.setRight(sb); // scroll bar
        main.setLeft(left); //end left

        Scene scene = new Scene(main);
        stage.setScene(scene);
        stage.show();
    }

    // Simple for testing
    double prevY;
    boolean dragging;

    // Makes node resizable on drag.
    private void makeResizable(Region region)
    {
        region.addEventFilter(MouseEvent.MOUSE_PRESSED, e ->
        {
            this.dragging = true;
            region.setPrefHeight(region.getHeight());
            this.prevY = e.getSceneY();
        });
        region.addEventFilter(MouseEvent.MOUSE_DRAGGED, e ->
        {
            if (!this.dragging) return;
            region.setPrefHeight(region.getPrefHeight() + (e.getSceneY() - this.prevY));
            this.prevY = e.getSceneY();
        });
        region.addEventFilter(MouseEvent.MOUSE_RELEASED, e -> this.dragging = false);
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}

It will produce GUI with ScrollPane on the left with a custom ScrollBar that appears when content (2 nodes p1 and p2) exceed bounds. In order to make it easy to test - both p1 and p2 are made resizable when dragging them with mouse (try it). While the ScrollBar appears and works as expected, there is a flaw in layout if we would start maximizing and minimizing window.

For example:

Start program

Resize content so ScrollBar appears, but not too
much (make it so that when you maximize it, it will be in bounds)

Maximize window - you will notice that bar might have disappeard, but "empty space" appears.

Now, if you would somehow make refresh (e.g by resizing content again), bar would disappear due to layout pass update.

Other bug:

Start program and maximize.

Resize content so it is still contained in maximized window, but is big enough that when you minimize, it will exceed bounds.

Minimize

Notice how ScrollBar is misplaced.

There are few other bugs if you would try other stuff, but all originate from the fact that when you maximize/minimize this happens (using 1st example):

ScrollBar is managed and visible (considering content exceeds).

Maximize

Window is resized layout is calculated (using old values - managed=true && visible=true)

Layout happens, everything is in place, all properties receive update, including sb.visibleAmountProperty() making ScrollBar set managed and visible to false (since they are bound, see code).

ScrollBar becomes invisible and unmanaged, but layout already happened, and will not re-run.

How do I make it work with window maximizing? How else could I bind ScrollBar so it doesn't break when maximizing? Please note that we talk about maximizing, not resizing (which works).

Body:
I found one workaround, but it doesn't seem like absolutely best thing to do, if there is more proper one - please share.

sb.managedProperty().addListener(e -> Platform.runLater(() -> content.requestLayout()));

Since this will be ran "later" (and since also on main thread which 1st should finish previous layout), this will cause relayout to happen.

Why is it not best? Well for one it would be called also when not really needed (while not maximizing) causing double layout (and we can't really resove this with some if statement).


问:
Where on memory are struct fields allocated if we allocate struct with malloc?
Here we have a struct, then, we allocate an instance of it with malloc:

```<code>typedef struct _MyStruct {
    struct *nextStruct;
    char array[4];
} MyStruct

/* Allocates space on heap for the struct */
_MyStruct *m = malloc(sizeof(MyStruct));
printf("%zu bytes\n", sizeof(MyStruct)); /* Outputs: 8 bytes */

int r;

/* We intentionally overflow the buffer inside of the struct */
r = (int)gets(m->array); /* Input */
    if (r == 0)
         return;
</code>```

As per what I have understood so far. Are these affirmations correct?

When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.

If we insert the string 'abcdefghi' (9 bytes), we overrun the struct itself, which I assume is on the heap. But we also overrun the char array on the stack.

Edit: To be more accurate, this question is based on the C99 standard, implemented by an i686 O.S.

答:
When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.

No, the struct, and its associated elements are created dynamically via malloc.  So the entire struct, including the char array lies on the heap.

Body:
Here we have a struct, then, we allocate an instance of it with malloc:

typedef struct _MyStruct {
    struct *nextStruct;
    char array[4];
} MyStruct

/* Allocates space on heap for the struct */
_MyStruct *m = malloc(sizeof(MyStruct));
printf("%zu bytes\n", sizeof(MyStruct)); /* Outputs: 8 bytes */

int r;

/* We intentionally overflow the buffer inside of the struct */
r = (int)gets(m->array); /* Input */
    if (r == 0)
         return;

As per what I have understood so far. Are these affirmations correct?

When we populate the string 'abcde' (5 bytes), we overrun the char array inside the struct, which resides on the stack.

If we insert the string 'abcdefghi' (9 bytes), we overrun the struct itself, which I assume is on the heap. But we also overrun the char array on the stack.

Edit: To be more accurate, this question is based on the C99 standard, implemented by an i686 O.S.


答:
Assuming the rectifications suggested in the comments are correct, please find a dplyr solution below:

```<code>merge(DT1, DT2, by = "id", all = TRUE) %>%
    filter(t2 >= start_time, t1 <= end_time) %>%
    mutate(t1_adj = if_else(start_time > t1, start_time, t1),
           t2_adj = if_else(end_time < t2, end_time, t2),
           difftime = difftime(t2_adj, t1_adj, units = "secs")) %>%
    group_by(id, start_time, end_time) %>%
    summarize(durationFromDT2 = sum(difftime)) %>%
    right_join(DT1) %>%
    mutate(durationFromDT2 = coalesce(durationFromDT2, 0))
</code>```

cross join all records between each of the tables

filter down the cross join to contain just those DT2 times that have a timepoint within the DT1 interval.

mutate _adjusted columns to force the t1 and t2 times to remain constrained between DT1 start and end timepoints, and then calculate the time intervals.

group and summarize the durations by DT1 records.

To list all of the NULL records in the final result, right_join the DT1 table back on again.

Replace the NAs with 0's.

The result looks like this:

```<code># A tibble: 5 x 4
# Groups:   id, start_time [5]
     id          start_time            end_time durationFromDT2
  <int>              <dttm>              <dttm>          <time>
1   604 2017-08-10 18:44:14 2017-08-10 19:33:17        180 secs
2   604 2017-08-10 20:38:20 2017-08-10 20:44:44        240 secs
3   604 2017-08-10 20:54:26 2017-08-10 20:58:48          0 secs
4   604 2017-08-10 21:35:50 2017-08-10 22:03:14        300 secs
5   604 2017-08-10 22:05:42 2017-08-10 22:17:12          0 secs
</code>```

Reproducible (rectified) sample dataframes from the OP are below:

```<code>library(lubridate)
DT1 <-
    read.table(text = "
                        id         start_date start_time  end_date   end_time
                        604        2017-08-10 18:44:14    2017-08-10 19:33:17
                        604        2017-08-10 20:38:20    2017-08-10 20:44:44
                        604        2017-08-10 20:54:26    2017-08-10 20:58:48
                        604        2017-08-10 21:35:50    2017-08-10 22:03:14
                        604        2017-08-10 22:05:42    2017-08-10 22:17:12
                      ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(start_time = ymd_hms(paste(start_date, start_time)),
           end_time   = ymd_hms(paste(end_date, end_time))) %>%
    select(-c(start_date, end_date))

DT2 <-
    read.table(text = "
                         id         d1         t1          d2         t2
                         604        2017-08-10 18:40:14    2017-08-10 18:44:14
                         604        2017-08-10 18:44:14    2017-08-10 18:47:14
                         604        2017-08-10 19:44:14    2017-08-10 19:47:14
                         604        2017-08-10 20:30:14    2017-08-10 20:42:20
                         604        2017-08-10 21:44:14    2017-08-10 21:49:14
                         604        2017-08-10 22:44:14    2017-08-10 22:48:14
                      ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(t1 = ymd_hms(paste(d1,t1)),
           t2 = ymd_hms(paste(d2,t2)),
           ) %>%
    select(-c(d1, d2))
</code>```

Title: How to find the accumulated time between two

Body:
I have a two datatables like below:

DT1

  id            start_time             end_time
 604        2017-08-10 18:44:14    2017-08-11 19:33:17
 604        2017-08-10 20:38:20    2017-08-11 20:44:44
 604        2017-08-10 20:54:26    2017-08-11 20:58:48
 604        2017-08-10 21:35:50    2017-08-11 22:03:14
 604        2017-08-10 22:05:42    2017-08-11 22:17:12

.......

DT2

 id             t1                            t2
 604        2017-08-10 18:40:14    2017-08-11 18:44:14
 604        2017-08-10 18:44:14    2017-08-11 18:47:14
 604        2017-08-10 19:44:14    2017-08-11 19:47:14
 604        2017-08-10 20:30:14    2017-08-11 20:42:20
 604        2017-08-10 21:44:14    2017-08-11 21:49:14
 604        2017-08-10 22:44:14    2017-08-11 22:48:14

......

From these two I want to identify the accumulation of the DT2 rows lying inbetween the range of DT!.For example row 1 is starting from 2017-08-10 18:44:14 to 2017-08-11 19:33:17 So I want to take the accumulation of time in DT between that period and attach as column fro eah row  in DT1
for example the first row would be like

   id            start_time             end_time           durationFromDT2
   604        2017-08-10 18:44:14    2017-08-11 19:33:17       420
   604        2017-08-10 20:38:20    2017-08-11 20:44:44       240

The 420 is because of (2017-08-11 18:44:14-2017-08-10 18:40:14)+(2017-08-11 18:47:14-2017-08-10 18:44:14) .If there are no occurences in DT2 in the time period then I would like it to be 0.Like wise I have to group by many id's as well.

The 240 because of the time is (2017-08-11 20:42:20-2017-08-10 20:38:20)

So it's basically the coverage of DT2 for DT1 time period
I tried looping through the rows but did not go well.Instead I am looking for any dplyr or data table solutions.Because looping was not working well

Any help is appreciated.

Body:
Assuming the rectifications suggested in the comments are correct, please find a dplyr solution below:

merge(DT1, DT2, by = "id", all = TRUE) %>%
    filter(t2 >= start_time, t1 <= end_time) %>%
    mutate(t1_adj = if_else(start_time > t1, start_time, t1),
           t2_adj = if_else(end_time < t2, end_time, t2),
           difftime = difftime(t2_adj, t1_adj, units = "secs")) %>%
    group_by(id, start_time, end_time) %>%
    summarize(durationFromDT2 = sum(difftime)) %>%
    right_join(DT1) %>%
    mutate(durationFromDT2 = coalesce(durationFromDT2, 0))

cross join all records between each of the tables

filter down the cross join to contain just those DT2 times that have a timepoint within the DT1 interval.

mutate _adjusted columns to force the t1 and t2 times to remain constrained between DT1 start and end timepoints, and then calculate the time intervals.

group and summarize the durations by DT1 records.

To list all of the NULL records in the final result, right_join the DT1 table back on again.

Replace the NAs with 0's.

The result looks like this:

# A tibble: 5 x 4
# Groups:   id, start_time [5]
     id          start_time            end_time durationFromDT2
  <int>              <dttm>              <dttm>          <time>
1   604 2017-08-10 18:44:14 2017-08-10 19:33:17        180 secs
2   604 2017-08-10 20:38:20 2017-08-10 20:44:44        240 secs
3   604 2017-08-10 20:54:26 2017-08-10 20:58:48          0 secs
4   604 2017-08-10 21:35:50 2017-08-10 22:03:14        300 secs
5   604 2017-08-10 22:05:42 2017-08-10 22:17:12          0 secs

Reproducible (rectified) sample dataframes from the OP are below:

library(lubridate)
DT1 <-
    read.table(text = "
                        id         start_date start_time  end_date   end_time
                        604        2017-08-10 18:44:14    2017-08-10 19:33:17
                        604        2017-08-10 20:38:20    2017-08-10 20:44:44
                        604        2017-08-10 20:54:26    2017-08-10 20:58:48
                        604        2017-08-10 21:35:50    2017-08-10 22:03:14
                        604        2017-08-10 22:05:42    2017-08-10 22:17:12
                      ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(start_time = ymd_hms(paste(start_date, start_time)),
           end_time   = ymd_hms(paste(end_date, end_time))) %>%
    select(-c(start_date, end_date))

DT2 <-
    read.table(text = "
                         id         d1         t1          d2         t2
                         604        2017-08-10 18:40:14    2017-08-10 18:44:14
                         604        2017-08-10 18:44:14    2017-08-10 18:47:14
                         604        2017-08-10 19:44:14    2017-08-10 19:47:14
                         604        2017-08-10 20:30:14    2017-08-10 20:42:20
                         604        2017-08-10 21:44:14    2017-08-10 21:49:14
                         604        2017-08-10 22:44:14    2017-08-10 22:48:14
                      ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(t1 = ymd_hms(paste(d1,t1)),
           t2 = ymd_hms(paste(d2,t2)),
           ) %>%
    select(-c(d1, d2))


问:
Google Analytics click event not working, hitCallback also not firing
I have a text box on a web page that shows partial text and displays the rest of the paragraph when the user clicks on a "see full text" icon. We want to use google analytics to track how many users click on this icon.

Analytics is correctly tracking active sessions in live view, but no matter what I try, it cannot see the click events. There are no messages in the console.

```<code>$('document').ready(function() {
    $('.view-text').click(function(e) {
        ga('send', {
            'hitType': 'event',
            'eventCategory': 'button',
            'eventAction': 'Home',
            'eventLabel': 'View Text',
            'nonInteraction': true
        });
    });
});
</code>```

That was my code to send the events, but when I go to the analytics account Reports > Real-Time > Events, there are no events shown. I've clicked the box dozens of times now. I do see "1 active users on site" as expected.

To troubleshoot, I added a console.log in the click handler, which is showing up, so I know the ga function is being called. I then tried to add a 'hitCallback' option with an alert, and the 'alert' is NOT firing, but I don't know why that could be.

I'm wondering if I'm looking in the wrong place in the google analytics dashboard, or maybe I missed a step in the setup?

```<code>$('document').ready(function() {
    $('.view-text').click(function(e) {
        console.log('clickie');
        ga('send', {
            'hitType': 'event',
            'eventCategory': 'button',
            'eventAction': 'Home',
            'eventLabel': 'View Text',
            'hitCallback' : function () {
                alert("Event received");
            },
            'nonInteraction: true
        });
    });
});
</code>```

I've also tried this alternate syntax:

```<code>ga('send','event','button','Home','View Text', {
    nonInteraction: true
});
</code>```

Thanks very much SO for any help.

答:
Is it that your object properties are strings?

https://developers.google.com/analytics/devguides/collection/analyticsjs/events

Note on the above link that properties in the fieldsObject are not in quotation marks. Also, you have a syntax error on nonInteraction (missing closing quotation).

Body:
I have a text box on a web page that shows partial text and displays the rest of the paragraph when the user clicks on a "see full text" icon. We want to use google analytics to track how many users click on this icon.

Analytics is correctly tracking active sessions in live view, but no matter what I try, it cannot see the click events. There are no messages in the console.

$('document').ready(function() {
    $('.view-text').click(function(e) {
        ga('send', {
            'hitType': 'event',
            'eventCategory': 'button',
            'eventAction': 'Home',
            'eventLabel': 'View Text',
            'nonInteraction': true
        });
    });
});

That was my code to send the events, but when I go to the analytics account Reports > Real-Time > Events, there are no events shown. I've clicked the box dozens of times now. I do see "1 active users on site" as expected.

To troubleshoot, I added a console.log in the click handler, which is showing up, so I know the ga function is being called. I then tried to add a 'hitCallback' option with an alert, and the 'alert' is NOT firing, but I don't know why that could be.

I'm wondering if I'm looking in the wrong place in the google analytics dashboard, or maybe I missed a step in the setup?

$('document').ready(function() {
    $('.view-text').click(function(e) {
        console.log('clickie');
        ga('send', {
            'hitType': 'event',
            'eventCategory': 'button',
            'eventAction': 'Home',
            'eventLabel': 'View Text',
            'hitCallback' : function () {
                alert("Event received");
            },
            'nonInteraction: true
        });
    });
});

I've also tried this alternate syntax:

ga('send','event','button','Home','View Text', {
    nonInteraction: true
});

Thanks very much SO for any help.


问:
Why can template function parameters of type T& be binded to const lvalues but not rvalues?
Consider:

```<code>template <typename T> void f(T&);

const int b = 2;
f(b);      // ok
f(2);      // error, can not bind rvalue to lvalue reference
</code>```

Why is f(const int) allowed? the logic seems to indicate that if the programmer did not explicitly define the template parameter as const T&, he/she wanted to modify the binded-to variable.

So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required ?

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden? you can bind rvalues to const lvalue references. In that case, the template would be instantiated to f<const int>, and f(2) would be allowed.

I want to know the reasoning behind these decisions, not references to the standard.

答:
So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required?

Quite simply nothing in the implementation of f prevents instantiating the template with const int. Try the following instead and you'll observe a problem.

```<code>template <typename T> void f(T& v) { v = 3; };
const int b = 2;
f(b);      // error: assignment of read-only reference (within the template instance)
int c = 2;
f<const int>(c); // error
</code>```

The fact that b is const int means the template is instantiated as <const int> and this is not possible because v is modified. Explicit instantiation as <const int> is similarly disallowed.

Why is it deduced as const int? It should have been deduced as int.

When the type to instantiate the template is not explicitly specified, it is deduced based on the type passed into the function which is const int. Expecting it deduce a different type is impractical (if not outright absurd).

Please also note that if it did deduce the type as int then there would be an error passing const int into the function. As can be demonstrated by explicitly instantiating the template as <int>.

```<code>template <typename T> void f(T&) {};
const int b = 2;
f<int>(b); //error: no matching function for call to 'f<int>(const int&)
</code>```

why, in that case, would be binding to rvalues forbidden?

The compiler would need to implicitly assume an appropriate type to use for instantiating the template and then perform the implicit conversion from rvalue to const lvalue reference. (Seems a a stretch expectation to me.)

Note that if you explicitly instantiate the template as <const int> then binding rvalue to const lvalue reference works because the conversion can be done.

```<code>template <typename T> void f(T&);
f<const int>(2);      // OK
</code>```

Body:
Consider:

template <typename T> void f(T&);

const int b = 2;
f(b);      // ok
f(2);      // error, can not bind rvalue to lvalue reference

Why is f(const int) allowed? the logic seems to indicate that if the programmer did not explicitly define the template parameter as const T&, he/she wanted to modify the binded-to variable.

So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required ?

Even if there was a rationale for allowing template instantiation to instantiate with consts, then why, in that case, would be binding to rvalues forbidden? you can bind rvalues to const lvalue references. In that case, the template would be instantiated to f<const int>, and f(2) would be allowed.

I want to know the reasoning behind these decisions, not references to the standard.

Body:
So in this case the question is, why does template instantiation give itself the freedom to instantiate with consts when those were not explicitly required?

Quite simply nothing in the implementation of f prevents instantiating the template with const int. Try the following instead and you'll observe a problem.

template <typename T> void f(T& v) { v = 3; };
const int b = 2;
f(b);      // error: assignment of read-only reference (within the template instance)
int c = 2;
f<const int>(c); // error

The fact that b is const int means the template is instantiated as <const int> and this is not possible because v is modified. Explicit instantiation as <const int> is similarly disallowed.

Why is it deduced as const int? It should have been deduced as int.

When the type to instantiate the template is not explicitly specified, it is deduced based on the type passed into the function which is const int. Expecting it deduce a different type is impractical (if not outright absurd).

Please also note that if it did deduce the type as int then there would be an error passing const int into the function. As can be demonstrated by explicitly instantiating the template as <int>.

template <typename T> void f(T&) {};
const int b = 2;
f<int>(b); //error: no matching function for call to 'f<int>(const int&)

why, in that case, would be binding to rvalues forbidden?

The compiler would need to implicitly assume an appropriate type to use for instantiating the template and then perform the implicit conversion from rvalue to const lvalue reference. (Seems a a stretch expectation to me.)

Note that if you explicitly instantiate the template as <const int> then binding rvalue to const lvalue reference works because the conversion can be done.

template <typename T> void f(T&);
f<const int>(2);      // OK


问:
How to remove a light with shadowMode=deferred in Scenekit/ARKit?
I have ARKit-scene where i place a spotlight overhead to cast shadows.

Because i want to cast shadow on a transparent plane, i set the property shadowMode to deferred (https://developer.apple.com/documentation/scenekit/scnshadowmode/1523758-deferred) on the spotlight.

This works, but when i remove the spotlight again, the app crashes with:

[SceneKit] Error: The shadow node is not registered

[SceneKit] Error: _willExecuteDeferredShadows - no light

The app does not crash, when shadowMode is not set (defaults to "forward")

How can i remove the light without crashing?

答:
I found out that i need to set node.hidden=Yes on the node that contains the light before removing it. This provents the crash:</p>

```<code>if(node.light) {
  node.hidden = YES;
  [node removeFromParentNode];
}
</code>```

Body:
I found out that i need to set node.hidden=Yes on the node that contains the light before removing it. This provents the crash:

if(node.light) {
  node.hidden = YES;
  [node removeFromParentNode];
}


问:
How to configure a Amazon Route with SSL for a Heroku App
I need to set an Amazon Domain as a custom domain for a Heroku app. I found the next tutorial https://devcenter.heroku.com/articles/route-53 but it doesn't work if the app needs https requests. The first idea was to set up the SSL Certificate in Heroku, but the SSL Amazon Domain manager doesn't allow to download the certificate, so the SSL need to be managed by AWS.

What is the best way to add Amazon SSL to a Heroku app?

答:
The best option I found was to create an AWS CloudFront and configure it like Karan describes in his answer but with some add-ons:

Create a certificate from AWS Certificate Manager and approve it.

Create a CloudFront distribution with the Origin Domain Name as your Heroku URL such as myapp.herokuapp.com and the custom SSL certificate as the one you created from the AWS Cert Manager.

While creating the distribution, make sure that you have the TTL as 0, else all the responses will be cached

If you don't complete this step probably you will get an error like this:

This distribution is not configured to allow the HTTP request method that was used for the request. The distribution supports only cachable requests.

Follow the guide I mention in the question [https://devcenter.heroku.com/articles/route-53][4]


问:
Calling constructor of inherited class with only static methods
I have two Python classes. One inherits from the other. Both contain only static methods. The inherited class has class variables that need to be initialized from an external config file. I was trying to come up with a way to get the inherited class's constructor called without creating an instance.

The code below is a lean example of what I'm doing. The code works. I'm not sure, however, if this is just bad practice. I have no reason NOT to instantiate the class before use. I just wanted to develop a solution that did not require an instance to do what I need it to since the class is just static methods. It IS required that the inherited class's constructor is called.

Also, can someone tell me what the happens to the NEW class instance I create in the method 'foo'?

```<code>import json

class Cloud(object):
    val = None  # ....................................... Class Variable

    def __init__(self):  # .............................. Class Constructor
        with open('config.dat', 'r') as f:
            dat = json.load(f)
        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val):={}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()
</code>```

EDIT:

The class Cloud is used to MQTT data to a cloud server. Many other classes inherit from this so data transmissions are easily handled. The class Sensor is used to collect data from various sensors. At no point are any instances of these classes required because the data just gets passed along. The reason I use classes is to group certain methods together, again not required. The only thing I need is to run the constructor of Cloud so that the class variables get updated. I could handle this inside the staticmethod, I just didn't.

Again, just looking for feedback. Good idea, bad idea...

答:
Since it's effectively a static class variable, couldn't you just initialize it in the class definition?

I talking about something like this:

```<code>import json

class Cloud(object):
    with open('config.dat', 'r') as f:
        dat = json.load(f)
        val = dat['val']
        del dat  # Keep this variable from becoming a class attribute.

    def __init__(self):  # .............................. Class Constructor
#        with open('config.dat', 'r') as f:
#            dat = json.load(f)
#        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
#        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val): {}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()
</code>```

This way you wouldn't need to construct a throw-away instance of Cloud to get the variable initialized. Besides, it seems inefficient to be reading the (whole) file in everytime an instance is created.

Body:
I have two Python classes. One inherits from the other. Both contain only static methods. The inherited class has class variables that need to be initialized from an external config file. I was trying to come up with a way to get the inherited class's constructor called without creating an instance.

The code below is a lean example of what I'm doing. The code works. I'm not sure, however, if this is just bad practice. I have no reason NOT to instantiate the class before use. I just wanted to develop a solution that did not require an instance to do what I need it to since the class is just static methods. It IS required that the inherited class's constructor is called.

Also, can someone tell me what the happens to the NEW class instance I create in the method 'foo'?

import json

class Cloud(object):
    val = None  # ....................................... Class Variable

    def __init__(self):  # .............................. Class Constructor
        with open('config.dat', 'r') as f:
            dat = json.load(f)
        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val):={}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()

EDIT:

The class Cloud is used to MQTT data to a cloud server. Many other classes inherit from this so data transmissions are easily handled. The class Sensor is used to collect data from various sensors. At no point are any instances of these classes required because the data just gets passed along. The reason I use classes is to group certain methods together, again not required. The only thing I need is to run the constructor of Cloud so that the class variables get updated. I could handle this inside the staticmethod, I just didn't.

Again, just looking for feedback. Good idea, bad idea...

Body:
Since it's effectively a static class variable, couldn't you just initialize it in the class definition?

I talking about something like this:

import json

class Cloud(object):
    with open('config.dat', 'r') as f:
        dat = json.load(f)
        val = dat['val']
        del dat  # Keep this variable from becoming a class attribute.

    def __init__(self):  # .............................. Class Constructor
#        with open('config.dat', 'r') as f:
#            dat = json.load(f)
#        Cloud.val = dat['val']  # ....................... overwrite Class Variable
        print('Class Cloud -- constructor called.')

    @staticmethod
    def foo():  # ....................................... static method, does not require instance
#        Cloud.__init__(Cloud.__new__(Cloud))  # ......... call the constructor on a NEW instance
        print('Class Cloud, class variable (val): {}'.format(Cloud.val))

class Sensor(Cloud):

    @staticmethod
    def bar():
        print('bar')

# run Static Method of Inherited Class Cloud
# call Class Cloud constructor
Sensor.foo()

This way you wouldn't need to construct a throw-away instance of Cloud to get the variable initialized. Besides, it seems inefficient to be reading the (whole) file in everytime an instance is created.


问:
Resize a group of variably sized images both horizontally & vertically - need help optimising
WARNING CODE CRASHES IN EVERYTHING EXCEPT GOOGLE CHROME

I'm trying to create a feature on our website that takes 8 random images and places them in two rows and dynamically resizes the images to take up the full width of the page.

I've created a jsbin for this to try and demonstrate the issue.

https://jsbin.com/yijemazovi/edit?html,css,js,output

The comments in the code should give you an good idea of what I'm doing. What seems to be happening for everything but Google Chrome is that the while condition is never satisfied so it goes on infinitely and crashes the browser.

Perhaps it is something as simple as I am doing the do/while loop incorrectly or I should just be using a while loop???

Any help is appreciated!

```<code>/*****
 * Get the overall width of the container that we want to match
 **********/
var ContainerWidth = $('.feature-inim-collage .col.span_1_of_1').width();

/*****
 * Increase the height of the images until the total sum of the width
 * if the 4 images + the gutters is larger than ContainerWidth - then
 * stop
 **********/

/*****
 * Increment in jumps of 10px until we get within 80% of the width of
 * the ContainerWidth and then go to a more precise increment of 1px.
 * We can increase the px from 10 to 20 or 30 so there are less loops
 * but this can cause issues when we look at mobile and there is less
 * overall width in the containers and jumping by 30px will be too much
 **********/
var i = 0;
do {
  $('.feature-inims-top-row .growable-container').css('height', i);
  var RowWidth1 = CalculateTotalWidth(1);
  if(RowWidth1 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth1 < (ContainerWidth - 3));

/*****
 * Repeat above for the 2nd row
 **********/
var i = 0;
do {
  $('.feature-inims-bottom-row .growable-container').css('height', i);
  var RowWidth2 = CalculateTotalWidth(2);
  if(RowWidth2 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth2 < (ContainerWidth - 3));

/*********
 * Calculate the combined width of the images + the gutters
 ****/
function CalculateTotalWidth(Row) {
  var Image1Width = $('.growable-container-1').width();
  var Image2Width = $('.growable-container-2').width();
  var Image3Width = $('.growable-container-3').width();
  var Image4Width = $('.growable-container-4').width();
  var Image5Width = $('.growable-container-5').width();
  var Image6Width = $('.growable-container-6').width();
  var Image7Width = $('.growable-container-7').width();
  var Image8Width = $('.growable-container-8').width();
  var GutterSize = 24; // (3 gutters @ 8px each)

  if(Row == 1){
    var RowWidth = GutterSize + Image1Width + Image2Width + Image3Width + Image4Width;
  }else{
    var RowWidth = GutterSize + Image5Width + Image6Width + Image7Width + Image8Width;
  }
  return RowWidth
}
</code>```

答:
It turns out the issue with this was that in the CalculateTotalWidth() function I was checking the width of the container the image was in rather than the image itself. As soon as I changed this it worked perfectly.

```<code>var Image1Width = $('.growable-container-1 img').width();
</code>```

instead of

```<code>var Image1Width = $('.growable-container-1').width();
</code>```

Body:
WARNING CODE CRASHES IN EVERYTHING EXCEPT GOOGLE CHROME

I'm trying to create a feature on our website that takes 8 random images and places them in two rows and dynamically resizes the images to take up the full width of the page.

I've created a jsbin for this to try and demonstrate the issue.

https://jsbin.com/yijemazovi/edit?html,css,js,output

The comments in the code should give you an good idea of what I'm doing. What seems to be happening for everything but Google Chrome is that the while condition is never satisfied so it goes on infinitely and crashes the browser.

Perhaps it is something as simple as I am doing the do/while loop incorrectly or I should just be using a while loop???

Any help is appreciated!

/*****
 * Get the overall width of the container that we want to match
 **********/
var ContainerWidth = $('.feature-inim-collage .col.span_1_of_1').width();

/*****
 * Increase the height of the images until the total sum of the width
 * if the 4 images + the gutters is larger than ContainerWidth - then
 * stop
 **********/

/*****
 * Increment in jumps of 10px until we get within 80% of the width of
 * the ContainerWidth and then go to a more precise increment of 1px.
 * We can increase the px from 10 to 20 or 30 so there are less loops
 * but this can cause issues when we look at mobile and there is less
 * overall width in the containers and jumping by 30px will be too much
 **********/
var i = 0;
do {
  $('.feature-inims-top-row .growable-container').css('height', i);
  var RowWidth1 = CalculateTotalWidth(1);
  if(RowWidth1 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth1 < (ContainerWidth - 3));

/*****
 * Repeat above for the 2nd row
 **********/
var i = 0;
do {
  $('.feature-inims-bottom-row .growable-container').css('height', i);
  var RowWidth2 = CalculateTotalWidth(2);
  if(RowWidth2 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth2 < (ContainerWidth - 3));

/*********
 * Calculate the combined width of the images + the gutters
 ****/
function CalculateTotalWidth(Row) {
  var Image1Width = $('.growable-container-1').width();
  var Image2Width = $('.growable-container-2').width();
  var Image3Width = $('.growable-container-3').width();
  var Image4Width = $('.growable-container-4').width();
  var Image5Width = $('.growable-container-5').width();
  var Image6Width = $('.growable-container-6').width();
  var Image7Width = $('.growable-container-7').width();
  var Image8Width = $('.growable-container-8').width();
  var GutterSize = 24; // (3 gutters @ 8px each)

  if(Row == 1){
    var RowWidth = GutterSize + Image1Width + Image2Width + Image3Width + Image4Width;
  }else{
    var RowWidth = GutterSize + Image5Width + Image6Width + Image7Width + Image8Width;
  }
  return RowWidth
}

Body:
It turns out the issue with this was that in the CalculateTotalWidth() function I was checking the width of the container the image was in rather than the image itself. As soon as I changed this it worked perfectly.

var Image1Width = $('.growable-container-1 img').width();

instead of

var Image1Width = $('.growable-container-1').width();


问:
Code generation in software development
First broader view : I got assignment for school project that states "Design and implement tool for rapid development of IS by code generation of core of business and data layer. (paraphrased). Its specific for .NET and C#, but anything is fine in this case.

I dont have that extensive knowledge of code generation or development of information systems. I was looking around some code generation framewroks and tools. More specificaly T4 and CodeSmith Generator. One thing that hit my eye is .netTiers set of templates, that have some interesting ones, that can be used in software development. But I dont know how much usefull in actual development they can be.

Well my question : Is there a way to develop an information system based mostly on code-generation? Or some way to make bigger use of code generation tools and templates in general? If I have this, I can work on more specific things.

I also tried to look at some questions here, that concert code-generation, but most of them are about if it is good or bad, or general experience with them. What I want is specific experience with specific tools and templates and how much profit in development they have.

Thanks a lot for answers.

答:
For ASP.NET, you can use ASP.NET Dynamic Data Scaffolding.

Scaffolding refers to the Dynamic Data elements that automatically generate Web pages for each table in a database. These auto-generated Web pages provide create, read, update and delete (CRUD) operations for each table. Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These templates enable you to quickly build a functional data-driven Web site.

For desktop applications, you can use Visual Studio LightSwitch

Most business applications are forms-over-data applications, that is, a user interface for viewing, entering and editing data. With most development tools, much your time is spent doing the same task repeatedly. You write code to interact with a database, you write code for the user interface, and you write code for business logic. By using LightSwitch , much of the work is already done for you. In fact, it is possible to create a LightSwitch application without writing a single line of code. For most applications, the only code you have to write is the code that only you can write: the business logic.

Title: Code generation in software development


答: You are overwriting the adress of the struct on the heap, not the struct on the heap itself, assuming you meant the pointer to next struct</p>

Title: Where on memory are struct fields allocated if we allocate struct with malloc?


问:
Dynamic id with ng-repeat
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

```<code><label ng-repeat="x in placeTypes">

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}
    <br>
</label>
</code>```

But when I try to get the element by Id the element is null.

答:
You can do this:</p>

```<code>    <label ng-repeat="x in placeTypes track by $index">
       <input type="checkbox" id="checkbox{{$index}}">
       {{x.display}}
       <br>
   </label>
</code>```

Title: Dynamic id with ng-repeat

Body:
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}

But when I try to get the element by Id the element is null.

Body:
You can do this:

    <label ng-repeat="x in placeTypes track by $index">
       <input type="checkbox" id="checkbox{{$index}}">
       {{x.display}}
       <br>
   </label>


问:
Styling an input type="file" button
How do you style an input type="file" button?

<input type="file" />```

答:
This is a nice way to do it with material / angular file upload.
You could do the same with a bootstrap button.

Note I used  instead of <button> this allows the click events to bubble up.

```<code><label>
    <input type="file" (change)="setFile($event)" style="display:none" />

    <a mat-raised-button color="primary">
      <mat-icon>file_upload</mat-icon>
      Upload Document
    </a>

  </label>
</code>```

OwnerDisplayName: Shivanand

ContentLicense: CC BY-SA 4.0

Title: Styling an input type="file" button

Body:
This is a nice way to do it with material / angular file upload.
You could do the same with a bootstrap button.

Note I used <a> instead of <button> this allows the click events to bubble up.

<label>
    <input type="file" (change)="setFile($event)" style="display:none" />

    <a mat-raised-button color="primary">
      <mat-icon>file_upload</mat-icon>
      Upload Document
    </a>

  </label>


问:
why left_anti join doesn't work as expected in pyspark?
In a dataframe I'm trying to identify those rows that have a value in column C2 that does not exist in column C1 in any other row. I tryed the following code:

```<code>in_df = sqlContext.createDataFrame([[1,None,'A'],[2,1,'B'],[3,None,'C'],[4,11,'D']],['C1','C2','C3'])
in_df.show()
    +---+----+---+
    | C1|  C2| C3|
    +---+----+---+
    |  1|null|  A|
    |  2|   1|  B|
    |  3|null|  C|
    |  4|  11|  D|
    +---+----+---+
filtered = in_df.filter(in_df.C2.isNotNull())
filtered.show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+
</code>```

Now applying a left_anti join is expected to return only the row 4, however I also get row 2:

```<code>filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+
</code>```

If I 'materialize' the filtered DF the result is as expected:

```<code>filtered = filtered.toDF(*filtered.columns)
filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  4| 11|  D|
    +---+---+---+
</code>```

Why is this .toDF needed?

答:
in_df.C1 is actually refering to a filtered column as shows the following code:

in_df = sqlContext.createDataFrame([[1,None,'A'],[2,1,'B'],[3,None,'C'],[4,11,'D']],['C1','C2','C3'])
filtered = in_df.filter(in_df.C2.isNotNull()).select("C2")
filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()
```

<blockquote>
  <p>Py4JJavaError: An error occurred while calling o699.join.
  : org.apache.spark.sql.AnalysisException: cannot resolve '<code>in_df.C1</code>'  given input columns: [C2, C1, C2, C3];;
  'Join LeftAnti, ('in_df.C1 = 'filtered.C2)
  :- Project [C2#891L]
  :  +- Filter isnotnull(C2#891L)
  :     +- LogicalRDD [C1#890L, C2#891L, C3#892]
  +- LogicalRDD [C1#900L, C2#901L, C3#902]</p>
</blockquote>

<p>So basically when joining the 2 dataframes you actually use the condition <code>filtered.C1 == filtered.C2</code>:</p>

<pre class="lang-py prettyprint-override"><code>filtered = in_df.filter(in_df.C2.isNotNull())
filtered.join(in_df,(filtered.C1 == filtered.C2), 'left_anti').show()

    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+
</code>```

You might have changed the name of the dataframe but the columns in it can still be referred calling in_df.Ci. To make sure you're referring to the right dataframe you can use aliases:

import pyspark.sql.functions as psf
filtered.alias("filtered").join(in_df.alias("in_df"),(psf.col("in_df.C1") == psf.col("filtered.C2")), 'left_anti').show()

    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  4| 11|  D|
    +---+---+---+
```

The best way to deal with column name ambiguities is to avoid them from the start (renaming columns or using aliases for your data frame).

Body:
In a dataframe I'm trying to identify those rows that have a value in column C2 that does not exist in column C1 in any other row. I tryed the following code:

in_df = sqlContext.createDataFrame([[1,None,'A'],[2,1,'B'],[3,None,'C'],[4,11,'D']],['C1','C2','C3'])
in_df.show()
    +---+----+---+
    | C1|  C2| C3|
    +---+----+---+
    |  1|null|  A|
    |  2|   1|  B|
    |  3|null|  C|
    |  4|  11|  D|
    +---+----+---+
filtered = in_df.filter(in_df.C2.isNotNull())
filtered.show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+

Now applying a left_anti join is expected to return only the row 4, however I also get row 2:

filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+

If I 'materialize' the filtered DF the result is as expected:

filtered = filtered.toDF(*filtered.columns)
filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()
    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  4| 11|  D|
    +---+---+---+

Why is this .toDF needed?

Body:
in_df.C1 is actually refering to a filtered column as shows the following code:

in_df = sqlContext.createDataFrame([[1,None,'A'],[2,1,'B'],[3,None,'C'],[4,11,'D']],['C1','C2','C3'])
filtered = in_df.filter(in_df.C2.isNotNull()).select("C2")
filtered.join(in_df,(in_df.C1 == filtered.C2), 'left_anti').show()

Py4JJavaError: An error occurred while calling o699.join.
  : org.apache.spark.sql.AnalysisException: cannot resolve 'in_df.C1'  given input columns: [C2, C1, C2, C3];;
  'Join LeftAnti, ('in_df.C1 = 'filtered.C2)
  :- Project [C2#891L]
  :  +- Filter isnotnull(C2#891L)
  :     +- LogicalRDD [C1#890L, C2#891L, C3#892]
  +- LogicalRDD [C1#900L, C2#901L, C3#902]

So basically when joining the 2 dataframes you actually use the condition filtered.C1 == filtered.C2:

filtered = in_df.filter(in_df.C2.isNotNull())
filtered.join(in_df,(filtered.C1 == filtered.C2), 'left_anti').show()

    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  2|  1|  B|
    |  4| 11|  D|
    +---+---+---+

You might have changed the name of the dataframe but the columns in it can still be referred calling in_df.Ci. To make sure you're referring to the right dataframe you can use aliases:

import pyspark.sql.functions as psf
filtered.alias("filtered").join(in_df.alias("in_df"),(psf.col("in_df.C1") == psf.col("filtered.C2")), 'left_anti').show()

    +---+---+---+
    | C1| C2| C3|
    +---+---+---+
    |  4| 11|  D|
    +---+---+---+

The best way to deal with column name ambiguities is to avoid them from the start (renaming columns or using aliases for your data frame).


问:
In python, how do I cast a class object to a dict
Let's say I've got a simple class in python

```<code>class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __what_goes_here__(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}
</code>```

I can cast it to an integer very easily

```<code>>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> int(w)
9006
</code>```

Which is great! But, now I want to cast it to a dict in a similar fashion

```<code>>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
</code>```

What do I need to define for this to work? I tried substituting both __dict__ and dict for __what_goes_here__, but dict(w) resulted in a TypeError: Wharrgarbl object is not iterable in both cases. I don't think simply making the class iterable will solve the problem. I also attempted many googles with as many different wordings of "python cast object to dict" as I could think of but couldn't find anything relevant :{

Also! Notice how calling w.__dict__ won't do what I want because it's going to contain w.version and w.sum. I want to customize the cast to dict in the same way that I can customize the cast to int by using def int(self).

I know that I could just do something like this

```<code>>>> w.__what_goes_here__()
{'a': 'one', 'c': 'three', 'b': 'two'}
</code>```

But I am assuming there is a pythonic way to make dict(w) work since it is the same type of thing as int(w) or str(w). If there isn't a more pythonic way, that's fine too, just figured I'd ask. Oh! I guess since it matters, this is for python 2.7, but super bonus points for a 2.4 old and busted solution as well.

There is another question Overloading __dict__() on python class that is similar to this one but may be different enough to warrant this not being a duplicate. I believe that OP is asking how to cast all the data in his class objects as dictionaries. I'm looking for a more customized approach in that I don't want everything in __dict__ included in the dictionary returned by dict(). Something like public vs private variables may suffice to explain what I'm looking for. The objects will be storing some values used in calculations and such that I don't need/want to show up in the resulting dictionaries.

UPDATE:
I've chosen to go with the asdict route suggested but it was a tough choice selecting what I wanted to be the answer to the question. Both @RickTeachey and @jpmc26 provided the answer I'm going to roll with but the former had more info and options and landed on the same result as well and was upvoted more so I went with it. Upvotes all around though and thanks for the help. I've lurked long and hard on stackoverflow and I'm trying to get my toes in the water more.

答:
Like many others, I would suggest implementing a to_dict() function rather than (or in addition to) allowing casting to a dictionary. I think it makes it more obvious that the class supports that kind of functionality. You could easily implement such a method like this:</p>

```<code>def to_dict(self):
    class_vars = vars(MyClass)  # get any "default" attrs defined at the class level
    inst_vars = vars(self)  # get any attrs defined on the instance (self)
    all_vars = dict(class_vars)
    all_vars.update(inst_vars)
    # filter out private attributes
    public_vars = {k: v for k, v in all_vars.items() if not k.startswith('_')}
    return public_vars
</code>```

Body:
Let's say I've got a simple class in python

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __what_goes_here__(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}

I can cast it to an integer very easily

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> int(w)
9006

Which is great! But, now I want to cast it to a dict in a similar fashion

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}

What do I need to define for this to work? I tried substituting both __dict__ and dict for __what_goes_here__, but dict(w) resulted in a TypeError: Wharrgarbl object is not iterable in both cases. I don't think simply making the class iterable will solve the problem. I also attempted many googles with as many different wordings of "python cast object to dict" as I could think of but couldn't find anything relevant :{

Also! Notice how calling w.__dict__ won't do what I want because it's going to contain w.version and w.sum. I want to customize the cast to dict in the same way that I can customize the cast to int by using def int(self).

I know that I could just do something like this

>>> w.__what_goes_here__()
{'a': 'one', 'c': 'three', 'b': 'two'}

But I am assuming there is a pythonic way to make dict(w) work since it is the same type of thing as int(w) or str(w). If there isn't a more pythonic way, that's fine too, just figured I'd ask. Oh! I guess since it matters, this is for python 2.7, but super bonus points for a 2.4 old and busted solution as well.

There is another question Overloading __dict__() on python class that is similar to this one but may be different enough to warrant this not being a duplicate. I believe that OP is asking how to cast all the data in his class objects as dictionaries. I'm looking for a more customized approach in that I don't want everything in __dict__ included in the dictionary returned by dict(). Something like public vs private variables may suffice to explain what I'm looking for. The objects will be storing some values used in calculations and such that I don't need/want to show up in the resulting dictionaries.

UPDATE:
I've chosen to go with the asdict route suggested but it was a tough choice selecting what I wanted to be the answer to the question. Both @RickTeachey and @jpmc26 provided the answer I'm going to roll with but the former had more info and options and landed on the same result as well and was upvoted more so I went with it. Upvotes all around though and thanks for the help. I've lurked long and hard on stackoverflow and I'm trying to get my toes in the water more.

Body:
Like many others, I would suggest implementing a to_dict() function rather than (or in addition to) allowing casting to a dictionary. I think it makes it more obvious that the class supports that kind of functionality. You could easily implement such a method like this:

def to_dict(self):
    class_vars = vars(MyClass)  # get any "default" attrs defined at the class level
    inst_vars = vars(self)  # get any attrs defined on the instance (self)
    all_vars = dict(class_vars)
    all_vars.update(inst_vars)
    # filter out private attributes
    public_vars = {k: v for k, v in all_vars.items() if not k.startswith('_')}
    return public_vars


问:
UIlabel Sizetofit unexpected behavious
I am facing an unexpected behavior with my UIlabel sizeToFit() method. Now I have tried making the numberOfLines = 0, I event called LayoutIfNeed(). But None of them works.

I even tried methods given in this question : Vertically align text to top within a UILabel

But Again None helped. I don't have to many constraints, I am just using Auto resizing pins. I even tried it with no constraints or no auto resize.

I have this label set up in TableViewCell and CollectionReusableView. Calling it in awakeFromNib() just doesnt affect.

UIcollectionReusableView code :

```<code>override func awakeFromNib() {
    super.awakeFromNib()

    label.sizeToFit()

    label.numberOfLines = 0
    label.layer.shadowOffset = CGSize(width: 0, height: 0)
    label.layer.shadowOpacity = 3
    label.layer.shadowRadius = 8

}
</code>```

constrains :

TableViewCell Code:

```<code>override func layoutSubviews() {
    super.layoutSubviews()

// this is the UIview on which the label is put on.
    contentView.layoutIfNeeded()

}

override func awakeFromNib() {
    super.awakeFromNib()
    // This is the label has the issue
    caption.sizeToFit()

}
</code>```

Constraints :

Also, Label in the text view is stacked with Another Label and stackview constrainst are :

here is the example:

It Just doesn't seem to work. I am totally out of idea.

Any help is greatly appreciated.

答: You need to call sizeToFit() after the text is added to the label, not before.</p>

Title: UIlabel Sizetofit unexpected behavious

Body:
I am facing an unexpected behavior with my UIlabel sizeToFit() method. Now I have tried making the numberOfLines = 0, I event called LayoutIfNeed(). But None of them works.

I even tried methods given in this question : Vertically align text to top within a UILabel

But Again None helped. I don't have to many constraints, I am just using Auto resizing pins. I even tried it with no constraints or no auto resize.

I have this label set up in TableViewCell and CollectionReusableView. Calling it in awakeFromNib() just doesnt affect.

UIcollectionReusableView code :

override func awakeFromNib() {
    super.awakeFromNib()

    label.sizeToFit()

    label.numberOfLines = 0
    label.layer.shadowOffset = CGSize(width: 0, height: 0)
    label.layer.shadowOpacity = 3
    label.layer.shadowRadius = 8

}

constrains :

TableViewCell Code:

override func layoutSubviews() {
    super.layoutSubviews()

// this is the UIview on which the label is put on.
    contentView.layoutIfNeeded()

}

override func awakeFromNib() {
    super.awakeFromNib()
    // This is the label has the issue
    caption.sizeToFit()

}

Constraints :

Also, Label in the text view is stacked with Another Label and stackview constrainst are :

here is the example:

It Just doesn't seem to work. I am totally out of idea.

Any help is greatly appreciated.


问:
system("foo.exe") requires to close foo in order to continue my program
I don't know if my question is clear, let me explain.

I call this in my main() function:

```<code>system("foo.exe")
</code>```

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

```<code>system("taskkill /F /im foo.exe")
</code>```

But it doesn't work.

Does anyone have an idea what to do?

答:
On Windows, system("command") launches a new process for cmd.exe /C command.  The /C tells cmd.exe to terminate when command is finished.  system() waits for cmd.exe to exit.

In your case, system("foo.exe") is waiting for cmd.exe /C foo.exe to exit, which in turn is waiting for foo.exe to exit.  That is why you have to close the foo.exe window before system("foo.exe") returns control to your code.

You can use system("start foo.exe"), like HolyBlackCat suggested. system() will wait for cmd.exe /C start to exit, and start will NOT wait for foo.exe to exit, thus allowing system("start foo.exe") to return your code while foo.exe is still running.

A better solution is to call the Win32 API CreateProcess() function directly and avoid cmd.exe altogether:

```<code>#include <windows.h>

STARTUPINFO si = {};
si.cb = sizeof(si);
// populate si as desired...

PROCESS_INFORMATION pi = {};

if (CreateProcess("foo.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);

    // other commands while foo.exe is still running...
}
</code>```

Body:
I don't know if my question is clear, let me explain.

I call this in my main() function:

system("foo.exe")

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

system("taskkill /F /im foo.exe")

But it doesn't work.

Does anyone have an idea what to do?

Body:
On Windows, system("command") launches a new process for cmd.exe /C command.  The /C tells cmd.exe to terminate when command is finished.  system() waits for cmd.exe to exit.

In your case, system("foo.exe") is waiting for cmd.exe /C foo.exe to exit, which in turn is waiting for foo.exe to exit.  That is why you have to close the foo.exe window before system("foo.exe") returns control to your code.

You can use system("start foo.exe"), like HolyBlackCat suggested. system() will wait for cmd.exe /C start to exit, and start will NOT wait for foo.exe to exit, thus allowing system("start foo.exe") to return your code while foo.exe is still running.

A better solution is to call the Win32 API CreateProcess() function directly and avoid cmd.exe altogether:

#include <windows.h>

STARTUPINFO si = {};
si.cb = sizeof(si);
// populate si as desired...

PROCESS_INFORMATION pi = {};

if (CreateProcess("foo.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);

    // other commands while foo.exe is still running...
}


问:
Converting netmask number to 32 bit in golang
I am trying to get the IP address and subnet mask by

```<code>ifaces, err := net.Interfaces()
for _, iface := range ifaces{
        localip, _ = iface.Addrs()
}
</code>```

However, I am looking forward to get the subnet as something like 255.255.255.0 rather than /24. How can I get that? If there are no modules that can do this, what is the logic to do this as a program?

答:
Converting netmask to type "IP" before printing does the trick:</p>

```<code>func mask_print(ipnet *net.IPNet){
  fmt.Println("%v", net.IP(ipnet.Mask))
}
</code>```

Body:
I am trying to get the IP address and subnet mask by

ifaces, err := net.Interfaces()
for _, iface := range ifaces{
        localip, _ = iface.Addrs()
}

However, I am looking forward to get the subnet as something like 255.255.255.0 rather than /24. How can I get that? If there are no modules that can do this, what is the logic to do this as a program?

Body:
Converting netmask to type "IP" before printing does the trick:

func mask_print(ipnet *net.IPNet){
  fmt.Println("%v", net.IP(ipnet.Mask))
}


问:
Ionic 3 - Polyfill for ES6 in IE11 Not Working
I am aware that Ionic have stated that they will not be supporting IE11 - however I am still currently obliged by work to try and come up with a workaround of some sort if possible!

The issue I am having is the main.js file built by Ionic in the dev environment  is throwing an error in IE11 due to it using template literals.

I have created a polyfills.ts file which includes the following

polyfills.ts

```<code>import 'core-js/es6/string';
import 'core-js/fn/string/raw';
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'classlist.js';
import 'web-animations-js';
import 'hammerjs';
</code>```

and in my main.ts file

```<code>import './polyfills'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {enableProdMode} from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

However it doesn't seem to be resolving the issue. Am I perhaps missing a module from core-js that would solve this issue?

Any advice as always is much appreciated.

Thanks!

答:
Fix

Your import is wrong.

```<code>import './polyfills.ts'
</code>```

It should be

```<code>import './polyfills'
</code>```

You might have other issues beyond this, but this is the first mistake making your current attempt a noop.

Body:
I am aware that Ionic have stated that they will not be supporting IE11 - however I am still currently obliged by work to try and come up with a workaround of some sort if possible!

The issue I am having is the main.js file built by Ionic in the dev environment  is throwing an error in IE11 due to it using template literals.

I have created a polyfills.ts file which includes the following

polyfills.ts

import 'core-js/es6/string';
import 'core-js/fn/string/raw';
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'classlist.js';
import 'web-animations-js';
import 'hammerjs';

and in my main.ts file

import './polyfills'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {enableProdMode} from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();

platformBrowserDynamic().bootstrapModule(AppModule);

However it doesn't seem to be resolving the issue. Am I perhaps missing a module from core-js that would solve this issue?

Any advice as always is much appreciated.

Thanks!

Body:
Fix

Your import is wrong.

import './polyfills.ts'

It should be

import './polyfills'

You might have other issues beyond this, but this is the first mistake making your current attempt a noop.


问:
backspace key has stopped working in Visual Studio 2017
I've just encountered an extremely frustrating problem in VS 2017 Pro. Backspace is completely non-functional in the editor.

I've tried some Googling, but the only references I've found to this kind of problem are very old, and in most cases, various other keys were effected, enter, arrows etc. For me it's only backspace.

I should add, the key is definitely ok, and works fine in all other applications.

I've obviously tried restarting Visual Studio, and Windows, to no effect.

As far as I'm aware there has been no recent windows or VS updates. I've been using VS 2017 without any problems for a few weeks now. This has only just happened this morning.

Does anyone have any idea what could cause this, or what I could try to do to fix it?

答: There is another way - The command is Edit.DeleteBackwards and just map that to your Backspace key for the Text Editor.</p>