text:
Q: What are some common admissible heuristics for distance? What are the most common heuristics used to estimate distance in intelligent search problems? In particular, I'm interested in metrics that can (usually) be used as admissible heuristics for A* search. I came across straight line distance and Manhattan distance but are there any others?

A: Heuristics are something that tends to be very specific to a given problem, as the idea is to incorporate additional knowledge that you might have about that problem. So "general heuristics" isn't a very useful category. That said, it sounds like you are specifically talking about distance metrics, which is a slightly more well-defined subset.
In terms of admissible heuristics for distance, the two that you already mentioned are definitely the most common:

*

*Straight line distance is the only admissible heuristic for general, unconstrained movement in space, because the shortest path between any two points is a straight line.

*Of course, just about any challenging problem will have some constraints on movement. A common one of these constraints in that movement must occur along a single axis at a time, and for such problems, Manhattan distance is appropriate.

There are some other popular distance metrics, but they are less generally applicable as heuristics.

*

*Chebyshev Distance - the distance along a single coordinate, whichever is bigger. While this should usually be admissible (it will underestimate because it doesn't take into account movement along the other axes), it is strictly less informative than Manhattan distance. There may be some occasions where this is useful, but they are uncommon.

*Minkowski Distance - a general case of Manhattan Distance and Euclidean (straight line) distance. However, it is notably less intuitive than either of those special cases, so, again, I can't come up with a good example of when you would choose it over one of them.

*Hamming Distance - This isn't applicable to all problems, but it is calculated as the minimum number of edits that you would need to make to two vectors to make them identical. Since it is the minimum number, it would potentially be admissible for some problems, such as the word mutation game with equal length words. (If word lengths were unequal you would need to use Levenshtein Distance, which allows gaps to be inserted. This takes a fairly long time to compute (O(n^2)) and so is less likely to be an efficient heuristic).

*Canberra Distance, a sort of scaled Manhattan Distance, is often used for points scattered around the origin, but would be inadmissible in many cases.

*Jaccard Distance is a similarity measure used when comparing sets of features. It weights presences of features more strongly than absences. Problems in which you need to use a heuristic on feature sets are relatively uncommon, so it's hard to know what reasonable default assumptions for admissibility would be. In general, I would guess that the asymmetry between present and absent features could make Jaccard distance inadmissible for some problems, but that it's likely to not be a problem if you truly only care about present features.

There are, of course, many other distance metrics, but these are most of the ones that are less popular than straight line and Manhattan distance while still being reasonably common.


text:
Q: Can't sync SIP Address, can't query it in search even when added manually Issue 1
I'm trying to pull back a user's SIP address using the search service. I have this manually entered for the time being in a particular profile. My query:
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + ":" + query + "*'&selectproperties='LastName,FirstName,JobTitle,WorkEmail,WorkPhone,Department,SipAddress'&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31'&sortlist='LastName:ascending,FirstName:ascending'&rowlimit=500&startRow=" + startRow,
        method: "GET",
        headers: {
            "accept": "application/xml",
        },
        success: function (xml) {
            onSuccess(xml, startRow);
        },
        error: onError
    });

And in my XML response, I find the profile (that I manually entered the SIP address for in the User Profile SA) and here's the SIP Address:
<d:element m:type="SP.KeyValue">
    <d:Key>SipAddress</d:Key>
    <d:Value m:null="true" />
    <d:ValueType>Null</d:ValueType>
</d:element>

I have run a full crawl since adding this to the user's profile and verified its success... So for some reason the SIP address for this profile is coming back null. This is the only profile that has a SIP address entered for now, which leads me to issue 2.
Issue 2
When I sync the User Profile SA with AD, none of my profiles get any SIP addresses sync'd in. For the same profile above, I have the user attribute msRTCSIP-PrimaryUserAddress populated with a value, but it is not sync'd in to the User Profile Service.
Any ideas on either of these issues?

A: I just tested this configuration in my demo environment. After running a Full sync the SIP Address attribute was correctly imported to the User Profile. To troubleshoot you may need to look at the MIISClient logs to ensure that the attributes are being retrieved from AD correctly. In my case the initial value was coming from ProxyAddress and was not populated. This change updated it correctly.
Once you get the import working:
For the User Profile Property, you need to set it to Indexed.
For Search, you'll have to run a full crawl on the User Profiles. (sps3://)
I ran your query and the JSON result was this:
{
  "__metadata": {
    "type": "SP.KeyValue"
  },
  "Key": "SipAddress",
  "Value": "sip:willa@doghousetoys.com",
  "ValueType": "Edm.String"
},

redpajama_set_name: RedPajamaStackExchange


text:
Q: why alignment of char array is 4 byte(gcc-arm-none-eabi-4_9, cotrex-M4F) define const char aa bb cc variables, the alignment of memory map seems likes difference between const char bb and const char bb[1]
const char aa = 0;
const char bb = 1;
const char cc = 2;

.rodata.aa
                0x0005dbb0        0x1 ./source/main.o
                0x0005dbb0                aa
.rodata.bb
                0x0005dbb1        0x1 ./source/main.o
                0x0005dbb1                bb
.rodata.cc
                0x0005dbb2        0x1 ./source/main.o
                0x0005dbb2                cc

const char aa = 0;
const char bb[1] = {1};
const char cc = 2;

.rodata.aa
                0x0005dbb0        0x1 ./source/main.o
                0x0005dbb0                aa
*fill*          0x0005dbb1        0x3
.rodata.bb
                0x0005dbb4        0x1 ./source/main.o //why align to 4 byte here?
                0x0005dbb4                bb
.rodata.cc
                0x0005dbb5        0x1 ./source/main.o
                0x0005dbb5                cc

why, const char bb[1] align to 4 byte ?
how to make const char bb[1] align to 1 byte, like const char bb


text:
Q: What is the bulk compressibility of a system that contains both water and steam? Let's say I have a volume that contains both water and steam, e.g. there is a lower pressure top part that is steam and a higher pressure bottom part that is water (temperature is constant).
If I know the fraction of steam and the respective compressibilities of both phases, how can I calculate the bulk compressibility of the whole system?

A: Isentropic Case:
Let $T=T_R$ and $P=P_R$ be the reference state of zero enthalpy for liquid water.  So $H(T_R, P_R)=0$.  Let $n_L$ be the number of moles of liquid water in the cylinder and $n_V$ be the number of moles of water vapor.  Then, the enthalpy of the liquid phase in the cylinder is:
$$H_L=n_L[C_{PL}(T-T_R)+V_L(P-P_R)]$$and the enthalpy of the vapor phase in the cylinder is:$$H_V=n_V [C_{PL}(T-T_R)+V_L(P-P_R)+\lambda(T)]$$where $\lambda(T)$ is the heat of vaporization at temperature T and pressure P, and $C_{PL} $ is the molar heat capacity of the liquid, and $V_L$ is the molar volume of the liquid.  So the total enthalpy of the cylinder contents is $$H=n[C_{PL}(T-T_R)+V_L(P-P_R)]+n_V\lambda(T)\tag{1}$$where $$n=n_V+n_L=const\tag{2}$$
The total volume of vapor and liquid in the cylinder is $$V=n_LV_L+n_VRT/P\tag{3}$$
The variations in temperature and pressure are going to be related by the Clapeyron equation:
$$\frac{dP}{dT}=\frac{\lambda(T)}{T[\frac{RT}{P}-V_L]}\tag{4}$$
Now the next thing we will do is increase the pressure P slightly by dP.  This causes a change in the temperature dT, a change in the number of moles of liquid $dn_L$, a change in the number of moles of vapor $-dn_L$, a change in total volume dV, and a change in total enthalpy dH.  For an isentropic pressure change dP, the behavior is constrained by the first law which requires that $$dH=VdP\tag{5}$$
I think I'll stop here for now an let you ask any questions you might have.  I'll also let you continue the development if you'd like.


text:
Q: xmlstarlet: filter out element with attribute How to filter out elements of certain type which to not have an attribute with a magic value and retain the rest of the document? All this using xmlstarlet?
What I have to far is:
cat << EOF > database.xml
<?xml version="1.0"?>
<database>

    <some name="A" />
    <some name="B" />
    <some name="C" />
    <text>this is some text to be applied...</text>
    <project>
        <test deeper="structure"/>
    </project>

</database>
EOF

and
xmlstarlet sel -t -m "*" -c "*[not(self::some[@name != 'A'])]" database.xml

yields
<some name="A"/><text>this is some text to be applied...</text><project>
        <test deeper="structure"/>
    </project>

But this hides my precious <database> tag. Besides the indentation, which is not a problem... And doesn't work when <some> are not a direct descendant of <database>, childs of <project> for example.
What I want to get is the database as it is, but all <some> removed except the one named A:
<database>

    <some name="A" />

    <text>this is some text to be applied...</text>
    <project>
        <test deeper="structure"/>
    </project>

</database>

Greetings

A: Unfortunately, xmlstarlet's sel doesn't support apply-templates, but you can use the ed command for this:
xmlstarlet ed -d '/database//some[@name != "A"]' input.xml

A: Write an XSLT stylesheet doing
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="some[@name != 'A']"/>

</xsl:stylesheet>

then call xmlstarlet to apply that stylesheet to your input XML: xmlstarlet tr sheet.xsl input.xml.


text:
Q: Fixed Point Representation of Double Type I am trying to convert a double type to fixed type representation. Depending on the input selected, my raw values can be for example 0.00996, 989.15, 1600.25, 89.72 and so on. The point here is that all my input values are always positive but the number of digits before (and after) the decimal place can vary. I am trying to convert these double types to fixed point representation via suitable scaling. I have tried 2.14 scaling (multiply by 16,384) but am not sure how to extend that to the case of variable number of digits before the decimal place. Also, how can I best ensure the maximum accuracy/precision in the converted values? Any help would be greatly appreciated. Thank you.
Code I am using:
fixedScale = (int) Math.Pow(2.0, 64.0);
int new_val = (int) (fixedScale * value);

A: If you want a fixed point representation then you simply need to decide on the scale. Once you have decided that you convert from floating to fixed like this:
int fixedValue = (int)Math.Round(floatValue*Scale);

And in the other direction like this:
double floatValue = (double)fixedValue/Scale;

As to what scale to use, that depends on what you are trying to achieve and what the input data are.


text:
Q: More efficient way to gather ripened mushrooms? I am having my progress stone-walled by a seemingly simple quest to gather 5 ripened mushrooms.
I understand that to get them I need to beat it out of the bugs carrying them but there simply don't appear to be enough of them actually carrying mushrooms to gather enough.
Is there some other way to gather them that I am missing or am I just having abysmal luck on the spawns?

A: Wait for the Altaroth to move to a mushroom spot and suck up mushrooms before killing them. When they spawn they haven't ingested anything yet.


text:
Q: Win32 notification area access: getting user clicks after balloon timeout The notification balloon's message stays in the Windows 11 notification area (the one that opens when clicking the date/time) after the balloon has timed out. Is there a way to get notifications when the user clicks there?
I'm currently using the SDK example for Shell_NotifyIcon(). Getting the event for an immediate click on the primary desktop balloon shown outside of that area works fine.


text:
Q: How to map a DataFrame to another based on a column that starts with strings contained in the first DataFrame? I have two DataFrames and I want to map information from one to the other.
First DataFrame:
    A         B
0   pokaichi  56156
1   klavatur  45156
2   monopol   32154
3   berate    98741

Second DataFrame:
    C   D      E
0   be  18485  Bond
1   mo  14285  Roger
2   kl  74853  Mika
3   po  85655  Loki

How can I map the E column from the second DataFrame to the first DataFrame, so that the new column from the first DataFrame is a result of the string in the A column that starts with the string in C column?
So the first DataFrame should look like this after applying the mapping:
    A         B      E
0   pokaichi  56156  Loki
1   klavatur  45156  Mika
2   monopol   32154  Roger
3   berate    98741  Bond

I tried using str.startswith with map, but to no success.

A: You can use the below steps:
pat=r'({})'.format('|'.join(df2.C))
#'(be|mo|kl|po)'
d=df2.set_index('C')['E'] #creating a series with C as Index and E as values

Then we use: series.str.extract() to extract df2.C from df1.A and using series.map() we map the values to generate the expected output.
df1['E']=df1.A.str.extract(pat,expand=False).map(d)
print(df1)

          A      B      E
0  pokaichi  56156   Loki
1  klavatur  45156   Mika
2   monopol  32154  Roger
3    berate  98741   Bond

A: In [31]: df1
Out[31]:
          A      B
0  pokaichi  56156
1  klavatur  45156
2   monopol  32154
3    berate   9741

In [32]: df2
Out[32]:
    C      D      E
0  be  18485   Bond
1  mo  14285  Roger
2  kl  74853   Mika
3  po  85655   Loki

In [33]: df1['C'] = df1['A'].str[:2].map(df2.set_index('C')['E'])

In [34]: df1
Out[34]:
          A      B      C
0  pokaichi  56156   Loki
1  klavatur  45156   Mika
2   monopol  32154  Roger
3    berate   9741   Bond

Alternatively, you could do a merge if you are okay with creating a new dataframe.
In [43]: df1.merge(df2[['C', 'E']], left_on=df1['A'].str[:2], right_on='C').drop('C', axis=1)
Out[43]:
          A      B      E
0  pokaichi  56156   Loki
1  klavatur  45156   Mika
2   monopol  32154  Roger
3    berate   9741   Bond


text:
Q: Casting a String as Integer in a .net DataTable Disclaimer: This is my very first .net c# project
I am attempting to import a CSV into MSSQL but need to iterate through the CSV values first for sanitization purposes. Some of the columns in the CSV will be integer (will be used for calcuations later) and some are regular varchar.
My script above appears to force all values (that is row column values) in the DataTable as a string which throws an Exception later in my application when SQL cannot write a string as an integer.
Here is my method I am using for the getCSVImport which creates a datatable and populates it.
What I am thinking is to add another condition which checks if the value is an integer and then cast it as an integer (this kind of thing is new to me as PHP would does not handle types so strongly) but I fear that wont work as I am not sure if I can mix the values within a dataTable with various types.
So my question is, is there a way for me to have different values in a datatable as different types? My code below takes the line as a whole and writes it as a string, I need the values to be assigned either as string or as integer.
   /*
     * getCsvData()
     * This method will create a datatable from the CSV file. We'll take the CSV file as is.
     * and collect the data as needed:
     *
     *  - Remove those original 4 lines (worthless info)
     *  - Line 5 starts with the headers, remove any of the brackets around the values
     *  - Iterate through the rest of the fields and sanitize them before we add it to the datatable
     *
     */

    private DataTable getCsvData(string csv_file_path)
    {
        // Create a new csvData tabletable object:
        DataTable csvData = new DataTable();
        try
        {
            using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                int row = 1;
                while (!csvReader.EndOfData)
                {
                    // Read the string and collect the row data
                    string[] rowData = csvReader.ReadFields();

                    if (row <= 4)
                    {
                        // We want to start on row 5 as first rows are nonsense :)
                        // Incriment the row so that we can do our magic above
                        row++;
                        continue;
                    } if(row == 5)
                    {
                        // Row 5 is the headers, we need to sanitize and continue:
                        foreach (string column in rowData)
                        {
                            // Remove the [ ] from the values:
                            var col = column.Substring(1, column.Length - 2);
                            DataColumn datecolumn = new DataColumn(col);
                            datecolumn.AllowDBNull = true;
                            csvData.Columns.Add(datecolumn);
                        }
                        // Incriment the row so that we can do our magic above
                        row++;
                    } else
                    {
                        // These are all of the actual rows, sanitize and add the rows:
                        //Making empty value as null
                        for (int i = 0; i < rowData.Length; i++)
                        {
                            // First remove the brackets:
                            if (rowData[i].Substring(0,1) == "[")
                            {
                                rowData[i] = rowData[i].Substring(1, rowData[i].Length - 2);
                            }
                            // Set blank to null:
                            if (rowData[i] == "" || rowData[i] == "-")
                            {
                                rowData[i] = null;
                            }

                            // Lastly, we need to do some calculations:

                        }
                        // Add the sanitized row to the DataTable:
                        csvData.Rows.Add(rowData);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Could not parse the CSV file: "+ ex.Message);
        }
        return csvData;
    }

A: You can cast the string to a int:
int j;
bool parsed=Int32.TryParse("-105", out j))

With TryParse you can check if it succeeded.
Then when you want to save it to the table again, cast it to string. You can simply do <variable>.ToString()

A: By default, data columns are initialized to a string data type.
There's an overload that allows you to specify the type, so I'd suggest you try that. Since your columns are known beforehand, you can easily handle this in your code.
private DataColumn AddColumn(string columnName, Type columnType)
{
    // Remove the [ ] from the values:
    var col = column.Substring(1, columnName.Length - 2);
    DataColumn dataColumn = new DataColumn(col, columnType);
    dataColumn.AllowDBNull = true;
    return dataColumn;
}

if (row == 5)
{
    csvData.Columns.Add(AddColumn(rowData[0], typeof(string)));
    csvData.Columns.Add(AddColumn(rowData[1], typeof(int)));
    csvData.Columns.Add(AddColumn(rowData[2], typeof(DateTime)));
    csvData.Columns.Add(AddColumn(rowData[3], typeof(string)));
    // etc
}

I'm not sure you'll even need to convert the other values before adding them to the DataTable, but if you do, many built-in types have TryParse methods, such as DateTime.TryParse and Int32.TryParse. You can call each of them in succession, and one of the "tries" succeeds, you'll know your type.
Alternatively, since you know the column types beforehand, you can just cast each value.
csvData.Rows.Add(Convert.ToString(rowData[0]),
                 Convert.ToInt32(rowData[1]),
                 Convert.ToDateTime(rowData[2]),
                 Convert.ToString(rowData[3]));

A: I would use *.TryParse(), ie: With this sample CSV:
*A sample csv file with
*some comment lines at top
-- with different comment
// comment strings.
[charField],[dateField],[intField],[decimalField]
"Sample char data 1",2016/1/2,123,123.45
"Sample char data 2",,2,1.5
"Sample char data 3",,3,
"Sample char data 4",,,
,,,
"Sample char data 6",2016/2/29 10:20,10,20.5

You might use TryParse on those datetime, int, decimal fields:
void Main()
{
    var myData = ReadMyCSV(@"c:\MyPath\MyFile.csv");
    // do whatever with myData
}

public IEnumerable<MyRow> ReadMyCSV(string fileName)
{
    using (TextFieldParser tfp = new TextFieldParser(fileName))
    {
        tfp.HasFieldsEnclosedInQuotes = true;
        tfp.SetDelimiters(new string[] { "," });

        //tfp.CommentTokens = new string[] { "*","--","//" };
        // instead of using comment tokens we are going to skip 4 lines
        for (int j = 0; j < 4; j++)
        {
            tfp.ReadLine();
        }

        // header line.
        tfp.ReadLine();

        DateTime dt;
        int i;
        decimal d;

        while (!tfp.EndOfData)
        {
            var data = tfp.ReadFields();

            yield return new MyRow
            {
                MyCharData = data[0],
                MyDateTime = DateTime.TryParse(data[1], out dt) ? dt : (DateTime?)null,
                MyIntData = int.TryParse(data[2], out i) ? i : 0,
                MyDecimal = decimal.TryParse(data[3], System.Globalization.NumberStyles.Any, null, out d) ? d : 0M
            };
        }
    }
}

public class MyRow
{
    public string MyCharData { get; set; }
    public int MyIntData { get; set; }
    public DateTime? MyDateTime { get; set; }
    public decimal MyDecimal { get; set; }
}

I could further sanitize the data loaded, such as:
myData.Where( d => d.MyIntData != 0 );

Note: I didn't use a DataTable, which I could if I wanted to. For MSSQL loading, I would probably use an intermediate in-memory SQLite instance to save the sanitized data and then push to MSSQL using SqlBulkCopy class. A DataTable is of course an option (I just think it is less flexible).


text:
Q: What should I use instead of FlowLayout()? So, my JFrame is not turning out the way I want it to, because of the FlowLayout() but I don't know what else to use to fix this. It just makes my JButton fill the entire JFrame. Is there a way I can get FlowLayout() to apply my custom sizes and location for the JFrame components, or is there an alternative that could easily replace it?
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MTGSAMPServerReference extends JFrame implements ActionListener {

    public static Toolkit tk = Toolkit.getDefaultToolkit();
    static int ScrnWidth = ((int) tk.getScreenSize().getWidth());
    static int ScrnHeight = ((int) tk.getScreenSize().getHeight());

    private static final long serialVersionUID = 1L;
    private static JList list1;
    private static JButton next;

    public MTGSAMPServerReference() {
        // set flow layout for the frame
        this.getContentPane().setLayout(new FlowLayout());
        Object[] data1 = { "Value 1", "Value 2", "Value 3", "Value 4", "Value 5" };
        list1 = new JList<Object>(data1);
        next = new JButton("Next");
        next.addActionListener(this);
        // add list to frame
        add(list1);
        add(next);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Next")) {
            int index = list1.getSelectedIndex();
            System.out.println("Index Selected: " + index);
            String s = (String) list1.getSelectedValue();
            System.out.println("Value Selected: " + s);
        }
    }
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame f = new MTGSAMPServerReference();
        //Display the window.
        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.setSize(1200, 800);
        f.setLocationRelativeTo(null);
        list1.setSize(250, 250);
        list1.setLocation(0, 0);
        next.setSize(75, 25);
        next.setLocation(251, 276);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
        createAndShowGUI();
        }
        });
    }
}

Any ideas?
Thanks in advance!
EDIT: Here is a picture of the problem.

EDIT: Here is what I want it to look like (approximately):

A: This example puts the button below the list, and adds a border to the list using a scroll pane.  'White space' in the GUI is provided partly by spacing defined in the constructor of the layout (e.g. the space between list and button), and partly by using an EmptyBorder.
The control panel (which uses a BorderLayout) is then placed inside the other FlowLayout.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class MTGSAMPServerReference extends JFrame implements ActionListener {

    public static Toolkit tk = Toolkit.getDefaultToolkit();
    static int ScrnWidth = ((int) tk.getScreenSize().getWidth());
    static int ScrnHeight = ((int) tk.getScreenSize().getHeight());

    private static final long serialVersionUID = 1L;
    private static JList list1;
    private static JButton next;

    public MTGSAMPServerReference() {
        // set flow layout for the frame
        this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));
        Object[] data1 = { "Value 1", "Value 2", "Value 3", "Value 4", "Value 5" };

        JPanel controls = new JPanel( new BorderLayout(5,5) );

        list1 = new JList<Object>(data1);
        list1.setVisibleRowCount(5);
        next = new JButton("Next");
        next.addActionListener(this);
        // add list to frame
        controls.add(new JScrollPane(list1));
        controls.add(next, BorderLayout.PAGE_END);
        // adjust numbers as needed.
        controls.setBorder(new EmptyBorder(25,25,0,0));

        add(controls);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Next")) {
            int index = list1.getSelectedIndex();
            System.out.println("Index Selected: " + index);
            String s = (String) list1.getSelectedValue();
            System.out.println("Value Selected: " + s);
        }
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame f = new MTGSAMPServerReference();
        //Display the window.
        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.setSize(1200, 800);
        f.setLocationRelativeTo(null);
        list1.setSize(250, 250);
        list1.setLocation(0, 0);
        next.setSize(75, 25);
        next.setLocation(251, 276);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
        createAndShowGUI();
        }
        });
    }
}

A: If you want complete control over where the components are placed, and have setBounds work, you need to remove the layout manager. This can be done by setting the layout manager to null. That's not a good idea, though, and you are better off only using a layout manager and not using setBounds at all, because you are not tied down to a particular window size and default component sizes, and components that look good with a specific size on one look and feel might not look nice on another.


text:
Q: How to get updated Context's state values to it's child components? I am developing a react application ,So I need to get an immediate update to all the children of Context component in a change of the state of Context component but I can't get the updated context values .
export default class Home extends Component{
    state = {
       user:{name:"Rob"},

    }
    componentDidMount() {
        this.setState({user:this.context.user});
    }

    render(){
         return(
              <DetailsConsumer>
                   {value=>(
                        <button onClick={value.setName} >
                    )}
              </DetailsConsumer>

);
}

class DetailsProvider extends Component{

    state={
       user:{}
    }

     setName= ()=>{
        this.setState({user:{name:"Hasindu"}})
     }
    render(){
        return(<DetailsContext.Provider value={
            {user:this.state.user,

                changeName:this.changeName

            }
        }>

            {this.props.children}
        </DetailsContext.Provider>);
    }
}

const DetailsConsumer = DetailsContext.Consumer;
export{DetailsConsumer,DetailsProvider,DetailsContext};

SO What I need is when ever I click on the button of class Home and invoke the setName() method of DetailsProvider (Context) I need to update the context state to the object in setName() method and I also need to get the updated value to my Home class.[Which means I need to update my Home component state attribute user with that new value ]

A: The problem is that your Home component is duplicating the context state, and therefore isn't getting its state updated when the context state updates. The best way to solve this is by removing the duplicate state in Home and using the context state directly.
export default function Home(){
     return(
          <DetailsConsumer>
               {value=>(
                    <>{value.user.name}: <button onClick={value.setName} /></>
                )}
          </DetailsConsumer>
     )
}


text:
Q: KAL Calendar does not allow select any row for the list of events tableview I used below code
- (void)viewDidLoad
    {

      EKEventStore * store = [[EKEventStore alloc] init];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dateSelected:) name:@"D" object:nil];

        KalViewController *kal = [[KalViewController alloc] init];
        kal.delegate = self;
        kal.title= [NSString stringWithFormat:@"%@",kal.selectedDate];
        [kal loadView];

        EventKitDataSource * dataSource = [[EventKitDataSource alloc]init];
        kal.dataSource = dataSource;

         navController = [[UINavigationController alloc] initWithRootViewController:kal];
        [self.customView addSubview:kal.view];

// when I add  kal.view inside of my custom view then It displays the list of events and when I click on any row then It does not get pushed to next view screen
    }

A: You have to make change two changes in KalView.m file..
First:In that class,there is an initwithFrame method in which you will get this below code.In that you can change color as per your requirement..
   UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, frame.size.width, kHeaderHeight)] autorelease];
headerView.backgroundColor = [UIColor orangeColor];
[self addSubviewsToHeaderView:headerView];
[self addSubview:headerView];

Second :In the same class ,there is a one more method i.e addSubviewsToHeaderView:
In that method you will get this code
//Header background gradient
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Kal.bundle/kal_grid_background.png"]];
CGRect imageFrame = headerView.frame;
imageFrame.origin = CGPointZero;
backgroundView.frame = imageFrame;
[headerView addSubview:backgroundView];
[backgroundView release];

Comment this whole code because this is setting image in HeaderView..


text:
Q: NullPointerException while using jruby I embed jruby script engine into my java program by using javax.script.ScriptEngineManager
I made some jruby code that end with do ~ end block,
after running all code, NullPointerException occured.
but code ends with any other statement, no exception occurs.
version : 1.7.19
Caused by: java.lang.NullPointerException
    at org.jruby.embed.variable.Argv.updateARGV(Argv.java:169)
    at org.jruby.embed.variable.Argv.retrieve(Argv.java:158)
    at org.jruby.embed.variable.VariableInterceptor.retrieve(VariableInterceptor.java:154)
    at org.jruby.embed.internal.BiVariableMap.retrieve(BiVariableMap.java:378)
    at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:124)

in ARGV.java updateARGV
if (vars.containsKey((Object)name)) {
    var = vars.getVariable((RubyObject)receiver.getRuntime().getTopSelf(), name);
        var.setRubyObject(argv);

vars.getVariable returned null because of isReceiverIdentical return false
in BiVariableMap.java
if (var.isReceiverIdentical(receiver)) {
    return var;
}

In isReceiverIdentical, this method just compare receiver with BiVariable's receiver usgin '=='.
Is this jruby bug? Or do I have to do something for this?
If you need more information about this problem, plz comment it!

I got ScriptEngine(engine) from ScriptEngineManager and set some java instance and method like this
engine.put("this", console);
engine.eval("$command = $this.java_method :command, [java.lang.String]");

here is my test ruby code. result and tab is java object
that has some method return String and list.
result = $command.call "something to pass"
puts result.getMessage
tabular = result.getData

tabular.each do |tab|
  rows = tab.getRows
  rows.each do |row|
    puts row
  end
  puts tab.getColumnNames
end

A: I had created ruby type object in my java code by creating new Ruby object...
This causes checking fail in updateARGV because a receiver that register variable in BiVariableMap and another receiver that update variable are different.
So, I got a Ruby object from new ScriptingContainer(from it we can always get a same Ruby object if local context is singleton) and used it to create new ruby type object in my java code.
Reference: https://github.com/jruby/jruby/wiki/RedBridge#Singleton


text:
Q: Problema con el cambio de valor de un input type text ¿ Como puedo modificar el valor asignado en html al siguiente input type text ?
<input type="text" class="form-control text-right o-decimal-number" id="input-tipoiva"   name="tipoiva" value="{{$factura->tipodeiva}}"tabindex="5" maxlength="5" size="5">

Está incluido en un form y al darle otro valor y validar  continúa manteniendo el value="{{$factura->tipodeiva}}"
Espero haberme explicado mejor


text:
Q: ds.getConnection hangs indefinitely with tomcat 6 to MSSQL DB I am trying to connect mssql database with my war file deployed on tomcat 6.0.41, java version 1.5.0_22.
Tomcat hangs for indefinite time at the following line of code.
DataSource ds;
this.conn = ds.getConnection();

And also it works fine with Oracle database.
I have tried making changes at tomcat in context.xml file but of no use.
Thanks,


text:
Q: My favorite drink or my best drink? I know that we say 'My best friend'. What is the difference between:

*

*My favorite drink

*My best drink

A: Favorite usually means "the one that I like most", as in "Clam chowder is my favorite soup."  (That is, Clam chowder is the soup that I like most.)
Best usually means "highest in quality", as in "The French onion soup is their best."  (That is, the French onion is their highest quality soup.)
So my favorite drink is the drink that I like most.  My best drink is the highest-quality drink that I have.  You're right that best friend looks confusing in this context, but it's idiomatic.

A: I think I will say "My favorite drink" if I am telling someone about it.
I think I will say "My best drink" if I made the drink myself and that's the one I can make very delicious or I am best at.

A: When it comes to food and drink, we typically say my favorite, but the best:

Their lobster bisque is my favorite.
  Their lobster bisque is the best!

When it comes to superlatives and people, though, employing a possessive pronoun is quite normal and idiomatic, particularly when describing some kind of personal relationship:

Brian has been my best friend since childhood.
  Michelle is my closest confidant at work.
  David and Juanita are their closest neighbors.
  Linda is our favorite stylist.
  Ted is his biggest ally.


text:
Q: Retrieve multiple record from database in Laravel 5.2 I want to check if user login only if email exist and activated==1
set  in database but activated always show null value.
Image 1:

Image 2:

A: Try this one
$user = DB::table('users')->where([
   ['email', '=', $email],
    ['activated', '=', '1'],
])->get();

or
make your where clause with array to check multiple conditions.

You can use Model class to get data using where clause.

See Queries: Laravel

Another Example (eloquent):
$matchThese = ['email' => $email, 'activated' => '1'];
//........
//........
$results = User::where($matchThese)->get();


text:
Q: reload pickerview depending on data in textfield I'm using Swift 3.
Here is the code:
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if (selectedstatename == nil) {
        return dataList.count
    } else {
       return dataList1.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if (selectedstatename == nil) {
        return dataList[row].title
    } else {
        return dataList1[row].dist
    }
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    if (selectedstatename == nil) {
        cityField.text = dataList[row].title
        selectedstatename = cityField.text
        self.pickerView.reloadAllComponents()
        cityField.resignFirstResponder()
    } else {
        self.pickerView.reloadAllComponents()
        cat.text = dataList1[row].dist
        cat.resignFirstResponder()
    }
}


text:
Q: Android emulator error message, running React Native demo from react-native-cli ERROR:
SyntaxError: Strict mode does not allow function declarations in a lexically nested statement. (http://10.0.2.2:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:24821)

system:

*

*win 10 x64

*android studio 2.2.3

*AVC  Nexus_5x_API_23

I used react-native-cli and react-native run-android the CMD states `BUILD SUCCESSFUL
Total time: 1 mins 10.929 secs
Starting the app on emulator-5554 (adb -s emulator-5554 shell am start -n com.albums/.MainActivity)..`
but I get the error above
Error of emulator


text:
Q: Accidentally deleted my Windows 8 boot entry from dual boot with EasyBCD I installed Ubuntu with a live USB and it's running great, but I had one problem, Windows was always booting. I tried to set up a dual boot with EasyBCD, but I deleted my Windows 8 boot entry.
Through GRUB I can choose Windows Boot Manager, but I get this error:
Windows failed to start. A recent hardware or software change might be the cause.
To fix the problem:

  1. Insert your windows installation disc and restart your computer.
  2. Choose your language settings, and then click "Next."
  3. Click "Repair your computer."

If you don't have this disc, contact your system administrator or computer manufacturer for assistance.

    File: \Boot\BCD

    Status: 0xc0000098

    Info: The Windows Boot configuration Data file does not contain a valid OS entry.

I tried to rerun a Windows 8 install from USB, but only the Ubuntu GRUB launches, even after I changed the boot order.
I tried to fix it with Boot-Repair and got this: http://paste.ubuntu.com/8883078/
For now I can't do the bootrec method.
So is there a way to "re-enable" Windows 8 from GRUB?

A: Test this:
Insert the Windows 8 usb install
Open a terminal,Press Ctrl+Alt+T
Run it:
sudo -i
dd if=/media/user/windows-usb of=/windows.iso
apt-get update
apt-get install unetbootin

Run Unetbootin.
Select the Diskimage option.
Then browse for /windows.iso
Under Type select Hard Disk
Leave / for the Drive.
Press OK
Restart your computer.
Select Unetbootin in the Grub 2 menu.
When the computer boots off Windows 8 iso.
Press the Troubleshoot option.
Select Advanced Options.
Select Command Prompt.
Recreate the Boot Configuration Data store:
bcdboot c:\Windows /l en-us /s v: /f ALL

A: I had a similar problem, the same error message,  but I had no windows installation disc. I couldn't boot Ubuntu either. I thought everything was lost. So then I used Ubuntu live USB which I had and chose to "Try Ubuntu before installing"  and performed boot repair and finally I could get Ubuntu working. (finally relieved that something was working). Then I added windows option to the Ubuntu grub menu. I got windows 8 loader option in the grub while booting but same error when I select it. I googled a lot but found no solution and I  gave up. But finally after a few days I realized something and tried it. It worked right.
THE  SOLUTION  : EasyBCD actually creates a backup of your BCD file. (or you would have been prompted to create one when you run the software)
I could access windows files from the drive in Ubuntu. Then I searched for the location where easybcd was installed and  and found backups of the bcd file. (gave me little hope that something could be possibly done)
Then I went to the folder "Root" of windows and found a file named BCD. I copied the file to other directory (just in case if I needed  it later).
Then I removed the BCD File (I didn't know if it was advisable to do it) and copy pasted the .bcd backup file into  the root folder.(The file had a name like EasyBCD Backup(-date-).bcd    )
Then I renamed the file as BCD ( same as the one I deleted) without the extensions .bcd  (the file I deleted was plainly called BCD)
After that restarted the laptop and chose the windows option from the grub and............ To my surprise..................  it worked.
It was a great relief as I was very new to all these things and had completely lost hope.

A: I suffered from the same issue and have fixed it properly. I followed the instructions from Windows:

*

*Create a USB boot of your Windows (the same as your current Windows).

*Access the boot menu and choose to boot from USB.

*Choose the language and go to next, then click Repair your computer.

*go to Troubleshoot, then cmd, and type the following commands.
 bootrec /rebuildbcd
 bootrec /fixmbr
 bootrec /fixboot

I hope you can fix your problem.

A: Have you checked correct settings using Recovery Center? If not, try these steps:

*

*Press Windows Key + C.

*Click Settings, and then Change PC Settings ->> Update & Recovery ->> Recovery ->> Get Started.

Detailed diagnostic info published here.


text:
Q: Lazy arithmetic in C As far as I know, C uses lazy calculation for logical expressions, e. g. in expression
f(x) && g(x)

g(x) will not be called if f(x) is false.
But what about arithmetic expressions like
f(x)*g(x)

Does g(x) will be called if f(x) is zero?

A: Yes, arithmetic operations are eager, not lazy.
So in f(x)*g(x) both  f and g are always called (pedantically the compiler is transforming that into some A-normal form and could even avoid some calls if that is not observable), but there is no guarantee about the order of calling f before or after g. And evaluating x*1/x or y*1/x is undefined behavior when x is 0.
This is not true in Haskell AFAIU

A: Yes, g(x) will still be called.
Generally, it would be a quite slow to conditionally elide the evaluation of the right-hand side just because the left-hand side is zero. Perhaps not in the case where the right-hand side is an expensive function call, but the compiler wouldn't presume to know that.

A: It's called "Short Circuit" instead of lazy. And, at least as far as the standard cares, yes -- i.e., it doesn't specify short-circuit evaluation for *.
A compiler might be able to do short-circuit evaluation if it can be certain g() has no side effects, but only under the as-if rule (i.e., it can do so only by finding that there's no externally observable difference, not because the standard gives it any direct permission to do so).

A: In case of logical operators && and || order of evaluation bound to take place from left to right and short circuiting takes place.
There is a sequence point between evaluation of the left and right operands of the && (logical AND), || (logical OR) (as part of short-circuit evaluation). For example, in the expression *p++ != 0 && *q++ != 0, all side effects of the sub-expression *p++ != 0 are completed before any attempt to access q, but not in case of arithmetic operators .

A: While that optimization would be possible, there are a few arguments against it:

*

*You might pay more for the optimization than you get back from it: Unlike with logical operators, the optimization is likely to be beneficial in only a small percentage of all cases with arithmetic operators, but at the same time requires an additional check for 0 for every operation.
Because boolean truth values only have two possible values, there is a theoretical 50 % chance (1 ÷ 2) with short-circuiting boolean expressions that the second operand will not have to be evaluated. (This assumes uniform distribution, which is perhaps not realistic, but bear with me.) That is, you are likely to profit from the optimization in a relatively large percentage of cases.
Contrast this with integral numbers, where 0 is only one out of millions of possible values. The probability that the first operand is 0 is much lower: 1 ÷ 232 (for 32-bit integers, again assuming uniform distribution). Even if 0 were in fact somewhat more probable to occur than that (i.e. with a non-uniform distribution), it's still unlikely that we're dealing with the same order of magnitude as with truth values.
Floating point math further aggravates that issue. Here you need to deal with the possibility of rounding errors and denormalization. The probability that some calculation yields exactly 0 is likely to be even lower than with integral numbers.
Therefore the optimization is relatively unlikely to result in the remaining operand not being evaluated. But it will result in an added check for zero, 100 % of the time!

*If you want evaluation rules to remain reasonably consistent, you would have to redefine short-circuit evaluation order of && and ||: Division has one important corner case, namely division by 0: Even if the first operand is 0, the quotient is not necessarily 0. Divison by 0 is to be treated as an error (except perhaps in IEEE floating-point math); therefore, you always have to evaluate the second operand in order to determine whether the calculation is valid.
There is one alternative optimization for /: division by 1. In that case, you wouldn't have to divide at all, but simply return the first operand. / would therefore be better optimised by starting with the second operand (divisor).
Now, unless you want &&, ||, and * to start evaluation with the first operand, but / to start with the second (which might seem unintuitive), you would have to generally re-define short-circuiting behavior such that the second operand always gets evaluated first, which would be a departure from the status quo.
This is not per se a problem, but might break a lot of existing code if the C language were thus changed.

*The optimization might break "compatibility" with C++ code where operators can be overloaded. Would the optimizations still apply to overloaded * and / operators? Or would there have to be two different forms of these operators, one short-circuiting, and one with eager evaluation?
Again, this is not a deficiency inherent in short-circuit arithmetic operators, but an issue that would arise if such short-circuiting were introduced into the C (and C++) language as a breaking change.


text:
Q: Importing multiple files at once I have three excel files as:
C:\business folder\RPT-325-Loan Fee Waivers\2017 01\new_loans_as_of_20170131.xls
C:\business folder\RPT-325-Loan Fee Waivers\2016 12\new_loans_as_of_20161231.xls
C:\business folder\RPT-325-Loan Fee Waivers\2016 11\new_loan_as_of_20161130.xls

I need to count the number of observations in these three files. Is it possible to count the number of obs without importing it in SAS?
Also, if we really need to import the file then how can we import these three files together. In the file name 2017 and 2016 is the year name; 01,12 and 11 are the month names and 31 and 30 are the month end dates.
Thank you

A: Unfortunately, excel files do not have their observations counted when connecting them with the LIBNAME engines (either XLS/X or EXCEL).  So I think you will have to import them if you want to do this in SAS.
You could either run three PROC IMPORT steps, or three LIBNAME statements, and then perform your analysis that way. There's really no faster way; you of course could write a macro and execute that three times, and have it calculate your names (given month dates etc.), but honestly that seems like overkill unless this is a production system.
If it is a production system, look at this macro on a similar question (h/t Snorehorse for reminding me about it).


text:
Q: push().setValue() function do nothing when I try to insert data to firebase database I'm trying to insert to my Realtime Database on Firebase user data.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DatabaseReference reference;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    reference = FirebaseDatabase.getInstance().getReference().child("User");

}

public void onClick(View view) {
    String phone = "+00000000", firstName = "John", lastName = "Smith", email = "johnsmith@gmail.com";
    User user = new User(phone,firstName,lastName,email);
    reference.push().setValue(user);
}

I tried this code but when I click on the button nothing happen beside the Toast..
Database Rules:
{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

I don't get any error when I click the button.

I'm trying to create database of users every user have phone, first name, last name, email.


text:
Q: One particular ImageView causing severe lag One particular activity uses a gallery view and many images that are displayed when one item in the gallery view is clicked. When you scroll through the gallery, the scrolling is very smooth ONLY if one certain image is commented out (even if 40+ images/textviews are displayed). We've tried changing the resolution of that image, changing the scaletype, but it still lags the gallery view. This image takes up a large portion of the background. Have you ever encountered any problems similar to this? We would really appreciate any advice you have to offer.

A: Try loading the image with ImageIO. Then check the type of the BufferedImage it returns (BufferenImage.getType()). Most likely it is not TYPE_INT_ARGB or  TYPE_INT_RGB. (Probably TYPE_CUSTOM.) When this is the case there is a conversion being performed on every paint.


text:
Q: Unconnected port warning in VHDL I get this warning after synthesis is completed in Vivado. I have a single port ram which is constructed using block memory generator. Its output is connected to Brightness_Contrast module's data_in input but apperantly something is not right. But everything seems right interestingly. How can I solve this issue??
Here is the warning
signal data_out_ram : std_logic_vector(11 downto 0); --in top_module

[Synth 8-3331] design Brightness_Contrast has unconnected port data_in[11]

Here what I have
component Brightness_Contrast
port (
clk_in : in  std_logic;
operation : in std_logic_vector(1 downto 0);
data_in: in std_logic_vector(11 downto 0);
output_of_operation: out std_logic_vector(11 downto 0);
mode: in std_logic
);

component Block_Ram
port(addra :in std_logic_vector(15 downto 0);
     clka : in std_logic;
     dina : in std_logic_vector(11 downto 0);
     douta: out std_logic_vector(11 downto 0);
     wea: in std_logic);
     end component;

U4: Block_Ram port map(addra => address_ram,
                       clka => clk,
                       dina => data_in_ram,
                       douta => data_out_ram,
                       wea => write_enable);

U5: Brightness_Contrast port map(clk_in => clk,
                                 operation => operation,
                                 data_in => data_out_ram,
                                 output_of_operation => output_of_operation,
                                 mode => mode);

library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.NUMERIC_STD.all;
use IEEE.std_logic_unsigned.all;
use IEEE.std_logic_arith.all;

entity Brightness_Contrast is
generic (
PICTURE_WIDTH_HEIGHT : integer := 250;
COLOR_BIT : integer := 4);
port (
clk_in : in  std_logic := '0';
operation : in std_logic_vector(1 downto 0);
data_in: in std_logic_vector(11 downto 0);
output_of_operation: out std_logic_vector(11 downto 0);
mode: in std_logic
);
end Brightness_Contrast;

architecture Behavioral of Brightness_Contrast is

signal check : std_logic_vector(11 downto 0) := data_in;

begin

       BRIGHTNESS_CONTRAST: process(clk_in,operation,mode) is

       begin

       if rising_edge(clk_in) then --clk

              if operation = "00" then

              if mode = '0' then

              if check(3*COLOR_BIT-1 downto 2*COLOR_BIT) < "1110" then
              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <= ((check(3*COLOR_BIT-
 1 downto 2*COLOR_BIT)) + "0010");
              end if;

              if check(2*COLOR_BIT-1 downto COLOR_BIT) < "1110" then
              check(2*COLOR_BIT-1 downto COLOR_BIT) <= ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) + "0010");
              end if;

              if check(COLOR_BIT-1 downto 0) < "1110" then
              check(COLOR_BIT-1 downto 0) <= ((check(COLOR_BIT-1 downto 0)) +
 "0010");
              end if;

              output_of_operation <= check;

              elsif mode = '1' then

              if  check(3*COLOR_BIT-1 downto 2*COLOR_BIT) > "0001" then
              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <= ((check(3*COLOR_BIT-
 1 downto 2*COLOR_BIT)) - "0010");
              end if;

              if  check(2*COLOR_BIT-1 downto COLOR_BIT) > "0001" then
             check(2*COLOR_BIT-1 downto COLOR_BIT) <= ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) - "0010");
              end if;

              if check(COLOR_BIT-1 downto 0) > "0001" then
              check(COLOR_BIT-1 downto 0) <= ((check(COLOR_BIT-1 downto 0)) -
 "0010");
              end if;

              output_of_operation <= check;

              end if;

              elsif operation = "01" then

              if mode = '0' then

              if   check(3*COLOR_BIT-1 downto 2*COLOR_BIT) < "1000" and
 check(3*COLOR_BIT-1 downto 2*COLOR_BIT) > "0001" then

              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <=
 ((check(3*COLOR_BIT-1 downto 2*COLOR_BIT)) - "0010");

              elsif  check(3*COLOR_BIT-1 downto 2*COLOR_BIT) > "0111" and
 check(3*COLOR_BIT-1 downto 2*COLOR_BIT) < "1110" then

              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <=
 ((check(3*COLOR_BIT-1 downto 2*COLOR_BIT)) + "0010") ;
              end if;

              if   check(2*COLOR_BIT-1 downto COLOR_BIT) < "1000" and
 check(2*COLOR_BIT-1 downto COLOR_BIT) > "0001" then

              check(2*COLOR_BIT-1 downto COLOR_BIT) <=  ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) - "0010");

              elsif  check(2*COLOR_BIT-1 downto COLOR_BIT) > "0111" and
 check(2*COLOR_BIT-1 downto COLOR_BIT) < "1110" then

              check(2*COLOR_BIT-1 downto COLOR_BIT) <=  ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) + "0010") ;
              end if;

              if   check(COLOR_BIT-1 downto 0) < "1000" and  check(COLOR_BIT-
 1 downto 0) > "0001" then

              check(COLOR_BIT-1 downto 0) <=  ((check(COLOR_BIT-1 downto 0))
 - "0010");

              elsif  check(COLOR_BIT-1 downto 0) > "0111" and
 check(COLOR_BIT-1 downto 0) < "1110" then

              check(COLOR_BIT-1 downto 0) <=  ((check(COLOR_BIT-1 downto 0))
 + "0010") ;
              end if;

              output_of_operation <= check;

              elsif mode = '1' then

              if  check(3*COLOR_BIT-1 downto 2*COLOR_BIT) < "1000" and
 check(3*COLOR_BIT-1 downto 2*COLOR_BIT) > "0010" then

              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <= ((check(3*COLOR_BIT-
 1 downto 2*COLOR_BIT)) - "0011");

              elsif check(3*COLOR_BIT-1 downto 2*COLOR_BIT) > "0111" and
 check(3*COLOR_BIT-1 downto 2*COLOR_BIT) < "1101" then

              check(3*COLOR_BIT-1 downto 2*COLOR_BIT) <= ((check(3*COLOR_BIT-
 1 downto 2*COLOR_BIT)) +"0011") ;
              end if;

              if  check(2*COLOR_BIT-1 downto COLOR_BIT) < "1000" and
 check(2*COLOR_BIT-1 downto COLOR_BIT) > "0010" then

              check(2*COLOR_BIT-1 downto COLOR_BIT) <= ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) - "0011");

              elsif check(2*COLOR_BIT-1 downto COLOR_BIT) > "0111" and
 check(2*COLOR_BIT-1 downto COLOR_BIT) < "1101" then

              check(2*COLOR_BIT-1 downto COLOR_BIT) <= ((check(2*COLOR_BIT-1
 downto COLOR_BIT)) +"0011") ;
              end if;

              if  check(COLOR_BIT-1 downto 0) < "1000" and check(COLOR_BIT-1
 downto 0) > "0010" then

              check(COLOR_BIT-1 downto 0) <= ((check(COLOR_BIT-1 downto 0)) -
 "0011");

              elsif check(COLOR_BIT-1 downto 0) > "0111" and check(COLOR_BIT-
 1 downto 0) < "1101" then

              check(COLOR_BIT-1 downto 0) <= ((check(COLOR_BIT-1 downto 0)) +
 "0011") ;
              end if;

              output_of_operation <= check;

              end if; --mode
              end if; --Operation
              end if; --CLK

              end process BRIGHTNESS_CONTRAST ;

  end Behavioral;

A: I do not have a direct answer to your question as it's not obvious to me what you have declared where and what is in which file. But I can give you a few tips how to test and debug such a design.

*

*Simulation is a powerful little helper to verify a VHDL design. As you're quite limited with debug outputs a proper simulation can show you quite easy where things go wrong. A tool I'm always using (like it because it's platform independent) is GHDL in combination with GTKWave.

*If a synthesis does run through read all the warnings and errors carefully (actually this is good practise even if the synthesis is succesfull). In case of an error like yours I tend to start reducing my design down to simple parts and verify their functions 1 by 1 until the design breaks again. As your fault is about port mapping, remove all your code and start with just the port mapping.


text:
Q: How to feature-ize timeseries data in Pandas? I have data that are structured as below:
Group, ID, Time, Feat1, Feat2, Feat3
A, 1, 0, 1.52, 2.94, 3.1
A, 1, 2, 1.67, 2.99, 3.3
A, 1, 4, 1.9, 3.34, 5.6

In this data, there are individuals who have been measured repeatedly.
I'd like to restructure the data such that each feature-time combination is a unique column, as below:
Group, ID, Feat1_Time0, Feat1_Time2, Feat1_Time4, Feat2_Time0, Feat2_Time2, Feat2_Time4, Feat3_Time0, Feat3_Time2, Feat3_Time4
A, 1, 1.52, 2.94, 3.1, 1.67, 2.99, 3.3, 1.9, 3.34, 5.6

Is there a simple way to handle this, without using a for-loop? I've tried accomplishing what I need with the for-loop method, but it is inelegant and clunky, and given real data of 104 columns, it would take a while as well.

A: df = pd.DataFrame({'Group': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A'},
                   'Time': {0: 0, 1: 2, 2: 4, 3: 0, 4: 2, 5: 4},
                   'ID': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2},
                   'Feat1': {0: 1.52, 1: 1.6699999999999999, 2: 1.8999999999999999, 3: 1.52, 4: 1.6699999999999999, 5: 1.8999999999999999},
                   'Feat3': {0: 3.1000000000000001, 1: 3.2999999999999998, 2: 5.5999999999999996, 3: 3.1000000000000001, 4: 3.2999999999999998, 5: 5.5999999999999996},
                   'Feat2': {0: 2.9399999999999999, 1: 2.9900000000000002, 2: 3.3399999999999999, 3: 2.9399999999999999, 4: 2.9900000000000002, 5: 3.3399999999999999}})

df1 = df.set_index(['Group', 'ID', 'Time']).unstack()
df1

df1.columns = df1.columns.to_series().apply(pd.Series).astype(str).T.apply('_'.join)
df1.reset_index()


text:
Q: Why git branch without any ancestor Yesterday afternoon a college of mine did the git commit seen in the picture below. I wonder how you can do such strange things in git. Normally, every branch should have an ancestor branch that exists before. At least in my understanding of git.
How is this git history possible to get and why should this be useful?

A:
But all branches after the first should have an ancestor.

No: you can create one or more orphan branch at any time with
git checkout --orphan newbranch

The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.
In your case, check the history of the 4-x-dev-cam branch on the remote repo side, and see if its history starts with a commit without parent.

why should this be useful

*

*The repo git itself has at least one orphan branch (beside master): the todo branch, in order to keep management scripts which are not part of the git sources themselves.

*Any GitHub page projects has at least another orphan branch (beside master): gh-pages, in order to manage an website associated to your project.

Basically, any time you need, in the same repo, to manage a content which is orthogonal to your main project (management script, website to illustrate your project, ...), an orphan branch is a good way to isolate that secondary history.
In the case of the 4-x-dev-cam, one possible explanation would be a massive rewrite of the project, starting from scratch.
In that case, an orphan branch is also a good way to separate that new history from the previous branches.


text:
Q: Spark Shell: SQL Query doesn't return any results when data is integer/double I am using the MongoDB Spark Connector to import data from MongoDB and then perform some SQL queries. I will describe the whole process before getting into the actual problem in case I have done something wrong since it's the first time I am using these tools.
I initialize spark-shell with the specific Collection, including the connector package:
spark-shell --conf "spark.mongodb.input.uri=mongodb://127.0.0.1/myDb.myBigCollection"
 --packages org.mongodb.spark:mongo-spark-connector_2.12:3.0.1

I enable the connector:
import com.mongodb.spark._

I make an RDD of the collection I want:
val rdd = MongoSpark.load(sc)

I make a Dataframe out of it so I can use SQL on it:
val df = rdd.toDF()

I create a temporary view of the dataset:
df.createOrReplaceTempView("sales")

The database has 1 million entries in this format:
_id: 61a6540c3838fe02b81e5339
Region: "Sub-Saharan Africa"
Country: "Ghana"
Item Type: "Office Supplies"
Sales Channel: "Online"
Order Priority: "L"
Order Date: 2017-03-22T22:00:00.000+00:00
Order ID: 601245963
Ship Date: 2017-04-14T21:00:00.000+00:00
Units Sold: 896
Unit Price: 651.21
Unit Cost: 524.96
Total Revenue: 583484.16
Total Cost: 470364.16
Total Profit: 113120

The datatypes are string/date/number/double.
A simple query like this works just fine:
spark.sql("SELECT * FROM sales").show()

Queries on strings work fine too:
spark.sql("SELECT Country FROM sales WHERE Region = 'Sub-Saharan Africa'").show()

But when I do a query on numerical values I get back an empty table:
spark.sql("SELECT * FROM sales WHERE 'Units Sold' > 4000").show()

I have tried assigning the query to a val and then using show() on it but it's the same thing.

A: If it is not a typo/cut-n-paste error in your SELECT, the WHERE clause in it compares string "Units Sold" to a numeric value 4000 which is never true. The proper way to escape column names in SparkSQL is using a ` (backticks) not an ' (apostrophes).
So use the following query
spark.sql('SELECT * FROM sales WHERE `Unit Sold` > 1').show()


text:
Q: Comparing while vs do-while loops I'm used to doing while loops -- and not even considering whether it would be in better interest to use a while or do-while loop -- out of familiarity. Here are two examples of a do vs while loop:
// do-while vs. while --
char *string = "String!";
int pos_d=0, pos_w=0;

// while
while (string[pos_w] != 0) {
    printf("At Pos %d The letter is: %c\n", pos_w, string[pos_w]);
    pos_w ++;
}

// do-while
do {
    printf("At Pos %d The letter is: %c\n", pos_d, string[pos_d]);
} while (string[pos_d++] != 0);

Obviously in the above case, the latter loop allows us to see the last character in the string (\0) whereas the while loop quits upon encountering that. What are some examples where a do loop would be used over a while loop? For example, couldn't a do loop be gotten rid of by just adding the same compound statement after the loop if it's needed. What might be some cases where a do loop is better (and should be encouraged) over a while loop?

A: The C language was designed to allow even very simple compilers to produce reasonably efficient machine code.  While it would be possible to express while(condition) {block}; as if (condition) do {block} while(condition); or to express do {block} while(condition); as if (1) {block} do {block} while (condition);, simple compilers would often generate somewhat different code for these alternative ways of writing the same thing, different ways of writing the code would yield better results in different cases.
For example, a common way for compilers to process while(condition) {block}; is to treat it as equivalent to either:
loop:
  if (!condition) goto exit;
  {block};
  goto loop;
exit:

or as
  goto end;
loop:
  {block};
end:
  if (condition) goto loop;

If one were to rewrite the code as if (condition) do {block} while(condition); the result would be equivalent to:
  if (!condition) goto exit;
loop:
  {block};
  if (condition) goto loop
exit:

The code executed by all of these is identical except for conditional branches that are taken (T), conditional branches that are not taken (N), and unconditional jumps (U).  The costs of branches and jumps will vary between platforms, but one can determine how many of each kind of branch or jump will be required for each way of writing the code.  In particular, for the three ways of writing the code, the counts would be:
                  --First--  --Second-- --Third--
                  T  N  U    T  N  U    T  N  U
Zero iterations:  1  0  0    0  1  1    1  0  0
One iteration:    1  1  1    1  1  1    0  2  0
Addl. iteration:  0  1  1    1  0  0    1  0  0

Note that the third approach requires the fewest branches and jumps for any number of iterations, but at the expense of duplicating the code required to test the condition.  On systems where the combined cost of an unconditional branch and a conditional branch not taken would exceed the cost of a conditional branch taken, the first approach will be cheaper in cases where a loop executes zero times, the costs will be the same if a loop executes exactly once, and the second will be cheaper if the loop executes two or more times.
If it's known that a loop is always going to execute at least once, the duplicated condition test and a non-taken branch can be eliminated from the third approach, making it a very clear winner.  It's also easier for compilers to generate code for than the second approach.  Having a do {} while() construct in the language makes it easier for simple compilers to easily generate efficient code in such cases.

A: Suppose you write some game. If someone opened the program then supposedly he wanted to play at least once, right?
int replay;
do
{
   // Game logic goes here

   //Game finishes

   printf("Wanna play again? Press 1 to replay. Press other number to quit. Your option: ");
   scanf("%d", &replay);
} while(replay == 1);

Of course you could do:
int replay = 1;
while(replay == 1)
{
   //Game logic goes here

   //Game finishes

   printf("Wanna play again? Press 1 to replay. Press other number to quit. Your option: ");
   scanf("%d", &replay);
}

But using do while for an occasion like this one could be more readable, don't you agree?

A: You should use a do-while loop if you want to execute the loop body at least once and check the loop condition afterwards.
It provides better readability and maintainability for your co workers than e.g. using some counter variable.
You can use a do-while loop at least every time when you can guarantee that there is at least one iteration.
A concrete example which comes to my mind are parsers. There, I often see lots of do-while loops.


text:
Q: Teradata SQL - two counts from same column I'm new to SQL and Teradata. I tried searching for an answer to this but have been unsuccessful so far.
I created a volatile table with a column that holds a value of <100 (can include negatives). I want to get a total count, a count of all "0"values, a count of all values where 0

I know I could just do a separate statement for each type but for my own knowledge I want to learn the "proper" way. I tried using a similar solution found at this link - Different value counts on same column - but that doesn't seem to work since I need to use >, <, and similar operators.
A layout similar to the table in that thread would be sufficient.
Thanks for the help.

A: count cannot be conditional. It counts all records or if you specify a column, all records where the column is not null. use sum
select count(*) as total,
       sum(case when some_col = 0 then 1 else 0 end) as count_0,
       sum(case when some_col > 0 then 1 else 0 end) as count_above0
from your_table


text:
Q: How do I search the next element in a list of multiple dropdowns It is choosing the same dropdown element twice. Overriding the already selected Captain . How can I ensure that the next element chooses Wicket keeper and not the same one chosen earlier. There is no other way of finding the element but by name.
This is the code:
Select dropC = new Select(driver.findElement(By.name("playerRole")));
dropC.selectByVisibleText("Captain");

Select dropW = new Select(driver.findElement(By.name("playerRole")));
dropW.selectByVisibleText("Wicket Keeper");

This is the html code:
select ng-model="playerRole" name="playerRole" id="plr16" ng-change="selectPlayersRole(this)" class="ng-valid ng-dirty ng-valid-parse ng-touched">  Player Captain Wicket Keeper Captain / Wicket Keeper
There is a list of 11 dropdowns and I need to assign one of the dropdown as "captain" and the other as "wicketkeeper".

A: Take 11 players in an array say String[] players = {"captain", "Wicket Keeper", "Batsman", "Batsman", "Batsman", "Batsman" "Batsman", "Bowler", "Bowler", "Bowler", "Bowler"} then write below code to select them
List<WebElement> playerLocators = driver.findElements(By.name("playerRole"));
int playerCounter = 0;
for(WebElement playerLocator : playerLocators ) {
new Select(playerLocator).selectByVisibleText(players[playerCounter++]);
}

All 11 players in drop downs will be selected respectively.
Note: if there are more than 11 drop downs with the locator By.name("playerRole"), code may fail due to an exception ArrayIndexOutOfBoundsException


text:
Q: shared object file path that is executed by the current thread Is there a way to get the file path/file name of the .so that is currently under execution by a thread? The program is written in c++ and run on a 64-bit Linux 3.0 machine.

A: You can sequentially read (from inside your process) the file /proc/self/maps to get the memory mapping (including those for shared objects) of the current process.
Then you could get your program counter (or those of the caller) and find in which segment it is. Perhaps backtrace or GCC builtin_return_address is relevant.
You might also use the dladdr function.
See proc(5), backtrace(3), dladdr(3) man pages, and also this answer.
addenda
From a signal handler you could get the program counter when the signal was sent by using sigaction(2) with SA_SIGINFO. The sa_sigaction function pointers gets a ucontext_t from which you could get the program counter register (using machine dependent C code). Then you could handle it.
I suggest looking into detail into what GCC is doing

A: I think the closes thing is to get a list of all shared libraries loaded by your process. You can do that either by using pmap or lsof.


text:
Q: Chrome extension "MAX_WRITE_OPERATIONS_PER_MINUTE" error I use below code:
setInterval(function(){
    chrome.storage.sync.set({'serverTime': "***"}, function() {
        console.log('Settings saved');
    });
}, 50);

After 10 seconds I get below error:
Unchecked runtime.lastError: This request exceeds the MAX_WRITE_OPERATIONS_PER_MINUTE quota.

manifest.json

"permissions": [
    "storage",
    "activeTab",
    "declarativeContent",
    "tabs",
    "unlimitedStorage"
]

A: Look again at your code. The setInterval repeats the code after every 50ms. After 10 seconds you will have sent around 200 calls to the API. Understandably, Google won't accept you clobbering it in this way, hence the quota error. Try increasing the interval time, or better yet, making your calls event based. I don't have enough context for what you are attempting to do, but constantly syncing times is not the intended purpose of storage.sync.


text:
Q: "All I did was do something" is correct? I saw several the following examples beginning with "All I did was":

*

*All I did was see something.

*All I did was hire her.

*All I did was tell him the truth.

Are these sentences correct?
Why a verb that following "was" is in a bare form, instead of a form that would be more appropriate for an object?
If those are correct, what is an object?
If those are grammatically incorrect, so how does a correct form look like?

A: If you follow the link to previous questions, you will find further links of undoubted interest. Nevertheless, in English as spoken by native speakers you will find usages comparable with the examples quoted by the OP. Such usages would certainly not raise eyebrows amongst highly educated native speakers.
If you define "correct" by reference to how such people use their language then there is nothing wrong with any of the examples. If they do not appear to comply with rules defined by grammarians, then it is up to the grammarians to revise their rules.


text:
Q: Total newbie confusion with pandoc and changing fonts on pdf export I have pandoc and would like to change the awful default font when I convert a .MD to a .PDF.
I understand I can pass -V on the command line and that pandoc uses --pdf-engine=pdflatex by default. I would like to change the font family to https://tug.org/FontCatalogue/clearsans/. I try:
pandoc -V fontfamily="ANYTHING" test.md -o test.pdf

and just get
Error producing PDF.
! LaTeX Error: File `ANYTHING.sty' not found.

I am reading about different engines, which don't seem to be installed. I can look at a config file that is total mumbo-jumbo.
Can I just list what fonts or font family's are available and choose one on the command line?
I installed texlive on Centos 8 and it installed a lot... but there seems still more packages. It seems a lot of work to change a font!
tex --version
TeX 3.14159265 (TeX Live 2018)
kpathsea version 6.3.0

also I see included in the install were:
Name         : texlive-latex-fonts
Summary      : A collection of fonts used in LaTeX distributions
URL          : http://tug.org/texlive/
License      : LPPL
Description  : This is a collection of fonts for use with standard latex
             : packages and classes. It includes 'invisible' fonts (for use
             : with the slides class), line and circle fonts (for use in the
             : picture environment) and 'latex symbol' fonts. For full support
             : of a latex installation, some Computer Modern font variants
             : cmbsy(6-9), cmcsc(8,9), cmex(7-9) and cmmib(5-9) from the
             : amsfonts distribution, are also necessary. The fonts are
             : available as Metafont source, and metric (tfm) files are also
             : provided. Most of the fonts are also available in Adobe Type 1
             : format, in the amsfonts distribution.

Name         : texlive-collection-basic
Summary      : Essential programs and files
URL          : http://tug.org/texlive/
License      : Artistic 2.0 and GPLv2 and GPLv2+ and LGPLv2+ and LPPL and MIT
             : and Public Domain and UCD and Utopia
Description  : These files are regarded as basic for any TeX system, covering
             : plain TeX macros, Computer Modern fonts, and configuration for
             : common drivers; no LaTeX.

Name         : texlive-collection-fontsrecommended
Summary      : Recommended fonts
URL          : http://tug.org/texlive/
License      : Artistic 2.0 and GPLv2 and GPLv2+ and LGPLv2+ and LPPL and MIT
             : and Public Domain and UCD and Utopia
Description  : Recommended fonts, including the base 35 PostScript fonts,
             : Latin Modern, TeX Gyre, and T1 and other encoding support for
             : Computer Modern, in outline form.

A: On a recent TeX Live installation
pandoc -V fontfamily:ClearSans -V fontfamilyoptions:sfdefault test.md -o test.pdf

should work. To make sure that the right package is installed use the package manager tlmgr¹
tlmgr install clearsans

*

*Maybe you need to use sudo, depending on your installation


text:
Q: optparse csv.reader Can somebody help me, I'm trying to link an optparse with a csv reader, but I have been unable to do so. Below is my code:
import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

data = csv.reader(open('input1file','r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

I don't know how to connect the add_option part so that the user can type in the filename path.
Thanks!
I updated my code. Still can't get it working though.
Update1:
import sys
import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

try:
    input1file = args[1]
except IndexError:
    sys.exit("Input file required, none given")

data = csv.reader(open(sys.args[1],'r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

A: data = csv.reader(open('input1file','r'))

should be
data = csv.reader(open(input1file,'r'))

Based on your comment, it looks like you're forgetting to use the --i1 argument.  If it is actually required, you should enforce that:
e.g.:
if not input1file:
  print "What?  you were supposed to give '--i1 filename', but you didn't.  Shame on you!"
  sys.exit(1)

note that this is easier to do in argparse.  You just pass required=True to the add_argument method

A: If you don't specify --i1 on the command line, options.input1file is None, since you don't provide a default value.
myscript.py --i1 input.txt

Since --i1 is required, it really shouldn't be an option (since it is not optional). Take the input file from args, instead:
parser = OptionParser()
(options, args) = parser.parse_args()
try:
    input1file = args[0]
except IndexError:
    sys.exit("Input file required, none given")

Or, as mgilson suggested, use argparse instead. It supports named positional parameters.


text:
Q: Use Obfuscar for publishing applications I am able to obfuscate a .dll in my visual studio solution upon running it.
The problem is that I have no idea how this can be done upon publishing the application into an .exe. Because the source code of the dll inside the published exe can still be seen with a de-obfuscator.
Could someone help me out please? Thanks in advance.

A: I just found the solution. By installing Obfuscar Global Tool and adding the following code to my .csproj file.
<Target Name="Obfuscation" AfterTargets="AfterCompile">
    <Message Text="Obfuscating" Importance="high" />
    <!--Optional to log a message.-->
    <Exec Command="obfuscar.console obfuscar.xml" />
        <!--Assuming you have installed Obfuscar.GlobalTool(attpsifluww.nuget.org/packages/Obfuscar.GlobalTool). -->
    <Exec Command="COPY $(ProjectDir)$(IntermediateOutputPath)Protected\$(TargetFileName) $(ProjectDir)$(IntermediateOutputPath)$(TargetFileName)" />
</Target>

This allowed me to change the dll file on publish.
Thanks everyone for helping me solve this. I really appreciate it!


text:
Q: What am I doing wrong: Structure cannot be indexed because it has no default property (WITH CLAUSE) Am getting: "Structure cannot be indexed because it has no default property". What am I doing wrong?
With grid.Rows(10).Cells
    Dim note As New Note With {.ID = "Blah", _
                               .Date = "1/1/2011", _
                               .Message = "AAA", _
                               .Type = "ABC", _
                               .SubType = "DEF", _
                               .ReferenceKey = !SetRefNum.Value}
End With

And Note looks like:
Public Structure Note
    Public Property ID As String
    Public Property [Date] As Date
    Public Property Message As String

    Public Property Type As String
    Public Property SubType As String
    Public Property ReferenceKey As String
 End Structure

A: The problem is with !SetRefNum.Value.  You use the ! operator to reference an index in a collection, usually a dictionary.  The Note class requires a Default property to use this terminology.
Class Note
    Public ReadOnly Default Property Item(Key As String) As String
        Get
            Return Settings(Key)
        End Get
    End Property
    Private Settings As New Dictionary(Of String, String)
End Class

So the term !SetRefNum.Value will translate to note.Item("SetRefNum.Value").
I'm going to take a guess you're after something completely different.
See the Member Access Operators section of the page Special Characters in Code (Visual Basic) for more information.
Edit: Ammended answer for ammended question.
I suggest the following approach:
With grid.Rows(10).Cells
    Dim ReferenceKey As String = !SetRefNum.Value
    Dim note As New Note With {.ID = "Blah", _
                               .Date = "1/1/2011", _
                               .Message = "AAA", _
                               .Type = "ABC", _
                               .SubType = "DEF", _
                               .ReferenceKey = ReferenceKey}
End With

Somehow, I doubt that will work either.  You might need something like:
With grid.Rows(10).Cells
    Dim ReferenceKey As String = .Item(SetRefNum.Value)

A: The ! character is used in C#. For VB, you'll want to use the Not keyword. So, it should look like this:
Dim note As New Note With {.ID = "Blah", _
                           .Date = "1/1/2011", _
                           .Message = "AAA", _
                           .Type = "ABC", _
                           .SubType = "DEF", _
                           .ReferenceKey = Not SetRefNum.Value}

Also, assuming you're using Visual Studio 2010 because of the auto properties in your Structure, you don't need the trailing underscores. I would write it like this:
Dim note = New Note With {.ID = "Blah",
                          .Date = "1/1/2011",
                          .Message = "AAA",
                          .Type = "ABC",
                          .SubType = "DEF",
                          .ReferenceKey = Not SetRefNum.Value}

Edit: Well, your ReferenceKey field is a String, so I'm not sure you were going for the boolean value. Maybe @Hand-E-Food was closer to the right answer.


text:
Q: Attempt to call global 'gameover' (a table value) So i'm working on a little game using onCollision event's :
local function onCollision(event)
    if event.phase == "began" and gameIsActive == true then
        local obj1 = event.object1;
        local obj2 = event.object2;

        if obj1.name == "bill" then
        if     obj2.name == "rocks" then gameover()
        elseif obj2.name == ""   then
        end
    end
    end
end
Runtime:addEventListener( "collision", onCollision )

But i have a bit of a problem the code works as expected the first time it runs but is you restart the game i'm getting this error :
File: game.lua
Line: 649
Attempt to call global 'gameover' (a table value)

stack traceback: game.lua:649: in function <game.lua:643> ?: in function <?:221>

649 = if obj2.name == "rocks" then gameover()
643 = local function onCollision(event)

Any idea what this could be?
gameover function :
function gameover()

rightTAP:removeEventListener("tap", movePLAYERr)
leftTAP:removeEventListener("tap", movePLAYERl)

timer.pause(spawnBits)
timer.pause(Rockspawner1)
timer.pause(tmrscore)
timer.pause(updateScoretimer)
timer.pause(spawnDinosControll)

audio.pause( drillingChannel )

drillbg.isVisible = false
scoreText.isVisible = false

Restartg = display.newText( "Restart", 0, 0,nil, 20)
Restartg:setFillColor(0, 0, 0)
screenGroup:insert(Restartg)
Restartg.x= display.contentWidth/2
Restartg.y= display.contentHeight/2 + 160

Restartg:addEventListener("tap", RestartGame1)

end

A: The error message is clear: you are trying to call gameover and it has a table value instead of a function value. You get the same error is you run the following: gameover = {}; gameover().
This means that either you are not correctly defining gameover function or overwriting gameover value somewhere in your script.

A: if you have an object of functions you can call whit the key that you use to declare.
example
el = {}

print(el)
table: 0x7f8fe9e003f0

el.f1 = function()
print('hola')
end

el.f1()
hola

A: On restart you have to remove all Runtime listeners. Otherwise they will be still listening and it may cause errors, because they lead to already removed methods.
Place it in RestartGame1:
Runtime:removeEventListener( "collision", onCollision )

A: fixed by adding "transition.pause( thisRock )" to the gameover function


text:
Q: A father has nine identical coins to give to his three children. How many total allocations are possible? There's three parts to this question:
How many total allocations are possible? (This one I understand -- it's ${11 \choose 9}$ because it's unordered with replacement.)
How many allocations are possible if each child must receive at least one coin?
How many are possible if each child must receive at least two coins?
I have the answers but I have no idea how to explain them without counting out all the options that don't work and subtracting them from the total.

A: If each child must receive one coin, then give each child one coin and figure out how many ways there are to distribute the remaining $6$ coins. Similarly if each child must have at least two coins, begin by giving them all exactly two coins.
Note: If the father must give away all his coins, then this is a typical stars and bars problem. For the total number of allocations, it would be equivalent to placing $2$ bars between $12$ objects which gives $11\choose2$ possibilities.

A: Each one of the other two questions can be easily reduced to the first one:

*

*If each child must receive at least $1$ coin, then solve the first question with $9-3\cdot1$ coins

*If each child must receive at least $2$ coins, then solve the first question with $9-3\cdot2$ coins


text:
Q: Is there a way of overlaying two ggplot set of panels without rescaling any of the y-axes? I want to overlay two sets of ggplot panels (each panel is a different country) into one, single ggplot panel, without any rescaling of any of the two plots, but ggplot rescales either one or the other.
I have tried using only one ggplot to include both variables, by doing ggplot(df, aes(x=t, y=a)), and, within that ggplot, then using geom_point and geom_smooth for the second variable (y=b), but this rescales variable a.
# plot 1
g <-ggplot(df, aes(x=year, y=a))
p <-g + geom_point(alpha=0.7) + geom_smooth(method="auto") + facet_wrap(~country, scales="free") + theme_bw() +
  xlab("Year") + ylab(bquote('a')) +
  scale_x_continuous(breaks=seq(1960, 2020, 15))

# plot 2
a <-ggplot(df, aes(x=year, y=b))
b <-a + geom_point(alpha=0.7, color="green") + geom_smooth(method="auto", color="darkgreen") +
  facet_wrap(~country, scales="free") + theme_bw() +
  xlab("Year") + ylab(bquote('b')) +
  scale_x_continuous(breaks=seq(1960, 2020, 15))

I expect to be able to overlay these two ggplots into a single set of panels, with both y-axes appearing exactly as they appear when they're plotted alone (including units). I would then need to somehow make one of the y-axis appear to the right of the panels, so I have two y-axes, one at each side.
Image 1. ggplot rescales left y-axis. I don't want this to happen.
Image 2. What I want instead is to be able to somehow merge each of these images to get a single panel per country, displaying both the green and the blue lines with the scales that appear here.


text:
Q: How to call vector function from main() in C++? I'm trying to call the vector function 'twoSum' which is inside the class 'Solution' but is giving me 'Expected variable name or 'this' in lambda capture list' error when I'm trying to call the function.
Here's the code:
#include <iostream>
#include <list>
#include <vector>
using namespace std;

class Solution {
public:
        vector<int> twoSum(vector<int>& nums, int target) {
        for (int i=0; i+1<=nums.size(); i++){
            if ((nums[i] + nums[i+1]) == target){
                //cout << "[" << i << i+1 << "]";
                return (i,i+1);
            }
        }
        return {2, 3};
    }
};

int main()
{
    Solution solobject;
    solobject.twoSum([1,2],2); //Not Calling function
    return 0;
}

What am I doing wrong?

A: In C++, you can't create a std::vector with a [1, 2] expression.
The most similar thing will be implicitly creating an instance of std::vector by list initializer with {1, 2}. See more about this in std::vector and std::initializer_list documentation.
Also, there will be an issue with passing to the function. Because right now your signature accepts a non-const lvalue reference vector<int>& nums and you are passing an rvalue instead.
You need to either make your method to accept a value like this:
vector<int> twoSum(vector<int> nums, int target)

or accept an rvalue:
vector<int> twoSum(vector<int>&& nums, int target)

or create an instance of the vector in main() before calling the method.
Also, as mentioned by @Stephen Newell, you may want to make it a const reference, because we don't change the std::vector in the method:
int main()
{
    Solution solobject;
    auto vec = std::vector<int>({1,2})
    solobject.twoSum(vec,2); //Not Calling function
    return 0;
}

And as mentioned by @tangy, we can't create a std::vector with (i,i+1), we need to use the same initialiser list with {i, i + 1}.


text:
Q: TableCell doesn't show item.toString() value with custom CellFactory I installed a custom CellValueFactory and CellFactory on my TableColumn: I'm programming an address book, Salutation is an enum with values "Mr" and "Mrs".
salutation.setCellValueFactory(c->new ReadOnlyObjectWrapper<>(c.getValue().getSalutation()));
salutation.setCellFactory((tableColumn)->new TableCell());

Unfortunatelly the cells set by my CellFactory don't show anything.
(Note: actually I want to use a custom TableCell, I only used TableCell for testing).
What is the best way to show the item.toString() String on each cell?
Thanks :)
Thanks

A:
Note: actually I want to use a custom TableCell, I only used TableCell for testing

This is exactly the issue. TableCell in contrast to the cell type produced by the default cell factory simply updates the empty property of the cell. Removing this initialisation or replacing the assignment of the factory with
salutation.setCellFactory(TableColumn.DEFAULT_CELL_FACTORY);

would show the result of invoking toString on the cell item as would the following cellFactory:
salutation.setCellFactory((tableColumn)->new TableCell() {

    @Override
    protected void updateItem(Object item, boolean empty) {
        super.updateItem(item, empty);
        setText(item == null ? "" : item.toString());
    }

});

Note: I recommend not using the raw type but lacking the knowledge about the types involved, I decided to keep using the raw type in the above snippet.


text:
Q: Is Inverse Variance Weighting biased if my samples come from correlated data? I have a brief question about whether or not inverse-variance weighting is a biased or unbiased estimator when the samples themselves are means of correlated data themselves. To elaborate on this, let's say I have 10 "measurements" which have a mean $\mu_i$ and variance $\sigma^2_i$ each. The sample values are independent to one another but their mean and variance come from correlated samples themselves. Where $\mu_i$ is the mean of subsamples of a given measurement, $i$, and $\sigma_i^2$ is the variance of those subsamples for a given measurement $i$ (this variance includes the statistical autocorrelation between the subsamples which emerge from markov-chain monte carlo).
I compute the total mean and total variance by using the weights as, $w_i = \frac{1}{\sigma_i^2}$, and taking the weighted mean $\mu_{ave}$ = $\sum_{i=1}^{10} w_i \mu_i$ / $\sum_{i=1} w_i$ and the variance as $\sigma^2_{ave}$ = $\sum_{i=1}^{10} w_i^2 \sigma^2_i$ / $\left( \sum_{i=1}^{10} w^2_i \right)^2$ The Wikipedia article does mention that the individual measurements have to independent of each other but also unbias which I'm pretty sure values are. However, I'm not 100% sure about the variance as the wiki does state " if the measurements are performed under identical scenarios" and because my subsamples are correlated I'd assume this would invalidate this weighted-average.
I'm not 100% sure about this statement so I was wondering if someone else with more experience might be able to clarify some points for me! Any help is appreciated! Thank you!


text:
Q: Can I import an external .css file from a view file (*.ui.xml ) in my GWT project? I wanna know if this is possible. I have an external .css file in my project and in a *.ui.xml file I have my view code, but I don´t wanna put the .css file within the .ui.xml file, so, can I import this external .css to my view code and used It there?.

A: yes you can. Or as src attribute or as client bundle via attribute type to <ui:style>· See the GWT documentation for more information: http://code.google.com/webtoolkit/doc/latest/DevGuideUiBinder.html#Hello_Stylish_World


text:
Q: Why can cc compile a c++ program? I have a makefile for macOS and Linux, which contains the following command:
cc -std=c++14 foo.cpp bar.cpp

And it compiles fine. foo.cpp and bar.cpp are, as the name suggests C++ files and it contains C++11 syntax. The compilation works fine.
Now if I include <fstream> I get hundred of linker errors. I am wondering, why that is?
Undefined symbols for architecture x86_64:
"std::__1::locale::has_facet(std::__1::locale::id&) const", referenced from:
    bool std::__1::has_facet<std::__1::codecvt<char, char, __mbstate_t> >(std::__1::locale const&) in DiceInvaders-6f5dd4.o
"std::__1::locale::use_facet(std::__1::locale::id&) const", referenced from:
...

Afaik, cc links to the c compiler, and I would assume due to it's auto detection it compiles it with the C++ compiler. But why does it fail with an additional C++ include?
Is there any counterpart of cc for c++ on a system? If I use g++, I would assume that command is available, and what if the user actually wanted to compile it with his compiler of preference (as in cc)?
Edit: Is $(CXX) a good replacement for cc?

A: Most probably cc on your system is a symlink to gcc executable. Assuming that is true:
The difference between gcc and g++, quoting the man page, is:

g++ is a program that calls GCC and automatically specifies linking against the C++ library.

So when you invoke gcc it does not link against c++ library. You can link standard c++ library manually:
gcc -lstdc++ 1.cpp

Is there any counterpart of cc for c++ on a system?

The cc command is just a convention that most system follow. It's not standardized, at least I haven't heard where, the utility c99 is standarized by posix. On my linux system with archlinux distribution with the gcc package there is also installed symlink /usr/bin/c++ to g++.


text:
Q: Can this be simplified further? Can this be simplified to isolate the variable by itself?
$$\begin{align}
\dfrac{\displaystyle{83 - x}\choose{\displaystyle x}}{\displaystyle{82}\choose{\displaystyle x}} \geq 0.50
\end{align}$$
This is where I am.
$$\begin{align}
\dfrac{(83 - x)!}{(83 - 2x)!} \geq 0.50 \dfrac{82!}{(82 - x)!}
\end{align}$$

A: I suppose you are looking for the lowest integer value of "x" which satisfies the inequality.
In my mind, an easy way would consist in using Jeff Snider's formulation and take the logarithms of both sides. So, the equation is just a sum of "x" logarithms.
If we assume that "x" is small, we could use the approximation Log(1+y) = y and if we also assume that "k" is small compared to 82, just forget the "k" in the denominator. All of this lead to the search of "x" such that
x (1-x) / 82 > Log(1/2)
Solve the quadratic equation assuming, for the time being that "x" is real : the only positive root is 8.06. Then try x=8; you get a value equal to 0.473355. Since your ratio decreases when "x" increases, try x=7; you get a value equal to 0.575047. So x=7 is your solution.
Just for testing puroposes, I replace the value of 0.5 by 0.01. Using the same method as before, the root of the quadratic equation is 19.94 while the solution is 17.


text:
Q: How to exec the Windows Foto Viewer in order to show a png image using TCL In my TCL code running on windows I use
exec Notepad $somefilename

in order to show the content of a text file using the windows standard text editor.
How can I launch the standard windows image viewing application in order to show a png image?
I can not find the correct name of the standard viewing application.