text:
Q: Add TextField on Chart I'm using JavaFX in Swing so I have method:
private Scene createScene()  {
Group root = new Group();
Scene scene = new Scene(root);
BorderPane borderPane = new BorderPane();

...
//adding data series to Linechart baseChart
...

StackChart chart = new StackChart(baseChart); //returns StackPane with LineChart-s on it
borderPane.setCenter(chart);

root.getChildren().add(borderPane);

return scene;
}

How can I place edditable text on Linechart like here?
I tried to add it in ChartStack to LineChart (chartBackground is the first LineChart in StackPane):
chartBackground.setOnMouseClicked(event ->  {
            if (event.getTarget() == chartBackground) {
                chartBackground.add(
                        new EditableDraggableText(event.getX(), event.getY())
                );
                super.getChildren().addAll(new EditableDraggableText(event.getX(), event.getY()));
            }
        });

but it draws Text not on LineChart but on the left side of the Frame
All MCVE is next
Main Class:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.function.Function;

public class GrinMain extends Application {

    public static final int X_NUMBER = 800;
    public double[] x;
    public double[] y;

    @Override
    public void start(Stage primaryStage) throws Exception {
        NumberAxis xAxis = new NumberAxis(0, X_NUMBER, 200);
        NumberAxis yAxis = new NumberAxis();
        yAxis.setLabel("Series 1");

        LineChart baseChart = new LineChart(xAxis, yAxis);
        baseChart.getData().add(prepareSeries("Serie 1", (x) -> (double) x));

        StackChart chart = new StackChart(baseChart, Color.RED);
        chart.addSeries(prepareSeries("Serie 3", (x) -> (double) -2*x * x), Color.BLUE);

        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(chart);
        borderPane.setBottom(chart.getLegend());

        Scene scene = new Scene(borderPane, 1024, 600);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private XYChart.Series<Number, Number> prepareSeries(String name, Function<Integer, Double> function) {
        XYChart.Series<Number, Number> series = new XYChart.Series<>();
        series.setName(name);
        for (int i = 0; i < X_NUMBER; i++) {
            series.getData().add(new XYChart.Data<>(i, function.apply(i)));
        }
        return series;
    }

    private XYChart.Series<Number, Number> prepareSeries(String name, double[] xValues, double[] yValues)   {
        XYChart.Series<Number, Number> series = new XYChart.Series<>();
        series.setName(name);
        for (int i = 0; i < yValues.length; i++){
            series.getData().add(new XYChart.Data(xValues[i], yValues[i]));
        }
        return series;
    }

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

StackChart class:
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.chart.Axis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;

public class StackChart extends StackPane {

    private final LineChart baseChart;
    private final ObservableList<LineChart> backCharts = FXCollections.observableArrayList();

    private final double yAxisWidth = 60;
    private final AnchorPane details;

    private final double yAxisSeparation = 20;
    private double strokeWidth = 0.3;

    public StackChart(LineChart baseChart, Color lineColor) {
        this(baseChart, lineColor, null);
    }

    public StackChart(LineChart baseChart, Color lineColor, Double strokeWidth) {
        if (strokeWidth != null) {
            this.strokeWidth = strokeWidth;
        }
        this.baseChart = baseChart;
        baseChart.setCreateSymbols(false);
        baseChart.setLegendVisible(false);
        baseChart.getXAxis().setAutoRanging(false);
        baseChart.getXAxis().setAnimated(false);
        baseChart.getXAxis().setStyle("-fx-font-size:" + 18);
        baseChart.getYAxis().setAnimated(false);
        baseChart.getYAxis().setStyle("-fx-font-size:" + 18);

        setStyle(baseChart, lineColor);
        setFixedAxisWidth(baseChart);
        setAlignment(Pos.CENTER_LEFT);

        backCharts.addListener((Observable observable) -> rebuildChart());

        details = new AnchorPane();
        bindMouseEvents(baseChart, this.strokeWidth);

        rebuildChart();
    }

    private void bindMouseEvents(LineChart baseChart, Double strokeWidth) {

        getChildren().add(details);

        details.prefHeightProperty().bind(heightProperty());
        details.prefWidthProperty().bind(widthProperty());
        details.setMouseTransparent(true);

        setOnMouseMoved(null);
        setMouseTransparent(false);

        final Axis xAxis = baseChart.getXAxis();
        final Axis yAxis = baseChart.getYAxis();

        final Line xLine = new Line();
        final Line yLine = new Line();
        yLine.setFill(Color.GRAY);
        xLine.setFill(Color.GRAY);
        yLine.setStrokeWidth(strokeWidth/2);
        xLine.setStrokeWidth(strokeWidth/2);
        xLine.setVisible(false);
        yLine.setVisible(false);

        final Node chartBackground = baseChart.lookup(".chart-plot-background");
        for (Node n: chartBackground.getParent().getChildrenUnmodifiable()) {
            if (n != chartBackground && n != xAxis && n != yAxis) {
                n.setMouseTransparent(true);
            }
        }
        chartBackground.setCursor(Cursor.CROSSHAIR);
        chartBackground.setOnMouseEntered((event) -> {
            chartBackground.getOnMouseMoved().handle(event);
            xLine.setVisible(true);
            yLine.setVisible(true);
            details.getChildren().addAll(xLine, yLine);
        });
        chartBackground.setOnMouseExited((event) -> {

            xLine.setVisible(false);
            yLine.setVisible(false);
            details.getChildren().removeAll(xLine, yLine);
        });
        chartBackground.setOnMouseMoved(event -> {
            double x = event.getX() + chartBackground.getLayoutX();
            double y = event.getY() + chartBackground.getLayoutY();

            xLine.setStartX(65);
            xLine.setEndX(details.getWidth()-10);
            xLine.setStartY(y+5);
            xLine.setEndY(y+5);

            yLine.setStartX(x+5);
            yLine.setEndX(x+5);
            yLine.setStartY(12);
            yLine.setEndY(details.getHeight()-28);
        });

        chartBackground.setOnMouseClicked(event ->  {
            if (event.getTarget() == chartBackground) {
                super.getChildren().addAll(new EditableDraggableText(event.getX(), event.getY()));
            }

        });
    }

    private void setFixedAxisWidth(LineChart chart) {
        chart.getYAxis().setPrefWidth(yAxisWidth);
        chart.getYAxis().setMaxWidth(yAxisWidth);
    }

    private void rebuildChart() {
        getChildren().clear();

        getChildren().add(resizeBaseChart(baseChart));
        for (LineChart lineChart : backCharts) {
            getChildren().add(resizeBackgroundChart(lineChart));
        }
        getChildren().add(details);
    }

    private Node resizeBaseChart(LineChart lineChart) {
        HBox hBox = new HBox(lineChart);
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.prefHeightProperty().bind(heightProperty());
        hBox.prefWidthProperty().bind(widthProperty());

        lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
        lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));
        lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth+yAxisSeparation)*backCharts.size()));

        return lineChart;
    }

    private Node resizeBackgroundChart(LineChart lineChart) {
        HBox hBox = new HBox(lineChart);
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.prefHeightProperty().bind(heightProperty());
        hBox.prefWidthProperty().bind(widthProperty());
        hBox.setMouseTransparent(true);

        lineChart.minWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
        lineChart.prefWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));
        lineChart.maxWidthProperty().bind(widthProperty().subtract((yAxisWidth + yAxisSeparation) * backCharts.size()));

        lineChart.translateXProperty().bind(baseChart.getYAxis().widthProperty());
        lineChart.getYAxis().setTranslateX((yAxisWidth + yAxisSeparation) * backCharts.indexOf(lineChart));

        return hBox;
    }

    public void addSeries(XYChart.Series series, Color lineColor) {
        NumberAxis yAxis = new NumberAxis();
        NumberAxis xAxis = new NumberAxis();

        // xAxis
        xAxis.setAutoRanging(false);
        xAxis.setVisible(false);
        xAxis.setOpacity(0.0);
        xAxis.lowerBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).lowerBoundProperty());
        xAxis.upperBoundProperty().bind(((NumberAxis) baseChart.getXAxis()).upperBoundProperty());
        xAxis.tickUnitProperty().bind(((NumberAxis) baseChart.getXAxis()).tickUnitProperty());

        // yAxis
        yAxis.setSide(Side.RIGHT);
        yAxis.setLabel(series.getName());

        // create chart
        LineChart lineChart = new LineChart(xAxis, yAxis);
        lineChart.setAnimated(false);
        lineChart.setLegendVisible(false);
        lineChart.getData().add(series);

        styleBackChart(lineChart, lineColor);
        setFixedAxisWidth(lineChart);

        backCharts.add(lineChart);
    }

    private void styleBackChart(LineChart lineChart, Color lineColor) {
        setStyle(lineChart, lineColor);

        Node contentBackground = lineChart.lookup(".chart-content").lookup(".chart-plot-background");
        contentBackground.setStyle("-fx-background-color: transparent;");

        lineChart.setVerticalZeroLineVisible(false);
        lineChart.setHorizontalZeroLineVisible(false);
        lineChart.setVerticalGridLinesVisible(false);
        lineChart.setHorizontalGridLinesVisible(false);
        lineChart.setCreateSymbols(false);
        lineChart.getXAxis().setStyle("-fx-font-size:" + 18);
        lineChart.getYAxis().setStyle("-fx-font-size:" + 18);
    }

    private String toRGBCode(Color color) {
        return String.format("#%02X%02X%02X",
                (int) (color.getRed() * 255),
                (int) (color.getGreen() * 255),
                (int) (color.getBlue() * 255));
    }

    private void setStyle(LineChart chart, Color lineColor) {
        chart.getYAxis().lookup(".axis-label").setStyle("-fx-text-fill: " + toRGBCode(lineColor) + "; -fx-font-size: 24;");
        Node seriesLine = chart.lookup(".chart-series-line");
        seriesLine.setStyle("-fx-stroke: " + toRGBCode(lineColor) + "; -fx-stroke-width: " + strokeWidth + ";");
    }

    public Node getLegend() {
        HBox hbox = new HBox();

        final CheckBox baseChartCheckBox = new CheckBox(baseChart.getYAxis().getLabel());
        baseChartCheckBox.setSelected(true);
        baseChartCheckBox.setDisable(true);
        baseChartCheckBox.getStyleClass().add("readonly-checkbox");
        baseChartCheckBox.setOnAction(event -> baseChartCheckBox.setSelected(true));
        hbox.getChildren().add(baseChartCheckBox);

        for (final LineChart lineChart : backCharts) {
            CheckBox checkBox = new CheckBox(lineChart.getYAxis().getLabel());
            checkBox.setSelected(true);
            checkBox.setOnAction(event -> {
                if (backCharts.contains(lineChart)) {
                    backCharts.remove(lineChart);
                } else {
                    backCharts.add(lineChart);
                }
            });
            hbox.getChildren().add(checkBox);
        }

        hbox.setAlignment(Pos.CENTER);
        hbox.setSpacing(20);
        hbox.setStyle("-fx-padding: 0 10 20 10");

        return hbox;
    }
}

EditableText Class:
import com.sun.javafx.tk.FontMetrics;
import com.sun.javafx.tk.Toolkit;
import javafx.application.Platform;
import javafx.scene.control.TextField;

class EditableText extends TextField {
// The right margin allows a little bit of space
// to the right of the text for the editor caret.
private final double RIGHT_MARGIN = 5;

EditableText(double x, double y) {
    relocate(x, y);
    getStyleClass().add("editable-text");

    //** CAUTION: this uses a non-public API (FontMetrics) to calculate the field size
    //            the non-public API may be removed in a future JavaFX version.
    // see: https://javafx-jira.kenai.com/browse/RT-8060
    //      Need font/text measurement API
    FontMetrics metrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(getFont());
    setPrefWidth(RIGHT_MARGIN);
    textProperty().addListener((observable, oldTextString, newTextString) ->
                    setPrefWidth(metrics.computeStringWidth(newTextString) + RIGHT_MARGIN)
    );

    Platform.runLater(this::requestFocus);
}

}
EditableDraggableText Class:
import javafx.scene.Cursor;
import javafx.scene.layout.Pane;

class EditableDraggableText extends Pane {
private final double PADDING = 5;
private EditableText text = new EditableText(PADDING, PADDING);

EditableDraggableText(double x, double y) {
    relocate(x - PADDING, y - PADDING);
    getChildren().add(text);
    getStyleClass().add("editable-draggable-text");

    // if the text is empty when we lose focus,
    // the node has no purpose anymore
    // just remove it from the scene.
    text.focusedProperty().addListener((observable, hadFocus, hasFocus) -> {
        if (!hasFocus && getParent() != null && getParent() instanceof Pane &&
                (text.getText() == null || text.getText().trim().isEmpty())) {
            ((Pane) getParent()).getChildren().remove(this);
        }
    });

    enableDrag();
}

public EditableDraggableText(int x, int y, String text) {
    this(x, y);
    this.text.setText(text);
}

// make a node movable by dragging it around with the mouse.
private void enableDrag() {
    final Delta dragDelta = new Delta();
    setOnMousePressed(mouseEvent -> {
        this.toFront();
        // record a delta distance for the drag and drop operation.
        dragDelta.x = mouseEvent.getX();
        dragDelta.y = mouseEvent.getY();
        getScene().setCursor(Cursor.MOVE);
    });
    setOnMouseReleased(mouseEvent -> getScene().setCursor(Cursor.HAND));
    setOnMouseDragged(mouseEvent -> {
        double newX = getLayoutX() + mouseEvent.getX() - dragDelta.x;
        if (newX > 0 && newX < getScene().getWidth()) {
            setLayoutX(newX);
        }
        double newY = getLayoutY() + mouseEvent.getY() - dragDelta.y;
        if (newY > 0 && newY < getScene().getHeight()) {
            setLayoutY(newY);
        }
    });
    setOnMouseEntered(mouseEvent -> {
        if (!mouseEvent.isPrimaryButtonDown()) {
            getScene().setCursor(Cursor.HAND);
        }
    });
    setOnMouseExited(mouseEvent -> {
        if (!mouseEvent.isPrimaryButtonDown()) {
            getScene().setCursor(Cursor.DEFAULT);
        }
    });
}

// records relative x and y co-ordinates.
private class Delta {
    double x, y;
}
}

A: The problem exists because you are trying to add the Text in .chart-plot-background which is a Region. The Region serves right for options like showing the Mouse Lines, it is not exactly where you should be adding the EditableDraggableText.
Add the EditableDraggableText in the .chart-content which is a Pane and contains

*

*Chart Plot Background

*X-Number Axis

*Y-Number Axis

Use the following code :
Pane chartContent = (Pane)baseChart.lookup(".chart-content");
chartContent.setOnMouseClicked(event ->  {
     chartContent.getChildren().addAll(new EditableDraggableText(event.getX(), event.getY()));
});

Great. But, how do you avoid creating TextFields outside the graph-plot?

Compare the event's X and Y co-ordinates with that of the chart-plot-background and it works :)
Pane chartContent = (Pane)baseChart.lookup(".chart-content");
chartContent.setOnMouseClicked(event ->  {
    if(event.getX() >= chartBackground.getBoundsInParent().getMinX() &&
                event.getX() <= chartBackground.getBoundsInParent().getMaxX() &&
                event.getY() >= chartBackground.getBoundsInParent().getMinY() &&
                event.getY() <= chartBackground.getBoundsInParent().getMaxY()) {
        chartContent.getChildren().addAll(new EditableDraggableText(event.getX(), event.getY()));
    }
});


text:
Q: Why simulated and calculated t-distribution pdf at degree-of-freedom=1 doesn't match See the attached graph, I am simulating the pdf of t-distribution at different degrees of freedom (dof), when dof is low (e.g. dof=1), why don't they match? Is it because my experiment wasn't done correctly, or is that expected?
The code
def t_dist_pdf(t, dof):
    p1 = special.gamma((dof + 1) / 2)
    p2 = np.sqrt(dof * np.pi) * special.gamma(dof / 2)
    p3 = (1 + t ** 2 / dof) ** (- (dof + 1) / 2)
    return p1 / p2 * p3

fig, axes = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(12, 6))
axes = axes.ravel()

bins = np.linspace(-5, 5, 100)
num = int(1e6)

for k, dof in enumerate(range(1, 7)):
    ax = axes[k]
    t_dist_data = np.random.standard_t(df=dof, size=num)
    ax.hist(t_dist_data, bins=bins, normed=True, histtype='step', label='sim. $t$-dist pdf')

    ax.plot(xs, t_dist_pdf(xs, dof), lw=1, alpha=1, label='$t$-dist pdf')
    ax.plot(xs, stats.t.pdf(xs, dof), lw=5, alpha=0.2, label='scipy $t$-dist pdf')
    ax.plot(xs, stats.norm.pdf(xs), lw=1, alpha=1, label='normal pdf')

    ax.legend(fontsize=8)
    ax.set_title('$t$-distribution dof={0}'.format(dof))
plt.tight_layout()

I verified my implementation of t-dist pdf by comparing it to scipy's.
The result.
The X and Y axes of all subplots are the same.
PDF:

Update: CDF:

Version info:
python: 3.5.3,
numpy: 1.12.1,
scipy: 0.19.1

A: wuber pointed out the problem,

In particular, by limiting it to the range [−5,5][−5,5] and requiring
  the plot to integrate to unity, you are estimating a truncated
  t-distribution. For the smaller values of df, an appreciable
  proportion of its probability lies beyond that range (12.6% for df=1,
  3.8% for df=2, etc). Accordingly, your plot of the simulated distribution for df=1 should be about 1/(1-12.6%) = 14% too high, etc.
  Equivalently, you should renormalize the theoretical expressions to
  account for the truncation.

Here is the fixed code with proper normalization for the theoretical t-distribution PDF before comparing it to the simulated one:
fig, axes = plt.subplots(4, 3, sharex=False, sharey=False, figsize=(12, 15))
axes = axes.ravel()

bins = np.linspace(-5, 5, 100)
delta_bin = bins[1] - bins[0]

xs = (bins[1:] + bins[:-1]) / 2
num = int(1e6)

for k, dof in enumerate(range(1, 7)):
    ax = axes[k]

    # IMPORTANT: used to correct the theorectical pdf
    # for truncated regions of t dist and gaussian/normal dist
    t_renorm = 1 - stats.t.cdf(bins[0], df=dof) * 2
    g_renorm = 1 - stats.norm.cdf(bins[0]) * 2

    t_dist_data = np.random.standard_t(df=dof, size=num)

    ax.plot(xs, stats.t.pdf(xs, dof) / t_renorm, lw=5, alpha=0.2, color='cyan', label='scipy pdf')
    ax.plot(xs, t_dist_pdf(xs, dof) / t_renorm, lw=1, alpha=1, color='red', label='self implemented pdf')
    ax.plot(xs, stats.norm.pdf(xs) / g_renorm, lw=1, alpha=1, color='black', label='normal pdf')
    ax.hist(t_dist_data, bins=bins, normed=True, histtype='step', color='blue', label='simulated pdf')

    ax.legend(fontsize=10)
    ax.set_title('$t$-distribution PDF dof={0}'.format(dof))
    ax.set_xlim(bins[0], bins[-1])
    ax.set_ylim(0, 0.6)

    ax2 = axes[k + 6]
    ax2.plot(xs, cdf(stats.t.pdf(xs, dof) / t_renorm, delta_bin), lw=5, alpha=0.2, color='cyan', label='scipy cdf')
    ax2.plot(xs, cdf(t_dist_pdf(xs, dof) / t_renorm, delta_bin), lw=1, alpha=1, color='black', label='simulated cdf')
    ax2.plot(xs, cdf(stats.norm.pdf(xs) / g_renorm, delta_bin), lw=1, alpha=1, color='black', label='normal cdf')
    ax2.legend(loc='lower right', fontsize=10)
    ax2.set_title('$t$-distribution CDF dof={0}'.format(dof))
    ax2.set_xlim(bins[0], bins[-1])
    ax2.set_ylim(-0.05, 1.05)
plt.tight_layout()

The output

Now, everything matches.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CursorAdapter with different layout(ImageView,TextView) I am currently working on a chat application that uses Smack and XMPP Server.
I'm storing all the messages in the database and load in the fragment with the help of cursor adapter in the ListView.
Below code doesn't show messages in the ListView and crash when cursor loader is called.
Thanks in advance
private LayoutInflater mInflater;
private int mChatType;
private ReceiveMediaMessage receiveMediaMessage;
private ArrayList mArrayList;
private File pathDirectory;
private LayoutInflater inflater;

public CustomMessageCursorAdapter(Context context, Cursor c, int chatType) {
    super(context, c);
    mChatType = chatType;
    mAutoRequery = true;
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    if (view != null) {
        ViewHolder holder = (ViewHolder) view.getTag();
        int jidCol = cursor.getColumnIndexOrThrow(DbHelper.USERS_JID);
        int nicknameColId = cursor.getColumnIndexOrThrow(DbHelper.USERS_NAME);
        String jid = cursor.getString(jidCol);
        String nickname = cursor.getString(nicknameColId);
        MessageContainer messageContainer = MessageContainer.fromCursor(cursor);
        DateFormat df = new SimpleDateFormat("[dd.MM.yyyy HH:mm:ss]");
        String createdAtDate = df.format(messageContainer.getCreated());

        Log.v(Constants.LOG, messageContainer.getUserId());
        if (messageContainer.getBody() != null) {
            if (messageContainer.getIncoming() == 0) {
                //myMessages
                holder.chatContainer.setGravity(Gravity.RIGHT);
                if (messageContainer.getBody().contains(ChatConstants.IMAGE_MESSAGE)) {
                    holder.imageView.setBackgroundResource(R.drawable.grey);
                    receiveImage(messageContainer.getBody(), holder);
                } else if (messageContainer.getBody().contains(ChatConstants.VIDEO_MESSAGE)) {

                } else if (messageContainer.getBody().contains(ChatConstants.AUDIO_MESSAGE)) {

                } else if (messageContainer.getBody().contains(ChatConstants.DOCS_MESSAGE)) {

                } else{
                    holder.messageText.setBackgroundResource(R.drawable.grey);
                    holder.messageText.setText(messageContainer.getBody());
                }

            } else {
                // other's messages

                holder.chatContainer.setGravity(Gravity.LEFT);
                if (messageContainer.getBody().contains(ChatConstants.IMAGE_MESSAGE)) {
                    holder.imageView.setBackgroundResource(R.drawable.red);
                    receiveImage(messageContainer.getBody(), holder);
                } else if (messageContainer.getBody().contains(ChatConstants.VIDEO_MESSAGE)) {

                } else if (messageContainer.getBody().contains(ChatConstants.AUDIO_MESSAGE)) {

                } else if (messageContainer.getBody().contains(ChatConstants.DOCS_MESSAGE)) {

                } else {
                    holder.messageText.setBackgroundResource(R.drawable.red);
                    holder.messageText.setTextColor(context.getResources().getColor(R.color.primary_text_material_light));
                    holder.messageText.setText(messageContainer.getBody());
                }
            }
        }
        if (mChatType == ChatConstants.MULTICHAT_CHAT_STATE) {
            //holder.from.setText(nickname);
        } else {
            //holder.from.setText(jid);
        }

        //holder.messageDate.setText(createdAtDate);
    }
}

private void receiveImage(String body, final ViewHolder holder) {
    mArrayList = new ArrayList();
    String fid = splitFid(body);

    receiveMediaMessage = new ReceiveMediaMessage(mContext, new ReceiveMediaMessage.ReceiveMediaMessageCallBack() {
        @Override
        public void onStart() {

        }

        @Override
        public void onEnd(ArrayList response) {
            mArrayList = response;
            pathDirectory = new File(Constants.IMAGE_THUMB_PATH + "IMAGE_" + mArrayList.get(Constants.FID_INDEX).toString() + ".jpg");
            if (pathDirectory.exists()) {
                Bitmap myBitmap = BitmapFactory.decodeFile(pathDirectory.getAbsolutePath());
                holder.imageView.setImageBitmap(myBitmap);
            }
        }
    });
    receiveMediaMessage.execute(fid);

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View v = null;
    ViewHolder holder = new ViewHolder();
    inflater = LayoutInflater.from(context);
    MessageContainer messageContainer = MessageContainer.fromCursor(cursor);
    if (messageContainer.getBody().contains(ChatConstants.EDUCHAT_IMAGE_MESSAGE)) {
        v = inflater.inflate(R.layout.fragment_chat_image_view_row_layout, parent, false);
        holder.imageView = (ImageView) v.findViewById(R.id.fragment_chat_image_view_row);
        holder.chatContainer = (LinearLayout) v.findViewById(R.id.fragment_chat_image_view_container);

    } else {
        v = inflater.inflate(R.layout.fragment_chat_text_view_layout, parent, false);
        holder.messageText = (TextView) v.findViewById(R.id.fragment_chat_text_view_row);
        holder.chatContainer = (LinearLayout) v.findViewById(R.id.fragment_chat_text_view_container);
    }
    v.setTag(holder);
    return v;

}

private static class ViewHolder {
    LinearLayout chatContainer;
    TextView messageText;
    ImageView imageView;
}

private String splitFid(String data) {
    String delimiter = "_";
    String[] temp = data.split(delimiter);
    return temp[2];
}

@Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }
@Override
public int getViewTypeCount() {
    return 2;
}
@Override
public Object getItem(int position) {
    return super.getItem(position);
}

Error
02-10 00:14:19.125 25518-25518/in.tekticks.educhat E/InputEventReceiver: Exception dispatching input event.
02-10 00:14:19.126 25518-25518/in.tekticks.educhat E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-10 00:14:19.127 25518-25518/in.tekticks.educhat E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundResource(int)' on a null object reference
    at in.tekticks.educhat.adapters.CustomMessageCursorAdapter.bindView(CustomMessageCursorAdapter.java:73)
    at android.support.v4.widget.CursorAdapter.getView(CursorAdapter.java:256)
    at android.widget.AbsListView.obtainView(AbsListView.java:2344)
    at android.widget.ListView.makeAndAddView(ListView.java:1864)
    at android.widget.ListView.fillUp(ListView.java:732)
    at android.widget.ListView.fillGap(ListView.java:671)
    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
    at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:4008)
    at android.view.View.dispatchGenericMotionEventInternal(View.java:8493)
    at android.view.View.dispatchGenericMotionEvent(View.java:8474)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
    at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
    at android.view.View.dispatchGenericMotionEvent(View.java:8467)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:2322)
    at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1702)
    at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2775)
    at android.support.v7.view.WindowCallbackWrapper.dispatchGenericMotionEvent(WindowCallbackWrapper.java:70)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:2289)
    at android.view.View.dispatchPointerEvent(View.java:8580)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4021)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3887)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
    at android.view.ViewRootImpl.deliver
 02-10 00:14:19.130 25518-25518/in.tekticks.educhat E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.tekticks.educhat, PID: 25518
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundResource(int)' on a null object reference
  at in.tekticks.educhat.adapters.CustomMessageCursorAdapter.bindView(CustomMessageCursorAdapter.java:73)
  at android.support.v4.widget.CursorAdapter.getView(CursorAdapter.java:256)
  at android.widget.AbsListView.obtainView(AbsListView.java:2344)
  at android.widget.ListView.makeAndAddView(ListView.java:1864)
  at android.widget.ListView.fillUp(ListView.java:732)
  at android.widget.ListView.fillGap(ListView.java:671)
  at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
  at android.widget.AbsListView.onGenericMotionEvent(AbsListView.java:4008)
  at android.view.View.dispatchGenericMotionEventInternal(View.java:8493)
  at android.view.View.dispatchGenericMotionEvent(View.java:8474)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at android.view.ViewGroup.dispatchTransformedGenericPointerEvent(ViewGroup.java:2024)
  at android.view.ViewGroup.dispatchGenericPointerEvent(ViewGroup.java:1975)
  at android.view.View.dispatchGenericMotionEvent(View.java:8467)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchGenericMotionEvent(PhoneWindow.java:2322)
  at com.android.internal.policy.impl.PhoneWindow.superDispatchGenericMotionEvent(PhoneWindow.java:1702)
  at android.app.Activity.dispatchGenericMotionEvent(Activity.java:2775)
  at android.support.v7.view.WindowCallbackWrapper.dispatchGenericMotionEvent(WindowCallbackWrapper.java:70)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchGenericMotionEvent(PhoneWindow.java:2289)
  at android.view.View.dispatchPointerEvent(View.java:8580)
  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4021)
  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3887)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$InputStage.deliver(

A: I solved the problem. Thanks for your help.
private LayoutInflater mInflater;
private int mChatType;
private File pathDirectory;
private LayoutInflater inflater;

public CustomMessageCursorAdapter(Context context, Cursor c, int chatType) {
    super(context, c);
    mChatType = chatType;
    mAutoRequery = true;
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder holder = (ViewHolder) view.getTag();
    int jidCol = cursor.getColumnIndexOrThrow(DbHelper.USERS_JID);
    int nicknameColId = cursor.getColumnIndexOrThrow(DbHelper.USERS_NAME);
    String jid = cursor.getString(jidCol);
    String nickname = cursor.getString(nicknameColId);
    MessageContainer messageContainer = MessageContainer.fromCursor(cursor);
    DateFormat df = new SimpleDateFormat("[dd.MM.yyyy HH:mm:ss]");
    String createdAtDate = df.format(messageContainer.getCreated());

    int viewType = this.getItemViewType(cursor);
    if (view != null) {
        if (messageContainer.getBody() != null) {
            if (viewType == 0) {
                if (messageContainer.getIncoming() == 0) {
                    holder.chatContainer.setGravity(Gravity.RIGHT);
                    holder.imageView.setBackgroundResource(R.drawable.grey);
                    String fid =splitFid(messageContainer.getBody());
                    pathDirectory = new File(Constants.IMAGE_SEND_PATH + "IMAGE_" + fid + ".jpg");
                    Log.v(Constants.LOG, "File path:"+pathDirectory.getAbsolutePath().toString());

                    if (pathDirectory.exists()) {
                        Bitmap myBitmap = BitmapFactory.decodeFile(pathDirectory.getAbsolutePath());
                        holder.imageView.setImageBitmap(myBitmap);
                    }
                } else {
                    holder.chatContainer.setGravity(Gravity.LEFT);
                    holder.imageView.setBackgroundResource(R.drawable.red);
                    String fid =splitFid(messageContainer.getBody());
                    pathDirectory = new File(Constants.IMAGE_THUMB_PATH + "IMAGE_" + fid + ".jpg");
                    if (pathDirectory.exists()) {
                        Bitmap myBitmap = BitmapFactory.decodeFile(pathDirectory.getAbsolutePath());
                        holder.imageView.setImageBitmap(myBitmap);
                    }
                }
            } else {
                if (messageContainer.getIncoming() == 0) {
                    holder.chatContainer.setGravity(Gravity.RIGHT);
                    holder.messageText.setBackgroundResource(R.drawable.grey);
                    holder.messageText.setText(messageContainer.getBody());
                } else {
                    holder.chatContainer.setGravity(Gravity.LEFT);
                    holder.messageText.setBackgroundResource(R.drawable.red);
                    holder.messageText.setTextColor(context.getResources().getColor(R.color.primary_text_material_light));
                    holder.messageText.setText(messageContainer.getBody());
                }
            }
        }
    }
    if (mChatType == ChatConstants.MULTICHAT_CHAT_STATE) {
        //holder.from.setText(nickname);
    } else {
        //holder.from.setText(jid);
    }

    //holder.messageDate.setText(createdAtDate);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View v = null;
    ViewHolder holder = new ViewHolder();
    inflater = LayoutInflater.from(context);
    int viewType = this.getItemViewType(cursor);
    MessageContainer messageContainer = MessageContainer.fromCursor(cursor);
    if (viewType == 0) {
        v = inflater.inflate(R.layout.fragment_chat_image_view_row_layout, parent, false);
        holder.imageView = (ImageView) v.findViewById(R.id.fragment_chat_image_view_row);
        holder.chatContainer = (LinearLayout) v.findViewById(R.id.fragment_chat_image_view_container);

    } else {
        v = inflater.inflate(R.layout.fragment_chat_text_view_layout, parent, false);
        holder.messageText = (TextView) v.findViewById(R.id.fragment_chat_text_view_row);
        holder.chatContainer = (LinearLayout) v.findViewById(R.id.fragment_chat_text_view_container);
    }
    v.setTag(holder);
    return v;
}

@Override
public int getItemViewType(int position) {
    Cursor cursor = (Cursor) getItem(position);
    return getItemViewType(cursor);
}

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public Object getItem(int position) {
    return super.getItem(position);
}

private int getItemViewType(Cursor cursor) {
    String type = cursor.getString(cursor.getColumnIndex(DbHelper.MESSAGES_BODY));
    if (type.contains(ChatConstants.EDUCHAT_IMAGE_MESSAGE)) {
        return 0;
    } else {
        return 1;
    }
}

private static class ViewHolder {
    LinearLayout chatContainer;
    TextView messageText;
    ImageView imageView;
}
private String splitFid(String data) {
    String delimiter = "_";
    String[] temp = data.split(delimiter);
    return temp[2];
}


text:
Q: iOS Core Image face detection: CIFaceFeature's 'hasMouthPosition' always true even when covering mouth I'm using CoreImage's CIDetector with CIDetectorTypeFace to detect faces and want to detect when the mouth is missing.
However, the detected CIFaceFeature's hasMouthPosition always seems to be true when my face is visible, even when I cover my mouth with an object such as my hand or a book.
Other properties such as leftEyeClosed change as expected, such as when I blink or cover an eye. I've tried using different CIDetectorAccuracy levels but it didn't help. Anyone have any ideas?


text:
Q: WooCommerce Single Product Page Seperate Cost I'm trying to add a second button to a product page with a updated price.
For example I'm using [add_to_cart id='$product->id'] which displays correctly, but I would like to assign this short code a custom price.
The results should show two buttons on a single product page. One with the regular price value and the other with the custom price value.
I tried doing this through variables, but need them in two buttons instead of a drop down.
Thanks for the help!


text:
Q: Android - entries in dialog should be deleted when dialog is closed I have a customDialog with input fields. I want possible entries to be removed once the dialog is closed (either via back or when a certain button is pressed), i.e. the state should not be saved.
How can I do that?

A: If the back button is pressed means that dialog is canceled. Implement DialogInterface.OnCancelListener for your dialog and empty/delete/null the entries you want.

A: I think you might be getting another problem.
Say that you have shown a dialog which was dismissed. If the same dialog is going to be shown a second time, it won't be rebuilt. It will just be shown again.
This means that if you setup your dialog in the onCreateDialog method, the second time that the dialog is shown, this method isn't invoked! Instead, onPrepareDialog is invoked.
Alternatives? You can call Activity.removeDialog or take care of the setup process in the onPrepareDialog hook.


text:
Q: Modular arithmetic - Suggestions to begin I've always wanted to start studying modular arithmetic to try to solve problems like:
$$\text{find } n \in \mathbb{N} : 4n^2 \equiv 1 ~(\text{mod }{10^4})$$
I have a good basis in mathematical analysis and logic. Where can I start to study modular arithmetic?
I prefer some internet tutorial, but also a book is good.
Thank you very much!

A: There does not exist such n, where $ n \in \mathbb{N} $.
$$4n^2 = 10^4 k + 1$$
$4n^2$ is even, but $10^4 k + 1$ is odd.


text:
Q: In redux+react web app, how to know one async action is finally dispatched to state Rudx-thunk did a great job to dispatch async actions, it will eventually modify the state fetched in async action. But how do I know the moment when it finally modify the redux state fetched?
In my case, I want to read config from the server, because there are components need these config so I have to render the whole app after the config is fetched. But so far I cannot work out by using redux-thunk or any other redux async middlewares.
Update #1 show some code to express myself better.
// reducer
(state, action) => Object.assign({}, state, {config: action.config});

// action creator
const fetchConfig = () => (dispatch) => {
    fetch('http://server.com/...')
    .then(config=>dispatch({type: 'LOAD_CONFIG', config}))
}

// connect reducer to state
createStore({config: configReducer})

// render
import { render } from 'react-dom';
render (<App><News /></App>)

// some component consume state.config
@connect(state=>{config: state.config})
const News = props=>(

        {(props.config === '...')?
...
 :
...
}

)

The above looks good, however due to the action may take time and update the states after the component first render, so the component may display unexpected results. What I really want to do is (I just write down the render part, others should be the same):
// render
loadConfigFinished
.then(()=> render((<App><News /></App>)))

Or
// render
on('loadConfigFinished', ()=> render((<App><News /></App>)));

Probably, I should do the 2nd way, just afraid it is not redux-y.
Anyway, the above is just a example showing sometimes we do need to be notified when some action finally dispatch to the redux state.

A: Looking at your code, I gather your question is simply: When do I render a component that depends on data from the server, while waiting for that data, without passing undefined into my component?
I would have a container component that connects to the config state, and conditionally renders the component that needs it, or a loading template:
const Container = props => {
  if (props.config) {
    return <ConfiguredComponent config={props.config} />
  } else {
    return <Loading />
  }
}

A: export function readConfig() {
  return (dispatch) => {
    dispatch(readingConfig());

    someAsyncFunction((error, result) => {
      if (!error) {
        dispatch(readConfigSuccess(result));
      } else {
        dispatch(readConfigFail(error));
      }
    });
  }
}

And of course, readConfigSuccess, readConfigFail, and readingConfig are action creator functions that return action objects, e.g.:
export const READING_CONFIG = 'READING_CONFIG';
export function readingConfig() {
  return {
    type: READING_CONFIG,
  }
}

A: When your reducers process the readConfigSuccess action, they update the redux state.
The application gets re-rendered with updated props for all state changes so there's nothing special about this particular action.
Except that usually only a small part of the state changes and the rerender looks a lot like the previous render and here I'd expect that a relatively large part of the state gets changed by the reducers for this particular action and a rerender will render a much changed application.
That's not for you to worry about though, it should Just Work.
Or do you mean something else, would you like to do more async work as a result of retrieving the config?


text:
Q: Render parts of a template I have a Backbone view and I'm using Handlebars to load templates in my view.
I have a list #list in the template that have to be updated in the view and after that it needs to be re-rendered.
I want to re-render only the part that has changed so only #list without reload all my DOM (and so all the Handlebars helpers that I have).
I tried this:
template: Handlebars.compile(templateHtml),

render: function() {
  this.$el.html(this.template(this.model.toJSON());
},

renderList: function() {
  var html = this.template(this.model.toJSON());
  var selector = "#list";

  this.$el.find(selector).replaceWith($(selector, html));
}

but this is very slow because I think it re-renders all DOM before changing the #list content as I need.
Is there any better way to do that?
Is it a good idea to put the content of #list in another template and load it as a subView?
In this case how can I trigger an update of the list from my first view?
Thanks

A: It is better to update just the part of your rendered view by creating a dedicated render method, something I explained here.
In your situation it looks like you have to build whole html view from template, just to update the part of it. Which is neat, if you want to keep the template as one template.
If there really a lot of going on in the template beyond the list, you could have two templates in your view, one will be the general one, and the other one just for the list, which you will mount into the first one on global render, with the benefit of being able to update just the list.
Further, you might not even need a second template if the #list is simply a container for a list. I can imagine that might be an <ul> tag which you will mount at the right place during the global render, and then update it with other custom render methods.
Also, I wrote an example here, which might be potentially helpful in your case:
Backbone.js fetch() JSON to model get() returnes undefined - in the example there's a template, that has a container for a list, and the list is managed separately by it's own collection.
Just some thoughts.


text:
Q: Where to find ubuntu vagrant's home folder on windows? Does anyone know where I can find the home folder for vagrant on windows? I've tried typing /home/vagrant in windows file explorer but it still doesn't pop up.
I've also tried using vagrant's synced folders option by reconfiguring the vagrant file and that doesn't work either. Here is the code from the vagrantfile:
Vagrant.configure("2") do |config|
config.vm.synced_folder "c:/Users/Vanessa", "/home/vagrant"
config.vm.box = "mrgcastle/ubuntu-lucid32"
config.vm.box_version = "1.0.0.0"
end

Does anyone have any suggestions? Thanks for all your help in advance

A: Not sure what you are asking but follow this steps if you find what you want:

*

*ssh into vagrant from the folder which has your Vagrantfile. For me the path is C:\TaskMaster\sandbox and inside sandbox folder run vagrant ssh.

*Once you are in run: cd /home/ and do ls.

*cd vagrant

Let me know if you have a different question.


text:
Q: How to alias an output for automatic connection? I currently have this code:
self.add_subsystem('IntegrateForTheta2Ue6', utilities.CumulativeIntegrateTrapeziums(n=n),
                               promotes_inputs=[('x', 'panel_lengths'),
                                                ('x0', 'stagnation_point_position'),
                                                ('y', 'ue5'),
                                                ('y0', 'panel_start_external_tangential_velocity')],
                               promotes_outputs=[('cumulative_integral', 'intue5')])

self.add_subsystem('ThwaitesCalculateMomentumThickness', ThwaitesCalculateMomentumThickness(n=n),
                               promotes_inputs=['external_tangential_velocities',
                                                'intue5',
                                                'kinematic_viscosity'],
                               promotes_outputs=['momentum_thickness'])

It does not throw any errors when run, but when debugging it is clear that the output for intue5 aka cumulative_integral is not being passed into ThwaitesCalculateMomentumThickness - it appears as all ones. When I try the above with self.connect('IntegrateForTheta2Ue6.intue5', 'ThwaitesCalculateMomentumThickness.intue5'), I get Attempted to connect from 'IntegrateForTheta2Ue6.intue5' to 'ThwaitesCalculateMomentumThickness.intue5', but 'IntegrateForTheta2Ue6.intue5' doesn't exist.
Am I making a mistake in my output aliasing, or is this a bug?

A: Updating to the latest version of OpenMDAO worked. I believe I was already calling run_model(), so I'm not sure why it wasn't working.


text:
Q: Why use iostream instead of ios in struct Io_guard from "The C++ Programming Language"? struct Io_guard { // RAII class for iostream exceptions
    iostream& s;
    auto old_e = s.exceptions();
    Io_guard(iostream& ss, ios_base::iostate e) :s{ss} { s.exceptions(s.exceptions()|e); }
    ˜Io_guard() { s.exceptions(old_e); }
};

void use(istream& is)
{
    Io_guard guard(is.ios_base::badbit);
    // ... use is ...
}
catch (ios_base::badbit) {
    // ... bail out! ...
}

Above code is from 4th edition of "The C++ Programming Language", page 1080. I think it is better to do like
struct Io_guard {
    ios& s;

than
struct Io_guard {
    iostream &s;

because first one can be used to guard istream, ostream, and iostream since all of them are child classes of ios, but second one can only be used to guard iostream, since istream and ostream are not child classes of iostream.
Is Bjarne Stroustrup recommending to make three different Io_guards for each of istream, ostream, iostream?
Or is he just giving us an idea, so it is not important whether it is iostream or ios?

A: The code has more than one issue.
There is no constructor that would allow to create Io_guard via Io_guard guard(is.ios_base::badbit);. And the catch block is completely misplaced. ios_base::badbit is a constexpr iostate, ie not the type of an exception you can catch.
Given all this, I would not take the code too literally. Presumably it wasnt even meant as being ready to be used and compiled as is. Consider that it is in a section introduced via "For example ... For example...".  It merely demonstrates the general approach of how io exceptions can be handled by using a RAII wrapper.

The same example (same issues) can be found in an online 3rd edition version here: https://apprize.best/c/programming_2/38.html


text:
Q: Get name for all products of all orders I have a Magento store installed on localhost over WAMP server. I'm using Magento 1.7.
I need to do a table whose first column contains all the products from all the orders. I can't manage to get the product names; I found that there is more than one way to get product names from previous orders in Magento, but I'm not sure if I'm coding it properly.
My code for doing so is:
<?php
    $_orders = $this->getOrders();
    foreach ($_orders as $_order)
    {
        $items = $_order->getAllItems();
        foreach($items as $item) {$name = $item->getName();}
        echo $name;
    }
?>

Any ideas on what is wrong? Maybe I'm missing something or there is a better way to code it?
Any ideas/comments are much appreciated :-)

A: You can use the next variant:
/** @var Mage_Sales_Model_Mysql4_Order_Collection $_orders */
$_orders = Mage::getModel('sales/order')->getCollection(); // replace with yours $this->getOrders();
/** @var Mage_Sales_Model_Order $_order */
foreach ($_orders as $_order) {
    /** @var Mage_Sales_Model_Mysql4_Order_Item_Collection $itemsCollection */
    $itemsCollection = Mage::getModel('sales/order_item')->getCollection();
    $itemsCollection->setOrderFilter($_order);
    $itemsCollection->addFieldToSelect('name');
    $names[$_order->getId()] = $itemsCollection->getColumnValues('name');
}

Where result array keys is order id and value is array of the order item names:

PS: do not forget to replace the line $_orders = Mage::getModel('sales/order')->getCollection() with yours $this->getOrders()


text:
Q: What does the MDX error "Function expects a tuple set expression" mean? I am trying to create a set using MDX that contains a CASE statement.  I am recieving an error i cannot seem to get around. The error is:  The  function expects a tuple set expression for the  argument. A string or numeric expression was used.
There are only two members that could be returned, and they are 'Daily' and 'MonthEnd'.  I appreciate any help you can provide.  At first i thought the error meant i needed to use the {} to create a set, but that is not making since to me, and i do not know where they would need to be added.
    CREATE SET [BDW Report Prototype].[MyDimension] AS
    CASE [Grain].[Grain Dim ID]
     WHEN [Grain].[Grain Dim ID].&[1] THEN '1'
     WHEN [Grain].[Grain Dim ID].&[2] THEN '2'
    ELSE '3'
    END;

A: It means the set you're creating must a valid set (that is an ordered list of tuples) MDX expression. But you're assigning to this set a string. You're basically writing:
CREATE SET [BDW Report Prototype].[MyDimension] AS '1'

Obviously your [MyDimension] set is not a set but a string.
What do you want to create?


text:
Q: commiting to GitHub on IntelliJ-idea When I try to commit, the intellij show this error message:

That is only solved when I change the name of the folders in the local directory writing wrong like in pathspec Gere^encia, then the intellij-idea does the commit without error, but the commit doesn't go to the remote directory. The problem seems to be with the brazilian portuguese language, or with something in the encoding, but I tried everything, search on the web and nothing solved my problem.
If someone could give a little help I would appreciate.

A: I assume git add and git commit work from command line?
Looks related to https://youtrack.jetbrains.com/issue/IDEA-164612


text:
Q: Jcloud Nova unable to find Floating ip pool extension When i list extensions in nova from openstack i get floating ip extension as

http://docs.openstack.org/compute/ext/floating_ip_pools/api/v1.1

FloatingIPPoolApi in jcloud declares extension as(notice that in Jclouds namespace is missing "compute" in the URI

@Extension(of = "compute", namespace = "http://docs.openstack.org/ext/floating_ip_pools/api/v1.1")

jcloud returns that the floating ip extension is missing, even though its there in the extentions but under a different namespace.
is the FloatingIPPoolApi namespace is not correct in jclouds?
I thought by declaring extensions annotation with the "of" attribute, it gets automatically added to the namespace....maybe thats not the case at all.

A: This is a real bug, thanks for reporting it!
https://github.com/jclouds/jclouds/pull/813


text:
Q: How to write a jenkins file defining 5 reposiotries together How to write a jenkins file defining 5 repositories together ,different repo needs to do different build jobs

A: You use one stage per Repo build. You can checkout different Repos using 'checkout'.
Example:
pipeline {
    agent any
    stages {
        stage('Repo 1') {
            steps {
                    checkout([$class: 'GitSCM',
                              branches: [[name: '*/master']],
                              doGenerateSubmoduleConfigurations: false,
                              extensions: [],
                              submoduleCfg: [],
                              userRemoteConfigs: [[url: 'YourRepo1']]])
                    echo "Build Repo1"
            }
        }
        stage('Repo 2') {
            steps {
                    checkout([$class: 'GitSCM',
                              branches: [[name: '*/master']],
                              doGenerateSubmoduleConfigurations: false,
                              extensions: [],
                              submoduleCfg: [],
                              userRemoteConfigs: [[url: 'YourRepo2']]])
                    echo "Build Repo2"
            }
            ...
        }
    }
}

For a cleaner solution you need to add some paths being check outed in an build in.


text:
Q: Difficulty installing gatsby-plugin-sass because of xcode I'm trying to install gatsby-plugin-sass and I'm getting the following error:
xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

I can't find anything that tells me how to get past this error and I absolutely do not want to download the memory hog known as Xcode.
xcode-select is already installed, verified when I run xcode-select -install.  And I vaguely remember installing it a long time ago to get Sass to work (and Sass still works on my system.)
Is there a way to satisfy this error that doesn't involve installing XCode?  I really don't want to waste the gigabytes on it.
It appears to actually be an issue with node-gyp yet none of the fixes on their issues page seem to work for me.


text:
Q: How to approach asking and answering a canonical question? Background: Over at Arqade, I've noticed an increasing number of questions about Clash Of Clans asking how to recover their lost account. These questions are not closed as duplicates since each case is slightly different based on the user's platform etc. I often answer these questions with the exact same answer. I wish to fix this problem by creating a canonical question on this topic, and answering it myself. However, since the act of making canonical questions applies across the entire the whole network, I decided to ask this question here.

I wish to create a canonical question and answer for a frequently-asked question, as the current questions and answers are highly specific to each case.
I created the question, answered it, and marked the answer as community wiki. But how do I let everyone know that this post is intended to be canonical, and all past and future questions on this topic should be closed as duplicates?
Should I:
a) Post a comment stating this
b) Create a meta discussion and link it to the question
c) Flag all other duplicate questions to show my intent
d) Do all of the above
e) Different order? Something else?

A: This answer is slightly edited based on my answer on MSO
The Steps towards a canonical question

*

*Improve the tag wiki
It could include links to a few frequently asked questions and in the end also the link to the canonical question. This helps your peers to find the question.

*Have some pre-cooked comments ready to point new users to the tag-wiki. This helps both new and regular users to read that stuff.

*Organize some regulars in a chat room to gather samples of questions and discuss topics that should go in the canonical question. This helps the sub-community to learn the mechanics

*Post on meta your intentions. Most important to see if the community at large supports your case.

*Make sure a moderator knows about it. This is needed to prepare for the launch so a wiki lock can be applied on the question.

*Prepare your question and the answer off-line in collaboration with your peers (For the regex post a Github Gist was used)

*Post your canonical question and answer.

*

*Mark both as Community Wiki to prevent that some members accuse you of gaining rep

*Start closing questions against the canonical question.

*Improve and update the canonical question and answer.

This sums up the process.
Don't go blindly close vote all questions now as duplicate because the other close reasons still apply. Overly broad or opinion based questions should still be closed against that reason. If and only if the question is answered by the canonical question closing as a duplicate is OK.


text:
Q: Publishing a google sheet using app script The below script was working till about a week ago.  I have checked the developer dashboard, and I cannot tell what has changed.  I am wondering if anyone has an alternative method for publishing a google spreadsheet via app script, or how I can get the script working again.
function publishSheet(sheetId) {
  //DriveApp.getRootFolder(); Needed for Scope
  if (!sheetId) {sheetId = "1gshaH5buTPFmm8elky0zWXqPYSO6BahK_OT7uFLrrgw"};

  var payload = {
    "published":true,
    "requireSignin":false,
    "entireDocument":true
  }

  var url = "https://docs.google.com/a/cc..org/spreadsheets/d/"+sheetId+"/publishingsettings?id=" + sheetId
//  var url = "https://docs.google.com/spreadsheets/u/2/d/"+sheetId+"/publishingsettings?id=" + sheetId
  var options = {
    method:"POST",
    contentType:"application/x-www-form-urlencoded;charset=UTF-8",
    headers:{
      Authorization:"Bearer " + ScriptApp.getOAuthToken()
    },
    payload:payload,
    muteHttpExceptions:true
  }

  var resp = UrlFetchApp.fetch(url,options);
  //Logger.log(resp) //no real response just some random characters.
}


text:
Q: Am I doing this epsilon-delta algebra correctly? I've done a handful of really basic epsilon/delta algebraic evaluations, but I'm not sure if my answer to this one is correct. Is it okay for delta to be a function rather than a constant? Are my steps valid?
Given $f(x) = \sqrt x, L = \frac{1}{2}, c = \frac{1}{4}, \epsilon = 0.1$,
What is a $\delta | 0 < |x-c| < \delta \implies |f(x) - L| < \epsilon$ ?
$| \sqrt x - \frac{1}{2} | < 0.1$
$| \frac{(x - \frac{1}{4})}{\sqrt x + \frac{1}{2}} | < 0.1$
$|\frac{1}{\sqrt x + \frac{1}{2}}| \cdot |x - \frac{1}{4}| < 0.1$
$\frac{1}{\sqrt x + \frac{1}{2}} \cdot |x - \frac{1}{4}| < 0.1$
$|x - \frac{1}{4}| < 0.1 \cdot (\sqrt x + \frac{1}{2})$
$|x - \frac{1}{4}| < 0.1 \cdot (\frac{1 + 2 \sqrt x}{2})$
$|x - \frac{1}{4}| < \frac{1 + 2 \sqrt x}{20}$
Let $\delta = \frac{1 + 2 \sqrt x}{20}$.
$0 < |x - c| < \delta \implies |f(x) - L| < \epsilon$

A: Notice that $\frac{1}{2}-.1<\sqrt{x}<\frac{1}{2}+.1\iff.4<\sqrt{x}<.6\iff.16<x<.36$,
so we can take $\delta=\min\{\frac{1}{4}-.16,.36-\frac{1}{4}\}=\min\{.09, .11\}=.09$,
since $\displaystyle 0<\left|x-\frac{1}{4}\right|<.09\implies.16<x<.36\implies.4<\sqrt{x}<.6\implies\left|\sqrt{x}-\frac{1}{2}\right|<.1$

More generally, a similar argument shows that we can take $\delta=\epsilon-\epsilon^2$ if $0<\epsilon<\frac{1}{2}$,
and we can take $\delta=\frac{1}{4}$ if $\epsilon\ge\frac{1}{2}$.


text:
Q: How do I change the state of a QProgressBar? I have a custom dialog that imitates and embellishes QProgressDialog with some additional application-specific information and enables pausing/resuming the worker thread running in the background. Ultimately what I'm looking for is the ability to change the appearance of the QProgressBar to reflect the paused state as described in this question.

Oddly enough QWinTaskbarProgress seems to support this exact functionality as of Qt 5.2, but a plain QProgressBar does not, in Qt4 or Qt5. I'm okay with fiddling around in the Qt source code, but I've dug around in the Qt source code and I can't figure out where the actual state of the form control is queried/provided, so I can't figure out what I need to change. Maybe it's not there because this is strictly a Windows thing, but maybe not?
Using CSS to override the StyleSheet as recommended in the docs (and here) results in a very ugly progress bar, completely different in appearance from the stock Windows 7 progress bar.
Normal:

Stylesheet:

I don't want to use this option.

A: The simple way is setting QGraphicsColorizeEffect to the progress bar.
Like this:
QProgressBar* progress = new QProgressBar;
progress->setGraphicsEffect(new QGraphicsColorizeEffect);

Result on Win7:

Umm...the result looks like fine, but we can make it better, only change the chunk colour.
Here is the final result:

Reimplement QGraphicsEffect::draw to specific & customize the colourize effect area:
class Colorize : public QGraphicsEffect {
public:
    explicit Colorize(QObject *parent = Q_NULLPTR) :
        QGraphicsEffect(parent),
        strength(1),
        color(Qt::red),
        effectRect()
    { }
    quint32 strength;
    QColor color;
    QRectF effectRect;

protected:
    void draw(QPainter* painter) {
        QPoint offset;
        const QPixmap pixmap = sourcePixmap(Qt::LogicalCoordinates, &offset);
        draw(painter, offset, pixmap, QRect());
    }

    void draw(QPainter *painter, const QPointF &dest, const QPixmap &src, const QRectF &srcRect) const
    {
        if (src.isNull())
            return;

        QImage srcImage;
        QImage destImage;

        if (srcRect.isNull()) {
            srcImage = src.toImage();
            srcImage = srcImage.convertToFormat(srcImage.hasAlphaChannel() ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
            destImage = QImage(srcImage.size(), srcImage.format());
        } else {
            QRect rect = srcRect.toAlignedRect().intersected(src.rect());

            srcImage = src.copy(rect).toImage();
            srcImage = srcImage.convertToFormat(srcImage.hasAlphaChannel() ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32);
            destImage = QImage(rect.size(), srcImage.format());
        }
        destImage.setDevicePixelRatio(src.devicePixelRatioF());

        // do colorizing
        QPainter destPainter(&destImage);
        grayscale(srcImage, destImage, srcImage.rect());
        destPainter.setCompositionMode(QPainter::CompositionMode_Screen);
        destPainter.fillRect(effectRect, color);
        destPainter.end();

        // alpha blending srcImage and destImage
        if(0 < strength && strength < 1){
            QImage buffer = srcImage;
            QPainter bufPainter(&buffer);
            bufPainter.setOpacity(strength);
            bufPainter.drawImage(0, 0, destImage);
            bufPainter.end();
            destImage = buffer;
        }

        if (srcImage.hasAlphaChannel())
            destImage.setAlphaChannel(srcImage.alphaChannel());

        painter->drawImage(dest, destImage);
    }
};

Calculate the grove rect of the progress bar:
QRectF getGrooveRect() const {
    StyleOptionProgressBar option;
    option.initFrom(this); // this ⇒ progress bar
    return style()->subElementRect(QStyle::SE_ProgressBarGroove, &option, this);
}

...

class StyleOptionProgressBar : public QStyleOptionProgressBar {
public:
    using QStyleOptionProgressBar::QStyleOptionProgressBar;

    void initFrom(const ColorizeProgressBar* w) {
        init(w);
        minimum = w->minimum();
        maximum = w->maximum();
        progress = w->value();
        text = w->text();
        textAlignment = w->alignment();
        textVisible = w->isTextVisible();
        orientation = w->orientation();
        invertedAppearance = w->invertedAppearance();
    }
};

Complete source on Github.
BTW, Referred Qt source code


text:
Q: How to set initial state from local storage in next js? I want to get value from local storage in next js. It should look some thing like this in next js. But this don't work. How to do it?
const initialState = {
  language: {
    lang: "eng",
    iconPath: "/imgFolder1/usaIcon.png",
    languageFullEng: "English",
    languageFullHeb: "אנגלית",
  },
};

const setInitialLanguage = () => {
  const language = JSON.parse(localStorage.getItem("language"));
  if (language) {
    return language;
  } else {
    return initialState;
  }
};

const languageSlice = createSlice({
  name: "language",
  initialState: setInitialLanguage(),
  reducers: {
    setLanguage: (state, action) => {
      state.language = action.payload;
      localStorage.setItem("language", JSON.stringify(state));
    },
  },
});

export const { setLanguage } = languageSlice.actions;
export default languageSlice.reducer;


text:
Q: Given an object ,how can I know its class in perl? I need this info to decide which of the classes with a specific method is being called.

A: You use the ref builtin to determine the reference type or class of a variable:
my $obj = bless [] => 'Some::Class';

print ref($obj), "\n";  # 'Some::Class';

More detail can be found with Scalar::Util's reftype (always returns the container type) and blessed (always returns the class name) subroutines.

A: ref will usually work fine but blessed in Scalar::Util may be a better choice. It will return undef for plain references that aren't blessed into a package for example.

A: ref($obj) will do the job for you.


text:
Q: Finding escalated value (compounded percentage) I have a table like this:
Year  V1   V2
2022  101% 102%
2023  103% 101%
2024  104% 103%
2025  102% 101%

I want to find escalated value based on start and end years (so an outcome would look like this):
Segment Value StartYear EndYear ValueEscalated
V1      100   2022      2023    104.03 (100*1.01*1.03)
V2      200   2022      2025    214.34 (200*1.02*1.01*1.03*1.01)

Is it possible to create a formula that would do this?
P.S. Assumption is that values in "Value" column in the outcome are typed in (so they are not formulas).

A: You could do a lookup on year and segment then use product as follows:
=LET(years,$A$2:$A$5,
segments,$B$1:$C$1,
data,$B$2:$C$5,
seg,A8,
val,B8,
sy,C8,
ey,D8,
col,XLOOKUP(seg,segments,data),
startrow,XLOOKUP(sy,years,col),
endrow,XLOOKUP(ey,years,col),
PRODUCT(val,startrow:endrow))


text:
Q: IOS present modally animation issue I am using the present model segue for load the next view controller. It is working fine. Now I am using some conditions. After that it is giving wrong animation.
Method 1
- (IBAction)loginClick:(id)sender {

        [self performSegueWithIdentifier:@"mainPageView" sender:self.view];
}

according to this method it is giving correct animation. IOS 7 and IOS 8
After that I am using simple condition
Method 2
- (IBAction)loginClick:(id)sender {

    if (self.txtUsername.text.length != 0) {
        [self performSegueWithIdentifier:@"mainPageView" sender:self.view];
    }

}

According to this method IOS 7 is working fine. But IOS 8 it is moving the next view controller. But animation is not working properly. It is showing more rotation and not regular method.
I am totally confused for this. Anyone have any idea?

A: In myself I found the solution for this problem. I am using the autolayout and some constraint. In my case that is the issue. I delete the constraint. Now it is working. But still I am confuse. Anyhow it is working


text:
Q: for var in {$1..$2} not working can any of you tell me what is shell's problem in this case?
When I write and execute this script(./cyklus.sh 5 10):
  1 #!/bin/bash
  2
  3
  4 if [ $# -eq 2 ]; then
  5         if [ $1 -le $2 ]; then
  6                 for i in {$1..$2}
  7                 do
  8                         if [ $i -lt $2 ]; then
  9                                 echo -n "$i "
 10                         else
 11                                 echo "$i"
 12                         fi
 13                 done
 14         elif [ $1 -gt $2 ]; then
 15                 echo "Prvy argument musi byt vacsi nez druhy."
 16         fi
 17 else
 18         echo "Nezadal si 2 argumenty"
 19 fi

it outputs an error:
./cyklus.sh: line 8: [: {5..10}: integer expression expected
{5..10}

even though the starting and ending integer is set there through $1 and $2.

A: You can use "seq" command to generate the sequence:
for i in `seq $1 $2`


text:
Q: Stop a tween animation in tween.js and three.js I'm having trouble stopping a tween in three.js, using tween.js.
The docs state to use tween.stop(), but that doesn't seem to work.
Example here:
http://jsfiddle.net/feLzjzy9/1/
As you hover with the mouse over a box, it starts to change color. This animation takes 10 seconds, but I try to stop it just to test the .stop() feature using setTimeout(function(){ tween.stop() }, 1000);but it doesn't do a thing...
Any help is much appreciated!

A: There is Reference problem and update problem.
I made some changes in you code. It is not a solution, you can use each change individually.
Best solution is to make each tween as var inside a function, integrate counting in tweened objects and use onUpdate(function(){if(this.counter > 1000){tween.stop}}) (INTERSECTED.material.color) because  you creating a lot of unrefferenced timers and tweens, which will be a performance problem.
function animate() {
      //
      TWEEN.update();
      //
}

    if (intersects.length > 0) {

        if (INTERSECTED != intersects[0].object) {

            if (INTERSECTED) INTERSECTED.material.color.setHex(INTERSECTED.currentHex);

            INTERSECTED = intersects[0].object;
            INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
            //INTERSECTED.material.emissive.setHex(0xff0000);
            TWEEN.remove(tween);
            tween = new TWEEN.Tween(INTERSECTED.material.color).onStart(function(){

      setTimeout(function(){ tween.stop() }, 1000); ///not good
}).start();
            .to({r: 0, g: 25, b: 155}, 10000) /// here set correct time
            .easing(TWEEN.Easing.Quartic.In)
            .start();

            setTimeout(function(){ tween.stop() }, 1000);/// will not work if you create anoter it that one second

        }
        else {
            if(tween) tween.update(time); // bad
        }

    }


text:
Q: Using block for callback from different class I have spent quite a bit of time reading about blocks, but for some reason it's very difficult for me to fully understand them. It's worth mentioning I'm a newbie developer, but blocks are the first real 'block' I've come across, so maybe you can help me.
I have a case where an object (instance of a ViewController) is talking to a class (via a class method - it's a utility class I've set up to request/get data). I want to implement a method with a callback using a block. Here are my current 'understandings' that I based my code on:

*

*A block can be passed as a method argument;

*A block can be called like a function.

OK, so here's my (simplified) method in my utility class:
+ (void)getDataWithCompletion:(void (^)(BOOL))completion {

    //Some code...
    completion(YES);
}

And this is how I call the method from my viewController:
[ClassName getDataWithCompletion:^(BOOL gotData) {

    if (gotData) {
        NSLog(@"Called");
    }
}];

Naturally, I was expecting that NSLog to be printed on my console, but alas... I know I am doing something wrong here, could someone please point that out? Any rookie-level explanation would be highly appreciated.

A: The mistake is really simple. You forgot a parameter name.
Cahnge your method to this.
(BOOL gotData) this is what you have missed.
+ (void)getDataWithCompletion:(void (^)(BOOL gotData))completion {

    //Some code...
    completion(YES);

}
Here is link to apple documentation apple block documentation


text:
Q: Fancybox Next/Previous buttons not showing up for simple content popup I have a Magento 1.9.3.0 CE running site with custom News slider on Homepage.
In every news item in slider there is "Read More" link which opens the same news (a hidden div box containing same but full content of news) in full mode in a fancybox popup.
Now I have used below code for implementing that and also applied rel="gallery" in every "Read More" link.
$cnjQ('.news-owlgrid').children().find('a.cn-read-more').each(function() {
    $cnjQ(this).click(function() {
        var contentHref = $cnjQ(this).attr('href');
        $cnjQ.fancybox({
            /*'width': 750,
            'height': 750,*/
            'type': 'iframe',
            'content': $cnjQ(contentHref).show(),
            //'content': $cnjQ(contentHref).html(),
            'beforeLoad': function() {

            },
        });
    });
});

Then why still the Next Previous button doesn't show up in the popup which opens on clicking "Read More" link ?


text:
Q: Reactive form add Drop down List Below is my html code for reactive form , after clicking "ADD category button" i am getting an input and a drop down list . I have written the code for input , but for drop down list im getting error.
<form [formGroup]="categoryForm">

                        <input
                          type="text"
                          [formControlName]="i"
                          class="form-control"
                          placeholder="Enter Category"
                        />

                        <select
                          class="form-control"
                         [formControlName]="i"
                          required
                          (change)="getVoteType( i)"
                        >
                          <option class="" selected disabled value="undefined">
                            Select Vote Type
                          </option>
                          <option *ngFor="let vote of vType" [value]="vote">
                            {{ vote }}
                          </option>
                        </select>

Below is the vType array
this.vType = [
      "Star - Rating", "Emoji - Voting", "Most - Liked"
    ];

And here is the code for getVoteType where i am just trying to display images
getVoteType(vote: any, x: any) {
    //console.log("Vote Selected is -------" , vote);
    this.voteType.push(vote);
    console.log(vote, x);
    if (vote.includes("Star")) {
      this.vTypeEmo = "star_emoji"
    }
    else if (vote.includes("Most")) {
      this.vTypeEmo = "thumps_emoji"
    }
    else if (vote.includes("Emoji")) {
      this.vTypeEmo = "heart_emoji"
    }
    else{
      this.vTypeEmo = "";
    }

    console.log("----- Vote Type is ",this.voteType);

    this.imageUrl = "Angular/src/assets/images/" + this.vTypeEmo + ".png";
    this.urlImageArray[x] = this.imageUrl;
    //this.urlImageArray.push(this.imageUrl);
    console.log("urlImageArray is ", this.urlImageArray);

I want to know how would i write the drop down list using reactive form in this situation ?
Hope i am clear to everyone. thanks


text:
Q: Scenario's for loseing messages with akka when all actors run in the same jvm I once wrote a multiplayer game in java with the help of the akka framwork. With their 'at-least-once' delivery I always wondered in which cases a message can get lost if all the akka actors are running in the same local jvm.
The design of the game was like a giant state machine (as events needed to be processed in order), so most of the times only 1 message was on it's way between all the involved actors. (Running multiple session in parralel was possible)
I have read that the communication of actors, when running locally, is done in-memory. So not considering out of memory error's, are their other (preferably reroducable) scenario's where messages are actually lost?
Note:
Message box manipulation is also not what I am looking for. Just legit cases where something goes wrong and the message is really lost.

A:
I have read that the communication of actors, when running locally, is done in-memory. So not considering out of memory error's, are their other (preferably reroducable) scenario's where messages are actually lost?

So, normally in-memory delivery is true, but you also specified that you are talking about the "at-least-once delivery" feature. And the docs ( https://doc.akka.io/docs/akka/current/persistence.html#at-least-once-delivery ) specifically talk about how at-least-once changes a lot of the normal behavior. Specifically, at-least-once uses persistence to track what has been sent and what has been acknowledged.
So, when you are using at-least-once, there is a whole dance that has to happen when sending a message. First the message has to to be stored such that if the sending actor fails, that work can resume elsewhere. Second, the message has to be sent. Third, any response has to be correlated with the sent message and the receipt persisted so that if the actor fails after that point that the resuming actor knows that the message doesn't have to be retried.
Because of this, there should be no case where a message is lost. Even when a JVM is lost. (Even when all JVM's are lost.) That, after all is the point of "at-least-once", that the message is guaranteed to be delivered (and replied to). However, note that this does come with tradeoffs. (See the docs for the tradeoffs, although one obvious one is performance.)


text:
Q: Let $a$ a positive integer such that $gdc(a,10) = 1$. Prove by induction: if $k>0, k \in \mathbb{Z}$ then $a^{4\cdot 10^k} \equiv 1 \pmod{10^{k+1}}$ Let $a$ be a positive integer such that $a$ is coprime with $10$.
Prove using induction that: for any positive integer k we have $a^{4\cdot 10^k} \equiv 1\pmod{10^{k+1}}$
I tried to use induction but I can't find any result. I need help.

A: $a^4 \equiv 1\pmod {10}$ from the Fermat - Euler theorem
Suppose
$a^{4\cdot 10^k} \equiv 1\pmod {10^k}$  (heck this is true from the Fermat-Euler theorem, I guess we need a different proof of the base case.)
base case revisitied:
$(a^4 - 1) = (a+1)(a-1)(a^2 + 1)$
One of $(a+1),(a-1)$ is even.
If $5$ does not divide $(a+1),(a-1)$
then $a \equiv 2,3 \pmod 5$ in which case $5$ divides $a^2 +1$
$10$ divides $(a^4 - 1)$
$a^4 \equiv 1 \pmod {10}$
Inductive hypothesis:
Suppose
$a^{4\cdot 10^k} \equiv 1\pmod {10^{k+1}}$
We must show that
$a^{4\cdot 10^{k+1}} \equiv 1\pmod {10^{k+2}}$
$a^{4\cdot 10^{k+1}} = (a^{4\cdot 10^{k}})^{10}$
$a^{4\cdot 10^{k}} = (n10^{k+1} + 1)$ from the inductive hypothesis
$(n10^{k+1} + 1)^{10} = \sum_\limits{i=0}^{10} {10 \choose i} n^i10^{i(k+1)}$
$10^{k+2}$ divides ten of the eleven terms of the above:
The remainder is 1.

A: Here is a much more simples proof without using induction.
If $gcd(a,10)=1$, then $gcd(a,10^{k+1})=1$.
So, $$a^{\phi(10^{k+1})}\equiv1(mod 10^{k+1}),$$ but, $$\phi(10^{k+1})=\phi(2^{k+1}).\phi(5^{k+1})=2^k.5^k.4=4.10^k,$$
$$\Rightarrow a^{4.10^k}\equiv1(mod 10^{k+1})$$


text:
Q: Different in Java SHA1 vs JavaScript SHA1 I am a little bit confused. I want to get the bytes of an String, which is hashed with SHA1.
JavaScript:
var content = "somestring";
console.warn(content.getBytes().toString());
console.warn(CryptoJS.SHA1(content.getBytes().toString()).toString().getBytes());

String.prototype.getBytes = function () {
var bytes = [];
for (var i = 0; i < this.length; i++){
    bytes.push(this.charCodeAt(i));
}
return bytes;
};

Array.prototype.toString = function(){
var result = "";
for(var i = 0; i < this.length; i++){
    result += this[i].toString();
}
return result;
}

which gives me
115111109101115116114105110103
[52, 99, 97, 54, 48, 56, 99, 51, 53, 54, 102, 54, 48, 53, 50, 49, 99, 51, 49, 51, 49, 100, 49, 97, 54, 55, 57, 55, 56, 55, 98, 52, 52, 52, 99, 55, 57, 102, 54, 101]

Java:
String message = "somestring";
byte[] sha1 = MessageDigest.getInstance("SHA1").digest(message.getBytes());
System.out.println(Arrays.toString(message.getBytes()));
System.out.println(Arrays.toString(sha1));
System.out.println(new String(sha1));

which gives me
[115, 111, 109, 101, 115, 116, 114, 105, 110, 103]
[-38, 99, -5, 105, -82, -80, 60, 119, 107, -46, 62, -111, -30, -63, -53, 61, -13, 1, 53, -45]
Úcûi®°<wkÒ>'âÁË=ó5Ó

The first output is equal on JavaScript and Java, but the second is different. Why and how is a checksum like Úcûi®°<wkÒ>'âÁË=ó5Ó possible?

A: In your JavaScript you're doing a SHA-1 on a String which is the numbers from a byte Array (so is different to your String content).
console.warn(CryptoJS.SHA1(content.getBytes().toString()).toString().getBytes());
//                                              ^^

In your Java, you're doing a SHA-1 on a byte[] (which is equivalent to your String content)
byte[] sha1 = MessageDigest.getInstance("SHA1").digest(message.getBytes());
//                                                                ^^

Your toString is creating a very different piece of data to what you're SHA-1-ing in Java.
Also (not sure if relevant): internally, JavaScript uses UTF-16 for Strings.

Further, the logged output of your JavaScript cannot be a SHA-1 as it is the wrong length; this is due to .toString().getBytes() repeated on the sha1 after it's been calculated (Stephen C mentions this in this comment).

A: Here's the solution:
Javascript:
key = 'testKey';
var hashedKey = CryptoJS.SHA1(key);
console.log(hashedKey);

Output: 2420e186fcdb8d0ea08d82fdfbfb8722d6cbf606
Java:
password="testKey";
final MessageDigest md = MessageDigest.getInstance("SHA1");
ByteArrayOutputStream pwsalt = new ByteArrayOutputStream();
pwsalt.write(password.getBytes("UTF-8"));
byte[] unhashedBytes = pwsalt.toByteArray();
byte[] digestVonPassword = md.digest(unhashedBytes);
System.out.println(bytesToHex(digestVonPassword));

Output: 2420E186FCDB8D0EA08D82FDFBFB8722D6CBF606
With the exceptions of capital vs. lowercase, the output is the same.  It's in hex, by the way.

A: I found this library. It produces same values as Java
https://caligatio.github.io/jsSHA/


text:
Q: No scrolling in scrollview i have a problem with my scrollview...
my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">

         <ScrollView android:id="@+id/scrollView1" android:layout_width="wrap_content" android:layout_height="match_parent">
             <RelativeLayout [...]>
                 <TextView [...]></TextView>
                 <Spinner [...]></Spinner>
                 <Button [...]></Button>
                 <ImageButton [...]></ImageButton>
                 <TextView [...]></TextView>
                 <TableLayout [...]>
                     <TableRow [...]>
                         <TextView [...]></TextView>
                         <TextView [...]></TextView>
                         <TextView [...]></TextView>
                     </TableRow>
                     <TableRow [...]>
                         <AutoCompleteTextView [...]></AutoCompleteTextView>
                         <AutoCompleteTextView [...]></AutoCompleteTextView>
                         <Spinner [...]></Spinner>
                     </TableRow>
                 </TableLayout>
            </RelativeLayout>
         </ScrollView>
</LinearLayout>

When i try to scroll in my App it wont work... what did i do wrong?
i deleted the properties from the elements. if you need them to solve the problem i can add them.
i did it to get a better overview.
thanks,
prexx

A: Try adding the ScrollView as the parent. Swich place with LinearLayout.
And dont forget to add the following on your ScrollView instead of the LinearLayout:
xmlns:android="http://schemas.android.com/apk/res/android"

And layout_widht and layout_height of the ScrollView should be set to "fill_parent"
This is my code which uses ScrollView in a calendar I made, could help you:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg">
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <Button android:id="@+id/dayView" android:text="Day" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/>
    <Button android:id="@+id/weekView" android:text="Week" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/>
    <Button android:text="Month" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:enabled="false"/>
    <Button android:id="@+id/eventsView" android:text="Events" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/prevMonth"
        android:src="@drawable/calendar_left_arrow_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ImageView>
    <Button
        android:id="@+id/currentMonth"
        android:layout_weight="0.6"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:background="@drawable/calendar_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>
    <ImageView
        android:id="@+id/nextMonth"
        android:src="@drawable/calendar_right_arrow_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ImageView>
</LinearLayout>
<LinearLayout
    android:layout_gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView android:layout_width="wrap_content" android:layout_height="20dp" android:text="Week" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/monday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/tuesday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/wednesday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/thursday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/friday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/saturday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
    <TextView android:id="@+id/sunday" android:layout_width="wrap_content" android:layout_height="20dp" android:text="" android:textColor="#000000" android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="1">
    <ViewFlipper
       android:id="@+id/flipper"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <GridView
            android:id="@+id/weeks"
            android:numColumns="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:scrollbars="none">
        </GridView>
        <GridView
            android:id="@+id/calendar"
            android:numColumns="7"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scrollbars="none">
        </GridView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <GridView
            android:id="@+id/weeks2"
            android:numColumns="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:scrollbars="none">
        </GridView>
        <GridView
            android:id="@+id/calendar2"
            android:numColumns="7"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scrollbars="none">
        </GridView>
    </LinearLayout>
</ViewFlipper>
</LinearLayout>
<LinearLayout
        android:id="@+id/bottom_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/create_event"
            android:text="Create event"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</ScrollView>

A: Try adding android:fillViewport="true" to your scrollView.
The height of your scrollView should probably be either match_parent or fill_parent aswell.

A: Please change to android:layout_width="wrap_content" android:layout_height="wrap_content"
 to fill parent.
Thank you

A: If the ScrollView content doesn't take up the whole space, it will behave as a normal layout, i.e. non-scrollable.
If you still need the ScrollView to fill the entire screen (but still not scroll since there is not enough content) you could do as Nicholas Magnussen mentioned and add android:fillViewport="true"


text:
Q: Multiple _PublishedWebsites Folders I am using VS Code on Manjaro and have setup a solution with 2 projects, a webapp and a test project.
Each time I do a build it appears to generate a new _PublishedWebsites folder with NetCoreApp underneath it.  I am surprised that nobody else seems to have encountered this issue.  Can anyone tell me why this is happening and how to fix it?
Many thanks.

A: You should check your csproj file, particularly PublishDir element which is your specified location for publishing output files and change that if your like.
However, I think this is required behavior for .net core support in app harbor, find more details in the support webpage over here.


text:
Q: If all moment of X are greater than all moment of Y, can we said something about their probability? Consider a continuous probability distribution $f$ and two random variables $X, Y$ both are greater than equal to $0$ and they are not identical random variables.
Let's say one can show that $E[X]^k \geq E[Y]^k$ for all $k \geq 0$ and suppose their moment generating function exists.
Can I conclude that $X \geq Y$ almost surely? This is my intuition
I can easily get $Pr[X^k \geq Y^k] \neq 0$ otherwise we get the contradiction. Or at least I want to find the lower bound of $Pr[X^k \geq Y^k]$.
Any comment is welcome and thanks for your help.