text:
Q: How to deal with NA in two lists? I have two lists and I want make them consistent in terms of NA. Put NA Whenever there is NA in one of the two lists without changing in anything else in the structure of the list.
set.seed(123)
m1 <- matrix(nrow=2,ncol=2,data=runif(4))
m1[1,1] <- NA
m2 <- matrix(nrow=2,ncol=2,data=runif(4))
m2[1,2] <- NA
lis <- list(m1, m2)
m1 <- matrix(nrow=2,ncol=2,data=runif(4))
m2 <- matrix(nrow=2,ncol=2,data=runif(4))
m2[2,1] <- NA
bis <- list(m1, m2)

I tried this but with no success bis[is.na(lis)]=NA
Desired output:
  > lis
[[1]]
          [,1]      [,2]
[1,]        NA 0.9568333
[2,] 0.4566147 0.4533342

[[2]]
         [,1]     [,2]
[1,] 0.9404673       NA
[2,] 0.0455565       NA

   > bis
 [[1]]
        [,1]      [,2]
[1,]        NA 0.9568333
[2,] 0.4566147 0.4533342

 [[2]]
         [,1]        [,2]
 [1,] 0.6775706        NA
 [2,] 0.5726334        NA

A: Using Map to create a list of matrices with the NA positions as NA:
naposmtx <- Map(function(mtx1, mtx2){
    nasmtx <- mtx1 + mtx2 # because NA + non-NA = NA
    nasmtx[!is.na(nasmtx)] <- 0
    nasmtx
}, lis, bis)

Then:
lis <- Map(`+`, lis, naposmtx)
bis <- Map(`+`, bis, naposmtx)

A: Here's an option:
z <- Map("|", lapply(lis, is.na), lapply(bis, is.na))
bis <- Map(function(mat, idx) {mat[idx] <- NA; mat}, bis, z)
lis <- Map(function(mat, idx) {mat[idx] <- NA; mat}, lis, z)

However, there may be faster / more efficient approaches due to the numerous Map and lapply calls.

For the case of >2 lists you can use the following approach (assuming that each list has the same length):
# create a named list - naming is important if you want to
# assign them back to the global environment later on
mylist <- list(lis = lis, bis = bis, kis = kis)

n <- max(lengths(mylist))
z <- lapply(1:n, function(i) {
  Reduce(`+`, Map(function(y) is.na(y[[i]]), mylist))>0
})

mylist <- lapply(mylist, function(mat) {
  Map(function(m, idx) {m[idx] <- NA; m}, mat, z)
})

# to assign them back to the global environment, run:
list2env(mylist, envir = .GlobalEnv)

Now your original lists are modified in the global environment.
Sample data:
set.seed(123)
n <- 4
lis <- list(
  m1 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE)),
  m2 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE))
)
bis <- list(
  m1 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE)),
  m2 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE))
)
kis <- list(
  m1 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE)),
  m2 = matrix(nrow=n,ncol=n,data=sample(c(NA, 1:10), n*n, TRUE))
)


text:
Q: Audio not playing in Flash AS3 I've been trying to play an external sound file in Flash and failing miserably.
The code couldn't be simpler:
var s:Sound = new Sound();
var req:URLRequest = new URLRequest(MovieClip(root).videoLink);
var context:SoundLoaderContext = new SoundLoaderContext(3000, true);
s.load(req, context);
var my_channel:SoundChannel;
my_channel = s.play(0);

videoLink is a string containing a valid link to a WAV file on the same server.
The problem with this code is, I can only run it while it's on a live server (the link is obtained from a MySQL database via XML), so I can't tell if any error when it's being run. Then again, I can't see how the above code can lead to any problems.
I've spent more than 2 hours trying different solutions. Any help would be greatly appreciated.
Andrey

A: Your sound file should be a mp3 , not a wav. try the same code with an mp3 version and it should play.
Check this article, for info on how to play wav files with as3
http://richapps.de/?p=97

redpajama_set_name: RedPajamaStackExchange


text:
Q: Purchase digital content with Crypto Currency in iOS application In one of our application, we are going to introduce digital content purchase mechanism with crypto currency. So here are my doubts:
1) Is it durable and achievable?
2) If yes, is Apple going to allow this kind of implementation and accept it to iTunes?.

A: The criteria is 'if goods cannot be used in the app'.  Only then you can use a system other than IAP (including a system like Crypto Currency)
Digital Goods which are ment to be used within the App must be purchased trough In-App Purchase. If you use any other mechanism, then your app will be rejected.
From the official docs

If you want to unlock features or functionality within your app, (by
  way of example: subscriptions, in-game currencies, game levels, access
  to premium content, or unlocking a full version), you must use in-app
  purchase. Apps may not use their own mechanisms to unlock content or
  functionality, such as license keys, augmented reality markers, QR
  codes, etc. Apps and their metadata may not include buttons, external
  links, or other calls to action that direct customers to purchasing
  mechanisms other than in-app purchase

Someone has asked similar question on Apple Thread also. have a look at the following thread

A: Answer on the second question: if you want to implement some kind of purchases in your app you also should follow items from the review guidelines:
From the official docs:

3.1.5 (a) Goods and Services Outside of the App: If your app enables people to purchase goods or services that will be consumed outside of the app, you must use purchase methods other than in-app purchase to collect those payments, such as Apple Pay or traditional credit card entry.
3.1.5 (b) Cryptocurrencies:

*Initial Coin Offerings: Apps facilitating Initial Coin Offerings ("ICOs"), cryptocurrency futures trading, and other crypto-securities or quasi-securities trading must come from established banks, securities firms, futures commission merchants ("FCM"), or other approved financial institutions and must comply with all applicable law.


text:
Q: Type in the textbox with LETTERS only and also with only one Minus sign(-) only Preferably using the ASCII code I want to use the ASCII code of minus sign. Is there possible way on doing it? Use minus sign only once.
45 is the ASCII code of minus sign(-)
private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);// e.KeyChar == (char)Keys.45);
}

A: To allow using the hyphen/minus character only once, you need to check if the TextBox already contains one. If it does, you set e.Handled to true. The rest of your logic should work fine.
You may use something like this:
private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    // If you want to use the ASCII code, for some reason.
    const int minusAsciiCode = 45;

    // if (e.KeyChar == '-')
    if (e.KeyChar == (char)minusAsciiCode)
    {
        e.Handled = txtcity.Text.Contains("-");
    }
    else
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
    }
}


text:
Q: Error: System.NullReferenceException at combo_company.SelectedIndexChanged event VS 2012, VB.net, Winforms (Desktop App)
When I change item of combobox (combo_company. SelectedIndexChanged event), I m getting error System.NullReferenceException.
I am trying to get value of combo_company.SelectedItem and combo_company.SelectedValue. I tried in two way to bind combobox, but what the problem is:
case 1 output:
combo_company.SelectedItem= output OK
combo_company.SelectedValue= System.NullReferenceException
case 2 output:
combo_company.SelectedItem= System.Data.DataRowview
combo_company.SelectedValue= output OK
common code for both case:
    Dim da As New SqlDataAdapter
    Dim cmd As New SqlCommand
    Dim dt As New DataTable
    cmd.Connection = con
    Dim sql As String = "select company_name, company_id from tbl_company"
    cmd = New SqlCommand(sql, con)
    If con.State = ConnectionState.Open Then con.Close()
    con.Open()
    da = New SqlDataAdapter(cmd)
    da.Fill(dt)

case 1 code:
    combo_company.DisplayMember = "company_name"
    combo_company.ValueMember = "company_id"
    If dt.Rows.Count >= 1 Then
        For i = 0 To dt.Rows.Count - 1
            combo_company.Items.Add(dt.Rows(i).Item(0).ToString)
        Next
    End If

case 1 output:
combo_company.SelectedItem= output OK
combo_company.SelectedValue= System.NullReferenceException
case 2 code:
combo_company.DisplayMember = "company_name"
combo_company.ValueMember = "company_id"
combo_company.DataSource = dt

case 2 output:
combo_company.SelectedItem= System.Data.DataRowview
combo_company.SelectedValue= output OK

A: Your case 2 is what you should be doing and it is working exactly as it should. When you bind a DataTable to a WinForms control, the data actually comes from its DefaultView, which is a DataView. Each item in a DataView is a DataRowView, so the SelectedItem of the bound control will be a DataRowView, which is exactly what you're seeing.
You say that you want the SelectedItem but I don't think that's actually the case, because the SelectedItem is the whole row. I suspect that what you actually want is the company_name value from that row, i.e. the text displayed in the ComboBox. To get that you use the Text property of the ComboBox. The SelectedValue will give you the value from the column specified in the ValueMember and the Text will give you the value (as a String) of the column specified in the DisplayMember.
To elaborate on the first paragraph, complex data-binding in WinForms requires an object that implements either the IList interface or the IListSource interface. The IListSource interface has one method: GetList, which returns an IList. If you bind an IList then its items are used. If you bind an IListSource then its GetList method is called and the items of the IList returned are used. The DataTable class implements the IListSource interface and its GetList method returns its DefaultView property value, which is a DataView, which implements IList and contains DataRowView objects. When you bind a DataTable, the data you see is from its DefaultView, which is how you're able to filter and sort the bound data.


text:
Q: App icon not displayed on MAC osX 10.5 for my app I have created  .icns using .iconset for my Mac app,containing all sizes of icon recommended by apple. But still I cannot see my app icon when I install and launch my app on Mac osX 10.5

A: Following Apple's current guidelines and using their latest toolset will give you icons that only work in newer versions of OS X. To get a set of icons that includes larger (@2x retina) resolutions and 10.5 compatible image formats, you need to use Uli Kusterer's oldiconutil.
Also, please see this related question--sometimes icon file sizes can be too large for 10.5, and require extra image compression.


text:
Q: cumsum() in Pandas gives "Memory Error" while creating values based on condition I am trying to populate new column with unique integer values, based on condition from another column. But getting memory error after using cumsum(). Is there any other way where i can do this without memory error?
Code:
s = df['create?'].cumsum().where(df1['create?'] == 'Yes')
df['new_id'] = df.groupby(s).ngroup()+1
df['new_id'].replace(0,'',inplace=True)

Error:
lambda y, axis: y.cumsum(axis),
MemoryError

Input(small Example):
create?
No
No
Yes
No
Yes
Yes
Yes
No
No
No
Yes

Expected Output:
create? new_id
No
No
Yes       1
No
Yes       2
Yes       3
Yes       4
No
No
No
Yes       5

A: Is this what you want?
df.loc[df['create?'] == 'Yes', 'new_id'] = 1
df['new_id'] = df['new_id'].cumsum().fillna('')
print(df)

Output:
   create? new_id
0       No
1       No
2      Yes      1
3       No
4      Yes      2
5      Yes      3
6      Yes      4
7       No
8       No
9       No
10     Yes      5

A: import pandas as pd

df = pd.DataFrame({'create?': ['Yes', 'No', 'Yes', 'Yes', 'No']})
df['new_id'] = [1 if a == 'Yes' else 0 for a in df['create?']]
df['new_id'] = df['new_id'] * df['new_id'].cumsum()
print(df)

create?  new_id
0     Yes       1
1      No       0
2     Yes       2
3     Yes       3
4      No       0


text:
Q: How to return values from an ActionListener which is not in inner class I am new in Java and also in StackOverflow so, please excuse me if I do wrong something. I will correct it immediately!
My question is: How could I return a variable which is in a class that implements an ActionListener into another class's variable?
The class that implements the ActionListener is not an inner class.
I voluntary omitted imports.
Here an example:
File_A.java
public class Gui extends JFrame {
    private JButton myButton;
    private String path;
    some other properties...

    public Gui () {
        myButton = new JButton("Some Text");
        myButton.AddActionListener(new Pick_Something());
    }
}

File_B.java
public class Pick_Something implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser selectElement = new JFileChooser();
        String path;
        int status = selectElement.showOpenDialog(null);

        if (status == JFileChooser.APPROVE_OPTION)
            path = selectElement.getSelectedFile().getAbsolutePath();
        else
            path = null;
    }
}

How could I return File_B.java's path variable in File_A.java's path variable?
I tried to write a method who returns it but the method does not appear in the list of all methods so it is impossible to call. And I tried also to extends Pick_Something with Gui and make path protected but I had a StackOverflowError.
Anyone see what I do wrong or have an idea about how to do?

A: I would recommend using a call-back, something that Java-8's java.util.function supplies for you, and in fact a Consumer<String> would work perfectly here. Create your Consumer in the original class, and have the ActionListener class call its .accept(...) method, passing information directly from the listener class to the GUI with low coupling. For example if your Gui has a JTextField called filePathTxtField that you want filled with the user's file path of choice, one obtained by the ActionListener, then the consumer could look like so:
Consumer<String> consumer = (String text) -> {
    filePathTxtField.setText(text);
};

This would be created in the Gui class, and then passed into the ActionListener class via a constructor parameter:
// in the Gui class's constructor
button.addActionListener(new PickSomething(consumer));

// the PickSomething class and its constructor
class PickSomething implements ActionListener {
    private Consumer<String> consumer;

    public PickSomething(Consumer<String> consumer) {
        this.consumer = consumer;
    }

Then the actionPerformed method could look like:
@Override
public void actionPerformed(ActionEvent e) {
    JFileChooser selectElement = new JFileChooser();
    String path;

    // get the path String and set it
    int status = selectElement.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
        path = selectElement.getSelectedFile().getAbsolutePath();
    } else {
        path = null;
    }

    // pass the path String into the Gui by calling the call-back method, passing it in
    consumer.accept(path);
}

The whole thing could look like:
import java.util.function.Consumer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class Gui extends JPanel {
    private JTextField filePathTxtField = new JTextField(45);
    private int foo = 0;

    public Gui() {
        filePathTxtField.setFocusable(false);
        add(filePathTxtField);

        JButton button = new JButton("Get File Path");
        Consumer<String> consumer = (String text) -> {
            filePathTxtField.setText(text);
        };
        button.addActionListener(new PickSomething(consumer));
        add(button);
    }

    private static void createAndShowGui() {
        Gui mainPanel = new Gui();

        JFrame frame = new JFrame("Gui");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.Consumer;
import javax.swing.JFileChooser;

public class PickSomething implements ActionListener {
    private Consumer<String> consumer;

    public PickSomething(Consumer<String> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser selectElement = new JFileChooser();
        String path;
        int status = selectElement.showOpenDialog(null);

        if (status == JFileChooser.APPROVE_OPTION) {
            path = selectElement.getSelectedFile().getAbsolutePath();
        } else {
            path = null;
        }
        consumer.accept(path);
    }
}

A:
My question is: How could I return a variable which is in a class that implements an ActionListener into another class's variable?

You can't.
A quick look at the JavaDocs for ActionListener will show you that you the method does not return a value.  I'm pretty sure that even if it could it would be worthless, as the only time your code knows the method has been triggered is when it's actually called.
The solution?  Pass a "model" to the ActionListener implementation...
Start by defining a simple interface or contract...
public PathPicker {
    public void setPath(File path);
}

Then update PickSomething to accept instances of this interface...
public class PickSomething implements ActionListener {
    private PathPicker picker;

    public PickSomething(PathPicker picker) {
        this.picker = picker;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser selectElement = new JFileChooser();
        int status = selectElement.showOpenDialog(null);

        if (status == JFileChooser.APPROVE_OPTION) {
            picker.setPath(selectElement.getSelectedFile());
        } else {
            picker.setPath(null);
        }
    }
}

Now, all you need to do is implement the PathPicker interface, pass a reference of of it to PickSomething when you create and wait till it calls setPath.
This is commonly known as "delegation" (and ActionListener is also an example of it), where the actual responsibility to "delegated" to some other object.  It's also an example of "observability", in a very simple sense, where the PickSomething can be observer by an instance of PathPicker for a change in its state (a path been selected).
It also decouples the code, as PathPicker doesn't care how the the path is set, only that it is notified when it is.
A note about paths...
File is an abstract representation of file system file or path.  It has a lot of really cool functionality to make working with the filesystem easier and simpler.
Many APIs also take a reference of File to perform their operations.  You should avoid converting a File to a String where ever possible, as you are going to rob yourself of this functionality and make your life more difficult in the long run

A: Here is a what I tried, and hope this helps. In this example, the listener class returns the selected path to the main window.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ActionListenerTester {

    private String path;
    private JLabel status;

    public static void main(String [] args) {
        new ActionListenerTester().gui();
    }
    private void gui() {
        JFrame frame = new JFrame();
        frame.setTitle("An External Listener");
        JLabel title = new JLabel("Get My Paths:");
        JButton button = new JButton("Get Path");
        button.addActionListener(new MyActionListener(this));
        status = new JLabel("Click the button to get path...");
        Container pane = frame.getContentPane();
        pane.setLayout(new GridLayout(3, 1));
        pane.add(title);
        pane.add(button);
        pane.add(status);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(500, 300);
        frame.setVisible(true);
    }

    public void setPath(String path) {
        this.path = path;
        status.setText(path);
    }
}

class MyActionListener implements ActionListener {

    private ActionListenerTester gui;

    public MyActionListener(ActionListenerTester gui) {
        this.gui = gui;
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser selectElement = new JFileChooser();
        String path = "";
        int status = selectElement.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            path = selectElement.getSelectedFile().getAbsolutePath();
        }

        path = path.isEmpty() ? "No path selected!" : path;
        gui.setPath(path);
    }
}

Alternative way:

This is another way to return the value from an action listener class when its not an inner class. to the main GUI class. This uses java.util.Observer and Observable objects. The main GUI class is the observer and the selected path in the action listener class is the observable. When the observable object (the path) is updated, the observer (the main GUI class) is notified with the path value.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observer;
import java.util.Observable;

public class ActionListenerTester2
        implements Observer {

    private String path;
    private JLabel status;

    public static void main(String [] args) {
        new ActionListenerTester2().gui();
    }
    private void gui() {
        JFrame frame = new JFrame();
        frame.setTitle("An External Listener 2");
        JLabel title = new JLabel("Get My Paths:");
        JButton button = new JButton("Get Path");
        button.addActionListener(new MyActionListener(this));
        status = new JLabel("Click the button to get path...");
        Container pane = frame.getContentPane();
        pane.setLayout(new GridLayout(3, 1));
        pane.add(title);
        pane.add(button);
        pane.add(status);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(500, 300);
        frame.setVisible(true);
    }

    /*
     * Observer interface's overridden method.
     * This method runs when the Observable object notifies
     * its observer objects (in this case, ActionListenerTester2)
     * about the update to the observable.
     */
    @Override
    public void update(Observable o, Object arg) {
        path = (String) arg;
        status.setText(path);
    }
}

class MyActionListener implements ActionListener {

    private PathObservable observable;

    public MyActionListener(ActionListenerTester2 gui) {
        observable = new PathObservable();
        observable.addObserver(gui);
    }

    public void actionPerformed(ActionEvent e) {

        JFileChooser selectElement = new JFileChooser();
        String path = "";
        int status = selectElement.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            path = selectElement.getSelectedFile().getAbsolutePath();
        }

        System.out.println("Path: " + path);
        path = path.isEmpty() ? "No path selected!" : path;
        observable.changeData(path);
    }

    /*
     * When the Observable object changes, the notifyObservers()
     * method informs all the Observer objects - in this example
     * the main gui class: ActionListenerTester2.
     */
    class PathObservable extends Observable {

        PathObservable() {
            super();
        }

        void changeData(Object data) {
            // the two methods of Observable class
            setChanged();
            notifyObservers(data);
        }
    }
}


text:
Q: How to find the speed and CL settings of DDR3 SODIMM? I bought a pair of Crucial 8GB DDR3 1866MHz SODIMM for my iMac 27 5K Retina Late 2015.  I suspect the SODIMM that I received is 1600MHz, potentially counterfeit.
Here is my question

*

*Is there any way to read the SPD data for the speed, CL settings, and manufacturer ID?

*How do I find the actual speed.  Is the System Report -> Memory the actual speed or reading from SPD?  I need both information.

*How do I check if it's a genuine Crucial memory? (EDIT: I called Crucial.  They said the material number 310536 isn't matching.  They are investigating)
The Crucial part number is CT102464BF186D.C16FN.

The marking on Micron DRAM chip is D9QBJ.

According to Micron the part number is MT41K512M8RH-125:E. Here is the link for datasheet. -125 means 1.25nsec speed grade.  1/1.25nsec = 800MHz which is 1600MHz since DDR is "double data rate".
FYI: Crucial web said CT102464BF186D is not compatible with Mac, but many people reported success and stable with their late 2015 iMac while small number of people reported random shutdown.  It's my wild guess they hit the counterfeit DIMM that has the SPD programmed for 1866MHz when the DRAM chips are 1600MHz rating.

A: The RAM does appear to be counterfeit as far as I can see.
I have that type of genuine Crucial memory (CT102464BF186D.C16FN) here - but it doesn't look like your picture.
The PCB is almost identical, but some markings on it are off. The number of components mounted at the top of the board are very much different. The actual DRAM IC on my memory has FPGA code C9BCM, which according to Micron is a 1.07 nsec rating - equalling a 1866 Mhz speed.
To top it off, the label looks very much the same - but instead of "Product of China", mine says "Assembled in USA".
I can't say for sure that this means that it is counterfeit - it could be some kind of labelling/production error, or another revision of the same product or similar.


text:
Q: Create array from nested lists A little difficult to explain, but here goes... (using .net 4.5, C#)
We currently have a list of items ( as per below "User") which contains a list of column objects. ie.
 public class TableColumn
{
    public string ColumnHeader { get; set; }
    public string ColumnValue { get; set; }
    public int ColumnWidth { get; set; }
}

public class User
{
    public string Username { get; set; }
    public string Address1 { get; set; }
    public int Age { get; set; }

    public List<TableColumn> Columns { get; set; }
}

We are working with JQGrid where we are required to pass back Json.
without the nested list we would use :-
var aaData = PatList.Select(d => new string[] {
              d.Username ,
              d.Address1 ,
              d.Age}).ToArray();

 return Json(new
        {
            sEcho = param.sEcho,
            aaData = aaData,
            iTotalRecords = Convert.ToInt32(totalRowsCount.Value),
            iTotalDisplayRecords = Convert.ToInt32(filteredRowsCount.Value)
        }, JsonRequestBehavior.AllowGet);

which works great.
What we are struggling with is how to add in the list of columns.
   var aaData = PatList.Select(d => new string[] {
              d.Username ,
              d.Address1 ,
              d.Age,
              d.Columns.forEach(????)}).ToArray();

so the columns are related to a user.
Hopefully that makes sense. Any assistance would be appreciated.

A: You can do something like this:
var aaData = PatList.Select(d => (new string[] {
        d.Username,
        d.Address1,
        d.Age.ToString()
    }.Union(d.Columns.Select(c => c.ColumnHeader))).ToArray()
).ToArray();

This generates for every User in PatList an array with Username, Address1, Age & all ColumnHeaders.


text:
Q: How do I make my responsive Navbar sticky with only HTML & CSS? So I currently have a navbar that is responsive to the size of the screen built with HTML & CSS only. But I want it to stick to the container and also remain responsive to different screen sizes. Is there anyway to do this with only HTML & CSS? I have included the responsive Navbar code in this post that I would to update and make sticky.

body {
  margin: 0;
  font-family: "Lato", sans-serif;
}

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #4CAF50;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: relative;
  }
  .sidebar a {
    float: left;
  }
  div.content {
    margin-left: 0;
  }
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    Home
    News
    Contact
    About

Responsive Sidebar Example

This example use media queries to transform the sidebar to a top navigation bar when the screen size is 700px or less.

We have also added a media query for screens that are 400px or less, which will vertically stack and center the navigation links.

Resize the browser window to see the effect.

```

A: You need position: fixed; and an actualy position like top: 0;.
But also you could use the position: sticky; property instead to avoid overlapping content, like the other answer mentioned. Here you can see the browser support which is pretty good for position sticky, but slightly worse than fixed.

body {
  margin: 0;
  font-family: "Lato", sans-serif;
}

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #4CAF50;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: fixed;
    top: 0;
  }
  .sidebar a {
    float: left;
  }
  div.content {
    margin-left: 0;
  }
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    Home
    News
    Contact
    About

Responsive Sidebar Example

This example use media queries to transform the sidebar to a top navigation bar when the screen size is 700px or less.

We have also added a media query for screens that are 400px or less, which will vertically stack and center the navigation links.

Resize the browser window to see the effect.

A: You can also use position:sticky; and top:0 in your first media query to keep the navbar in place at the top, even when you scroll. This will work better than position:fixed because the content won't slide up behind the header while you are at the top.
Edit - embedded code directly.

body {
  margin: 0;
  font-family: "Lato", sans-serif;
}

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #4caf50;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: sticky;
    top: 0;
  }
  .sidebar a {
    float: left;
  }
  div.content {
    margin-left: 0;
  }
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

    Home
    News
    Contact
    About

Responsive Sidebar Example

This example use media queries to transform the sidebar to a top navigation bar when the screen size is 700px or less.

We have also added a media query for screens that are 400px or less, which will vertically stack and center the navigation links.

Resize the browser window to see the effect.


text:
Q: How to open emailIntent without using chooser but having default account to send email I apologize if it's a repeated question but the answers that i found doesn't work for me. What i want is to open email Intent with chooser dialog but directly send email using emailClient that i set as default in settings of device:-
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

                emailIntent.setType("message/rfc822");
                String contactEmail = directoryDetails.getEmail();

                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ contactEmail});

                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");

                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");

                activity.startActivity(emailIntent);

It's using a fixed email that i setup very first one. but not variaying according to default  settings. Can anybody say what i am missing in my code.

A: try this :-
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:someone@example.com?subject=" +
    Uri.encode("my subject") +  "&body=" +
    Uri.encode("My big long body with spaces, new lines, and all sorts of invalid URI characters"));
startActivity(intent);


text:
Q: Set expression for @Pointcut I want to set annotation for class and when I call anyone method of object this class to execute interceptor before execute method.
@MyAnn
public class SomeClass {

    public void someMethod1() {}
    public void someMethod2() {}
}

@Aspect
public class SomeInterceptor {

    @Pointcut("execution(@my.package.aop.MyAnn* *.*(..))")
    public void checkMethod() {}

    @Around("checkMethod()")
    public Object method(ProceedingJoinPoint joinPoint) throws Throwable {

    }
}

What expression should be set in @Pointcut(...) that all methods my class processed the interceptor before execution?

A: Found a solution
@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}

@Pointcut("within(@my.package.aop.MyAnn *)")
private void withinMyAnn() {}

@Pointcut("anyPublicOperation() && withinMyAnn()")
public void checkMethod() {}

If there is a more successful solution I will be happy to see in the comments


text:
Q: How to query Where Datetime many time? I want query datetime many time.
but i try query it's not work.
Example
Table cus_bill
Number       Period
A-20160101   01/2015
A-20160410   04/2015
A-20160912   09/2015
A-20161020   10/2015
A-20161102   11/2015
A-20161219   12/2015

SQL
SELECT v.*
FROM cus_bill v
WHERE TO_DATE('01/'||V.PERIOD,'DD/MM/YYYY') >= TO_DATE('01/'|| '10/2015','DD/MM/YYYY')
and TO_DATE('01/'||V.PERIOD,'DD/MM/YYYY') <= TO_DATE('01/'|| '12/2015','DD/MM/YYYY')
and V.PERIOD IN ('01/2015','09/2015')

But it's not work (0 Rows).
Desired output:
Number       Period
A-20160101   01/2015
A-20160912   09/2015
A-20161020   10/2015
A-20161102   11/2015
A-20161219   12/2015

A: WHERE TO_DATE('01/'||V.PERIOD,'DD/MM/YYYY') >= TO_DATE('01/'|| '10/2015','DD/MM/YYYY')
and TO_DATE('01/'||V.PERIOD,'DD/MM/YYYY') <= TO_DATE('01/'|| '12/2015','DD/MM/YYYY')
and V.PERIOD IN ('01/2015','09/2015')

You won't get any rows because you are using AND condition along with IN condition which will never be true as you can never have '01/2015' or '09/2015' between 01/10/2015 and 01/12/2015. i.e. a date cannot be between Oct and Dec and also in Jan or Sep simultaneously.
You need an OR condition. Also, you could use BETWEEN condition for less code:
WHERE   TO_DATE('01/'|| V.PERIOD,'DD/MM/YYYY')
BETWEEN TO_DATE('01/'|| '10/2015','DD/MM/YYYY')
AND     TO_DATE('01/'|| '12/2015','DD/MM/YYYY')
OR      V.PERIOD IN  ('01/2015','09/2015')


text:
Q: Designing student monitoring sheet I want to design a monitoring Excel sheet to keep track of my students' progress.
It should look something like this:

*

*In the example picture, I'd be interested in assessing each student's performance in a said exercise for their reading competence in English. For example, if Marine got in (p.24 ex 1) a score of 5/8, it should appear like that, but also with colour change (see point 2).

*However, I'm also interested in the colour actually CHANGING when the student obtains half or more (the cell turning into green if they obtain 4/8 or more than that); alternatively, the cell turning into red if they get less than that (3/8, f.e.)

I got the template from here (XLS file).
I was wondering how I could change the settings in order to get the desired result.

A: Look into Conditional Formats on the home tab just to the left of the Table Formatter and Styles Gallery.
Generally speaking it it is best to think of each cell as a discrete unit that cannot be divided.  Just like what you've done with your template.  Sometimes though, a softer look is desired where colors blend across cell boundaries.  Or maybe a situation calls for symbols that appear next to your data instead of changing the cell color.
Conditional Formatting can do this with ease..  For your purpose, it is as simple as selecting the range you want to format, selecting an effect (perhaps a 3 color green to yellow to red gradient), and how the data should be evaluated (above and below a number, highest and lowest numbers, etc.)
There are a lot of visually appealing effects that are predefined and easily customized.  Choosing your favorite may be the hardest part.
If none of the predefined options are appealing then you may want to create your own formats by changing colors, borders, patterns, and more.

A: This can be acomplished in Excel:

*

*Go to Home Tab.

*Select the area you want to format. In your case Area is "C4:L7".

*Select "CONDITIONAL FORMATTING" from the Menu.

*Select "NEW RULE".

*Select " From Only Cells that contain value.

*From Drop Down Tabs select : " Cell Value " , " Equal to" , 0 "

*Format as you want Colour, Fill etc. say RED. The job is done. Now follow the same procedure, same steps  again and for value 1 select say Yellow Colour. Same for 2, 3, 4 etc. For other sheet and many other Reports, you can then apply  " FORMAT PAINTER " to get the same results.


text:
Q: Jquery .find() doesn't works in chrome but works in firefox i'm using a validation plugin(position absolute) and it's works in firefox but don't in chrome.
i detected issue is in .find() Jquery method, works different in both browsers.
take a look at http://jsfiddle.net/kwtp2/1/ for a detailed sample of this error.
please, run it on firefox then in chrome.
firefox: found 5 matches,
chrome: found 0 matches
any suggestion?
Kind Regards,
Rinaldo

A: You can't nest form elements. Your #dialogForm is being closed by the form immediately inside it (within the span helpDialog).
That this works in Firefox seems a fluke. Nesting forms is definitely not good form...no pun intended.

A: @Rinaldo Sassaroli: See updated jsFiddle -- http://jsfiddle.net/kwtp2/7/


text:
Q: Finding shortest regex match in HTML I would like to match the last column in the first row from the following HTML:
 (this is just an example)
<tr> <td> ABC </td> <td> DEF </td> <td> ABC </td> </tr>
<tr> <td> GHI </td> <td> JKL </td> <td> GHI </td> </tr>

So what I want to match is: <td> ABC </td> </tr>
I tried toying around with regex101.com but I just can't find a proper way to match the last <td> from the first row only.
What I got so far is the following regex: (<td>).*?(<\/tr>) which matches
<td> ABC </td> <td> DEF >/td> <td> ABC </td> </tr> though.
Is there any way to match only the shortest string between <td> and </tr> ? (I found similar questions but can't figure out a solution to this one.)

A: Prepend your pattern with "start of string" (^) + "anything but </tr>" ((?:.(?!<\/tr>))*) to ensure no </tr> appears before your pattern (and therefore your match is the first one before </tr>). The original pattern should be captured with a group then:
^(?:.(?!<\/tr>))*((?:<td>).*?(?:<\/tr>))

Demo: https://regex101.com/r/enGASL/1

A: I would use this to match the required text into a group:
.*(<td>.+<\/td>?.+<\/tr>)

Here is the Regex demo

A: Regex 1 is 11 characters,

<td.{14}tr>

Regex 2 is 30 characters but it'll cover any amount of content,

<td>\s*\w*?\s*<\/td>\s*<\/tr>

but the real problem is that you wanted only one match, while this regex like most others will match more than once when the string is a multi-line HTML fragment. The solution is simple:

No global flag - Once a match is found it stops

Demo

/* Regex 1
|| Literal: <td
|| Any 14 char or space (no line terminators)
|| Literal: tr>
|| NO GLOBAL FLAG - Once a match is found it stops
*/
const rgx1 = /<td.{14}tr>/;
/* Regex 2
|| Literal: <td>
|| Zero or more spaces
|| Zero or more word characters lazily collect until
|| Zero or more spaces
|| Literal: <\td>
|| Zero or more spaces
|| Literal: </tr>
*/
const rgx2 = /<td>\s*\w*?\s*<\/td>\s*<\/tr>/
const str = `<tr> <td> ABC </td> <td> DEF </td> <td> ABC </td> </tr>
<tr> <td> GHI </td> <td> JKL </td> <td> GHI </td> </tr>`;

let res1 = str.match(rgx1);
let res2 = str.match(rgx2);
console.log('Result 1: ' + res1);
console.log('Result 2: ' + res2);

BTW, there's a typo in the string: DEF >/td> and JKL >/td>

A:

console.log(
`<tr> <td> ABC </td> <td> DEF </td> <td> XCC </td> </tr>
<tr> <td> GHI </td> <td> JKL </td> <td> GHI </td> </tr>`
.match(/\w+(?=[</> td]+r>)/)
)

A: Be as precise as possible when writing your regexps.
(<td>)[^\<\>]*(<\/td>)\s*(<\/tr>)

This assumes that the contents of the td tag does not contain html markup.


text:
Q: Vue.js - How to use a child component inside parent component I have parent component inside file Usage.vue and I want to display a child component (Filter.vue).
This is how Usage.vue is:
 <template >

    <st-filter></st-filter>

USAGE

    <st-filter></st-filter>
    <st-filter></st-filter>
    <st-filter></st-filter>
    <st-filter></st-filter>

</template>

And this is my Filter.vue:

What am I missing for using  inside of Usage.vue?

A: Ok got it working:
Child:

Parent:
<template >

USAGE

    <st-filter></st-filter>

</template>


text:
Q: From shell script call a python function of python script located at custom location My python file: /root/src/foo.py
#/root/src/foo.py

def add(a,b):
    '''add(a,b) --> a+b'''
    return a+b

How do I call foo.add(a,b) from a shell script? I got this suggestion from somewhere:
python -c "import foo; print(foo.x(1, 2))"

But it won't work if the shell script and foo.py are in a separate locations.

A: you need to add the folder to your pythonpath
PYTHONPATH=/path/to/foo python -c "import foo;print(foo.add(5,6))"

should work (in this case it just sets pythonpath, not adds to it)


text:
Q: apicontroller not getting from ajax I get "404 Not Found" on doing a  Ajax call ,
maybe that I don't understand how routing works ...
function ApproveAlert(ID) {
     $.ajaxPost('/api/DeviceApi/ApproveAlertNew', { 'ID': ID }, function (data) {
        ... get error "404 Not Found"
    }, null);
}

in my mvc4 C# app I have a rout config :
RouteTable.Routes.MapHttpRoute(
                 name: "defaultapiaction",
                 routeTemplate: "api/{controller}/{action}"
             );
            RouteTable.Routes.MapHttpRoute(
                 name: "defaultapiid",
                 routeTemplate: "api/{controller}/{action}/{id}"
             );

and apicontroller :
public class DeviceApiController : ApiController
    {
        //
        // GET: /DeviceApi/
        [HttpPost]
        public bool ApproveAlertNew(int ID)
        {
            ..do
        }

A: Web API controllers don't use "Actions" in the same sense that MVC controllers do. Web API controllers also don't really use [HttpPost], [HttpGet] attributes either. They dispatch requests based on the names of the methods inside of the ApiControllers. I suggest to read up a little more on Web API differences from MVC as it is similar but sometimes hard to get up and running...
Here's some pretty generic examples from a Web API that I made for testing. I do not have JavaScript to post to this API because I was posting from a .NET WPF app. You would post to "/Important" NOT "/Important/Post" Hopefully this will get you on the right track...
WebAPIConfig.cs (Routes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ArrayTest.WebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ArrayTest.Models;
using System.Threading;

namespace ArrayTest.WebAPI.Controllers
{
    public class ImportantController : ApiController
    {
        // POST api/important
        public HttpResponseMessage Post(ImportantList values)
        {
            //manipulate values received from client
            for (int i = 0; i < values.ImportantIDs.Count; i++)
            {
                values.ImportantIDs[i] = values.ImportantIDs[i] * 2;
            }

            //perhaps save to database, send emails, etc... here.

            Thread.Sleep(5000); //simulate important work

            //in my case I am changing values and sending the values back here.
            return Request.CreateResponse(HttpStatusCode.Created, values);
        }

    }
}

Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayTest.Models
{
    public class ImportantList
    {
        public List<int> ImportantIDs { get; set; }
    }
}

A: Can you try with:
function ApproveAlert(ID) {
    $.ajax({
        type: 'POST',
        url: "/api/DeviceApi/ApproveAlertNew",
        data: {
            ID: ID
        },
        success: function (data) {
            //Handle your success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //Handle error
        }
    });
}


text:
Q: getting error while checking the network state in android retrofit I am trying to check the network state to manage the offline support in the application using retrofit to store cache of preloaded responses. here is my code
 public static Interceptor provideOfflineCacheInterceptor ()
    {
        return new Interceptor()
        {
            @Override
            public Response intercept (Interceptor.Chain chain) throws IOException
            {
                Request request = chain.request();

                if ( !AdeptAndroid.hasNetwork() )
                {
                    CacheControl cacheControl = new CacheControl.Builder()
                            .maxStale( 7, TimeUnit.DAYS )
                            .build();

                    request = request.newBuilder()
                            .cacheControl( cacheControl )
                            .build();
                }

                return chain.proceed( request );
            }
        };
    }

in this portion where i am checking the network state i am getting null pointer  exception here.
 if ( !AdeptAndroid.hasNetwork() )

here is AdepAndroid class
public class AdeptAndroid extends Application {

    private static AdeptAndroid instance;

    @Override
    public void onCreate()
    {
        super.onCreate();

        instance = this;

        if (BuildConfig.DEBUG)
        {
            Timber.plant(new Timber.DebugTree());
        }

        Timber.i("Creating our Application");
    }

    public static AdeptAndroid getInstance ()
    {
        return instance;
    }

    public static boolean hasNetwork ()
        {
            return instance.checkIfHasNetwork();
    }

    public boolean checkIfHasNetwork()
    {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

in this class i am simply checking the network state and getting error here as nullpointerException here.
 public static boolean hasNetwork ()
            {
                return instance.checkIfHasNetwork();
        }

please help to solve this issue. Thanks

A: You mean AdeptAndroid.getInstance().hasNetwork() ?
It seems that you are calling class itself, not a instance. So, call instance.

Update2: Your code need to be modified like this.
public static Interceptor provideOfflineCacheInterceptor ()
{
    return new Interceptor()
    {
        @Override
        public Response intercept (Interceptor.Chain chain) throws IOException
        {
            Request request = chain.request();

            // You need context at this point. Your Application can be called by getApplicationContext(), not by custom getInstance().
            if ( !((AdeptAndroid)context.getApplicationContext()).hasNetwork() )
            {
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxStale( 7, TimeUnit.DAYS )
                        .build();

                request = request.newBuilder()
                        .cacheControl( cacheControl )
                        .build();
            }

            return chain.proceed( request );
        }
    };
}

And your Application should be like this:
public class AdeptAndroid extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }

        Timber.i("Creating our Application");
    }

    public boolean hasNetwork () {
        return checkIfHasNetwork();
    }

    public boolean checkIfHasNetwork() {
        ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}


text:
Q: How to remove jQuery from render blocking resources? Is there any possibility to remove jquery.js and jquery-migrate.min.js scripts from render blocking resources? I see this error only on mobile, not on desktop. Scores in Google Page Speed Insights are hight, I know that is unnecessary but if there is any way I want to try...
https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fmanufakturamocy.pl%2F&tab=mobile


text: Q: s3 file storage image issue I stored an image in s3 and in GET request(it is showing Content-Type as image/jpeg) or browser I'm able to see the image but when I try HEAD request to it is showing Content-Type as application/xml. As Head request is defaultly used to find the type of file what should I do to change the Content-Type in S3.


text:
Q: python managing tasks in threads when using priority queue I'm trying to write a program which starts new tasks in new threads.
Data is passed from task threads to a single worker/processing thread via a priority queue (so more important jobs are processes first).
The worker/processing thread gets higher priority data from the queue and limits calls to a REST API
How can I passed the data back to it's origionating task thread, while tracking that all that particular task threads data has been processed?
Thanks

A: In your request queue entry include a response queue.  When finished place a response on the response queue.
The requesting thread waits on the response queue.
A callback method could alternately be used.


text:
Q: Java Hashmap to JavaFX Treeview and Back? I have a nested HashMap which looks like this:
Map<String,Object> myMap = new HashMap<String,Object>();

This myMap is nested, Like:
String key => String val
String key => String val
String key => Map<String,Object> val

And then that value may contain another similar Map<String,Object>.
I do not expect it to be nested more than 3 levels.
The leafs or last values are always String.
Now I'm trying to make a way to edit this HashMap in a JavaFX GUI.
From what I have learnt so far,
the best way seems like making a editable JavaFX TreeView
and somehow translating the Map to a TreeView and back.
So far I'm thinking
TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
treeMap.putAll(myMap);

And then somehow translating that TreeMap to a JavaFX TreeView.
But I can not figure out how to proceed.
Another headache is that after user edits I need to translate it all back to a HashMap such as the original myMap. Although sorting / sequence is not required.

A: Create a suitable class to represent the map entry. Since you need to modify the Map, you need to store key and Map in that class.
If you use TextFieldTreeCell as cell type, the StringConverter can be used to modify the source data structure on a edit:
private static TreeItem<MapItem> createTree(Map<String, Object> map) {
    TreeItem<MapItem> result = new TreeItem<>();

    for (Map.Entry<String, Object> entry : map.entrySet()) {
        result.getChildren().add(createTree(map, entry));
    }

    return result;
}

private static TreeItem<MapItem> createTree(Map<String, Object> map, Map.Entry<String, Object> entry) {
    MapItem mi = new MapItem(map, entry.getKey());
    TreeItem<MapItem> result = new TreeItem<>(mi);

    Object value = entry.getValue();

    if (value instanceof Map) {
        Map<String, Object> vMap = (Map<String, Object>)value;

        // recursive creation of subtrees for map entries
        for (Map.Entry<String, Object> e : vMap.entrySet()) {
            result.getChildren().add(createTree(vMap, e));
        }
    } else {
        result.getChildren().add(new TreeItem<>(new MapItem(null, value.toString())));
    }

    return result;
}

private static class MapItem {

    private final Map<String, Object> map;
    private final String value;

    public MapItem(Map<String, Object> map, String value) {
        this.map = map;
        this.value = value;
    }
}

private static class Converter extends StringConverter<MapItem> {

    private final TreeCell<MapItem> cell;

    public Converter(TreeCell<MapItem> cell) {
        this.cell = cell;
    }

    @Override
    public String toString(MapItem object) {
        return object == null ? null : object.value;
    }

    @Override
    public MapItem fromString(String string) {
        MapItem mi = cell.getItem();

        if (mi != null) {
            TreeItem<MapItem> item = cell.getTreeItem();
            if (item.isLeaf()) {
                MapItem parentItem = item.getParent().getValue();

                // modify value in parent map
                parentItem.map.put(parentItem.value, string);
                mi = new MapItem(mi.map, string);
            } else if (!mi.map.containsKey(string)) {
                // change key of mapping, if there is no mapping for the new key
                mi.map.put(string, mi.map.remove(mi.value));
                mi = new MapItem(mi.map, string);
            }
        }

        return mi;
    }

}

@Override
public void start(Stage primaryStage) {
    Map<String, Object> map = new HashMap<>();

    map.put("a", "b");

    Map<String, Object> inner = new HashMap<>();
    map.put("c", inner);
    inner.put("d", "e");

    Map<String, Object> inner2 = new HashMap<>();
    inner.put("f", inner2);
    inner2.put("g", "h");
    inner2.put("i", "j");

    TreeView<MapItem> treeView = new TreeView<>(createTree(map));
    treeView.setEditable(true);
    treeView.setShowRoot(false);

    treeView.setCellFactory(t -> {
        TextFieldTreeCell<MapItem> cell = new TextFieldTreeCell<>();
        cell.setConverter(new Converter(cell));
        return cell;
    });

    Button btn = new Button("Print Map");
    btn.setOnAction((ActionEvent event) -> {
        System.out.println(map);
    });

    VBox root = new VBox(10, btn, treeView);

    Scene scene = new Scene(root);

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

A: There is not build-in method that would convert:

*

*either Map directly to TreeView

*or TreeMap to TreeView
Moreover, If you see the structure of Map<?,?>, we can see that it is a combination of key, value pair whereas TreeView<?> consists of only value, like that of Collection interface. So It's not possible to insert key, value pair in TreeView. However you can insert only values from Map.
The best you can do is define a new data structure like this:
public class YourCustomDataStructure extends TreeItem<String> {
    ...

    /*
    Now you can define methods that will convert `List`s directly to `YourCustomDataStructure`.
    You can even define method to convert `Map` values to `YourCustomDataStructure`.
    */

    public boolean addAll(Map map) {
        //your implementation to convert map to TreeItem
    }

    public boolean addAll(List list) {
        //your implementation to convert list to TreeItem
    }

}

Now convert your list or map to YourCustomDataStructure using addAll() method from previous step.
List<Object> list = getListFromSomewhere();

YourCustomDataStructure<String> customList = new YourCustomDataStructure<String>("customList Node");
customList.getChildren().addAll(list);

Now since YourCustomDataStructure extends TreeItem so it's object's can be directly passed to TreeView's constructor and they will be automatically converted to TreeView.
TreeView<String> treeView = new TreeView<String>(customList);

P.S.: I know defining new data structure and all the methods will require lots of efforts at initial level, but once those methods are defined, then it will become too easy to convert TreeView to Map and vice versa.


text:
Q: Knowing whether to output terminal escape sequences? I have a C program that uses SGR ("Select Graphic Rendition") ANSI terminal escape sequences to produce color output.
However, if output is being redirected to a text file, then the escape sequences should not be output since they'd be seen as "garbage" in the generated file. To handle this, one can use the isatty(3) function: output color only if it returns true. Indeed, this is what programs like grep(1) do.
But if output is being being redirected to a Unix pipe, e.g., | less that, at least in my case, is primarily what someone would pipe the output of my program to, then the escape sequences should be output since less(1) correctly handles them and prints in color.
After some testing using isatty(3) and fstat(3), I've produced this table where C represents my C program, the "Should?" column is whether I should output color, and the remaining columns are T/F as the return value of isatty or fstat(STDOUT_FILENO):
COMMAND  Should? isatty ISCHR ISFIFO ISREG
======== ======= ====== ===== ====== =====
C          T      T      T     F      F
C > file   F      F      F     F    >>T<<---- The interesting case.
C | less   T      F      F     T      F

Hence, it would seem that I want to output color except when ISREG on the stat struct on stdout is T.
Are there any caveats with doing this? If there are, is there a better way to get what I want?
Note: I also have an option similar to grep's --color option to specify either auto or always (or none simply by not specifying any option at all). My hope in using fstat and ISREG is to make the auto case better the majority of the time.


text:
Q: How many ways am I doing this c# concurrent task management incorrectly? I'm writing an application that crawls a website and does various tests on each page. I'd like the option to have the crawler run several concurrent crawls of the website at once. I have a semi-working...solution. This will crawl the website OK with 1 task, when I sent it to max concurrent tasks 2 it runs faster as expected. However when I set it to 3 or above it seems slower. I'm from a PHP background so I'm fairly sure I'm doing this in the worst possible way.
var DontLockGuiTask = Task.Run(() =>
{
    while (true)
    {
        if (tokenSource2.IsCancellationRequested)
        {
            Logger.AddToActivityLog("Tasks stopped by user");
            break;
        }

        if (URLsToCheck.Count == 0 && CurrentNumberOfScrapes == 0)
        {
            EndOfCheck = true;
            break;
        }

        lock ("CurrentNumberOfScrapes")
        {
            CurrentNumberOfScrapes++;
        }

        var ScrapeTask = Task.Run(() =>
        {
            if (EndOfCheck)
            {
                CurrentNumberOfScrapes--;
                return;
            }

            URLCheckResultObject CheckResultForURL;

            Checker Checker                 = new Checker();
            URLsToCheckObject URLToCheck    = new URLsToCheckObject();

            lock ("URLsToCheck")
            {
                if (URLsToCheck.Count == 0)
                {
                    lock ("CurrentNumberOfScrapes")
                    {
                        CurrentNumberOfScrapes--;
                        return;
                    }
                }

                URLToCheck = URLsToCheck.First();
                URLsToCheck.Remove(URLToCheck);
            }

            CheckResultForURL = Checker.PerformCheckOnURL(URLToCheck, this);

            PagesCrawledCounter++;
            ChecksPerformedCounter += CheckResultForURL.Checkcounter;

            CheckResultForURL.URLID = PagesCrawledCounter;

            Logger.AddToActivityLog("Checking " + URLToCheck.URLAddress + "....");

            if(CheckResultForURL.NewListOFURLSToCheck != null)
            {
                foreach (LinkObject NewURLToAdd in CheckResultForURL.NewListOFURLSToCheck)
                {
                    lock ("URLsToCheck")
                    {
                        string CleanURL = NewURLToAdd.destinationURL;

                        if (CleanURL.EndsWith("/"))
                        {
                            CleanURL = CleanURL.Substring(0, CleanURL.Length - 1);
                        }

                        if (URlsWeKnownAbout.Contains(CleanURL)) continue;

                        URlsWeKnownAbout.Add(CleanURL);
                        URLsToCheck.Add(new URLsToCheckObject { URLAddress = CleanURL, Host = host });
                    }
                }
            }

            CheckResultForURL.NewListOFURLSToCheck = null;

            if(CheckResultForURL.SocialCheckResult != null)
            {
                ProblemID++;
                CheckResultForURL.SocialCheckResult.URLID = ProblemID;
                InsertSQLProblemIntoDataGrid(CheckResultForURL.SocialCheckResult);
            }

            lock ("CurrentNumberOfScrapes")
            {
                CurrentNumberOfScrapes--;
            }
        });

        while (CurrentNumberOfScrapes >= CurrentNumberScrapesMax)
        {
            if (tokenSource2.IsCancellationRequested == true)
            {
                Logger.AddToActivityLog("Tasks stopped by user");
                break;
            }

            Thread.Sleep(100);
        }
    }

    EnableUsedGUIForRun();

}, tokenSource2.Token);

As you can see I have a couple of while loops that check to see how many current tasks are running and sleeps if no more are needed and starts new ones when old ones finish or the current amount of tasks is under the CurrentNumberScrapesMax level.
How should I approach this? I want to manage multiple concurrent tasks all accessing the same variables.

A: If you do not add new tasks to URLsToCheck, then your code may be simplified to something like:
Parallel.ForEach(URLsToCheck,
    new ParallelOptions { MaxDegreeOfParallelism = Emvironment.ProcessorCount }, url => CrawlAcross(url));

But if you do get some more urls to crawl, then you need more complicated logic. You may give a try to TPL Dataflow here, with pipeline like this:
Buffer with urls --> Crawl the url processor --> Result saving

where second part can post additional url back to buffer. So it can be like this:
var buffer = new BufferBlock<string>();
var processor = new TransformBlock<string, CrawlResult>(url =>
{
    var result = CrawlAcross(url);
    foreach (var additionalUrl in result.AdditionalUrlsToParse)
    {
        buffer.Post(additionalUrl);
    }
    return result;
});
var handler = new ActionBlock<CrawlResult>(r => HandleResult(r));

buffer.LinkTo(processor, new DataflowLinkOptions() { PropagateCompletion = true });
processor.LinkTo(handler, new DataflowLinkOptions() { PropagateCompletion = true });

foreach (var url in URLsToCheck)
{
    buffer.Post(url);
}

Side notes about your code:

*

*while loops in tasks should be marked as LongRunning

*child tasks should be moved out

*lock statement should be done not on string constants, but on dedicated static objects for improved readability and predictive results

*if (tokenSource2.IsCancellationRequested == true) can be simplified to if (tokenSource2.IsCancellationRequested)

*if you got tokenSource2.IsCancellationRequested flag, you should call ThrowIfCancellationRequested

*You should deal with token, not with tokenSource

*Maybe something else, it's hard to say


text:
Q: Why is overshadowing not supported with Codename One? I've been trying to work with Codename One for years, but I still find errors that prevent me from releasing my apps.
Locally I can fix errors by I overshadowing erroneous classes. This works but for some reason it doesn't work when I send my apps to the build server.
If I could overshadow faulty classes would be good in many ways:

*

*I'd better get on with my work

*I could check how my corrections work on the different platforms

*I could contribute to the further development of Codename One

I suffer much from not being able to publish my apps because I see no way how I can fix basic problems.
I love iPhones and do not like the Mac. Therefore I do not own a Mac and prefer to work with Linux and use the Codename One build server.
What are the reasons for not supporting overloading classes like com.codename1.ui.Component? Can You see that it would be beneficial?

A: This isn't the first time people asked for that but we won't deliver it. Doing this creates huge problems:

*

*Developers don't file issues or submit fixes instead they make local fixes

*Developers break things due to complex behaviors then try to get support and blame us for the issues

We have a process of submitting patches to Codename One, patches are always accepted quickly when they are valid. If something needs fixing that's what you need to do. If you need a hack then submit a patch that defines the extension point that you need. That's why we are open source...
In the past this might have been painful as you would need to wait until we updated the servers, but since changes go in every week in recent revisions this is no longer an issue. Don't think of it as "contributing", think of it as free code reviews where the entire community pulls together to improve your work...


text:
Q: spring controller test by mock service Love Spring Testing Even More With Mocking and Unit Test Assistant:
A mocked service replaces multiple dependencies
enter image description here
@Controller
@RequestMapping("/people")
public class PeopleController {
    @Autowired
    protected PersonService personService;
    @GetMapping
    public ModelAndView people(Model model) {
        for (Person person: personService.getAllPeople()) {
            model.addAttribute(person.getName(), person.getAge());
        }
        return new ModelAndView("people.jsp", model.asMap());
    }
}

private MockMvc mockMvc:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
    @Autowired
    PersonService personService;

    private MockMvc mockMvc;

    @Configuration
    static class Config {
        // Other beans
        @Bean
        public PersonService getPersonService() {
            return mock(PersonService.class);
        }
    }
    @Test
    public void testPeople() throws Exception {
        // When
        ResultActions actions = mockMvc.perform(get("/people"));
    }
}

I get a mistake when I want to run mockMvc

java.lang.NullPointerException

A: Perform the following steps:

*

*create service mock instead of service original
("PersonServiceMock")

*replace service original by service mock
    @Autowired
    PersonService personService;

    @Autowired
    PeopleController peopleController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
    peopleController = new PeopleController(new personServiceMock());
    mvc = MockMvcBuilders.standaloneSetup(peopleController).build();
   }

    @Configuration
    static class Config {
        // Other beans
        @Bean
        public PersonService getPersonService() {
            return mock(PersonService.class);
        }
    }
    @Test
    public void testPeople() throws Exception {
        // When
        ResultActions actions = mockMvc.perform(get("/people"));
    }
}

A: That's because you are never initialising mockMvc in your code and the point where you access it results in nullPointerException. You need to initialise it before using it, and since multiple tests in your class could be using it, best place to do it is setup() method annotated with @before. Try below:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
@Autowired
PersonService personService;

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

@Configuration
static class Config {
    // Other beans
    @Bean
    public PersonService getPersonService() {
        return mock(PersonService.class);
    }
}
@Test
public void testPeople() throws Exception {
    // When
    ResultActions actions = mockMvc.perform(get("/people"));
}
}

A: from the source code I see that the mockMvc doesn't have any value, thats why it hits "java.lang.NullPointerException" for this line of code :
ResultActions actions = mockMvc.perform(get("/people"));

to make it run, I think need to give value to mockMvc first.
by constructor :
@Test
public void testPeople() throws Exception {
    mockMvc = new MockMvc();
    // When
    ResultActions actions = mockMvc.perform(get("/people"));
}

or Autowired :
@Autowired
MockMvc mockMvc

depends on the purpose of MockMvc Class


text:
Q: YUI editor toolbar button style I am working with the YUI editor and am stuck on a problem.
Specifically i want to change the style of the YUI toolbar forecolor button whenever someone selects a forecolor. For e.g. if one selects red forecolor then i want red background being applied to the forecolor button on the editor toolbar.
Button:-
{ type: 'color', label: 'Font Color', value: 'forecolor' ,id:'forecolor',disabled:false}
I am trying:-
editor.toolbar.on('colorPickerClicked', function (o2)
{
if (o2.button == 'forecolor')
{
//alert(o2.button+'The selected color was: #'+o2.color);
YAHOO.util.Dom.setStyle('forecolor', 'background-color','#'+o2.color );
}
}

But color changes are not reflected.
Is there a way to change the style (bg-color or button shadow etc) on selecting a color from forecolor button.
Thanks

A: yui editor forecolor button's id is not forecolor that's why its not working i guess .
Try using yui forecolor button class to identify it :
editor.toolbar.on('colorPickerClicked', function (o2)
{
   if (o2.button == 'forecolor')
   {
       YAHOO.util.Dom.setStyle(YAHOO.util.Dom.getElementsByClassName(
              'yui-toolbar-forecolor'), 'background-color','#'+o2.color );
   }
}

or you can use forcolor button id: editor_toolbar_forecolor_menu


text:
Q: Oauh with Stackoverflow : error code is invalid I want use oauth with stackexchange with my rails app. I use oauth gem. I take data from my home page app on : https://stackapps.com/apps/oauth/view/XXX
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :stackexchange, 'Client_Id', 'client_secret', public_key: 'key', site: 'stackoverflow', provider_ignores_state: true
end

I use the route /auth/stackexchange/callback but I have an error :
OAuth2::Error
: {"error":{"type":"0","message":"code is invalid"}}

What code are talking about? How debug?

A: Apparently you are using the Explicit flow? Stackexchange auth documentation. The error message is pretty clear your code (in this case authorization code) which is used to exchange to Access Token is invalid.
From stackexchange auth documentation see The explicit OAuth 2.0 flow points 3. and 4.


text:
Q: %>% or %.% operator in this R code I am new to R and I am having a hard time understanding and making the following snippet functional :
fMatrix <- DT[c(v1,v2), ] %.% select(f1,f2,f3) %.% lapply(...)

logically, it seems to make sense, as it is (probably) trying to take a subset and perform certain operations by some sort of method chaining using (dot operator). The problem is my R interpreter doesn't recognizes %.%
I am guessing the operator comes from a package I didn't import or something like that. Any insights are welcome.

A: Look at librarydplyr, in R. The docs say it is related to chain
See the dplyr docs here, at p.7.


text:
Q: Add the bin subdirectories of all folders to path I have a folder in my home called tools, it is where I place all the utilities I use for my projects. Each folder in tools has a /bin subdirectory that I want to add to my path. my .profile file currently has this piece of code added to it:
    # add directories to path below
if [-d "$HOME/tools"]; then
  for d in $HOME/tools/*/bin; do PATH="$PATH:$d"; done
fi

I scraped this together from related threads on how to add folders to path, but have ended up no further than where I began.
What i'd like for it to do is for each subfolder within tools, add the bin to path. Any pointers?

A: Thanks to Socowi for the info. I removed the if statement and edited for for loop a bit and its working how i intended.
for d in $HOME/tools/*; do PATH="$PATH:$d/bin"; done


text:
Q: Single code base for mobile and desktop app We have a requirement to work on an application which should run on mobile devices (iPhone/Android and Windows Phone) and Desktop browsers.
Can anyone please suggest me the technology stack to be used?
Thanks.
Suhas

A: Cross-platform HTML-app solutions seem like a good fit for this. They are cross platform app development platforms that are composed of HTML, CSS and JavaScript. They would allow you to compile for many platforms from a single codebase. Here's a few of the popular ones:

*

*PhoneGap

*Sencha Touch

*AppJS

A: 2022 We have two popular frameworks that build app for multiple platforms, for more information you could visit their home pages:

*

*Flutter (mobile, web, desktop and embedded apps)

*React Native (mobile), React Native Desktop


text:
Q: Adobe Animate CC 2017. No user is signed in. Web fonts cannot be used I'm trying to use google web fonts in Adobe Animate CC 2017. I'm following the steps in this article https://helpx.adobe.com/animate/using/google-fonts.html# , but when clicking the world icon and selecting google fonts a warning box pops up with the following text: "No user is signed in. Web fonts cannot be used".

A: This turned out to be an isolated issue. I reinstalled adobe creative cloud and now everything works as expected.


text:
Q: What is the default value for IMultiConverter? Background...
I have this code that crashes the entire application once every 4 months.
The crash is in the ConvertBack function (according to the stack trace):
public enum MultiBoolConverterType
{
    And,
    Or,
}

public class MultiBoolConverter : IMultiValueConverter
{
    public MultiBoolConverterType ConverterType { get; set; }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var booleans = values.OfType<bool>();

        switch (ConverterType)
        {
            case MultiBoolConverterType.And:

                return booleans.All(b => b);

            case MultiBoolConverterType.Or:

                return booleans.Any(b => b);

            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Question
What do I replace throw new NotImplementedException(); with to ensure that if ConvertBack is inadvertently called, it does no harm?

A: Binding.DoNothing is what you return if you actually have no value.
In ConvertBack you should throw NotSupportedException, because there is no inverse function for this converter. You will have to make sure that this is never called yourself, via BindingMode=OneWay and the like.

A: As per the comment from H.B., return an array of Binding.DoNothing:
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    _log.Warn("Warning. Reverse binding on MultiBoolConverter called. Prevent this by using OneWay.");

    List<object> result = new List<object>();
    foreach(var t in targetTypes)
    {
        result.Add(Binding.DoNothing);
    }
    return result.ToArray();
}


text:
Q: Can not integrate ignite with cassandra I can not integrate cassandra with ignite. I tried many methods but none of them worked.
I added the optional libraries to lib folder. But no result. When I tried the example1 provided in the ignite document, Then I got the classpath error.
I am using ignite version 2.6 and cassandra version 3.11.4
This is my config file
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Cassandra connection settings -->
    <import resource="classpath:org/apache/ignite/tests/cassandra/connection-settings.xml" />

    <!-- Persistence settings for 'cache1' -->
    <bean id="cache1_persistence_settings" class="org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings">
        <constructor-arg type="org.springframework.core.io.Resource" value="classpath:org/apache/ignite/tests/persistence/blob/persistence-settings-1.xml" />
    </bean>

    <!-- Persistence settings for 'cache2' -->
    <bean id="cache2_persistence_settings" class="org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings">
        <constructor-arg type="org.springframework.core.io.Resource" value="classpath:org/apache/ignite/tests/persistence/blob/persistence-settings-3.xml" />
    </bean>

    <!-- Ignite configuration -->
    <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="cacheConfiguration">
            <list>
                <!-- Configuring persistence for "cache1" cache -->
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="cache1"/>
                    <property name="readThrough" value="true"/>
                    <property name="writeThrough" value="true"/>
                    <property name="cacheStoreFactory">
                        <bean class="org.apache.ignite.cache.store.cassandra.CassandraCacheStoreFactory">
                            <property name="dataSourceBean" value="cassandraAdminDataSource"/>
                            <property name="persistenceSettingsBean" value="cache1_persistence_settings"/>
                        </bean>
                    </property>
                </bean>

                <!-- Configuring persistence for "cache2" cache -->
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="cache2"/>
                    <property name="readThrough" value="true"/>
                    <property name="writeThrough" value="true"/>
                    <property name="cacheStoreFactory">
                        <bean class="org.apache.ignite.cache.store.cassandra.CassandraCacheStoreFactory">
                            <property name="dataSourceBean" value="cassandraAdminDataSource"/>
                            <property name="persistenceSettingsBean" value="cache2_persistence_settings"/>
                        </bean>
                    </property>
                </bean>
            </list>
        </property>

        <!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. -->
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <!--
                        Ignite provides several options for automatic discovery that can be used
                        instead os static IP based discovery. For information on all options refer
                        to our documentation: http://apacheignite.readme.io/docs/cluster-config
                    -->
                    <!-- Uncomment static IP finder to enable static-based discovery of initial nodes. -->
                    <!--<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">-->
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                        <property name="addresses">
                            <list>
                                <!-- In distributed environment, replace with actual host IP address. -->
                                <value>127.0.0.1:47500..47509</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

Error Message is
 bin/ignite.sh /etc/ignite/config/config1.xml
    class org.apache.ignite.IgniteException: Failed to instantiate Spring XML application context [springUrl=file:/etc/ignite/config/config1.xml, err=Configuration problem:
 Failed to import bean definitions from URL location [classpath:org/apache/ignite/tests/cassandra/connection-settings.xml]
    Offending resource: URL [file:/etc/ignite/config/config1.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist]
        at org.apache.ignite.internal.util.IgniteUtils.convertException(IgniteUtils.java:990)
        at org.apache.ignite.Ignition.start(Ignition.java:355)
        at org.apache.ignite.startup.cmdline.CommandLineStartup.main(CommandLineStartup.java:301)
    Caused by: class org.apache.ignite.IgniteCheckedException: Failed to instantiate Spring XML application context [springUrl=file:/etc/ignite/config/config1.xml, err=Configuration problem: Failed to import bean definitions from URL location [classpath:org/apache/ignite/tests/cassandra/connection-settings.xml]
    Offending resource: URL [file:/etc/ignite/config/config1.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist]
        at org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.applicationContext(IgniteSpringHelperImpl.java:392)
        at org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.loadConfigurations(IgniteSpringHelperImpl.java:104)
        at org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.loadConfigurations(IgniteSpringHelperImpl.java:98)
        at org.apache.ignite.internal.IgnitionEx.loadConfigurations(IgnitionEx.java:744)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:945)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:854)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:724)
        at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:693)
        at org.apache.ignite.Ignition.start(Ignition.java:352)
        ... 1 more
    Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:org/apache/ignite/tests/cassandra/connection-settings.xml]
    Offending resource: URL [file:/etc/ignite/config/config1.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:118)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:103)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:233)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:184)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:169)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.applicationContext(IgniteSpringHelperImpl.java:379)
        ... 9 more
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:227)
        ... 18 more
    Caused by: java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist
        at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
        ... 22 more
    Failed to start grid: Failed to instantiate Spring XML application context [springUrl=file:/etc/ignite/config/config1.xml, err=Configuration problem: Failed to import bean definitions from URL location [classpath:org/apache/ignite/tests/cassandra/connection-settings.xml]
    Offending resource: URL [file:/etc/ignite/config/config1.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/apache/ignite/tests/cassandra/connection-settings.xml] cannot be opened because it does not exist]

A: This is not a classpath error. Spring reports, that there is no bean called cassandraDataSource. Judging by the comment in your configuration file <!-- Cassandra connection settings --> and no bean definitions under it, looks like you removed the corresponding configuration part.
So, you need to configure the data source for Cassandra. You can refer to the documentation for more details: https://apacheignite-mix.readme.io/docs/ignite-with-apache-cassandra
Configuration examples: https://apacheignite-mix.readme.io/docs/examples


text:
Q: Building one directional valve Is it possible to build check valve in dwarf fortress(fortress mode)?
If yes, then explain with picture.
I want flow of water to be unidirectional. preventing any back flow.

A: To summarize the comments, it can be done but needs at least two z levels.
Z+1    Z

+++   ++7
+ +   +7+
+P+   +++
+p+   +++
+ +   +7+
+++   +7+

+: Wall
P: Pump output
p: Pump input
7: Water

Water will taken from south, and exits to the north. The diagonal gap is required to remove the pressure from the water stream, otherwise it would flood onto Z+1 level whenever possible. Because this slows the stream very much, in some cases it might be better to avoid the gap (water will only flood Z+1, not Z+2) or place it further downstream.
Can be combined with a water wheel for automatic operation.
 Z+1    Z
 +++   ++7
 +w+   +7+
o-w+   +7+
|+w+   +7+
o-P+   +++
 +p+   +++
 + +   +7+
 +++   +7+

+: Wall
P: Pump output
p: Pump input
7: Water
w: Water wheel
-, |: Axles
o: Gear

Might cause slight spillage of water around the upper axle though.


text:
Q: How do threads actually work? Here is a scenario
We have two threads both access same piece of code and that code has a variable, for instance
int a=200;
thread A enters and changes it's value to a=300;
then thread B access this variable , what would thread B get 200 or 300?

A: Two threads aren't guaranteed to execute in any fixed sequence; any operation in A could precede any operation in B (provided that the operations still flow sequentially within their own threads).
Therefore, without synchronization, A might change its value before or after B accesses it. If A changes it before B, then B sees 300; otherwise, B sees 200.

A: The state chart diagram below describes the thread states.

*

*Runnable  — waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

*Running — The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily
gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should
not be used very frequently.

*Waiting — A thread is in a blocked state while it waits for some external processing such as file I/O to finish.

*Sleeping — Java threads are forcibly put to sleep (suspended) with this overloaded method:
Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

*Blocked on I/O — Will move to runnable after I/O condition like reading bytes of data etc changes.

*Blocked on synchronization — Will move to Runnable when a lock is acquired.

*Dead — The thread is finished working.

About your example, we don't know what thread B will take 200 or 300. If u start both threads at the same time since your method will be synchronized thread B should see 200 (in case if it will be 1st or 300).

A: Due to compiler optimization the threads may cache the data and first thread changes may not be seen by second thread. That is where 'volatile' is used for shared data to avoid the issues in multi-threading environment
Addendum- Well  I was talking about the visibility of variable changes across the threads, not synchronization.

A: if your threads access simultaneously your piece of code it will happen according to the thread priority in jvm level. We cant guaranteed which thread is going to access the code. If it is synchronized Thread B have to wait until thread A release the resource.

A: The result of the above execution depends on the consistency model.
In a sequential consistency model, the result of the execution is such that all the instructions are executed in some global order. In such case, the threadB will get a value 300.
However, modern machines use a weaker consistency model where all the synchronization (memory fence instructions) operations alone occur in a global sequential order.
If the load for threadB occurs after store for threadA has completed, threadB will get the value = 300. This is guaranteed by the cache coherence protocol.
However, if the load instruction for threadB occurs before/alongwith the store of threadA (due to some optimization), the value for the shared variable in threadB is undefined. It will be the result of a race condition between the load of threadB and store of threadA over a bus operation.


text:
Q: DLL Functions and pointers I am absolutely new to DLLs, but not to C++. For a project I need to implement some functions in DLL. My question : can I pass pointers, from my main project, to functions inside DLLs without worrying about nothing ? I find it strange because the address in my main project are relatives, so the address passed to the DLL should mean something else. Is there a trick anywhere ?
Thanks.

A: Any modules (exe, dll, etc.) in the same address space can be used the same pointer.
When OS execute the EXE. It will load the EXE to the virtual memory at the address specified in EXE header, or randomize address if EXE support relocation and ASLR (Address space layout randomization) is enabled. Then dependencies (All of DLL that EXE uses) will be loaded into the same address space afterward.
The things to be worried when you passed the pointer between modules is allocation and deallocation. You MUST use the same corresponding function to deallocate memory. If you use HeapAlloc, you must use HeapFree to free memory with the same heap.
In Visual C++, the real problems is malloc and free (new and delete too). Imagine module A allocate a block of memory with malloc and its compiled with Visual C++ 8.0. Module B compiled with Visual C++ 9.0. In this situation, you cannot use free in the module B to free a block of memory that allocated by malloc in the module A, since it is not the same corresponding functions.


text:
Q: rebuild all indexes in all tables but need to exclude a certain tables I was looking the way to rebuild all indexes in all tables and I found an script that does it, but i would like to get 6 specific tables for not getting index rebuild.
How can I accomplished that with the below script. In SQL I can add a where condition like : where table not in ('table1','table2').
USE sparcsn4prod

DECLARE @TableName varchar(255)

DECLARE TableCursor CURSOR FOR
SELECT table_name FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='base table'

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @Tablename
WHILE @@FETCH_STATUS=0

BEGIN

DBCC DBREINDEX(@TableName,' ',90)

FETCH NEXT FROM TableCursor INTO @Tablename

END

CLOSE TableCursor

DEALLOCATE TableCursor

A: Except the fact that I think that cursors are one of the worst inventions in the SQL Server Universe (at least according handling and performance), you can simply extend your cursor definition in order to filter the unwanted tablenames:
DECLARE TableCursor CURSOR FOR
SELECT table_name FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='base table'
  AND TABLE_NAME NOT IN ('table1','table2','table3')
OPEN TableCursor

A: Rather than re-invent the wheel, I suggest you consider using Ola Hallengren's Maintenance Solution. This allows one to exclude specific databases, tables, or indexes from normal index maintenance.
The dbo.IndexOptimize parameter value below will optimize all indexes except for the specified table.
@Indexes = N'ALL_INDEXES, -YourDB.YourSchema.YourTable'