text:
Q:  usage correctly? Can't get the columns to line up This is pretty painful.  I can't seem to line up my div's.  I just want 3 columns with input fields/description to the left.  I have tried to do this many ways and I just can't seem to get it to work.
This is the website if it helps, its a student project that a bunch of us got together and I am tasked unfortunately with programming the website.
http://www.fsaesim.com/Products.html
I'm fairly new to CSS but I have experience in HTML.  The Javascript file isn't included just yet but it worked the last time I had it uploaded, disregard that part.

    Tire Choice:
    &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp<select id="tireChoiceSel">
        <option value="1">Michelin 13"</option>
        <option value="2">Hoosier 13" Large</option>
        <option value="3">Hoosier 13" Small</option>
        <option value="4">Mexican Tires</option>
    </select>

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
Engine:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbs  p&nbsp&nbsp&nbsp&nbsp&nbsp<select id="engineSelectionSel">
        <option value="1">Yamaha R6 - 4 Cylinder</option>
        <option value="2">Yamaha WR450 - 1 Cylinder</option>
        <option value="3">Honda CBR600RR - 4 Cylinder </option>
        <option value="4">Suzuki GSXR600 - 4 Cylinder</option>
    </select>

    &nbsp&nbsp&nbsp
    Torque Curve:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<select id="torqueCurveSel">
        <option value="1">Cornell Curve 2008</option>
        <option value="2">MIT Curve 2008</option>
        <option value="3">RMIT Curve 2008 </option>
        <option value="4">Fullerton Curve 2008</option>
    </select>

    Vehicle Weight:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="vehicleWeightTxt" value="530" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    Number of NOS:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text1" value="100" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #1:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text2" value="3000" size="3" />

    Wheel Base: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp&nbsp&nbsp <input type="text" id="wheelBaseTxt" value="61" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #2:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text3" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #3:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text4" value="3000" size="3" />

    Wheel Radius: &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp&nbsp&nbsp<input type="text" id="wheelRadiusTxt" value="10.25" size="3"  />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #4:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text5" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #5:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text6" value="3000" size="3" />

    Track Width: &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="trackWidthTxt" value="50" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #6:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text7" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #7:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text8" value="3000" size="3" />

    Center of Gravity: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="hcgTxt" value="12" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #8:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text9" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #9:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text10" value="3000" size="3" />

    Weight Distribution: &nbsp&nbsp&nbsp<input type="text" id="weightDistributionTxt" value="0.50" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #10:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text11" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #11:&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text12" value="3000" size="3" />

    Shift RPM: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="shiftRpmTxt" value="9500" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #12:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text13" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #13:&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text14" value="3000" size="3" />

    Final Drive Ratio: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="ntTxt" value="2.86" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #14:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text15" value="3000" size="3" />

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    NOS Bottle #15:&nbsp&nbsp&nbsp&nbsp<input type="text" id="Text16" value="3000" size="3" />

    <input type="submit" value="Calculate" onclick="ShowCalculation(); return false;" />

A: You can't reliably line up text using  s. You can create the columns using floats, and use a similar technique to line up the labels with the selects - you just need to apply a consistent width to the labels.
Start by restructuring your HTML:
Tire Choice
<select id="tireChoiceSel">
    <option value="1">Michelin 13"</option>
    <option value="2">Hoosier 13" Large</option>
    <option value="3">Hoosier 13" Small</option>
    <option value="4">Mexican Tires</option>
</select>

Not only is that label good practise in terms of accessibility, it will also provide you a hook to target using CSS.
Then float your labels and give them an explicit width, e.g.
label { float: left; width: 10em; }

That will - more or less - get everything lined up. This isn't the whole story - depending on your requirements, you might want to make this more robust to handle different font sizes etc. - but it's a good start.

A: This will never work the way you are trying to do it. Between changing font widths and the rendering of non breaking spaces between browsers, its just a fail technique.
That being said, this could easily be considered tabular data, and so is entirely appropriate to use tables and rows. The cells will line up naturally, or you can use a row of spacers to set the column width, old school style.
This could definitely be done with divs or just styled elements, but I would go tables and rows on this.

A: 1. You should use
 sparingly:
- Utilize appropriate elements then combine them with CSS to form a line-break (in this case:  with CSS: (display: block))
2. Avoid styling the webpage using any markup:
- Instead of using   (an HTML Entity), you can use CSS' positioning (float or position) and spacing (padding or margin) properties.
3. Avoid using deprecated elements:
- The  is a deprecated element because it is presentational in nature, use CSS instead: (text-align: center).
4. Practice placing title for form elements to tell the user what the elements are for:
- You can chooose between  or placing a title attribute directly in the form elements:
Example:
A:
    Item Price:
    <input id="selection-id" type="text" />
B:
    <input type="text" title="Item Price" />
5. No, it's not a tabular data, because:

*

*The way you visually set it: the alignment 'seems' to not relate on each other (See left to right direction per row)

*It 'looks more like a list' because Tire Choice 'seems' to be related to Vehicle Weight until Final Drive Ratio.

*The <select> and <input> are elements of <form> and not
's (unless you want to place the form inside the table)


text:
Q: Bootstrap Overflow I design a new web site. I use bootstrap but ı hava a problem.

    asdasdlknadlamaslfknasjşklfnsadjşlkfnbasdşjlfksnadbfjşa

.red-border{
   text-align: center;
   margin-top: 50px;
   border: solid 2px red;
   height: 250px;
   margin-left: 20px;
}

When I wrote this code, ı see that.

Thank you everyone.

A: I'm not totally sure what result you are looking for but it looks like the column size you set in bootstrap col-md-2 is too small for your content. You could increase the size of it or handle the overflowing content in different ways. The following code will hide overflow:
.red-border{
  text-align: center;
  margin-top: 50px;
  border: solid 2px red;
  height: 250px;
  margin-left: 20px;

  // ADDED STYLE
  overflow: hidden;

}

A: What you need to do is "wrap" the text. just add this to your .red-border style:
word-wrap: break-word;

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# LINQ group and count questions I have the below query that groups up a bunch of printers and then calculates their downtime. What I would like to do is get how many printers are in each group. I'm not sure if I need to run two query or could I accomplish this in one?
Query:
var records = (from r in SharePoint.Records
    group r by new
    {
        Printer = getValue(r.Values["ows_printer_id_x003a_Device"]),
    } into g
    select new
    {
        Printers = g.Key.Printer,
        CurrentHours = g.Sum(x => getDownTime(x.Values["ows_Downtime"])),
        //  Total = g.Count()
        //CTDHours = g.Sum(x => x.Field<int>("CurrentHours") + x.Field<int>("CTDHours"))
    });

A: var records = (from r in SharePoint.Records
    group r by new
    {
        Printer = getValue(r.Values["ows_printer_id_x003a_Device"]),
    } into g
    select new
    {
        Printers = g.Key.Printer,
        CurrentHours = g.Sum(x => getDownTime(x.Values["ows_Downtime"])),
        Total = g.Count()
    });

Total = g.Count should work.
I'm curious why you're using getValue() here and I think that's where your problem might be.  Doesn't Printer = r.ows_printer_id_x003a_Device work?  Have you verified the data in the "ows_printer_id_x003a_Device" member, and does that part of the query produce the groupings you want?  Try using LinqPad to break it down.


text:
Q: Cassandra WHERE - Compare case-insensitive So I have a table with a username column (text).
Now I want to get a user by it's username but I want to perform the search case-insensitive.
In SQL you would do it like that:
SELECT * FROM users WHERE UPPER(username) = UPPER('foo');

But in CQL, there are no functions like UPPER or LOWER so how would I do that?
Thanks in advance!

A: See this thread: How to read cassandra data with out case sensitive
There are no features to check case sensitivity in Cassandra. Ideally you should write all the data through your application in lower case and stick with that. You could write a job to retrieve and update all the data as lower case as a once off.


text:
Q: Dynamic signal creation in VHDL and solution of VHDL error: Syntax error near "process" I'm new to the world of VHDL and I'm getting this error saying Syntax error near process. I checked for the solutions and found that there may be a missing end if statement but in my code I'm not having that problem.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.std_logic_unsigned.ALL;
USE ieee.std_logic_arith.ALL;
use STD.textio.all;

entity Main_Architecture is
port(
    SEN: out std_logic;
    reset: in std_logic;
    clk: in std_logic
    );
end Main_Architecture;

architecture Behavioral of Main_Architecture is
signal main_counter : std_logic_vector(7 downto 0)  := "00000000";
signal mux: std_logic_vector(1 downto 0) := "00";
signal output  : std_logic_vector(7 downto 0);
signal main_counter_int : integer range 0 to 127:=0;
signal main_generator : std_logic_vector(7 downto 0);

begin
process(main_counter,reset,clk)
    variable x: std_logic;
    variable y: std_logic;
    variable z: integer;
begin
    if(reset = '1') then
        main_counter <= (others => '0');
    end if;

    if(clk'event and clk='1') then

        if(mux="00") then                               --load main counter
            y:= main_counter(0);
            x:= (main_counter(0)XOR main_counter(6) XOR main_counter(7));
            main_counter(7 downto 1) <= main_counter(6 downto 0);
            main_counter(0)<=x;
            main_counter <= main_counter+'1';
            output(0)<=y;
            output(1)<=main_counter(0);
            output(2)<=main_counter(1);
            output(3)<=main_counter(2);
            output(4)<=main_counter(3);
            output(5)<=main_counter(4);
            output(6)<=main_counter(5);
            main_counter_int<=conv_integer(output);
            if(main_counter >= "11111111") then
                mux <= "01";
            end if;
        end if;

        if(mux="01") then
            if(main_counter_int < 2) then
                z:=1;
            else if(main_counter_int < 4) then
                z:=2;
            else if(main_counter_int < 8) then
                z:=3;
            else if(main_counter_int < 16) then
                z:=4;
            else if(main_counter_int < 32) then
                z:=5;
            else if(main_counter_int < 64) then
                z:=6;
            else if(main_counter_int < 128) then
                z:=7;
            end if;

        end if;

    end if;

end process;    -------- LINE 104  -------

end Behavioral;

Also I want to create a std_logic_vector which has a size from value z to 0. i.e. A vector of size z+1. How can i make it?

A: Question part 1
Without looking into any other issues in your code, I think the problem is this section, which I have re-formatted to show how many 'end if' statements you are missing:
    if(mux="01") then
        if(main_counter_int < 2) then
            z:=1;
        else
            if(main_counter_int < 4) then
                z:=2;
            else
                if(main_counter_int < 8) then
                    z:=3;
                else
                    if(main_counter_int < 16) then
                        z:=4;
                    else
                        if(main_counter_int < 32) then
                            z:=5;
                        else
                            if(main_counter_int < 64) then
                                z:=6;
                            else
                                if(main_counter_int < 128) then
                                    z:=7;
                                end if;

    end if;

I think you probably wanted to use elsif instead of else if.
Question part 2
For the second part of your question, assuming you want to produce code that can be realised in hardware, there is no such thing as a run-time sized std_logic_vector. The best you can do is to make your vector have the maximum size that it could need, then only assign or use parts of it, based on the value of 'z'.
A couple of other points:
USE ieee.std_logic_arith.ALL;

This is not a 'true' standard library, and there are many other answers where people recommend against using this library. If you need to perform math functions (e.g. +), USE ieee.numeric_std.all;, then create signals of type signed or unsigned. In your example, main_counter would be declared signal main_counter : unsigned(7 downto 0)  := "00000000";. Operations like + can then be performed on this signal, with no ambiguity as to whether it is supposed to be signed or not.
Lastly, the section:
        output(0)<=y;
        output(1)<=main_counter(0);
        output(2)<=main_counter(1);
        output(3)<=main_counter(2);
        output(4)<=main_counter(3);
        output(5)<=main_counter(4);
        output(6)<=main_counter(5);

could more compactly be written using the concatenation operator & as
        output(6 downto 0) <= main_counter(5 downto 0) & y;

Side note: output(7) doesn't seem to ever be assigned.


text:
Q: Trigger Oracle operator LIKE to respect a string format I'm trying to learn how triggers work and how to write them properly with a given exercise. I'm using SQL Developper with the version 4.2 of Oracle.
I have a table PERSON with these fields : 'matricule', 'pmatricule' and 'typpers'.
'typpers' is a letter to show if the person is a student (E), a professor (P) or other (X). 'matricule' is a chain of 3 to 7 numbers and 'matricule' is a chain with 'p' followed by a chain of 3 to 6 numbers. Example : 'p145', 'p123456'.
I want my trigger to check if the format of 'matricule' or 'pmatricule' is respected when someone wants to insert a row in the table PERSON.
CREATE OR REPLACE TRIGGER new_matricule
  BEFORE INSERT ON PERSONNE
  FOR EACH ROW

DECLARE
  new_pmatricule PERSONNE.pmatricule%type;
BEGIN
  IF((:NEW.TYPPERS = 'P' OR :NEW.TYPPERS = 'X') AND :NEW.pmatricule NOT LIKE 'p%______') THEN
    RAISE_APPLICATION_ERROR(-20100, 'pmatricule format is not good');
  END IF;
END;

My trigger works if I'm trying to insert a 'pmatricule' format like '52p' but it also activates when I'm trying to insert such as 'p145'.
I assume that my syntax is not good enough but I'm not finding the proper syntax to do that.
Has anyone an idea ?

A: First, simplify the syntax for the first part of the expression using in.  Then, if you want to count the number of characters, leave out the '%'.  Something like this:
  IF((:NEW.TYPPERS IN ('P', 'X') AND :NEW.pmatricule NOT LIKE 'p______') THEN
    RAISE_APPLICATION_ERROR(-20100, 'pmatricule format is not good');
  END IF;

This says that the "p" needs to be followed by six characters.  Your version says "at least 6 characters".
If you want two characters followed by a p, it would be:
:NEW.pmatricule NOT LIKE '__p'

Any number followed by a "p" would be:
:NEW.pmatricule NOT LIKE '%p'

If you want more advanced pattern matching, you probably want to use regexp_like().  It is much more versatile.
EDIT:
Based on your comment, you want:
where regexp_like(:NEW.pmatricule, '^p[0-9]{3,6}$')

This is probably the easiest way to write the condition.
If you mean 3-6 characters, you can use the cumbersome:
where :NEW.pmatricule like 'p___' or
      :NEW.pmatricule like 'p____' or
      :NEW.pmatricule like 'p_____' or
      :NEW.pmatricule like 'p______'


text:
Q: About Draw Ellipse in Static Control ( MFC) When I doubleclick in Static Control, I will draw ellipse in Static Control in the position of  mouse.(MFC);
But, It apears that:

And My code:
void CTreeShowLabel::OnLButtonDblClk(UINT nFlags, CPoint point)
{
//设置画笔
COLORREF black = RGB(255, 0, 0);
CPen pen(PS_SOLID, 1, black);
CClientDC Dc(GetDlgItem(IDC_TREESTATIC));
Dc.SelectObject(pen);
//在鼠标处画图
CPoint curPos;
GetCursorPos(&curPos);

CPoint point1(0,0);
point1.x = curPos.x - 50;
point1.y = curPos.y - 50;

CPoint point2(0,0);
point2.x = curPos.x + 50;
point2.y = curPos.y + 50;

    //画圆
Dc.Ellipse(CRect(point1, point2));
CStatic::OnLButtonDblClk(nFlags, point);

}
About the Circle is terrible.

A: It doesn't seem a good idea to draw the ellipse in the OnLButtonDblClk event catcher. You should create your own class derived from CStatic and overwrite the OnPaint method.
Then from the event catcher you should tell the static that it has to draw the ellipse and where (for instance two member variables: bool m_bDraw / CPoint m_DrawingPoint) and call Invalidate in the Static.


text:
Q: Perl - argument passing for function as function argument - nice and clear way Hello I have function to which I am passing arguments using hash, this way:
&group_AoA_to_HoA_by_AoAs_columns({
    AoA          => \@group_file_by_line_numbers_AoA,
    HoA          => \%group_file_by_group_names_HoA,
    key_index    => 0,
    columns      => "ALL",
    save_method  => \&append_or_overwrite,
    action       => "ADD"
});

In this function I am accessing passed variables this way:
my $AoA         = $args->{"AoA"};
my $HoA         = $args->{"HoA"};
my $key_index   = $args->{"key_index"};
my $columns     = $args->{"columns"};
my $save_method = $args->{"save_method"};
my $action      = $args->{"action"};

Argument "save_method" is name of another function (passed as argument to group_AoA_to_HoA_by_AoAs_columns function). This Function is also called (from group_AoA_to_HoA_by_AoAs_columns function) with some passed arguments:
$save_method->({
    action     => $action,
    position   => \$HoA->{ $array->[$key_index] },
    data       => [@selected_columns],
});

The argument "action" is passed first time for "group_AoA_to_HoA_by_AoAs_columns" function and second time to function which "save_method" is referring to. There is no other reason for this argument.
So finally my question is if it possible to rewrite this code to more uniform equivalent from which will be immediately clear that "action" parameter is only used by function which "save_method" is referring to? Something like this would be fine:
&group_AoA_to_HoA_by_AoAs_columns({
    AoA          => \@group_file_by_line_numbers_AoA,
    HoA          => \%group_file_by_group_names_HoA,
    key_index    => 0,
    columns      => "ALL",
    save_method  => \&append_or_overwrite({
                          action       => "ADD"
    })
});

A: You can use anonymous function if you want call append_or_overwrite with specified parameter,
save_method  => sub {
  # 'return' is optional
  return append_or_overwrite({
                      action       => "ADD"
  })
}

A: One option is to wrap the reference to your save method in an anonymous subroutine that provides any static arguments:
save_method => sub { append_or_overwrite({ action => 'ADD', %{shift()}}) },

The %{shift()} allows you to specify any additional arguments using the same pass-a-hashref convention that you do at present:
$save_method->({
    position => \$HoA->{ $array->[$key_index] },
    data     => [@selected_columns],
});

An alternate approach would be to specify the save method using an array reference where the first value is a CODE reference and any additional values are arguments to it.
save_method => [\&append_or_overwrite, action => 'ADD'],

Invoke it as:
my ($code, @args) = @$save_method;
$code->({
    position => \$HoA->{ $array->[$key_index] },
    data     => [@selected_columns],
    @args,
});

Tangent: Passing the save method data as [@selected_columns] creates a (shallow) copy. If you don't need a copy (because the save method doesn't modify it) it's better to write \@selected_columns to pass a reference to the original array. Similarly, I'm not sure why you're passing position via \$HoA->{ $array->[$key_index] } which appears to be a reference to an array reference instead of passing it the array reference directly as $HoA->{ $array->[$key_index] }.


text:
Q: Flash drive in OpenBSD: "specified device does not match mounted device" I have a small server running OpenBSD 4.4. I'm trying to plug in a 16GB USB flash drive to move some files. I followed the guidance of the Disk Setup documentation, and found the label and filesystem of the desired partition. But when trying to mount the partition, I get the following:
# mount -t ext2fs /dev/sd1i /mnt/flash
mount_ext2fs: /dev/sd1i on /mnt/flash: specified device does not match mounted device

I googled a bit, but nothing I found was particularly helpful. Can anyone shed some light on this message?
Edit:
Additional Info
# disklabel sd1
disklabel: warning, DOS partition table with no valid OpenBSD partition
# /dev/rsd1c:
type: SCSI
disk: SCSI disk
label: SanDisk Ultra
flags:
bytes/sector: 512
sectors/track: 63
tracks/cylinder: 255
sectors/cylinder: 16065
cylinders: 1946
total sectors: 31266816
rpm: 3600
interleave: 1
trackskew: 0
cylinderskew: 0
headswitch: 0           # microseconds
track-to-track seek: 0  # microseconds
drivedata: 0

16 partitions:
#                size           offset  fstype [fsize bsize  cpg]
  c:         31266816                0  unused      0     0
  i:         31262427               63  ext2fs

A: Ok, it turns out I was missing the real error message, which dmesg reported as:
Ext2 fs: unsupported inode size

Once I found that, a little Googling showed me that only 128-bit inode sizes are supported for ext2fs in OpenBSD 4.4. I moved the flash drive back to a Linux machine, reformatted with mke2fs -I 128, and voila! The drive can now be successfully mounted on the BSD machine with the mount command given in the question.

A: Most likely you are calling the wrong filesystem type.
ext2fs is typically linux specific and most drives use a FAT I would try fat32 instead that should get it mounted for you.
You can tell what the partitionis with fdisk like so: (assuming /dev/sd1i is your device)
#fdisk -l /dev/sd1i

from: http://en.wikipedia.org/wiki/USB_flash_drive
Most flash drives ship preformatted with the FAT12, FAT16 or FAT32 file systems. The ubiquity of this file system allows the drive to be accessed on virtually any host device with USB support. Also, standard FAT maintenance utilities (e.g. ScanDisk) can be used to repair or retrieve corrupted data. However, because a flash drive appears as a USB-connected hard drive to the host system, the drive can be reformatted to any file system supported by the host operating system.


text:
Q: Automated JavaScript testing with Intern fails randomly We are using Intern to run a suite of functional JavaScript tests for our application, against an Ubuntu VM launched using Vagrant.
Each test bootstraps itself with a data file that generates some UI output. Each of the tests run successfully in isolation. In fact, in many cases the tests run successfully together too.
However, we occasionally see failures of a selection of the tests. Currently we have 16 tests which are being run against Chrome and Firefox. It is not unusual to see a list of failures of maybe 4 of the 16 tests. If I isolate those tests into a smaller suite and re-run the tool, the tests pass successfully again.
Now, in theory, the tests are individually isolated from one another and the actual number of failures varies each time this is run so I don't think the fault is that one test is affecting another. The server that is providing the platform for the testing is running locally, on a very well resourced machine.
Is there a way to write the tests or a way to run Intern that will give us more reliable results?

A: We have discovered what was causing our tests to fail randomly when run together as a suite. One of our tests used modifier keys such as [Shift] and [Ctrl]. The limited documentation we have for WebDriver says of the keys command:
Press keys (keys may still be down at the end of command).
It seems that sometimes this command was leaving a modifier key depressed and therefore active for the next test in the chain. As some of our other tests use [Tab] sequences to reach certain page elements, and [Shift][Tab] goes backwards through the page, our tests were failing depending on their position in the suite.
We do still have issues to do with timing but the situation of random failures has been isolated to this problem.


text:
Q: Waypoints not triggering My waypoints is not triggering and I have been trying for more than 2 hours to figure it out!
It should trigger console.log when scrolled to paragraph id="damn".
Can someone help out? Code is below...Thanks
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Animations</title>

<link rel="stylesheet" type="text/css" href="animate.css">

Want to become successful?

            <button id="btn1">Button 1</button>

First, you need the right mentality

A: Found the solution myself.
It acutally was working all along, it was just that I didn't know that you're supposed to scroll down with the top of your browser to the waypoints area.
Stupid mistake :)


text:
Q: Document and image thumbnails via GoogleApps Script not working I used to get the Google generated thumbnail for Google Docs files and image files when executing the code below but now I only get null values. I have even tried sharing the files as public on the web.
function testThumbnail(){
    var theFile = DriveApp.getFileById('PlaceTestFileIDHere');//Use a test file id here
    //Show that you have a valid file by logging the name
    Logger.log(theFile.getName());
    //Get the Thumbnail
    var aBlob = theFile.getThumbnail();
   //Test the thumbnail result
   if(aBlob == null){
       Logger.log('no Thumbnail');
   }
   else{
       Logger.log(theFile.getThumbnail().getBytes());
   }
}

A: function getThumbnailLink(fileId) {
  var file = Drive.Files.get(fileId);
  return file.thumbnailLink;
}

var selectedDocument  =  app.createImage(getThumbnailLink(theFile.getId()))

Rather use the Drive service as shown above it works very well.


text:
Q: Global database in Microsoft-Access I have an Access program to create and search data (it's an inner system for my work- without any connection to the internet, but we do have a local drive).
How can I make a global database for Access?

A: I think you need to create a db with tables to be shared (the global db) and another db with forms, queries,reports,and code (the client db) . Make one copy of the shared db and put it on a shared drive on your LAN. You use the Access "link" feature to connect to the tables in the global db from the client db. The client db is then distributed to your users and resides on each of their local drives.


text:
Q: Embedding videos using media9 I'm really new to LaTeX and I'm not very good with computers. I'm trying to put videos into my PDF's. I'm using media9 and I've got the following going so far.
\usepackage{media9}

 \includemedia[
    width=0.6\linewidth,
    height=0.45\linewidth,
    addresource=/Users/tristanjohnson/Library/texmf/tex/latex/misc/media9/Ruinn.MP4,
    activate=onclick,
    deactivate=onclick,
  ]{Movie}{Ruinn.MP4}

\mediabutton[ mediacommand=some_dice:playPause, overface=\color{blue}{\fbox{\strut Play/Pause}}, downface=\color{red}{\fbox{\strut Play/Pause}}
]{\fbox{\strut Play/Pause}} \mediabutton[
mediacommand=some_dice:setSource [(random.mp4)] ]{\fbox{\strut random.mp4}} \mediabutton[
mediacommand=some_dice:setSource [(cube.mp4)] ]{\fbox{\strut cube.mp4}}

I merely copied and pasted the mediabutton stuff. When I hit "Typeset" it runs without any errors. But when I click the play button nothing happens. I want the video embedded in the PDF so other people can see the video without having to have the file locally. Help?

A: Media files to be played back are usually embedded into the PDF (although playing files from remote URLs via http and rtmp protocols is supported too).
Media9 implements playback of media files inside PDF documents using the FlashPlayer plugin in Adobe Reader. This feature is currently available on the Windows and OSX platforms.
Two prerequisites are necessary: The media file (a video in the MP4/H.264 or FLV formats) and a media player in the Flash format (e. g. VPlayer.swf provided by Media9).
The latter is embedded by setting it as the last argument of \includemedia, while option addresource=... instructs LaTeX to physically embed a video file into the PDF.
Furthermore, VPlayer.swf needs to be told what to play. Flash applications are configured via FlashVars. For this, \includemedia provides the flashvars option. The most important FlashVar of VPlayer.swf is source=... which sets the media source. More FlashVars exist, e. g. for setting the sound volume, or loop which tells VPlayer.swf to infinitely replay the video. Refer to the Media9 documentation for other configuration options.
It is a good idea to place media files for embedding into the directory of the document you are about to write, or into a sub-directory of it. Lets assume Ruinn.MP4 is in the subdirectory videos. A minimal working example would read:
\documentclass{article}
\usepackage{media9}

\begin{document}

\includemedia[
  width=0.4\linewidth,
  height=0.3\linewidth,
  activate=pageopen,
  addresource=videos/Ruinn.MP4,
  flashvars={source=videos/Ruinn.MP4}
]{}{VPlayer.swf}

\end{document}

Note that the paths to the video file used with the addresource option and with the source FlashVar must be identical. Further note, that MP4 is only a container file format for video. The video data inside the file must be encoded with the H.264 codec. Another option is the FLV file format.


text:
Q: Dynamically added controls are not visible in UWP C# I'm trying to create a download manager for UWP in C#. I need to add ProgressBar for download progress, TextBlock for showing download status and another TextBox for displaying download file name. My code works fine when I compile only download manager's code separately (on a new uwp app). It shows progress properly in runtime.
My codes are-
private async void Downloadbtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        Uri url = new Uri(urlBox.Text);
        string fileName = ResolveName(urlBox.Text);
        FolderPicker folderPicker = new FolderPicker();
        folderPicker.ViewMode = PickerViewMode.List;
        folderPicker.FileTypeFilter.Add("*.*");
        StorageFolder downloadfolder = await folderPicker.PickSingleFolderAsync();

        if (folderPicker != null)
        {
            StorageFile downloadFile = await downloadfolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
            BackgroundDownloader downloader = new BackgroundDownloader();
            operation = downloader.CreateDownload(url, downloadFile);

            try
            {

                TextBlock fileNameText = new TextBlock();
                fileNameText.Text = fileName;
                ProgressBar ProgressIndicator = new ProgressBar();
                ProgressIndicator.Name = "progress";
                TextBlock progressText = new TextBlock();
                progressText.Name = "progressText";

                StackPanel panel = new StackPanel();
                panel.Children.Add(fileNameText);
                panel.Children.Add(ProgressIndicator);
                panel.Children.Add(progressText);
                MainStack.Children.Add(panel);

                cts = new CancellationTokenSource();
                Progress<DownloadOperation> progressCallBack = new Progress<DownloadOperation>(Progress);
                await operation.StartAsync().AsTask(cts.Token,progressCallBack);
            }
            catch (Exception)
            {
                await operation.ResultFile.DeleteAsync();
                operation = null;
            }

        }
    }

    private string ResolveName(string fileName)
    {
        if (fileName.Contains("/"))
        {
            int last = fileName.LastIndexOf("/");
            fileName = fileName.Substring(last + 1, fileName.Length - last - 1);
        }
        if (fileName.Contains("%20"))
        {
            fileName = fileName.Replace("%20", " ");
        }

        return fileName;
    }

    private void Progress(DownloadOperation operation)
    {
        ProgressBar c = new ProgressBar();
        c = (ProgressBar)(MainStack.FindName("progress" ));
        TextBlock c1 = new TextBlock();
        c1 = (TextBlock)(MainStack.FindName("progressText"));

        double received = operation.Progress.BytesReceived;
        double toReceive = operation.Progress.TotalBytesToReceive;
        double progress = received * 100 / toReceive;
        ((ProgressBar)c).Value = progress;
        c1.Text = received + "KB received of " + toReceive + "KB";

        if (received == toReceive)
            c1.Text = "Download Completed";
    }

MainStack is the stackpanel where new download and its ui elements are added.
But UI elements (progressbar, textblock) are not visible when I'm putting above codes in a different app like-
private async void GetDownloadData(Uri uri)
    {
        string fileName = ResolveName(uri.tostring());
        FolderPicker folderPicker = new FolderPicker();
        folderPicker.ViewMode = PickerViewMode.List;
        folderPicker.FileTypeFilter.Add("*.*");
        StorageFolder downloadfolder = await folderPicker.PickSingleFolderAsync();

        if (folderPicker != null)
        {
            StorageFile downloadFile = await downloadfolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
            BackgroundDownloader downloader = new BackgroundDownloader();
            operation = downloader.CreateDownload(url, downloadFile);

            try
            {

                TextBlock fileNameText = new TextBlock();
                fileNameText.Text = fileName;
                ProgressBar ProgressIndicator = new ProgressBar();
                ProgressIndicator.Name = "progress" ;
                TextBlock progressText = new TextBlock();
                progressText.Name = "progressText";

                StackPanel panel = new StackPanel();
                panel.Children.Add(fileNameText);
                panel.Children.Add(ProgressIndicator);
                panel.Children.Add(progressText);
                MainStack.Children.Add(panel);

                cts = new CancellationTokenSource();
                Progress<DownloadOperation> progressCallBack = new Progress<DownloadOperation>(Progress);
                await operation.StartAsync().AsTask(cts.Token,progressCallBack);
            }
            catch (Exception)
            {
                await operation.ResultFile.DeleteAsync();
                operation = null;
            }

        }
    }

In the second code, I'm calling GetDownloadData(uri) method to initiate download rather than calling it upon button click event. And also this method is placed in different XAML page (other than main page).
The only problem with the second code is that, no progressbar or textblock is added at run time in MainStack (stackpanel). I tried solving this problem by replacing stackpanel with listview and listbox but problem doesn't resolve.
Any idea, what am I missing here.


text:
Q: CSS3: Vertically align an element while siblings maintain relative position I would like to center an element vertically and horizontally. The catch is that any sibling elements should maintain their position relative to the centered element. If the siblings are large enough, they may overflow the viewport. The siblings have variable heights.
I've started a code sample here: https://jsfiddle.net/hqmoz9xy/2/

html,
body {
  height: 100%;
}

body {
  margin: 0;
  padding: 1em;
}

body,
.container {
  box-sizing: border-box;
}

.container {
  border: 1px solid red;
  padding: 1em;
  width: 100%;
  height: 100%;
}

.main-display {
  width: 100px;
  height: 100px;
  background-color: #999;
  padding: 1em;
}

    Main box: this box should be at the center of the container.

These items should naturally follow the main box and not care about vertical centering.

Item 2

Item 3

This is easily accomplished using JS and negative margins but I would like to do it only with CSS. Is there a way to do this using flex?

A: You can use flexbox:
.container {
  display: flex; /* Magic begins */
  flex-direction: column;
}
.before, .after {
  flex: 1; /* If possible, center .main vertically */
  min-height: 0; /* Really, don't care about overflow, just center .main vertically */
}
.main {
  align-self: center; /* Center .main horizontally */
}

html,
body {
  height: 100%;
}
body {
  margin: 0;
  padding: 1em;
}
body,
.container {
  box-sizing: border-box;
}
.container {
  border: 1px solid red;
  padding: 1em;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.before,
.after {
  flex: 1;
  min-height: 0;
}
.main {
  width: 100px;
  height: 100px;
  background-color: #999;
  padding: 1em;
  align-self: center;
}

    Main box: this box should be at the center of the container.

These items should naturally follow the main box and not care about vertical centering.

Item 2

Item 3

A: setting negative margin to virtually reduce width down to zero for extra-info, using display:table to shrink on content and and center, you could do something like this :

html,
 {
  height: 100%;
}
body {
  min-height:100%;
  border: 1px solid red;
}
body,
.container {
  box-sizing: border-box;
}
.container {
  padding: 1em;
  display: table;
  margin: auto;
}
.main-display {
  width: 100px;
  height: 100px;
  background-color: #999;
  padding: 1em;
}
.extra-info {
  padding:0;
  margin:0;
  background:lightgray;
  margin-right: -50vw;
  max-width: 50vw
  /* size virtually reduce to zero with equal negative margin value*/
}

    Main box: this box should be at the center of the container.

These items should naturally follow the main box and not care about vertical centering.

Item 2

Item 3

A: I am not sure I quite understand what do you want but maybe ?
#main {
width: 100%;
height: 100px;
border: 0px;
display: -webkit-flex;
display: flex;
 }

#main div {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
 }

empty

Your box here

empty

You also can do it with margin only by setting left margin to 40% or 35% depending on your box width


text:
Q: Multicombox is not displaying tokens when value is selected from it I have one array of data and I want to bind that data to multicombobox.
I have binded that data to Multicombobox using javascript as shown below.
The problem is when I select any value from multicombobox, tokens are not displaying as per the default behavior of the control.
Please help me in this. As per my guess, this array is not associative array (do not have keys and values.) this might have caused this issue.
Below is the code:

var data = sap.ui.getCore().getModel("myModel").getData();
       var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData(data);
        this.getView().setModel(oModel, "myModel");

       var fruitsArray = data.fruits[0].names;
        for(var i = 0; i<fruitsArray.length; i++){
           var fruitsDD;
            if(!fruitsDD){
           fruitsDD = this.getView().byId("MCBId");
              }
          var oCoreItem = new sap.ui.core.Item();
              oCoreItem.setText(fruitsArray[i]);
               oCoreItem.setKey(fruitsArray[i]);
                 fruitsDD.addItem(oCoreItem);
           }
{
   "A":"Apple",
   "B":[
      {
         "key":1,
        "value":"ball",
         "fruits":[
            "Apple",
            "Orange",
            "banana",
            "Guava"

         ]
      }

   ]
}

XML view:
<MultiComboBox id="MCBId" width="280px" class="sapUiTinyMarginTop" ></MultiComboBox>


text:
Q: Dismiss Dialog on hyperlink click to another activity So i have a dialog that has a hyperlink like show below. When you click on it it opens up myacitivty over the current activity and the dialog box displaying over it.
"" + s + "" ;

My question is how do i close the dialog when i click the above hyperlink.


text:
Q: How many ways in which distinct people can get off a train I've been learning probability recently but I'm having trouble solving this question:
Suppose you have 50 people on a train and you have 4 stations you can get off at (call them Stations 1,2,3,4). If no one boards the train at any of these stations, in how many ways can the 50 people get off the train, assuming the people are distinguishable (I care who gets off where)?
If I didn't care who gets off where, then using stars and bars it would simply be 54 choose 3. But the problem for me arises in thinking when they're distinguishable. Right now my logic was for each of the 54 choose 3 ways, you can permute the groups among themselves in 4! ways. I'm pretty sure that's not right, but I don't know where to go.

A: We are counting the functions $f$ from a set of size $50$ to $\{1,2,3,4\}$.
To see this, for any person $p$ let $f(p)$ be the station she gets off at.
There are $4^{50}$ such functions.

A: You might be able to develop an intuition by trying smaller numbers
and building upward.
For example, suppose there is only one person on the train, and four stations.
In how many distinct ways can people alight from the train?
There are only $4$ ways, one for each station where the one person can alight.
Now put two people on the train. Presumably, the second person can alight
at any station regardless of what the first person does.
So for each way the first person can alight, we have $4$ independent
choices of where the second person alights;
so altogether $4$ times as many ways as before: $4 \times 4 = 16$.
Now put three people on the train. The first two can alight in any
of $16$ ways, as before, but for each of those ways the third person
has $4$ ways to alight, so the total number of ways is $16 \times 4 = 64$.
For four people, we have the $64$ ways the first three can alight,
and for each of those the fourth person can alight in $4$ ways,
so $64 \times 4 = 256$ altogether.
The pattern is, for $n$ people on the train:
For $n = 1$, the total is $4 = 4^1 = 4^n$.
For $n = 2$, the total is $16 = 4^2 = 4^n$.
For $n = 3$, the total is $64 = 4^3 = 4^n$.
For $n = 4$, the total is $256 = 4^4 = 4^n$.
And it's always going to be $4^n$ for $n$ people, because every
time we increase $n$ by $1$ we multiply the total by $4$,
and $4^n \times 4 = 4^{n+1}$.
You can prove this more rigorously by mathematical induction,
using the same idea.

A: Note that each person has 4 choices. So the answer would be $4^{50}$. Also you have made a mistake in the case of undistinguishable people (it should be ${53 \choose 3}$).

A: This is a problem of the form $x_1 + \dots + x_k = n$, where $k=4$ and $n=54$. A typical ball-picking problem, which is unordered and with replacement. The answer is therefore
$$\binom{n+k-1}{k}.$$
More information here: http://mathworld.wolfram.com/BallPicking.html .


text:
Q: What does ping not showing any results mean? I deployed a kolla-openstack and attached floating IP to an instance in it.
Now while I am trying to ping the IP I am getting no response, but when I do ctrl+c it shows 100% loss.
Now leaving this aside, if I try to ping an IP which is 100% not present in the network, I am getting a clear

I have two questions:

*

*How do I resolve the issue, what could be the most plausible issue?

*what is the meaning of ping not responding/not showing output but shows 100% packet loss mean?

A: There are many reasons why ping could fail. Firewalls are a major source of problems; for instance if the ICMP echo requests (what ping sends) are simply dropped by a firewall (here iptables on a Linux test virt) then that produces your first case of 100% packet loss:
[root@localhost]~# iptables-save
...
[root@localhost]~# iptables -I INPUT 1 -p icmp --icmp-type echo-request -j DROP
[root@localhost]~# ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
^C
--- localhost ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4004ms

Your second case may be legitimate, but can also be caused by a firewall rule that returns a suitable ICMP response, as simulated on the same test host:
[root@localhost]~# iptables -p icmp -h | grep host-unreach
   host-unreachable
   TOS-host-unreachable
[root@localhost]~# iptables -D INPUT 1
[root@localhost]~# iptables-save
...
[root@localhost]~# iptables -I INPUT 1 -p icmp --icmp-type echo-request -j REJECT --reject-with icmp-host-unreachable
[root@localhost]~# ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
From localhost (127.0.0.1) icmp_seq=1 Destination Host Unreachable
From localhost (127.0.0.1) icmp_seq=2 Destination Host Unreachable
^C
--- localhost ping statistics ---
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1000ms

So, 100% packet loss means that the echo requests (or maybe the responses on their way back) are being dropped by a firewall (or any network device) somewhere along the network route between the source and destination. "Host unreachable" means a firewall (or any network device anywhere along the route) is rejecting the echo requests with a specific ICMP response type.
Resolving the issue will involve figuring out the network topology (traceroute, checking the documentation, etc), using tcpdump or similar packet tracers, reviewing the firewall rules and logs, etc. This should be done from both the source and destination hosts, and may come to involve anyone who maintains the network systems (routers, firewall, load balancers that can fake network traffic, etc) between the source and destination.


text:
Q: Diffeomorphism from disk to plane I want to show that the disk $D = \{(x,y) \in \mathbb R^2 : x^2+y^2 < 1\}$, the open square $K = (-1, 1)^2$ and the whole plane $\mathbb R^2$ are all diffeomorphic to each other. Therefore I want to consider two functions, namely
$$f \colon D \to \mathbb R^2, \quad f(x,y) = \left(\frac{x^2+y^2}{1-x^2-y^2} \cdot x, \frac{x^2+y^2}{1-x^2-y^2} \cdot y \right)$$
and
$$g \colon K \to \mathbb R^2 = \left(\tan \frac{\pi x}{2}, \tan \frac{\pi y}{2}\right).$$
After calculating partial derivatives I know that both are differentiable (just like their inverses), but how to prove that they are even $C^\infty$ (e.g. infinitely often differentiable)?

A: The first map $f$ above has a problem: $Df(0,0)$ is the $0$ transformation. So it can't be a diffeomorphism.
Let's try $f(re^{it}) = \tan (\pi r/2)e^{it}.$ Then the inverse mapping is $f^{-1}(re^{it}) = [(2\arctan r)/\pi]e^{it}.$ Because $r=(x^2+y^2)^{1/2}$ is $C^\infty$ away from $0,$  as is $e^{it},$ these functions are $C^\infty$ away from $0.$ Near $0,$ they take the form $$re^{it} \to (a_1 + a_2r^2 + a_4r^4 +\cdots)\cdot re^{it},$$ where $a_1 \ne 0.$ That's the same as
$$(x,y) \to (a_1 + a_2(x^2+y^2) + a_4(x^2+y^2)^2 +\cdots)\cdot(x,y)$$
which is clearly $C^\infty$ near $0.$
Now relatively painless here is verifying $Df$ is nonsingular at each point in its domain. Near $0,$ we have $f(x,y) = a_1\cdot(x,y) +O(x^2+y^2).$ So $Df(0,0) = a_1I.$ Away from $0,$ you'll get
$$\partial f/\partial r = (\pi /2)\sec^2 (\pi r/2), \,\,\, \partial f/\partial t = \tan (\pi r/2)(ie^{it}).$$ Never mind the actual values, these are linearly independent vectors, in fact mutually perpendicular. This shows $Df$ is never singlular as desired.


text:
Q: Monitor goes in power save mode after startup My monitor goes in to Power Save Mode after Windows startup when plugged in to the DVI port. It works in safe mode, and also when I plug the computer in to the TV with HDMI the port.
I updated the drivers, and the monitor works on an other computer.
I also reset CMOS.
So my guess is a bad motherboard... Does anyone have an idea?
Here's the specs:

*

*Asus p8z68-v pro gen3

*Intel i7 2600k

*120 GB OCZ Agility 3

*16 GB RAM Blue Corsair DDR3

*H80 Corsair liquid cooling

*xfx PRO750W 80Plus bronze power supply

A: Have you tried going into the Control Panel and changing the power settings?
Also, you may want to try checking your video card to see whether it's loose/damaged.
Here's where I got my ideas from.

A: Just want to share my experience which is very similar to what is described but slightly different config. My set up:

*

*Asus p8z68-v lx

*Intel i7 2600k

*SSD

*16 GB RAM

*650W PSU

*ATI GPU card

*Dell 27-inch

After some fiddling, the issue disappeared when I replaced the graphics card.
Hope this helps.


text:
Q: How can I label a span of values on matplotlib axis? In my histogram, I need to annotate the X-axis like that:

The "0" label is spanning between two ticks since there is a separate bin for 0s only in the histogram, while rest of the axis is linear to indicate boundaries of other bins.
The underbrace is not crucial, but there shall be some indicator that "0" spans for entire bin.
The closest solution I found so far is "draw it yourself" (How to add group labels for bar charts in matplotlib?).
I am looking rather for .axvspan() equivalent for axis (as .axvline() is for ticks), like something intended for labelling .axvspan().

A: There is no ".axvspan() equivalent for axis". Also ".axvline()" is not "for ticks". And there is also nothing intended for labeling .axvspan().
So let's answer the question how to produce some red bracket (paranthesis) below the plot. You can basically just plot a line in form of the bracket and position it according to the xaxis transform. Below is a function to do that.
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.bar(range(-1,5),range(3,9), width=1, align="edge", ec="k", alpha=1)
ax.set_xticks(range(1,6))

def bracket(ax, pos=[0,0], scalex=1, scaley=1, text="",textkw = {}, linekw = {}):
    x = np.array([0, 0.05, 0.45,0.5])
    y = np.array([0,-0.01,-0.01,-0.02])
    x = np.concatenate((x,x+0.5))
    y = np.concatenate((y,y[::-1]))
    ax.plot(x*scalex+pos[0], y*scaley+pos[1], clip_on=False,
            transform=ax.get_xaxis_transform(), **linekw)
    ax.text(pos[0]+0.5*scalex, (y.min()-0.01)*scaley+pos[1], text,
                transform=ax.get_xaxis_transform(),
                ha="center", va="top", **textkw)

bracket(ax, text="0", pos=[-1,-0.01], linekw=dict(color="crimson", lw=2) )
plt.show()


text:
Q: Would you use v3.5 of the ADO.NET Entity Framework, or wait for v4.0? I was surprised to find a public letter proposing a vote of no confidence in the entity framework (see http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/)
Would the reasons stated in the letter keep you from using the current version of the entity framework? Would you rather wait for v4.0? Or rather use another ORM?

A: The current version of EF is definitely not perfect, and has lots of gotchas and drawbacks. I probably wouldn't use it right now - but the upgrade path to EF v2 (or is it EF4?) sure looks pretty rosy!

*

*complete persistence ignorance - you can use your straight up POCO classes

*deferred loading configurable as an option

*much improved designer with support for pluralization/singularization (even in multiple languages!)

*ability to do "domain first" design and create database from your model

*ability to have self-tracking entities across multiple layers that allow you to send data to the client and get back changes and apply them to your entity context

All in all, EF v2 looks very promising and I'm very eager to give it a serious spin. If it really keeps all the promises out there right now, it's definitely a winner!
Check out the ADO.NET team blog for a flurry of recent blog posts on EF v2.
Marc

A: Another ORM.
Don't get me wrong you should get flamed with responses, but currently only nHibernate is functionally complete.
I'm a TDD fan, so want an easily testable POCO ORM solution. If that's your bag then EF3.5 is out. EF4.0 is introducing it (http://blogs.msdn.com/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx) , but it still has at least 1 big drawback -> doesn't support inheritance.
NHibernate is more complete, but EF could be easier to use. As ever, best tool for the job... but if it's an Enterprise-scale TDD developed app, go nHibernate.
Also -> there's a profiler that makes nHibernate dev much easier -> http://www.nhprof.com/

A: I tried using it for my current project, which basically involves rewriting our current mess of a data layer.
It just doesn't work.
First, if you're trying to base an Entity off of a View, the designer tries to force every NOT NULL property to be an entity key... which is pretty much never what I wanted.  To work around that you have to edit the xml in at least two places, and do it every time you add an object because it refreshes and re-adds the EntityKey properties.  Must specify mapping for all key properties in Entity Framework?
Second, when you are creating associations you MUST use every entity key - How can you make an association without using all entity keys in entity framework?
Those two things held me up for 3 days, then I went back to Linq to SQL and had it done in a couple hours.  (Well, at least the part of the system I was struggling with... )  I don't know if those are in the Vote of No Confidence, but it's just not ready in my opinion.
Also with the lack of answers I got here on every EF question I've asked, I have to assume current usage is so low that getting help and support is going to be difficult... which is possibly the BIGGEST reason not to use something.
Let's hope the next version is better...
EDIT: OUr current plan is to stick with Linq 2 SQL (I have to finish a project by Friday) and then evaluate all the other ORMs to see if anything else is better.  The other developer hates L2S for the record, but I've never had any major problems using it...

A: EF has some rich design time support, but I have to agree that nHibernate is the way to go, despite the learning curve.  If you need to make something fast and don't care about TDD or serialization (which is a large weakness of all of MS's ORM offerings) go EF.

A: Well My experience of Version 1 was interesting. I wanted to use POCOs but it didn't support it. After reading around I came across some code from a bod at microsoft that did this.
It was a bit messy to generate the code but on the whole this part of the process was not so bad.
A real nasty part that I came across was the lack of Concurrency checking built in, for N-tier development. You have to manage this yourself which after looking at the problem was not so bad, especially if you want to hand back the versioning back to the client for user intervention.
Second nasty and absolutely stupid thing missing was the IN keyword for LINQ queries. Not supported and so needs to be worked around. I found a solution but was a real mess bringing in some other code that quickly patched up the omissions.
Would I use EF 4.0 (2.0). Yes, absolutely, why not? In fact on stage 2 I will be using this. It looks like it supports POCOs, it looks like my concurrency model will move straight across with no problems (basically delta copy stuff). Its all good so far and I hope this time round that the Big guys at Microsoft have seen the errors of their ways and provided a solution that works.
If your buying into entity development and the whole Concept Model first thing, then its the only way to go for a complete Microsoft solution. Although the stuff being done on the M language might eclipse the idea and move the whole modelling thing back to the Database.
If you not buying into the Entity stuff then I would strongly go Enterprise Library. Its a proven technology that works every time built on a solid code foundation and Database centric paradigm. I would also go this route if you think that Stored Procedures are the bees knees and like what they bring to the table.
If your feeling really exotic and feel a bit frisky I would go with a NO-SQL approach such as CouchDB. This however does take some getting used to. Its damn weird and feels really really wrong. But things get developed in super quick time and the solutions seem to be robust and faster than expected. I would not got for this type of solution though if your big into Normalization and think that it can be applied to a NO-SQL approach. The whole model needs to be shifted on its head and the application will be needed to be modelled in a way that is driven by the technology applied.
I find the CouchDB way a bit dirty and very very wrong. But it has so many compelling reasons to use it, that I think it will seep into the psyche of every programmer, and it will definitely go mainstream in the next couple of years.
My biggest gripe still with the whole Entity thing though even in the new version 4 is that there really has not been much thought into N-tier environments. It still got a feel about it being a 2 tier solution with a lot of boiler plate code still needed to be done by the end user (developer), to get it working in a robust and dependable N-Tier way.


text:
Q: Source files are not open while Visual Studio editor says the inverse ok, let me give you an example of what problem i'm currently facing in my Visual Studio 2013.

*

*I open my solution (MVC 4).

*I double-click on a source file in the solution explorer and I put a break point somewhere in the code.

*I run the debugger and I navigate in my web application till the visual studio stops on my breakpoint.

*I press F5 to continue.
remark: the VS editor has closed my source file where the break point resides.

*I press "stop debugging" and I double click on the source file in my solution explorer to open it.
=> nothing happens, the source file is not displayed!

*I decide to start again the debugger and make the necessary navigation in my app in order to reach the break point.
=> this time, a tabbed window is displayed (Tab title=source not found).
It invites me to find my source file.
The functionality to "Browse and find" the file does not work neither.
Now, if i want to be able to display my source file again, i must go to the Visual Studio menu -> Window -> Close all documents.
After that, a double-click on the source file in the solution explorer opens and displays the source file
remark: In this menu Window option, i can see that my source file is listed in the opened documents(?!).
    So it means that, for the editor, the document is displayed correctly.
Somebody knows what is happening?
I tried to re-install Visual Studio and all updates (Update 4)... but nothing has changed.
Thank you.
Fred


text:
Q: WPF - DataGrid bind column to method instead of property I have a class that represents a vertex, which can have multiple attributes. Each attribute is identified by its name.
public class Vertex
{
    private Dictionary<string, Attr> attributes;

    public Attr GetAttributeByName(string attributeName)
    {
        Attr attribute;
        if (attributes.TryGetValue(attributeName, out attribute))
        {
            return attribute;
        }

        return null;
    }
}

I want to have a DataGrid that will have its ItemsSource bound to some ObservableCollection<Vertex>. Each column should represent one attribute of the vertex. And I want to control the columns at runtime (adding new columns or removing old ones). But I am not able to do that, because new column binding wants the name of property that it will get the cell data from. But I need the binding to call method GetAttributeByName() with the name of the attribute to get the data, rather than just getting a property.
string newAttributeName = "some_name";
DataGridTextColumn newColumn = new DataGridTextColumn();
newColumn.Header = newAttributeName;
newColumn.Binding = ???;

dataGrid.Columns.Add(newColumn);

Is there some way to do it?

A:
Is there some way to do it?

No, you can't really bind to methods like this.
But if you expose the Dictionary<string, Attr> as a public property of the Vertex class, you should be able to bind to this one:
string newAttributeName = "some_name";
DataGridTextColumn newColumn = new DataGridTextColumn();
newColumn.Header = newAttributeName;
newColumn.Binding = new Binding($"Attributes[{newAttributeName}]");


text:
Q: Cfdocument of pdf type not showing images? Through cfdocument I am generating a pdf file and sending the same to the user. But the images are not appearing on that pdf document.
I am not sure what type path i should use absolute/relative and what should be the value of localurl attribute?

A: We have had issues in the past with images not showing up in PDFs generated using CFDOCUMENT.  Our issue was that our HTTP server required the use of an IP address for internal ColdFusion requests.
Although we could view the image in the browser using either URL, CFDOCUMENT couldn't access the images using the domain name.  This might be your issue.
// works in browser ~ does not work in cfdocument
http: //mydomain.com/myimage.gif

// works in browser ~ works in cfdocument
http: //123.456.789.0/myimage.gif

A: you can reference the file location on the server if you are hosting it.
<img src="file:///#ExpandPath('/exportPages/img/spritelogo.gif')#">

note: The 3 slashes are not a typo.
You can read a bit more at Team Ravenglass


text:
Q: JAVA: Execution Order between Callables submitted to ExecutorService and Threads Outside of the ExecutorService A simplified version of what I am build has the following:

*

*A pool of threads (an ExecutorService), containing threads, each of which

*

*Sends an request message onto a server

*Waits for a the request fullfiled by continous checking on a shared data structure

*Outside of this thread pool, I have a MessageListener thread that

*

*listens to the server.

*Once the request is fufiled, it will raise a 'flag' in the shared data structure

*Thread in in the pool previously mentioned will notice this. And hence continue to complete itself.

I found that the MessageListener thread is ONLY executed AFTER the ExecutorService is terminated, not running concurrently with it, i.e. threads in the ExecutorService are blocking the MessageListener thread from running. This is obviously undesirable for my purpose.
I wonder if someone can provide me with some pointers that whether my conclusion is valid and if so, why? and what is a good approach to get around it.
I pasted some semi-psudeo code below to further explain.
public static final int NUM_TASK = 10;
public static final int TIME_OUT = 5000;
public static boolean[] shared_data = new boolean[NUM_TASK];

public static void main(String[] args) throws InterruptedException{

    // CREATE the receiver which will be set as an LISTENER for a JMS consumer queue that
    //  later the tasks in the Executor Service will send request to
    setupJMSProducerConsumer();

    // CREATE the Executor Service (pool)
    ExecutorService fixThreadPoolES = Executors.newFixedThreadPool(10);
    List<Future<String>> futures = new ArrayList<Future<String>>();

    for(int i = 0; i < NUM_TASK; i++){

            // Submit a Callable task to Replay the file
            MyTask task = new MyTask(i);
            futures.add(fixThreadPoolES.submit(task));
    }

    // GATHER the result here, based on futures
    // gatherResult(futures);

    // TERMINATE the ExecutorService
    fixThreadPoolES.shutdown();
    fixThreadPoolES.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}

private static class MyTask implements Callable<String> {

    private static final int WAIT_TIME_SLOT = 1000;
    int _idx = -1;

    public MyTask (int idx){
        _idx = idx;
    }

    @Override
    public String call() throws Exception {
        return run();
    }

    private String run() throws InterruptedException{

        // SEND request
        // sendRequest(_idx);

        // WAIT until the corresponding result in the shared data is set to 'true' by the corresponding LISTENER
        int timeWaited = 0;
        while (getSharedData(_idx) != true){
            timeWaited += WAIT_TIME_SLOT;
            Thread.sleep(WAIT_TIME_SLOT);
            if (timeWaited > TIME_OUT){
                return "Listener timed out, flag not raised, task incompleted for: " + _idx;
            }
        }

        return "Listener raised the flag, task completed for: " + _idx;
    }
}

public static class MyMsgReceiver implements MessageListener{

    @Override
    public void onMessage(Message msg) {
        String msgTxt = null;
        try {
            msgTxt = ((javax.jms.TextMessage) msg).getText();
        } catch (JMSException e) {
            e.printStackTrace();
            return;
        }

        for (int i = 0; i < NUM_TASK; i++){
            if (msgTxt.contains(String.valueOf(i))){
                setSharedData(i, true);;
            };
        }
    }
}

private static void setupJMSProducerConsumer(){
    com.tibco.tibjms.TibjmsConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(TIBCO_URL);
    Connection connection = factory.createConnection(TIBCO_USER, TIBCO_PASS);
    Session session = connection.createSession(false, 24);
    MessageConsumer consumer = session.creatConsumer(session.createQueue(QUEUE_NAME));

    MyMsgReceiver receiver = new MyMsgReceiver();
    consumer.setMessageListener(receiver);
}

public static synchronized boolean getSharedData(int idx) {
    return shared_data[idx];
}

public static synchronized void setSharedData(int idx, boolean val) {
    shared_data[idx] = val;
}

A: I see two things wrong in your code:
1) You don't synchronize the access to shared_data, therefore you're not performing atomic reads and writes to the array and this will lead to unpredicatble results. Any access to the shared array should be within a synchronized(shared_data) { } block, or more conveniently using synchronized getSharedData(int i) and setSharedData(int i, boolean value) methods
2) the wait loop in MyTask.run() isn't quite right either. The way it's implemented, if the boolean flag isn't true, then the task will systematically wait until the timeout expires, then report completion of the task, when in fact it doesn't know that the task is completed.
Instead, you should do something like this:
long start = System.currentTimeMillis();
long elapsed = 0L;
boolean flag = false;
while (!(flag = getSharedData(_idx)) &&
  ((elapsed = System.currentTimeMillis() - start) < TIME_OUT)) {
  Thread.sleep(1L);
}
if (flag) {
  // handle completion
} else {
  // handle timeout expired
}


text:
Q: Adding children over children in windows phone 7 canvas is responding slowly I am using canvas in wp7 silverlight application.
I am facing two problems.

*

*So on Canvas_MouseLeftButtonDown event capturing single point and then in MouseMove event i am capturing the other point and then drawing a line and adding this children to Canvas. Everything is going fine except that in mouse move event some points are missing between two if i move my finger a little bit fast and the result is that i am getting straight lines instead of curves.
For grabbing point I am using e.GetPosition(where e is MouseButtonEventArgs and MouseEventArgs  type).Is there other way through which i can grab point like using Touch class.

*If i have already drawn many lines(added many children to canvas) then adding more lines with different color over prior lines is slow and points are missing again resulting in straight lines. I think its happening becos capturing of points in MouseMove events over already drawn area is becoming slow and middle points are missing.
So please suggests me any solutions or way to handle this problematic scenario. Basically what i have to achieve is to add children over children with different colors and different stroke size as the finger moves over canvas.
I am attaching my current logic so please tell me where I am lagging.
Thanks in Advance.
Code:
    void myCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        currentPoint = e.GetPosition(myCanvas);
        oldPoint = currentPoint;
    }

    void myCanvas_MouseMove(object sender, MouseEventArgs e)
    {
            currentPoint = e.GetPosition(myCanvas);
            Line line = new Line() { X1 = currentPoint.X, Y1 = currentPoint.Y, X2 = oldPoint.X, Y2 = oldPoint.Y };
            line.Stroke = new SolidColorBrush(myColor);
            line.StrokeThickness = 10;
            line.StrokeStartLineCap = PenLineCap.Round;
            line.StrokeEndLineCap = PenLineCap.Round;
            this.myCanvas.Children.Add(line);
            oldPoint = currentPoint;
        }
    }

A: i worked on something very alike not too long ago, when i had problems i found this.
Derik Whittaker
I hope this helps! :)


text:
Q: Remove multiple records serverside with ajax and jquery I'm trying to delete multiple tables with a same class name,  my js code snippet works once and it doesn't loop to the next table unless the page is refreshed again.
when I comment my ajax call and just run it plain jquery it works fine. , I think there's an issue with my ajax call somewhere....
This jsfiddle url http://jsfiddle.net/ehsansajjad465/ExnkV/ has the snippet without the ajax....how do I make sure the ajax call works properly rather refreshing my page every time?
$(".closeprod").live("click",function(e){
        e.preventDefault();
        elem = $(this).parents('.tbl');
        //get serial number
        prodsn = $(".tbl").find(".prodsn:eq(0)");
        sn = $(prodsn[0]).html().substr(5);
                    tpl = "anything";

        url = "delprod.asp?email=<%=email%>&sn=" + sn + "&t=" + tpl + "&nf=notfeatured";
        //remove product from xml file
        $.get(url, function(data,status){
            if (data == "OK") {
                //remove product from template
                elem.remove();
            }else{

            alert("opps something is wrong")
            }
        });
    });

A: I figured it out this line prodsn = $(".tbl").find(".prodsn:eq(0)"); should be prodsn = elem.find(".prodsn:eq(0)"); and it worked like this


text:
Q: Save list getting from JSON URL in firestore collection My small app, is getting list of users from JSON link then store it in the List, I wanna this list into usersCollection collection ref of firestore

my code
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:yat_flutter_app/main.dart';
import 'usersList.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  CollectionReference usersCollection =
  FirebaseFirestore.instance.collection('users');

  Future<List<User>> getUsers() async {
    var data = await http
        .get("https://www.json-generator.com/api/json/get/bYKKPeXRcO?indent=2");
    var jasonData = json.decode(data.body);
    List<User> users = [];

    for (var i in jasonData) {
      User user = User(i["index"], i["about"], i["name"], i["picture"],
          i["company"], i["email"]);
      users.add(user);
    }

    return users;
  }

  @override
  Widget build(BuildContext context) {

    List<User> usersList = getUsers() as List<User>;

    return Container(

      child: Column(
        children: [
          FutureBuilder(
            future: getUsers(),
            builder: (BuildContext context, AsyncSnapshot asyncSnapshop) {
              if (asyncSnapshop.hasData) {
                return Expanded(
                  child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: asyncSnapshop.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Card(
                          elevation: 5,
                          color: Colors.cyan[50],
                          child: ListTile(
                            trailing: Icon(Icons.share),
                            title: Text(asyncSnapshop.data[index].name, style: TextStyle(fontFamily: 'Tahoma',fontSize: 20,fontWeight: FontWeight.bold),),
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage(
                                  asyncSnapshop.data[index].picture +
                                      asyncSnapshop.data[index].index.toString() +
                                      ".jpg"),
                            ),
                            subtitle: Text(asyncSnapshop.data[index].email,style: TextStyle(fontFamily: 'Tahmoma',fontSize: 18),),
                            onTap: (){
                              Navigator.push(context, new MaterialPageRoute(builder: (context)=>
                                  detailsPage(asyncSnapshop.data[index])
                              ));
                            },

                            onLongPress: ()=>

                                Fluttertoast.showToast(
                                    msg: asyncSnapshop.data[index].name,
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIosWeb: 1,
                                    backgroundColor: Colors.green[900],
                                    textColor: Colors.white,
                                    fontSize: 16.0
                                ),

                          ),
                        );
                      }),
                );
              } else {
                return Text("Loading, please wait...");
              }
            },
          ),

          ElevatedButton(
              child: Text('Save data'),
              onPressed: () => {

      usersCollection.add(getUsers()); // here's I am trying to add the result of getUsers into usersCollection

              }),
        ],

      ),
    );
  }
}

A: To push an object to Firestore you need to convert your object to map.
You can just add this function to your class:
  Map<String, dynamic> toMap() {
    return {
      'field1': value1,
      'field2': value1,
    };
  }

To push a List , you need to convert all objects to map, you can do it with following method:
  static List<Map> ConvertToMap({List myList }) {
    List<Map> steps = [];
    myList.forEach((var value) {
      Map step = value.toMap();
      steps.add(step);
    });
    return steps;
  }

Or simply , see how to convert List to Map
I hope it will be useful

A: Firebase realtime database and firestore are no SQL databases where data will be stored in Parent child relation or Tree structure.
For you to store list of data you can convert your list into Map
Map can be initialised as follows
Map<String, String> toMap() {
  return {
    'Fruit': "Mango",
    'Flower': "Lotus",
    'Vegetable': "Potato",
  };
}

After you have Map you can set value to the firestore. You can use the below code to set value
Map<String, Object> city = new Map<>();
//Loop through your list and load Map (City) values
db.collection("cities").document("LA").set(city)
.addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
    Log.d(TAG, "DocumentSnapshot successfully written!");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
    Log.w(TAG, "Error writing document", e);
    }
});

You can convert List of items to map using this
Java: How to convert List to Map

A: To push this list to Firestore you need to fromJson and toJson methods in your model class
 factory User.fromJson(Map<String, dynamic> data){
    return User(
        index: data['index'] as int,
        about: data['about'] as String,
        name: data['name'] as String,
        picture: data['picture'] as String,
        company: data['company'] as String,
        email: data['email'] as String );
  }

  Map<String, dynamic> toJson(){

    return {
        "index": index,
        "about" : about,
        "name" : name,
        "picture" : picture,
        "company" : company,
        "email" : email,
    };
  }

instead that I would like to suggest using json_serializable library
then you need to do some changes in your future method like this
getUsers().then((users) {
// add users to map
});

and then you can use fromJson method to push it to firestore database


text:
Q: How to use arrays or vectors of pointers polymorphically? I have read in many different posts regarding this matter, that arrays are not to be treated polymorphically and that one should use arrays of pointers instead, and the reasoning behind it is clear to me.
However, I cannot find an example of how it is done and I cannot seem to get it working. Consider the following piece of code:
#include <vector>

class Base
{
    public:
        Base();
        virtual ~Base();
};

class Derived : Base
{
    public:
        Derived();
        ~Derived();
};

void foo( std::vector<Base*> )
{
    // do something
}

int main()
{
    std::vector<Derived*> bar;
    foo(bar);

    return 0;
}

Compiling this gives the error message
could not convert 'bar' from 'std::vector<Derived*>' to 'std::vector<Base*>

Am I missing something or is the design even fundamentally flawed? Thanks in advance.

A: std::vector<Derived*> and std::vector<Base*> are different types and there are no conversions between them. But it looks like what you need is
std::vector<Base*> bar;
foo(bar);

i.e. let the polymorphism work at the level of the elements of the vector.
However, note that in order to use polymorphism in the usual sense, Derived has to inherit publicly from Base:
class Derived : public Base
                ^^^^^^

or
struct Derived : Base

A: To complete juanchopanza's answer, this is how you could use your std::vector<Derived*>:
void itemfoo(Base* item)
{
    // do something
}

template<typename Iter>
void foo(Iter begin, Iter end) {
    // do stuff per element
    while(begin != end)
        itemfoo(*begin++);
}

int main()
{
    std::vector<Derived*> bar;
    foo(bar.begin(), bar.end());

    return 0;
}

if you need to do an operation on the whole range and do it as Base* then you can do this:
void foo(Base** begin, Base** end) {
     // do stuff on range [begin, end)
}

int main()
{
    std::vector<Derived*> bar;
    if(bar.empty())
        foo(nullptr, nullptr); // or however you handle the empty range
    else
        foo(&bar[0], &bar[0] + bar.size());

    return 0;
}

A:
Am I missing something or is the design even fundamentally flawed?

An object of std::vector<Derived*> cannot be automatically cast to std::vector<Base*>. They are two completely different types.
I can think of the following options to address the issue:

*

*Change foo to accept a std::vector<Derived*>.
void foo( std::vector<Derived*> )
{
    // do something
}

*Change foo to a function template.
template <typename T>
void foo( std::vector<T*> )
{
    // do something with the implicit understanding that
    // T is derived from Base.
}

*Change the calling code to use std::vector<Base*>.


text:
Q: ABAddressBook search logic, potential leaks I have this code for searching in the AddressBook and xcode suggests me that i have potential leaks in firstName, lastName, and another object that is unknown even to xcode. I tried to release the first 2 of them and the warning disappears but my app is crashing. Also i have a random crash on this line, i got it only once but appears in crashlytics for other people. Do you see anything wrong with my code? Thanks.
ABMultiValueRef phoneNumbers = ABRecordCopyValue((__bridge ABRecordRef)evaluatedObject, kABPersonPhoneProperty);

The code. It's purpose is to group all the contacts by the first letter of the name and to duplicate the contacts in case they have multiple numbers.
- (void)filterByKeyword:(NSString*)keyword completionBlock:(AddressBookSearchCompletionBlock)completionBlock {

dispatch_async(abQueue, ^{

    [self.filteredContacts removeAllObjects];

    // Iterate over original contacts

    for (id evaluatedObject in self.allContacts) {

        CFStringRef n = ABRecordCopyCompositeName((__bridge ABRecordRef)evaluatedObject);
        NSString *name = (__bridge_transfer NSString*)n;

        if (name == nil) {
            RCLog(@"name is nil. skip this contact");
            continue;
        }
        if (keyword == nil || [[name lowercaseString] rangeOfString:keyword].location != NSNotFound)
        {
            NSString *key = [[name substringToIndex:1] uppercaseString];
            if (key == nil || [key isEqualToString:@"_"]) {
                key = @"#";
            }
            NSMutableArray *arr = [self.filteredContacts objectForKey:key];
            if (arr == nil) {
                arr = [[NSMutableArray alloc] init];
            }

            ABMultiValueRef phoneNumbers = ABRecordCopyValue((__bridge ABRecordRef)evaluatedObject, kABPersonPhoneProperty);
            signed long num = ABMultiValueGetCount(phoneNumbers);

            if (num == 0) {
                [arr addObject:evaluatedObject];
            }
            else {
                for (CFIndex i = 0; i < num; i++) {

                    if (i > 0) {
                        // Create a separate contact with the alternative phone numbers of a contact
                        NSString* phoneNumber = (__bridge_transfer NSString*) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
                        NSString* phoneNumericNumber = [phoneNumber stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
                        if (phoneNumber != nil && phoneNumber.length > 0 && phoneNumericNumber.length > 0) {

                            ABRecordRef persona = ABPersonCreate();

                            CFStringRef firstName = ABRecordCopyValue((__bridge ABRecordRef)evaluatedObject, kABPersonFirstNameProperty);
                            CFStringRef lastName = ABRecordCopyValue((__bridge ABRecordRef)evaluatedObject, kABPersonLastNameProperty);
                            ABRecordSetValue (persona, kABPersonFirstNameProperty, firstName, nil);
                            ABRecordSetValue (persona, kABPersonLastNameProperty, lastName, nil);

                            ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
                            bool didAddPhone = ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(phoneNumber), kABPersonPhoneMobileLabel, NULL);
                            if (didAddPhone){
                                ABRecordSetValue(persona, kABPersonPhoneProperty, multiPhone, nil);
                            }

                            if (ABPersonHasImageData((__bridge ABRecordRef)evaluatedObject)) {
                                ABPersonSetImageData(persona, ABPersonCopyImageDataWithFormat((__bridge ABRecordRef)evaluatedObject, kABPersonImageFormatThumbnail), nil);
                            }

                            [arr addObject:(__bridge id)persona];

                            CFRelease(multiPhone);
                            CFRelease(persona);
                        }
                    }
                    else {
                        [arr addObject:evaluatedObject];
                    }
                }
            }

            CFRelease(phoneNumbers);

            [self.filteredContacts setObject:arr forKey:key];
            RCLog(@"%i contacts for key %@", arr.count, key);
        }
    }

    self.filteredKeys = [[self.filteredContacts allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    dispatch_async(dispatch_get_main_queue(), ^{
        completionBlock();
    });
});

}


text:
Q: Is that possible calling content script method by context menu item in Chrome extension? I'm trying to use context menu item to invoke my method written in content script.
Is that possible?
As i have tried, context menu could only doing stuff in backend.
E.g.
// A generic onclick callback function.
function genericOnClick(info, tab) {
console.log("item " + info.menuItemId + " was clicked");
console.log("info: " + JSON.stringify(info));
console.log("tab: " + JSON.stringify(tab));
}

// Create one test item for each context type.
var contexts = ["page","selection","link","editable","image","video",
            "audio"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test '" + context + "' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                   "onclick": genericOnClick});
console.log("'" + context + "' item:" + id);
}

This example could not log info on current page but on background page.
I have one content script to generate something on specified page:
var showInfo = function(){ var dialogBoxWrapper = document.createElement("div");
document.body.appendChild(dialogBoxWrapper);}

and i need invoke this function by context menu.
What shall i do?

A: You can refer to following code as a reference, where upon click of a context menu a function in content script is invoked.
Sample Demonstration
manifest.json
{
    "name": "Content to Context menu",
    "description": "http://stackoverflow.com/questions/14452777/is-that-possible-calling-content-script-method-by-context-menu-item-in-chrome-ex",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "myscript.js"
            ]
        }
    ],
    "permissions": [
        "contextMenus"
    ]
}

background.js
function genericOnClick(info, tab) {
    console.log("item " + info.menuItemId + " was clicked");
    console.log("info: " + JSON.stringify(info));
    console.log("tab: " + JSON.stringify(tab));

    //Add all you functional Logic here
    chrome.tabs.query({
        "active": true,
        "currentWindow": true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "functiontoInvoke": "showInfo"
        });
    });
}

// Create one test item for each context type.
var contexts = ["page", "selection", "link", "editable", "image", "video",
    "audio"];
for (var i = 0; i < contexts.length; i++) {
    var context = contexts[i];
    var title = "Test '" + context + "' menu item";
    var id = chrome.contextMenus.create({
        "title": title,
        "contexts": [context],
        "onclick": genericOnClick
    });
    console.log("'" + context + "' item:" + id);
}

myscript.js
var showInfo = function () {
    console.log("Show Info is invoked");
}
var showAnotherInfo = function () {
    console.log("Show Another Info");
}
chrome.extension.onMessage.addListener(function (message, sender, callback) {
    if (message.functiontoInvoke == "showInfo") {
        showInfo();
    }
    if (message.functiontoInvoke == "showAnotherInfo") {
        showAnotherInfo();
    }
});

References

*

*Content Scripts

*Context Menu

*Extension API


text:
Q: Documentation for using 3rd party intellectual property for Google Play I am in the process of submitting an app to Google Play for review. This app is built for a 3rd party, but will be published by me.
Google Play allows this, but requests documentation showing that I have permission to use this IP.
Does anyone have any clue what kind of documentation I need in order to get this approved so that I can get it from my client?
This is the link to the form that I will be submitting to Google: https://support.google.com/googleplay/android-developer/answer/6320428


text:
Q: Ubuntu One doesn't share some of my directories I have Ubuntu One installed in my Ubuntu 13.04 laptop and inside a Windows7 virtual machine.
The main Ubuntu One directory is in sync, this is Ok.
I use this Win7 virtual machine only to use my desktop scanner. This vm collects all my scans inside a directory .../Scans.
I have configured Ubuntu One inside the Windows 7 virtual machine to sync this .../Scans directory too - I have checked the sync locally checkbox associated with this folder. It seems to work, synchronizing has been under processing, and the size allocated on the ubuntu cloud drive has grown up slowly, percent by percent. Now it shows "Files SYnc is up to date". So I should say the Ubuntu One service is working.
My problem: If I check the Ubuntu One directory inside my linux Ubuntu 13.04 laptop, the sync folder and its data won't appear ?
What should I do so as my linux Ubuntu 13.04 has access to this Scans/ directory that is in sync with my win7 ?

A: You should check "sync locally" on your Ubuntu 13.04 client too. To ensure that your .../scans file is uploaded to the cloud, you should explore your files from Ubuntu One
and see if this file is uploaded.
If yes, then you haven't checked the "sync locally" in you Ubuntu 13.04 too.


text:
Q: How to ask the user if they wish to input another value in c This is how i attempted it, how ever when i enter q it just skips a line in command and continues the program.
int main()
{
int a;
char c;
cont(&a);
while(a != 'q' && a != 'Q')
{
while ( ( c = getchar() ) != EOF)
{
    putchar( r13( c ) );
 }
}

return 0;
 }

A: You need to pass the reference of a to cont() -
void cont(int* a)
{
    printf("If you do not want to enter a value press q");
    scanf("%c", a);
}

and call it like that:
cont(&a);

otherwise, only the the copy of a (that is passed to the function) is changed, not a itself.
If you want to change the value of a in the function, then you need to store the return value somewhere, but you ignored it (e.g. a = cont(a);).
Or, give a reference (e.g. address of) a to the function, so it will be able to change the value of a.


text:
Q: Displaying reports for files using Python Question about general possibilities using Python here, I don't really know enough about programming to know whether it's something that's doable, and if so, how do I go about it.
I have a program which is a simple desktop program, which you load files into. The program can then output various properties of the thing that's in the file, and depending on what you ask it to do will output a report. It outputs the report in text format, but not as a file, and instead actually, just in the program itself displays the report. Like this:

My question is that if I want to get this text output for a large number of files, I'm currently manually loading the files individually into the program making the report, copying this to a text file, and saving the text file.
Basically I want to know whether it's extremely difficult to get Python to do this for me, or not. If it is doable, are the resources available for me to read about how it might be done? Are there conditions about being able to run my program and various commands from the Python command box?
Hope my question's clear enough. Sorry if it's a bit garbled.

A: The tricky part here is

The program can then output various properties of the thing that's in the file, and depending on what you ask it to do will output a report.

Basically, if the desktop application you use has a command line interface, it is possible and relatively easy.
If this program has command line option to open a document and output a report in any format (print the report on the standard output, write it into a file on the disk, etc.), you can call that commands from a script python for each files you set in a list.
If your software doesn't have a CLI (Command Line Interface), it might be possible but more diffficult. In that case, you have to automate actions by using a library that will emulate clicks on the Window of you software (1. Click on Open 2. Click, click, click to select the file to load 3. Click on the button to generate a report etc.) It's a pain, but it can be considered.
You will find plenty of resources to learn by yourself how to code a python script. You will probably need to learn about lists, loops, files manipulations and maybe the subprocess library which will let you call any command from your python script.
I suggest you to start with Python3 instead of Python2 because it has a better support for unicode that could quickly become an issue if you have non ascii characters in your input files or in reports from your software.
Good luck ;)

A: If the only way you can get report is selecting and copy/pasting it from program GUI, the situation just begs for AutoIt instead of Python.
With Python it would be much more difficult. Unless you want to improve your python knowledge or course...
Simulating keypresses, you can open specific file in program (through sending ctrl+o or alt and navigating file menu). Simulating mouse or keypress - start report generation. Then simulate a mouse click in text area, and perform something like:
(just a skeleton of script, probably need to be modified to suit your situation and needs)
send("^{a}^{c}") ; to select all and copy (if these keys are supported in this program
$text = ClipGet() ; get contents of clipboard
$fout = FileOpen("somefile.txt",2)
FileWrite($fout,$text)
FileClose($fout)

To fully automate the task, in script you can get a list of source files in specific folder, and run this macro for each of them, automatically naming resulting txt files.


text:
Q: Remove activity from stack, create new instance on Top My activity flow is like this
A -> B -> C -> B
When I launch B from C, the back stack should be re-ordered to:
A -> C -> B
I'm using FLAG_ACTIVITY_REORDER_TO_FRONT but that re-uses instance from stack, I don't need previous state (I need to call onCreate again.)
Update: Why I need it (Use case)
User navigates from A -> B (changes something here) -> C
Opens up Drawer Navigation on C and launches B.
B should be launched with initial state.

A: Use FLAG_ACTIVITY_REORDER_TO_FRONT and add an extra to the Intent, like this:
Intent intent = new Intent(this, ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("reinitialize", true);
startActivity(intent);

Then, in ActivityB do this to recreate the activity when it is brought to the front:
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (intent.hasExtra("reinitialize")) {
        // We need to recreate this activity
        Intent launchIntent = new Intent(this, this.getClass());
        startActivity(launchIntent);
        finish();
    }
}