text:
Q: How to Select XML Nodes with XML Namespaces with C# I have to analyze a XML doc with special namespace using C#, and I get some idea from this post. But my code fail to get the expected XML node, because the XML structure is very special...
There is a namespace in root node in XML
<MDOC xmlns="urn:schemas-microsoft-com/PSS/PSS_Survey01">

Here is my code to get this root node
        XmlDocument doc = new XmlDocument();
        doc.Load(path);

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("urn", "schemas-microsoft-com/PSS/PSS_Survey01");

        XmlNode root = doc.SelectSingleNode("MDOC", nsmgr);

Help me!

A: I am not sure what is special about your XML structure.
I would write the code little differently
string xmlNamespace = String.Empty;
XmlNamespaceManager nsmgr;
XmlNodeList nodeInfo = FABRequestXML.GetElementsByTagName("RootNodeName");
xmlNamespace = Convert.ToString(nodeInfo[0].Attributes["xmlns"].Value);
nsmgr = new XmlNamespaceManager(MyXml.NameTable);
nsmgr.AddNamespace("AB", xmlNamespace);

XmlNode myNode = MyXml.DocumentElement.SelectSingleNode("AB:NodeName", nsmgr);

Hope that helps


text:
Q: Inserting Memberpress Rule into Elementor I'm looking to protect Elementor content with a Memberpress Rule. I created a partial rule which provided a shortcode + PHP snippet. The shortcode widget doesn't seem to be protecting the content.
Any advice on how I can protect a block with this partial rule?
https://i.stack.imgur.com/Cc0cc.jpg

redpajama_set_name: RedPajamaStackExchange


text:
Q: input only numbers in the datatable WPF I have a Datatable, how to make, so the user can enter only numbers in rows Datatable?
DataColumn column;
            DataRow row;

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "Типы";
            column.ReadOnly = true;

A:  DataTable myTable = new DataTable();
 myTable.Columns.Add("numericColumn", typeof(Int32)); // for integer column
 myTable.Columns.Add("CharColumn", typeof(char)); // for character column
 myTable.Columns.Add("DecimalColumn", typeof(Decimal)); // for Decimal column


text:
Q: Unique Value For Each Button I have two php pages. The first page queries a database and places some data into a form
The second page, grabs the data submited from the previous page and displays the data.
THE ISSUE:
On the second page, the information is displayed in a table. At the end of each row, there is a "information" button that allows the user to click and see more details related to the data in that particular column. For some reason, the information button for every record in the table is holding the value of the first record returned in the database query. In other words no matter what button I click on in the table, it always relates to the first record returned in the query.
I'm hoping someone can help me find a solution to linking each "information" button to each unique record. In other words If I click the info button in row one, it will display the data for the record related to row 1...etc. Here's my code.
PAGE 1
<?php

$query = mysql_query ("SELECT  * from cust_data group by cabinet_number ORDER by cabinet_number ASC");

WHILE ($rows = @mysql_fetch_array($query)) {

    if (($rows['account_number']=="") &&
        ($rows['customer_first_name']=="") &&
        ($rows['customer_last_name']=="") &&
        ($rows['company_name']=="")) {

        echo '<form method="GET" action="cabinet_result_page.php">
                <input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
                <input type="hidden" value="'.$rows['company_name'].'" name="company_name">

                <input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['cabinet_number'].'" id="submit">
              </form>';

    } else if ($rows['cabinet_number']!=="") {

        echo '<form method="GET" action="cabinet_result_page.php">
                      <input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
                      <input type="hidden" value="'.$rows['company_name'].'" name="company_name">

                      <input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['company_name'].'" id="submit">
              </form>';
    }
  }
}

PAGE 2:
GRABS THE DATA IN PAGE ONE AND PLACES IT IN A TABLE.  WHEN THE 'INFO' BUTTON IS CLICKED, MORE INFORMATION IS DISPLAYED IN A JQUERY POPUP
db_connect();

$cabinet_number = $_GET['cabinet_number'];
$company_name = $_GET['company_name'];
$query = @mysql_query ("SELECT * FROM cust_data WHERE cabinet_number = '$cabinet_number' ");

WHILE ($rows = @mysql_fetch_array($query)) {

    echo'

            '; echo $rows['account_number']; echo'
            '; echo $rows['customer_first_name']; echo '
            '; echo $rows['customer_last_name']; echo '
            '; echo $rows['company_name']; echo '
            '; echo $rows['cabinet_number']; echo'
            '; echo $rows['key_tag_number']; echo'	';

    if ($rows['switch_and_port1'] =="") {

        echo '';

    } else if ($rows['switch_and_port1'] !== "") {

        echo '';
        echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '	';

    }

    {
        echo ''; echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '	';
    }

    echo '
';
    echo '
';
    echo '
';
    echo '

','  ', 'Cabinet: ', $id, '

';
    echo '
';
    echo '
';
    echo '';
    echo 'Power:     ', $rows['power_circuit'];
    echo '
';
    echo'';
    echo 'Sw/Po:     ', $rows['switch_and_port1'];

    if ($rows['switch_and_port2'] =="") {

        echo '';

    } else if ($rows['switch_and_port2'] !== "") {
        echo '
';
        echo '';
        echo 'Sw/Po:     ', $rows['switch_and_port2'];
    }

    if ($rows['switch_and_port3'] =="") {

        echo '';

    } else if ($rows['switch_and_port3'] !== "") {

        echo '
';
        echo '';
        echo 'Sw/Po:     ', $rows['switch_and_port3'];
    }

    if ($rows['switch_and_port4'] =="") {

        echo '';

    } else if ($rows['switch_and_port4'] !== "") {

        echo '
';
        echo '';
        echo 'Sw/Po:     ', $rows['switch_and_port4'];
    }

    echo '
';
    echo'
</form>';

}
echo'

                ';
}

A: The issue is that you are setting the same id attribute to all the modals (which is invalid HTML markup) and expecting the click handler on the button to figure out which one to open.
UPADTE
Another issue with your markup is that you can't have
s as siblings of a table row, it will produce unexpected results as browsers will attempt to fix the markup and rearrange the elements, you could place the divs inside a td or use a second loop to build them.
Now I also did some digging in your popup plugin and I must say it's not very well implemented, I would recommend you look for another one. That being said I did manage to get it working, here's what you need to do:

*

*Set an unique id for each of the modal divs, if you have some sort of id in your database data you can use that, if not then you can set up a counter variable inside the loop:
echo '
';

*Use the same id as the class for the button that should open the modal but add "_open" as a suffix:
echo '<input type = "image" src="images/view_details.png" height="16" width="16" class="my_modal'.rows['id'].'_open">

*You can now initialize the popup plugin on your divs and it will automatically assign the open action to the corresponding button:
echo'';

That should fix the modal problem, here's a working demo.
Now I also have a couple observations about your code:

*

*You should avoid the use of inline styles and as I mentioned earlier the  tag should be replaced for proper CSS, I would also suggest using CSS padding/margin to add space between words instead of

*This type of code:
if ($rows['switch_and_port1'] =="") {
    echo '';
} else if ($rows['switch_and_port1'] !== "") {
    echo 'SOME CONTENT';
}

can be optimized to just:
if ($rows['switch_and_port1'] !== "") {
    echo 'SOME CONTENT';
}

echoing an empty string produces no output whatsoever and there's no need for an elseif


text:
Q: how to keep the div content displayed even I browse through the pages of the site? I want to show the content of a div keeping displayed even I browse through the pages of the website. I want to place it fixed at the bottom and display an audio player. I've never studied AJAX, so I have no idea how it works. At the moment I would like to be able to view the contents of the div and later I will add the player. Can you help me or can you link a reference? Thanks in advance
I'm using wavesurfer js to display audio player.


text:
Q: Fancyhdr does not apply the right style I am using Latex for the first time, to write my thesis.
I organized my work as a main file that calls several others using subfiles, since I like to compile a single chapter while I am working on it. However, the chapters produced in this way do not have the same layout of the main file (this is a problem only for the final version, that I have to send to my supervisor).
I overcame this problem compiling the main file with all the code commented but the one necessary to produce the chapter I an intersted in, and changing \setcounter{chapter}{} in order to have the right number.
It works fine, but I saw that if I comment \pagestyle{plain} in the code below, the package fancyhdr does not apply the page style I defined. May someone explain me why? I expected that since I entered \pagestyle{MyStyle} then the style of the pages following this command should be MyStyle.
\documentclass[12pt,twoside,openright]{report}

\usepackage[english]{babel}

% Page layout
\usepackage[a4paper,
            inner=41mm,
            outer=32mm,
            top=43mm,
            bottom=44mm,
            headheight=20pt,
            headsep=\baselineskip,
            bindingoffset=0mm]{geometry}

\usepackage{emptypage}

\usepackage[T1]{fontenc}
\usepackage{mathptmx}

\usepackage{lipsum}

\usepackage{subfiles}

% Page style
\usepackage{fancyhdr}
% Defining MyStyle
\fancypagestyle{MyStyle}{%
    \fancyhead{}
    \fancyhead[RO]{\rightmark \ \ {\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt} \ \leftmark}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\chaptermark}[1]{\markboth{\thechapter. \ \textsc{##1}}{}}
    \renewcommand{\sectionmark}[1]{\markright{\thesection\ {##1}}}
}
% Redefining the PLAIN style
\fancypagestyle{plain}{%
    \fancyhead{}
    \fancyhead[RO]{{\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt}}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
}

\begin{document}

\pagenumbering{Roman}
\pagestyle{plain}

%Abstract

%Table of Contents

%Lists of Figures

%Lists of Tables

\clearpage

\pagenumbering{arabic}
\pagestyle{MyStyle}

% Previous chapters...

\setcounter{chapter}{3}
\chapter{Chapter Title}
\section{First section title}
\lipsum
\section{Second section title}
\lipsum

% Following chapters...

\end{document}

A: From the package manual section 9 "The scoop on LATEX's marks" (page 9):

You can influence how chapter, section, and subsection information
  (only two of them!) is displayed by redefining the \chaptermark,
  \sectionmark, and \subsectionmark commands. You must put the
  redefinition after the first call of \pagestyle{fancy} as this sets up
  the defaults.

More specifically the first call of \ps@fancy sets the defaults.
The definition of \fancypagestyle (from the fancyhdr.sty):
\newcommand{\fancypagestyle}[2]{%
  \@namedef{ps@#1}{\let\fancy@gbl\relax#2\relax\ps@fancy}}

Note that \fancypagestyle{MyStyle} is not executed until the first call of \pagestyle{MyStyle} is done. So if the \pagestyle{MyStyle} is the first call of a fancyhdr pagestyle it is also the first call of \ps@fancy. Hence the redefinitions of \chaptermark and \sectionmark in the second argument of \fancypagestyle are overwritten by the defaults. But if you call an other fancyhdr pagestyle before MyStyle or you use \pagestyle{MyStyle} again it works fine.
\documentclass[12pt,twoside,openright]{report}
\usepackage{emptypage}
\usepackage[T1]{fontenc}
\usepackage{lipsum}

% Page style
\usepackage{fancyhdr}
\pagestyle{fancy}% <- !
% Defining MyStyle
\fancypagestyle{MyStyle}{%
    \fancyhead{}
    \fancyhead[RO]{\rightmark \ \ {\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt} \ \leftmark}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\chaptermark}[1]{\markboth{\thechapter. \ \textsc{##1}}{}}
    \renewcommand{\sectionmark}[1]{\markright{\thesection\ {##1}}}
}
% Redefining the PLAIN style
\fancypagestyle{plain}{%
    \fancyhead{}
    \fancyhead[RO]{{\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt}}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
}

\begin{document}
\pagestyle{MyStyle}
% Previous chapters...
\setcounter{chapter}{3}
\chapter{Chapter Title}
\section{First section title}
\lipsum
\section{Second section title}
\lipsum
% Following chapters...
\end{document}

It is also possible to use
\documentclass[12pt,twoside,openright]{report}
\usepackage{emptypage}
\usepackage[T1]{fontenc}
\usepackage{lipsum}

% Page style
\usepackage{fancyhdr}

% Defining MyStyle
\fancypagestyle{MyStyle}{%
    \fancyhead{}
    \fancyhead[RO]{\rightmark \ \ {\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt} \ \leftmark}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\chaptermark}[1]{\markboth{\thechapter. \ \textsc{##1}}{}}
    \renewcommand{\sectionmark}[1]{\markright{\thesection\ {##1}}}
}
% Redefining the PLAIN style
\fancypagestyle{plain}{%
    \fancyhead{}
    \fancyhead[RO]{{\vrule height 13pt width 1pt} \ \textbf{\thepage}}
    \fancyhead[LE]{\textbf{\thepage} \ {\vrule height 13pt width 1pt}}
    \fancyfoot{}
    \fancyfoot[RO,LE]{}
    \renewcommand{\headrulewidth}{0pt}
}

\begin{document}
\pagestyle{MyStyle}% or \pagestyle{fancy} or \pagestyle{plain}
\pagestyle{MyStyle}
% Previous chapters...
\setcounter{chapter}{3}
\chapter{Chapter Title}
\section{First section title}
\lipsum
\section{Second section title}
\lipsum
% Following chapters...
\end{document}

Note that \pagestyle{plain}\pagestyle{MyStyle} only works if plain is redefined by \fancypagestyle{plain}{...}.

Additionally here is another suggestion using scrlayer-scrpage
\documentclass[12pt,twoside,openright]{report}
\usepackage{emptypage}
\usepackage[T1]{fontenc}
\usepackage{lipsum}

% Page style
\usepackage[automark,markcase=noupper]{scrlayer-scrpage}
\addtokomafont{pagehead}{\normalfont}
\addtokomafont{pagenumber}{\bfseries}
\providepairofpagestyles{MyStyle}{
  \rohead%
    [{\vrule height 13pt width 1pt} \ \pagemark]%
    {\headmark \ \ {\vrule height 13pt width 1pt} \ \pagemark}
  \lehead%
    [\pagemark \ {\vrule height 13pt width 1pt}]%
    {\pagemark \ {\vrule height 13pt width 1pt} \ \scshape{\headmark}}
  \renewcommand\chaptermarkformat{\thechapter. \ }
}
\DeclarePageStyleAlias{plain}{plain.MyStyle}

\begin{document}
\pagestyle{MyStyle}
% Previous chapters...
\setcounter{chapter}{3}
\chapter{Chapter Title}
\section{First section title}
\lipsum
\section{Second section title}
\lipsum
% Following chapters...
\end{document}


text:
Q: Elavon Converge - emvchipsale field ssl_tlv_enc I'm working on finishing an integration with a custom POS using an ipp320 and the Elavon Converge platform. I have EMV working with the ipp320 (using RBA SDK) to the authorization request message. Converge message emvchipsale for an EMV transaction requires ssl_tlv_enc which says it is the "encrypted tlv defining the EMV record" (including transaction amount). I have not been able to figure out where, how or even what data is in the single encrypted hex string.
The person I spoke to at the Elavon integration support did not have any information beyond what the API documentation has.
Does anyone know how to get the information as required by converge?

A: Answering in hopes someone else will find this useful and saves them a lot of time.
Turns out the documentation was wrong. It should have said "encoded tlv defining the EMV record" instead of "encrypted tlv defining the EMV record". This is what was causing the confusion. The encoding is documented in the EMV spec sheet.
Some very helpful TLV utilities can be found here: https://emvlab.org/


text:
Q: Альтернатива UIScrollView для более точного скроллинга? Есть такая линия времени, сделанная на UIScrollView:

Начало ограничено конкретной датой, а конец - текущей. Для определения даты и времени я преобразую contentOffset в секунды. Т.к. минимальный сдвиг оффсета ограничен 1.0 / UIScreen.main.scale, отсюда вытекает проблема, что при таком масштабировании минимальный сдвиг составляет несколько десятков секунд (при scale = 2).
Есть ли способ или альтернатива UIScrollView для определения более точного сдвига вплоть до 1 секунды? В популярных плеерах как-то же делают возможным сдвигать временную отметку посекундно.


text:
Q: Transfer a WordPress domain I recently wanted to transfer a wordpress.com blog on my own server.
The domain was purchased from wordpress.com, so WordPress is the owner of domain.
The domain was expired few weeks ago, and I didn't renew it from wordpress.com because I want to be the owner and purchase it from a registrar. Actually, the whois say that this domain will expire in 1 year, so WordPress has renewed it, in order to force me to purchase it on wordpress.com.
But since few days, even if I want to renew my domain on wordpress.com, WordPress say this domaine is already taken and I can't use it. But WordPress is still the owner of domain, and no one took it.
I don't get any answer from the WordPress support. So I don't know what I do for get my domain. Any ideas?
Thanks

A: You will probably need to renew the domain through wordpress.com and then follow these domain transfer steps to move the domain do another registrar.
https://en.support.wordpress.com/transfer-domain-registration/


text:
Q: ruby weird behavior with integer#times and modulo If I run this
100.times do |i|
  unless i == 0 || i.modulo(2) == 0
  p "odd number #{i}"
  end
end

I only get back odd numbers, which is the way it should work.
if I run this though
100.times do |i|
  unless i == 0 || i.modulo(3) == 0
  p "even number #{i}"
  end
end

then I get back a mixture of numbers, some of which are even.
Maybe it's me, or 'unless' isn't the best control to use here.  Kind of weird though that one gives me the result I want, the other not.

A: i.modulo(3) == 0 is not a test for odd; it is a is a test of numbers divisible by 3.
Recall the definition of even is divisible by two (or x % 2 == 0) and odd is !even. Therefore only modulo test for even vs odd is mod 2 with a result of 0 or 1.
Example:
100.times { |i|
     p "even number #{i}" unless i % 2==1 # better as if i % 2==0
     p "odd number #{i}" unless i % 2==0  # better as if i % 2==1
}

To keep it straight, you can also use .even? and .odd?


text:
Q: odd-pages printed as left pages...why? Sorry, I´m newbie to latex.
I´m using KOMA-Script Book as document class and two-sided document as page layout and I have the following problem: chapters do correctly start with their first page odd-numbered. BUT (and for me it´s a big BUT), as the title page (first page of the document) is the first page to be printed, the impact when printing the whole document is the following:

*

*chapters, although starting by an odd-numbered page, do start with their first page on the left-side (i.e. the first page of each chapter is on the back of the printed pages as you pile them).

Can anyone help me on this? Thanks in advance.

A: Without a working example, it's hard to diagnose, but I'm going to guess you're using a titlepage environment rather than \maketitle to generate your title page. If that's the case, it looks like there's a bug in the definition of the titlepage environment where it does a \newpage instead of \cleardoublepage in the \end{titlepage} command. Adding \cleardoublepage after \end{titlepage} should resolve the issue.
Update: Without a MWE, I'm unable to replicate the issue. The following produces the expected results without any special handling.
\documentclass{scrbook}

\begin{document}
\begin{titlepage}
 Titlepage
\end{titlepage}
\chapter{Chapter}
Chapterpage
\end{document}


text:
Q: Ran a wrong sed command. All source code files messed up So basically, I ran this:
sed -i '/s/icap_infos/icap_servers/g' *

instead of this:
sed -i 's/icap_infos/icap_servers/g' *

Notice the leading forward slash before 's' in the command?
Now all my source files have a weird text string scattered across the whole file. How do I fix this?

A: /s/ is a regular expression address that matches any line containing an s character. In GNU sed, itext is an extension to the standard
i\
text

that inserts text after the addressed line. So your command inserted text cap_infos/icap_servers/g before any line containing an s.
Assuming your original files contained no such files you should be able to reverse it using
sed -i.old '\:^cap_infos/icap_servers/g$:d' *

to delete lines matching cap_infos/icap_servers/g exactly. Note the use of alternate delimiter : (introduced by \:) since the pattern itself contains the default delimiter /. The current files will be backed up with suffix .old in case it doesn't work and you need to try something different.
In future get into the habit of dry-running sed commands without -i first and/or making backups using -i.bak instead of plain -i.

A: The /s/ is interpreted as an address, so the next command will only be applied for lines containing an s. This next command is i, inserting the following text, namely cap_infos/icap_servers/g.
Three things to do:

*

*As it is unlikely that you have intentionally lines with only cap_infos/icap_servers/g in it, you can delete them with sed '/^cap_infos\/icap_servers\/g$/d' (again, you address what to delete)

*Do the intended change

*Learn always to check the changes before using -i option in future


text:
Q: Why the validation errors dont appear? I have this function below to update the email of an authenticated user.
The issue is that if there are validation errors, the custom messages are not appearing in the view.
Do you know why?
public function updateEmail(Request $request){

    $rules = [
        'email' => 'required|email'
    ];

    $customMessages = [
        'email.required' => 'The email field is required.',
        'email.email' => 'Please insert a valid email.'
    ];

    $validator = Validator::make($request->all(), $rules, $customMessages);

    if ($validator->fails()) {
        return redirect(route('user.index', ['user' => Auth::id()]) . '#loginData');
    }

    $user = Auth::user();
    $user->email = $request->email;

    $user->save();

    Session::flash('success', 'Email updated with success.');

    return redirect(route('user.index', ['user' => Auth::id()]) . '#loginData');
}

View:

    @include('includes.errors')
    <form method="post" action="{{route('user.updateEmail')}}">
        {{csrf_field()}}

                Email
                <input type="email" value="{{$user->email}}" class="form-control" name="email">

                Email
                <button>Update Email</button>

    </form>

A: Change this:
if ($validator->fails()) {
        return redirect(route('user.index', ['user' => Auth::id()]) . '#loginData');
    }

Change to this, so that you can return the errors in the session and use {{$errors->first}} or foreach loop through them with $errors->all() as $error
if ($validator->fails()) {

    return redirect()->back()->withErrors($validator);
}

In laravel 5.6, when using the withErrors method, the $errors variable will automatically be shared with your view after redirection.


text:
Q: Recording all mouse click and keyboard events in linux [Python] I need a function that when will return true or false depending on whether a mouse event was recorded. Right now I'm using python-Xlib to record cursor positions, but the amount of documentation for the module is really sparse. It seems the only way to get familiar with it is to dig through the source code.
I'm not talking about keeping track of a gui being pressed or anything like that, I need raw input from the mouse.

A: Check out pyHook.
It handles tons of events at relatively low-level (Windows Only).
If you need examples, you'll find a lot of projects around the web, such as this one
If you are on Linux, there is also pyxhook


text:
Q: SQL Rollup to Sum Totals of a Grouped Table I have a table that is grouped by 'Group Type'.  What I need is for the last row to display the sum of the values in the above rows in the Total row.
Below is the code currently but I am not sure how to sum multiple fields at once.
Actual

Expected Result

Do I need to add another CASE statement to

select
CASE when GROUP_TYPE is null then 'Total' ELSE GROUP_TYPE END as 'Group Type',
Sum_Amount, TotalER, [Discount Report]
    from
    (select GROUP_TYPE, sum(cast(AMOUNT as float)) as Sum_Amount FROM [dbo].[a]
        where cast(ACTIVITY_DATE as date) between @startdate and @enddate
             group by GROUP_TYPE with rollup) a
left join
    (select [Charge Group] , sum(cast([Earned Revenue] as float)) as
    TotalER, sum(cast(Discount as float)) as 'Discount Report'
        from [dbo].[er] group by [Charge Group]) er
on
    a.GROUP_TYPE = er.[Charge Group]

select sum(cast([er] as float)) from [dbo].[er]

A: I would do a union all before the aggregation.  This makes it easier to specify the multiple aggregation sets:
select coalesce(group_type, 'Total') as group_type, -- the easy way
       sum(amount) as sum_amount, sum(er) as totaler, sum(discount) as discount
from ((select group_type, cast(amount as float) as Amount, 0 as ER, 0 as discount
       from [dbo].a
       where cast(ACTIVITY_DATE as date) between @startdate and @enddate
      ) union all
      (select [Charge Group], 0, cast([Earned Revenue] as float) as er, cast(Discount as float)
       from [dbo].er
       where cast(ACTIVITY_DATE as date) between @startdate and @enddate
      )
     ) aer
group by grouping sets ( (group_type), () );


text:
Q: Avoiding alert on key board shortcut of C# winform I am making key board shortcuts to a Winform application in C# using Visual Studio 2012. My shortcuts work perfect. But it gives a annoying beep sound.
I added e.Handled = true; and e.SuppressKeyPress = true; according to many threads. But it does not work and my winform stuck.
How can I avoid this?
private void textBoxSearch_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Down)
        {
            do stuff
        }
        else if (e.KeyCode == Keys.Enter)
        {
            //do stuff
        }
        e.Handled = true;
        e.SuppressKeyPress = true;
    }

and I need a solution for this too.
 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.F))
        {
            //do stuff
        }
        else if (keyData == (Keys.Control | Keys.G)) {
            //do stuff
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }

A: What you have in the KeyDown event should work.  The SupressKeyPress = true stopped the ding for me when I copied your code.
In the ProcessCmdKey event you would need this:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.F))
    {
        //do stuff
        return;
    }
    else if (keyData == (Keys.Control | Keys.G)) {
        //do stuff
        return;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}


text:
Q: Proving that $\sum_{n=0}^{\infty }\frac{3(n!)^2}{(2n+2)!}=\sum_{n=1}^{\infty }\frac{1}{n^2}=\frac{\pi ^2}{6}$ Proving that $$\sum_{n=0}^{\infty }\frac{3(n!)^2}{(2n+2)!}=\sum_{n=1}^{\infty }\frac{1}{n^2}=\frac{\pi ^2}{6}$$
I know the proving of second series which is very famous series to give us $\zeta(2)$, but I dont know how to prove the first series which is faster than second series, any help

A: Using the series expansion of $\arcsin^2(x)$ (see this question) given by
$$\arcsin^2(x) = \frac{1}{2}\sum_{n=1}^\infty\frac{(2x)^{2n}}{n^2{2n\choose n}}$$
we see that your sum is
$$\sum_{n=0}^\infty \frac{3(n!)^2}{(2n+2)!} = \sum_{n=1}^\infty \frac{3}{n^2{2n\choose n}} = 6\arcsin^2\left(\frac{1}{2}\right) = \frac{\pi^2}{6}$$


text:
Q: How can I sum the key value of a list of records? For example:
{defrecord Item [cost value]}
{def items [(Item. 20 50)
            (Item. 30 40)
            (Item. 10 70)]

How would I go about summing the cost of items? (so I'd get 60)

A: user=> (defrecord Item [cost value])
user.Item
user=> (def items [(Item. 20 50)
            (Item. 30 40)
            (Item. 10 70)])
#'user/items
user=> (reduce + (map :cost items))
60


text:
Q: If a function copies an element of a slice to a variable, is it working with a pointer to that element or a copy? Example situation:
There's a global struct holding a slice of structs.
type stctUser struct {
    user string
    privilege int
    created time.Time
}

type stctAllUsers struct {
    sync.RWMutex
    slcUsers []stctUser
}
var strctAllUsers stctAllUsers

There's a function that wants to operate on the users, and to reduce the time it's locking that global struct, I want to grab a user and release the lock
var strctUserTemp stctUser
strctAllUsers.RLock
for a := range strctAllUsers.slcUsers {
    if tmpName == strctAllUsers.slcUsers[a].user {
        strctUserTemp = strctAllUsers.slcUsers[a]
        break
    }
}
strctAllUsers.RUnlock

Is strctUserTemp working with a separate copy of slcUsers[a], or is it a pointer to that element of the slice? For example, strctAllUsers.slcUsers[a] is "Tom" and changing strctUserTemp.user = "Bob", would strctAllUsers.slcUsers[a] still be Tom?
(Before, it seems that making a copy of a slice to a new variable would mean changes to that new variable slice could change the original...so it assigned a pointer instead of creating a copy. Or am I misremembering?)
Update: Seeing as I was too stupid to take five minutes to test this out...here's a link to the behavior that had me questioning this in the first place, and I wanted to clarify the implementation before assuming I understood what was happening and creating a bug in the actual stuff I was working on. https://play.golang.org/p/ndmJ0h1z-sT

A: Most importantly: assignment always copies. However, it could be a copy of a pointer.
There are three basic scenarios:

*

*You have a slice of values. You assign an element from the slice to a local variable, creating a copy of the value. There is no connection between the local variable and the slice element.

*You have a slice of pointers. You assign an element from the slice to a local variable, creating a copy of the pointer. Changes to the pointed-to value will be reflected in any other use of the slice element, because the local pointer and the pointer in the slice point to the same memory.

*You have a slice of values. You assign a reference to an element from the slice to a local variable (e.g. myVar := &mySlice[0]). The local variable contains a copy of the reference created by the addressing expression. Changes to the local variable's value are reflected by any other use of the slice element, because the local pointer points directly to the memory where that slice element is held.

Note that the last option means you'll have a fragile pointer - if you append to the slice and the underlying array moves around in memory you'll get some confusing behavior.


text:
Q: When does f# async check its CancellationToken? I'm reading F# for fun and profit - Asynchronous programming. Under Cancelling workflows they have the following example:
let testLoop = async {
    for i in [1..100] do
    // do something
    printf "%i before.." i

    // sleep a bit
    do! Async.Sleep 10
    printfn "..after"
    }

open System
open System.Threading

// create a cancellation source
let cancellationSource = new CancellationTokenSource()

// start the task, but this time pass in a cancellation token
Async.Start (testLoop,cancellationSource.Token)

// wait a bit
Thread.Sleep(200)

// cancel after 200ms
cancellationSource.Cancel()

About this they say:

In F#, any nested async call will check the cancellation token automatically!
In this case it was the line:
do! Async.Sleep(10)

As you can see from the output, this line is where the cancellation happened.

However, for me (VS2010, F# 2.0, F# Interactive) I get the following output. Notice how it also prints ..after after I have canceled the token. Are they simply wrong?
1 before....after
2 before....after
3 before....after
4 before....after
5 before....after
6 before....after
7 before....after
8 before....after
9 before....after
10 before....after
11 before....after
12 before....after
13 before..
val cancellationSource : CancellationTokenSource

>
..after

So perhaps the check for cancellation is done when entering Async.Sleep? No, then it would've printed:
13 before....after
14 before..
val cancellationSource : CancellationTokenSource

>

So it seems like the check is actually in the for-loop! I.e. it keeps running until the for loop after being cancelled. Is this how it works? What then if I'd rather want it to check after the sleep?
This question seems to hint at cancellation working like I described above: Can I explicitly check for cancellation / terminate async computation?
Edit:
Regarding if this is only in FSI 2.0: What happens with the following loop, if one sleep 200ms, 2500ms and 4000ms respectively? Does it print middle?
let testLoop = async {
    for i in [1..5] do
    printf "%i before.." i
    do! Async.Sleep 2000
    printfn "..middle.."
    do! Async.Sleep 1000
    printfn "..after"
    }

A: I see the same results as you with F# 2.0 only in interactive Fsi. If I put the same code in a file and run fsi cancel.fsx, then the output does not have the final after and is what you expect.
Fsi v11 and v12 show the expected output for both ways of running the code.
This suggests there is some bug or difference when running Fsi v2.0 interactively that was fixed in a later version of FSharp.


text:
Q: Redshift SUM function issue I am facing an issue with the SUM function of the redshift.
I just used
SUM(col1) as T1 from "table_name" where ...

to fetch the data. Which have numeric type values in data type varchar of the column.
But it is not giving me correct total amount in T1.
An eg. col1 have two different row with the amount of "34.50". So it should return 69. But it is returning 68.
column "col1" data type is varchar.

A: You don't use the correct datatype, try casting it before like this:
SUM(col1::numeric) as T1 from "table_name" where ...

A: In redshift the easiest way to convert datatypes is like this
SUM(col1::numeric) as T1 from "table_name" where ...


text:
Q: parent div with img child with width: 100%, height: auto, always leaves 2px height gap I'm trying to have a stack of divs with fullscreen image as its child, but the parent div height doesn't match the img height.
The CSS is not too complicated
  .content {
    overflow: hidden;
    position: relative;

    min-width: 1024px

  }

  .content img {
    width: 100%;
    height: auto;
  }

Here's the JSBin http://jsbin.com/baqexonu/1/ , you'll notice a 2px gap between the divs
please help.

A: It's the white-space. Add line-height: 0 to .content.

A: You can also add display: block to .content img.


text:
Q: Area in between two concentric circles Area in between two concentric circles.
I am working on a problem and a bit stuck.
The problem is that we have two concentric circles, with the area inclosed by the inner circle equal to $7000\pi$ square meters . We are then given that the ratio of the circumference of the outer to the inner circle is equal to $8:7$ .
I realize that in order to solve this we need to understand the formulas for the area of a circle and the circumference of a circle.
Thus, we recognize that $C = 2\pi r$ and $A = \pi r^2$
We then conclude that $7000\pi = \pi r^2$ and find $r = \sqrt{7000}$
Now that we have this value, we need to find it in terms of the ratio $8:7$ in order to find the radius of the larger circle so that we can calculate its area and subtract that of the smaller circle. This is where I am stuck however, how do we convert the radius $\sqrt{7000}$ in to the appropriate ratio?
Do we just simply divide by seven and then multiply this value by eight?
Thanks.

A: $$7C_{outer}=8C_{inner}$$
$$7(2\pi r_{outer})=8(2\pi r_{inner})$$
$$14\pi r_{outer}=16\pi r_{inner}$$
$$r_{outer}=\frac{8}{7} \ r_{inner}$$
$$r_{outer}=\frac{8}{7}\sqrt{7000}$$

A: If you need to find the area between those two circles , use the hint given below :
$ \frac {Area_{outer}}{Area_ {inner}} =\frac{ R²_{1}} {R²_{2}}. \,$
$\frac{Area_{outer}} {Area_ {inner}} =\frac{ 64}{49}. $
$\frac{(Area_{outer} - Area_ {inner})} { Area_{inner}} = \frac{15} {49}.  $
${Area_{outer} - Area_ {inner}} = Area_{remaining} $
$ =\frac {15}{49}× Area_{ inner} = \frac{15}{49} × 7000π = \frac{15000π}{7} sq. unit$
Hope it helps.


text:
Q: How to tell whether zeros originate from trim or from actually writing zeros on an SSD Say if I write zero to a certain range of LBAs of a drive, then I TRIM those logical blocks (say, with blkdiscard or even hdparm). Given the drive has the Read Zero After TRIM behavior, is there a way for someone to tell whether the the logical blocks were TRIM'd or not?
(One way I could think of, which might work, could be a timed read to detect a faster response on trimmed data block than on a non-trimmed data block with all zeros, but this question is more about an API to just ask the disk.)

A: First, trim is not used for zeroing blocks.  Trim is used to tell an SSD that a block is no longer needed and its contents can be discarded.  The intent of trim is to actually help an SSD do write leveling by telling it that it can freely rewrite a block without first preserving its contents.  As such, it doesn't necessarily make sense to take an extra step to zero the block first.
The SSD trim standard states that reading a trimmed block will produce undefined results, rather than a zero block, although some versions of the standard do include a "read zero after trim" version of trim.  Since reading a trimmed block has undefined behavior, even ignoring cache issues, it is unlikely you will be able to tell if a block is trimmed by timing a read of it.  Writing to a trimmed block might not have a timing difference either, as write leveling might cause a different physical block to be written anyway.
Since trim is intended to discard blocks, a filesystem would not use trim on a block in a file -- but only on a block freed from a file.  So to ask if there is a way to tell if a block in a file has been trimmed makes no sense, because a filesystem would not do this to a file.   If you do have a filesystem with trimmed blocks in files, the filesystem is likely corrupt.  Even if you do have such a corrupt filesystem, the trim standard does not include any way to query if a block is trimmed, or even how many blocks on the SSD are trimmed.  A better question would be to ask if there is a way to determine if a block in a file is corrupt.  Some filesystems (e.g., zfs, others) do have this ability, but it may not be directly accessible outside of filesystem internals.  In a RAID, on reading a corrupt block, the raid might log this event, but will also reconstruct the block and likely rewrite a good block in its place.  If that fails, presuming the RAID doesn't just go offline, it might return an I/O error.
However if your filesystem is actually an image of a filesystem that is actually a file in another filesystem, fstrim can tell the operating system to release free blocks, which causes the underlying filesystem to actually create holes in the filesystem image file.  Unlike trim on SSDs, the behavior of holes in files is very well defined, and will always return zeros.  There are also (somewhat unportable) system calls that will allow a program to ask the filesystem where the holes in a file are.

A: I think you should ask the question in a better way, by not involving file or filesystem at all, since that seems to be your actual intest:

Say if I write zero to a certain range of LBAs of a drive, then I TRIM those logical blocks (say, with blkdiscard  or even hdparm). Given the drive has the Read Zero After TRIM behavior, is there a way for someone to tell whether the the logical blocks were TRIM'd or not?

And the answer (from me) is, unless the vendor provides some vendor-specific way to check the mapping of the logical blocks to the actual storage, or you manage to hack the controller by some means to do the equivalent, no, there's no standard way in common protocols / command sets for someone to tell reliably.

A: For NVME disks, there's a thing called DULBE, or Deallocated or Unwritten Logical Block Error. Here's a quote from chapter 3.2.3.2.1 Deallocated or Unwritten Logical Blocks in NVM Express® NVM Command Set Specification revision 1.0c October 3rd, 2022.

Using the Error Recovery feature (refer to section 4.1.3.2), host software may select the behavior of the controller when reading deallocated or unwritten blocks. The controller shall abort Copy, Read, Verify, or Compare commands that include deallocated or unwritten blocks with a status of Deallocated or Unwritten Logical Block if that error has been enabled using the DULBE bit in the Error Recovery feature.

For certain NVME disk models that support this feature, it seems you can utilize it to retrieve whether one block is trimmed/unwritten or not.
But I don't know any model by which this feature is supported, at least not by Samsung SSD 980 PRO 1TB or INTEL P4510 1TB:
# nvme id-ns /dev/nvme0n1 -H | grep "Deallocated or Unwritten Logical Block error"
  [2:2] : 0     Deallocated or Unwritten Logical Block error Not Supported


text:
Q: Unable to save R script as an R file When trying to save a script as an R file, I am not able to. The save as window opens, but the 'save as type' bar below the 'file name' bar is blocked/greyed-out. I am, however, able to save the script as an unreadable file. When I open it again to continue working on it, it cannot run. I then have to copy paste it to a new script to continue working on it and running the commands. I cannot seem to find many questions on the internet relating to this problem except this one: https://support.rstudio.com/hc/en-us/community/posts/219163988-Can-not-save-new-R-script-save-as-bar-grayed-out.
I have tried save() which does not work. I have also uninstalled R and installed the latest version of R, this does not help either. Would anyone know how to fix this problem so that I can save it as an R file?
EDITED:
I am using RStudio version 3.4.4. on the Windows 10 Home edition.
Processor: Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz.
RAM: 8.00 GB.
System type: 64-bit Operating System, x64-based processor.
Many thanks

A: friend!
I had the same problem as you. But what resolved was just put ".R" (example: save.R) in the end of the name, even with the grey bar, it generated the script automatically.
Hope it can help.

A: Windows 10 now prevents Rstudio to save a new document.
Give Rstudio permission, restart it and than it worked for me.

A: These other answers don't solve it for me. What I noticed is:

*

*Working off of a network drive is a nightmare for R Studio.

*Even if you do save it as an .R file, R Studio may not be able to open it.
What I did was:

*

*Paste my script into a notepad file; save it as .R

*Right click my .R file and Open With RStudio.
This minimizing RStudio doing the driving of opening files. And once the file is NAMED (it was named and saved as .R in notepad) RStudio seems to be able to save/overwrite changes to the file. It just cannot save the file the first time nor save TXT files it opens as .R files.
So yeah, for the initial script; template it in notepad and never change it's name.

A: By saving the R script with .R at the end automatically saves it as an R file!


text:
Q: Why don't black holes form from forces other than gravity? Gravity is the weakest of the fundamental forces, so what is so special about gravity that it can form an inescapably strong field while a force like the EM force cannot?  It seems to me that if there were some extremely strong electric field, that it would only have an influence on particles that carry a charge, and so it would make sense that a black hole could not from from the EM force because it could not affect particles like neutrons.  However, the same logic cannot be applied to black holes caused by gravity, because things like photons, which have no mass, still cannot escape the intense gravitational field.  Why does gravity influence things that have no "gravitational charge" while the EM force cannot influence things that have no "electric charge."  Because otherwise it would follow that a strong enough EM field should be fundamentally inescapable in the same way a black hole is inescapable. I know E=mc^2, so obviously a strong enough EM field would eventually act like a gravitational black hole, but why wouldn't it be easier for an EM black hole to form than a gravitational one since the EM force is so much stronger?

A: The forces other than gravitation include strong, electroweak, and electromagnetism.  The first two could not produce a black hole because they are both very short range forces.  Beyond dimensions much larger than an atomic nucleus, these effects (strong, electroweak) are negligible. Chiefly this is because the bosons that carry those forces soon decay into other particles outside of the range of atomic nuclei.
Coulomb forces (electromagnetic) do not create black holes for several reasons, but probably the best one is that a collection of like charges tend to repel each other, and mixed charges become electrically neutral outside of the scale of the atom (and thus are no longer able to attract additional charge of either sign, positive or negative.

A: The answer can be found in the nature of gravity. It is a force that arises due to curvature of spacetime which underlies everything. A black hole is a specific configuration of spacetime where nothing can leave by definition, not even light. Since there is no concept comparable to curved spacetime underlying the other forces, we observe no such phenomena.


text:
Q: Operations with lists I have the following list:
Words = ['This','is','a','list','and','NM,']

Note: Words[5] >>> NM, (with a comma(,))
New_List = []
for word in Words:
    if word[:2] =="NM":
        Words.insert((Words.index("NM")),input("Input a " + ac_to_word("NM") + ": "))
        Words.remove("NM")

Whenever I try to run this I get:
 Words.insert((Words.index("NM")),input("Input a " + ac_to_word("NM") + ": "))
ValueError: 'NM' is not in list

Yet "NM" is the in index 5. What's going on here? I am asking for word[:2] not the whole word.
I tried figuring out the problem,but no one was around to look at my code, and give me feedback, so I though maybe some people out there might be able to help. If you see a mistake, please show me where. Any help is appreciated!

A: Several problems:

*

*You're trying to access a string 'NM' in the list that has no such item.

*You're modifying the list as you iterate over it. Don't do this! It will have unexpected consequences.

An easier way here would probably be to iterate over the list indices instead of the items:
Words = ['This','is','a','list','and','NM,']
for i in xrange(len(Words)):
    if Words[i].startswith('NM'):
        Words[i] = input("Input a " + ac_to_word("NM") + ": ")

Notice that I'm simply replacing the NM... items with the result of input(). This is more efficient than inserting and removing elements.

A: The error is coming from here:
Words.index("NM")

'NM' is not in your list of strings.
Doing insert and remove operations on a sequence while you iterate over it is a bad, bad idea.  It is a surefire way to skip an item, or to double-operate on an item.  Also, you should not be doing linear searches with index since a) it is slow and b) what happens if you have duplicates?
Just use enumerate:
for i,word in enumerate(words):
    if word[:2] == 'NM':
        words[i] = input('replace NM with something: ')


text:
Q: Application Not Installed Android When I try to install my application on my phone it says "Application not installed"
Here is the code of my manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tasklite.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
    android:name=".TaskLiteApplication"
    android:label="@string/app_name" >
    <activity
        android:name="activity.TaskLiteActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="activity.PrefsActivity" />
    <activity android:name="activity.ToDoActivity" />
    <activity android:name="activity.ProjectActivity" />
    <activity android:name="activity.TaskActivity"/>
    <activity android:name="activity.TabLayoutActivity"
        android:theme="@style/taskLiteTheme"/>
    <service android:name="service.UpdaterService"></service>
</application>
</manifest>

EDIT: It's fix, the apk needed to be signed, i didn't had to change anything in the manifest file thank you

A: Try adding this attributes to <application > element in AndroidManifest.
    android:debuggable="false"
    android:testOnly="false"

A: Usually that means a few things.

*

*Are you installing this from eclipse onto a device? If so, have a look at your adb logcat output.

*Are you installing an exported, signed application from eclipse onto a device through email or a browser download? Then make sure you have Unknown sources enabled in Settings > Applications

A: If you have a release build on your phone, installing a debug version will fail, and vice versa.
Assuming you're going back and forth between debug and release versions, uninstall the one that's there, then install the new one.


text:
Q: React cannot read property of undefined when accessing from e.g. IF statement Redux turned my app state to props and I would like to access the properties of certain props once the API request is done. Yet, my page can't render as I get the above message.
kicking off GET reqest:
componentWillMount() {
  this.props.renderRoles(this.props.params.roleID);
};

Rendering users does work though:
renderUsers(){
  return this.props.roleDetails.userList.map((user)=>{
    return(

      {user.userName}

      );
     });
   };

  render() {

    const { handleSubmit, fields: {} } = this.props;

This is the problem part. Somehow, properties of this.props get undefined if I look for their properties:
    if (this.props.roleDetails.roleName){
    return (

If I only look for this.props.roleDetails, it does work, but not when for its properties:
    if (this.props.roleDetails){
    return (

  <form>

      {this.props.roleDetails.roleName}

Role Owner :

      {this.renderUsers()}

Apply

    </form>

    );
}else {
  return (

  );
}
  }
}

function mapStateToProps(state) {
return{
  roleDetails: state.api.roleDetails,
  refreshedRole: state.api.refreshedRole
}
}

export default reduxForm({
  form: 'roleView',
  fields: []
}, mapStateToProps, actions)(roleView);

Other similar questions are related to functions, but in my case is about accessing props therefore .bind(this) doesn't work.

A: if (this.props.roleDetails.roleName) looks like roleDetails undefined befor You get data with request, so if You will try to get access to it's property roleName you will get an error.
if (this.props.roleDetails && this.props.roleDetails.roleName) shouldn't throw errors.
And it's not good idea to fetch data in componentWillMount, use componentDidMount instead.


text:
Q: Cannot convert value of type 'CFTimeInterval.Type' to 'CFTimeInterval'? I'm going over a programming example in a book on Swift and have an initializer to an SKScene that looks like this:
class GameOverScene: SKScene
{
    init(size:CGSize,won:Bool,time:CFTimeInterval)
    {
       ...........
    }
}

This initializer is then called in another part of the program with the following line:
let gameOverScene=GameOverScene(size:self.size,won:true,time:CFTimeInterval)

It seems that this should all be fairly simple but then I get this strange looking error that says:

Cannot convert value of type 'CFTimeInterval.Type (aka 'Double.Type')
  to expected argument type 'CFTimeInterval' (aka 'Double').

Does anyone know (1) what this error means and (2) how to correct it?

A: CFTimeInterval is a type. It's not an instance of CFTimeInterval that you can pass into that function.
CFTimeInterval is a typealias to Double. So this function expects a value of type Double. 1.0, NaN, -1.5, Double.pi are all valid instances of Double. But what you're trying to give it is CFTimeInterval, which refers to the type itself.
This, for example, would work:
let gameOverScene = GameOverScene(size: self.size, won: true, time: 1.23)


text:
Q: Load text file into structure, check for searched word in list and delete from text file My problem is that I want to load and split data from text file into some python structure. From every split find exact line that starts with some word and check if It exists in list. If It exists delete It from file. Some records may have the same code, but will always have different data. Example:
Data.txt
0|A
1|B
5|C1
5|C2
7|User: 1111
0|D
1|E
5|F
7|User: 2222
0|G
1|I
5|J
7|User: 3333

And I want to load this file with every 0| so nested list should look like this:
[
 [
0|A
1|B
5|C1
5|C2
7|User: 1111
]
[
0|D
1|E
5|F
7|User: 2222
]
[
0|G
1|I
5|J
7|User: 3333
 ]
]

Then I have a list with user codes. If a user code exists in this list I want to delete this child-list. So I want to take the 3333 from 7|User: 3333 and check If it exists in list with user codes. Then after this check my nested list should look like this.
[
 [
0|A
1|B
5|C1
5|C2
7|User: 1111
]
[
0|D
1|E
5|F
7|User: 2222
 ]
]

and then I want to overwrite the loaded text file with this data:
Data.txt after
0|A
1|B
5|C1
5|C2
7|User: 1111
0|D
1|E
5|F
7|User: 2222

The problem is I don't really know how to do It all especially the loading part. Right now I only tried to load the file into nested list like this.
main_list = []
with open('input.txt') as f:
    for line in f:
        while not line.startswith('7|'):
            if line.startswith('0|'):
                help_list = []
            help_list.append(line)
        main_list.append(help_list)

print(main_list)

Any help would be greatly appreciated!

A: Since the records will be excluded by user and they can have repeated "fields", we use a dictionary with two entries: data, which is a list of lines in a record as you had on your question, and user, which saves the line with the user id (this line is also present in data, so the order when writing out is always preserved). The function create_record below creates this structure. If you are using python >= 3.7, you could use a dataclass to have a solution that is more elegant.
The code below first reads all the records in memory, then remove the ones with users that we are not interested and finally write the output in another file. Unless you have a very large number of records, this approach works well.
def create_record():  # Represents a record in the file, making the user line easily accessible
    return {'user': '', 'data': []}

current_record = None
records = []
# Note: well-formedness checks are not done
with open('Data.txt', 'r') as fh:
    for line in fh:
        line = line.strip()
        if not line:
            continue  # Skip empty lines, particularly empty lines in the end of the file
        if line.startswith('0|'):
            current_record = create_record()
            records.append(current_record)
        elif line.startswith('7|'):
            current_record['user'] = line   # Record the user line to make searching more efficient
        current_record['data'].append(line)

# Let's assume your list of user codes is a series of strings.
user_ids_to_delete = ['2222', '0000']
users_to_delete = {f'7|User: {user_id}' for user_id in user_ids_to_delete }  # Sets are used because checking set membership is faster

remaining_records = [record for record in records if record['user'] not in users_to_delete]

# Finally, save the file with the deleted users
with open('CleanData.txt', 'w') as fh:
    fh.writelines((f'{line}\n' for record in remaining_records for line in record['data']))

A: Here's one way to do it, using dataclasses:
from __future__ import annotations  # not needed PY 3.10+

from dataclasses import dataclass, field, InitVar
from pathlib import Path
from typing import TextIO

@dataclass
class User:
    id: int = field(init=False)
    codes: dict[str, int] = field(default_factory=dict, init=False)

    def add_id(self, line: str):
        id = self.id = int(line.rsplit(':', 1)[-1])
        return id

    def add_code(self, line: str):
        num, code = line.split('|', 1)
        self.codes[code] = int(num)

    def __str__(self):
        record = [f'{num}|{code}' for code, num in self.codes.items()]
        record.append(f'7|User: {self.id}')
        return '\n'.join(record)

@dataclass
class UserDict(dict):
    file_or_name: InitVar[TextIO | str]

    def __post_init__(self, file_or_name: TextIO | str):
        curr_user = User()
        contents: str = Path(file_or_name).read_text() \
            if isinstance(file_or_name, str) else file_or_name.read()

        for line in contents.splitlines():
            if line.startswith('7|'):
                id_ = curr_user.add_id(line)
                self[id_] = curr_user
                curr_user = User()
            elif line.strip():
                curr_user.add_code(line)

    def delete(self, *ids_to_delete: int):
        for id_ in ids_to_delete:
            self.pop(id_, None)

    def __repr__(self):
        prefix = self.__class__.__name__
        spaces = ' ' * (len(prefix) + 1)
        users_repr = f',\n{spaces}'.join(f'{id_}={user!r}'
                                         for id_, user in self.items())
        return f"{prefix}({users_repr})"

    def save_to_file(self, filename: str):
        with open(filename, 'w') as f:
            f.write(str(self))

    def __str__(self):
        return '\n'.join(str(u) for u in self.values())

if __name__ == '__main__':
    from io import StringIO

    # use a file-like object for simplicity
    file_obj = StringIO("""\
0|A
1|B
5|C1
5|C2
7|User: 1111
0|D
1|E
5|F
7|User: 2222
0|G
1|I
5|J
7|User: 3333
    """)

    users = UserDict(file_obj)

    # uncomment to read from file
    # users = UserDict('Data.txt')

    print(repr(users))
    print()

    user_ids_to_delete = [3333]
    users.delete(*user_ids_to_delete)

    new_file_contents = str(users)
    print(new_file_contents)

    # uncomment to update file
    # users.save_to_file('Data.txt')

Out:
UserDict(1111=User(id=1111, codes={'A': 0, 'B': 1, 'C1': 5, 'C2': 5}),
         2222=User(id=2222, codes={'D': 0, 'E': 1, 'F': 5}),
         3333=User(id=3333, codes={'G': 0, 'I': 1, 'J': 5}))

0|A
1|B
5|C1
5|C2
7|User: 1111
0|D
1|E
5|F
7|User: 2222


text:
Q: Giving 4 types of presents to 5 children. I have five children: Jackie, Tito, Jermaine, Marlon and Michael. I am going to give each of them a present. The available presents are: A candy, a paperback, a dolly, or a Mercedes.
I can't give Michael and Jermaine the same gift
I can't give Tito and Michael the same gift
I can't give Tito a paperback
In how many ways can I give each of my children a gift?
I was thinking 4^5 for total number of ways to give gifts with no restrictions.  Then subtracting 4^4 the number of times michael and jermaine have the same gift and 4^4 for the number of times tito and michael have the same gift. 4^4 for the number of times tito has a paperback.  Not sure what to add back on to the end to account for the double counting.  Will this work to start, and how can I finish?

A: We can try doing this with a direct counting argument.
Let's start with Tito. He can have any gift other than the paperback, which leaves us with three choices for him. Michael cannot have the same gift as Tito, which means that once Tito's  gift is decided, we have 3 choices for Michael. Jermaine should not get the same gift as Michael, which means Jermaine has 3 possibilities. Jackie and Marlon have no constraints which means they have  4 possible gifts each. The total number of ways to give the children gifts is $4^2 \times 3^3=432$.

A: Start giving in the order: Ti, Mi, Jer, Mar, Ja. $3\times 3\times 3\times 4\times 4=432$ possibilities.
Edit: svenkatr gives the details


text:
Q: How to fix in Blue Prism - Exception has been thrown by the target of an invocation I am trying to automatize SAP with Blue Prism.
The thing is that, for now I can write what I want in the fields I have spied (with SAP MODE) in Business Object. When I go to Process Studio and I send the data to the Business Object, it goes fine, until it gets to the Write Stage to use this data in the field from SAP, it does not work. It appears: Failed to perform step 1 in Write Stage 'Escrever o Nome' on page 'Action 1' - Exception has been thrown by the target of an invocation.
*I'm not using Code Stage yet.
Do you have any idea how to fix it?

A: This specific error is clearly documented within Blue Prism's Knowledge Base:

Why do I get "Exception has been thrown by the target of an invocation" error while using Write stage in SAP?
This error is due to the "sapgui/user_scripting_set_readonly" (SAP GUI
  Scripting Permission) profle parameter being set to TRUE[...]
How to resolve your issue
Ask your SAP security team or SAP administrator to set the
  "sapgui/user_scripting_set_readonly" to FALSE, and also ensure that
  the scripting is enabled in the SAP server and client.
These changes will allow Blue Prism to write into SAP.

Additionally, you really should review section 2. "Installation and Setup" in the Blue Prism's SAP Implementation Guide v1.4, as it has precise instructions that should be followed during installation and initial configuration in order to avoid errors like these.


text:
Q: Read Objects inside Array inside JSON object using Javascript In provided encoded JSON object that stores an array of objects that I want to read the value of Id/factorType/provider.
{"factors":{
    "factors":[{
    "id":"reytfufsiwdg",
    "factorType":"email",
    "provider":"ABC",
    "factorsProfile":{
    "email":"a...r@gmail.com"
    }}]}}

A: This would do it:
data.factors.factors.forEach(factor => {
    console.log(`ID is: ${factor.id}`)
  console.log(`Type is ${factor.factorType}`)
  console.log(`Provider is: ${factor.provider}`)
})

You can even try it here: https://jsfiddle.net/qe4a4Lmg/

A:

var data = {"factors":{
    "factors":[{
    "id":"reytfufsiwdg",
    "factorType":"email",
    "provider":"ABC",
    "factorsProfile":{
    "email":"a...r@gmail.com"
    }}]}};

   for(var key in data){
    for(var innerKey in data[key]){
     for(var innerKey2 in data[key][innerKey]){
        for(var innerKey3 in data[key][innerKey][innerKey2]){
          if(innerKey3 == "factorType" || innerKey3 == "provider"|| innerKey3 == "id")
         console.log(data[key][innerKey][innerKey2][innerKey3])
        }
      }
    }
  }

or you can use

var data = {"factors":{
        "factors":[{
        "id":"reytfufsiwdg",
        "factorType":"email",
        "provider":"ABC",
        "factorsProfile":{
        "email":"a...r@gmail.com"
        }}]}};

data.factors.factors.forEach(factor => {
  console.log(factor.id)
    console.log(factor.factorType)
      console.log(factor.provider)
});


text:
Q: Other method to create indentation in alert JS object alert(JSON.stringify(student, null, 4));

Why is null used in this code, what is the use of the 4 and how do we use it in an array?
Please explain to me the above JS code and the output.


text:
Q: I need a step by step guide with demo web app on how to build a PHP & MySQL web app on IBM Bluemix? I need a step by step guide with demo web app on how to build a PHP & MySQL web app on IBM Bluemix ?
I want to build a simple data management web app on IBM Bluemix . (uses PHP & MySQL) .
Please help .
Thank you !

A: Here's one example of a web app combining PHP, MySQL and IBM Bluemix.
http://www.ibm.com/developerworks/mobile/library/mo-bluemix-php-nutritionix-angularjs/index.html


text:
Q: Bootstrap 3: Div does not work as before I have section divs inside my form. And Each section can have multiple fields. It works fine with Bootstrap 2.3 css. When I replaced it with Bootstrap 3.0 css, all the fields came out of the section div. I tried inspecting the element but could not find any difference.
CSS
.section {
    position: relative;
    margin: 15px 0;
    padding: 39px 19px 14px;
    background-color: #fff;
    border: 1px solid #649300;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;

}

HTML

        Amount Information

                Amount Of
                <input type="text" name="amount" required="">

                Customer First Name
                <input type="text" name="firstName" required="">

                Customer Last Name
                <input type="text" name="lastName" required="">

                Middle intials
                <input type="text" name="middleIntials" required="">

                Date
                <input type="text" id="datepicker" class="datepicker" name="date">

                Street Address
                <input type="text" name="address">

                City
                <input type="text" name="city">

                State
                <input type="text" name="state">

                State 2
                <input type="text" name="state">

A: Bootstrap 3 has obsoleted the spanX classes. Replace those with col-lg-X classes.
See this migration guide from v2.x to v3 of Bootstrap.

A: Try closing your input tags, leaving them open may cause problems.
Example:
    <input type="text" name="state"></input>
Or:
    <input type="text" name="state" />


text:
Q: Are specific instances of a view controller accessible without the use of singletons? When a UINavigationController pushes a view controller into view, the nav controller creates its own instance of that view controller behind the scenes. Using this nav controller delegate:
extension Main_ProfileViewController: UINavigationControllerDelegate {

    // called just after the navigation controller displays a view controller's view and navigation item properties
    open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        print(viewController)
    }

}

That instance can be "determined". The console prints something like this:
<ElChapo.SomeRandomViewController: 0x7fbe8b003640>

That 14-character hash is different each time that view controller is pushed by the nav controller so clearly they are different instances each time. My question: is that specific instance somehow accessible without using singletons? By accessible, I mean accessible where I can run a delegate to it and call specific methods within that specific instance.
This is what I'm trying to accomplish:
To pop a navigation stack back to its root, I would execute this function from within the view controller at the top of the stack.
// pop to root
func popToRoot() {
    self.navigationController?.popToRootViewController(animated: true)
}

This method must be called from within that specific instance of that view controller. If I call popToRoot() from another object, like the tab bar, by passing a delegate to it, it doesn't work because the delegate needs to find that exact instance to execute the pop.

A: The Nav controller doesn't "create its own instance", or at least that is a somewhat confused way of looking at it. It only appears that way if you are using storyboards. You can use a Navigation Controller without use of storyboards at all if you so wish, in which case you would manually instantiate a new View Controller to push onto the nav controller stack. If you use a storyboard, it will contain defined segue's which "cause" the next view controller to get pushed onto the stack. It is the segues in the storyboard that define which view controllers get created when. There is no need to create a singleton to "get to" the child view controllers pushed onto the navigation stack. Each time one is pushed onto the navigation controller's stack, by default it will be created, and when it is popped, unless you specifically maintain a strong reference to it (which would almost always be a bad idea) it will be destroyed.
If you haven't already subclassed your navigation view controller, do so, and in the subclass override the prepare(for:sender:) to be able from the navigation controller, to access an instance of the child view controller pushed onto the navigation controller's stack. If you want to access that view controller, either save a reference to it in that method, or, better, find it in the navigation controllers stack using one of the following properties of the navigation controller:
var topViewController: UIViewController?
var visibleViewController: UIViewController?
var viewControllers: [UIViewController]

BTW the reference number you refer to isn't a hash but rather the hexadecimal value of a pointer (e.g. to the memory address) of where the view controller object is stored, but as you say, distinct view controllers will have distinct hex values.


text:
Q: Randomly getting ERR_CONNECTION_CLOSED only on chrome Sometimes I get an error "ERR_CONNECTION_CLOSED" for my application https://coach5.isxapps.com/ and the wired thing is that it only happen with google chrome and that too randomly.
It am not getting this error with Firefox or IE, Systems are scanned for any kind of viruses, spywares, malwares (no add-ons/extensions are installed on browser)
Attached are the screen-shots and net-internal json log files.
Any kind of help will be highly appreciated.


text:
Q: JSF+Facelets treating bean action as property Guys, for some reason EL is not telling actions from properties. I have this page test.xhtml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html   xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core">

<body>

<form action="#{TestBean.test}">
    <p>#{TestBean.status}</p>
    <input type="submit" value="Test Again"/>
</form>

</body>

</html>

TestBean.status is a string property (there is a getStatus method) and TestBean.test is a method which return "sucess".
Every time I call the page I get this exception:
ERROR [STDERR] 05/08/2009 17:41:07 com.sun.facelets.FaceletViewHandler handleRenderException
SEVERE: Error Rendering View[/etc/test/test.xhtml]
javax.el.ELException: /etc/test/test.xhtml: Bean: test.TestBean, property: test
    at com.sun.facelets.compiler.AttributeInstruction.write(AttributeInstruction.java:53)
    at com.sun.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:39)
    at com.sun.facelets.tag.jsf.ComponentSupport.encodeRecursive(ComponentSupport.java:232)
    at com.sun.facelets.tag.jsf.ComponentSupport.encodeRecursive(ComponentSupport.java:239)
    at com.sun.facelets.FaceletViewHandler.renderView(FaceletViewHandler.java:580)
    at org.ajax4jsf.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:108)
    at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:216)
    at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:384)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:138)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.jboss.web.tomcat.tc5.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:156)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    at java.lang.Thread.run(Unknown Source)

Maybe it's a long shot, I can describe better my environment. But at first glance, any tips?
tks

A: As far as I know, EL does not have a syntax to invoke an arbitrary method.  The syntax you're using, when applied to anything other than a Map, List, or array, will look for a property getter corresponding to the name; the dot is syntactic sugar for TestBean["test"].
While it is possible to define custom functions for EL as part of a JSP tag library, they must be implemented by static methods.  See this tutorial for more information on how to do so.
This feature is currently in the JSR pipeline however.

A: I think the problem was forgetting the jsfc attribute.
It should be:
<form **jsfc="h:form"** action="#{TestCaseBean.test}">

tks.


text:
Q: SSL for dummies I want to add some security to a client(iPhone) - server(c#) application I'm working on, mainly to encrypt messages sent between client and server.
I know i should use SSL but not really sure what the steps i need to do in both client and server to implement it.
Can someone please give me some guidance?
I don't use HTTP protocol, i use my own textual protocol, but any way with HTTP or my own protocol how do i add ssl support? i know that in c# there is SSLStream instead of regular Stream. And on ios there is some stream settings i need to configure, i just don't know how to do it.

A: Take the easy approach, which is allowed to go on the App Store without having to go through all the encryption law stuff. Simply use a HTTP server and a client.
C# runs the HTTP server (maybe use IIS to handle that? Maybe C# has its own software for that) and the iPhone simply uses NSURLRequest.
Easy to implement and safe, since you'll benefit from patches from Apple and Microsoft.
Update for the updated question: I did some quick research and this kept popping up: kCFStreamPropertySSLSettings - maybe it helps you. It's apparently something for NSStream that allows it to create SSL connections, or something. I'm afraid I can't help you more than that.

A: Host the application using SSL in IIS, then use HTTPS as the service point. [edit] Don't forget you'll need a cert.


text:
Q: Ionic 4 - easiest way to a button add/remove component from page I'm using page variables to add/remove components from my page.
This sounds weird but it actually works.
mypage.html
<pop-product *ngIf="this.pop_product_open" [data]="this.pop_product_data"></pop-product>

mypage.ts
public pop_product_open:boolean = false;
public pop_product_data:any = null;

...

async openPopProduct(product){
  this.pop_product_open = true;
  this.pop_product_data = product;
}

Is there any other/simplest/better way to add/remove component from the page?
I'm asking cause I'm going to have about 15 components and it's scary how messy the code is going to be on managing lots of variables this way.

A: In case of having more than for example two pages, you can use something like this.
First, you need to have one function for selecting the component that you want to show.
example.ts
selectedPage: string = 'DefaultPage';

exampleFunction(page){
  this.selectedPage = page;
}

And then, that component will be shown. As a default, you can show some sample data if a specific component doesn't yet exist (!selectedPage).
exapmle.html
<ion-content>
    <map *ngIf="selectedPage == 'Map'"></map>
    <offers *ngIf="selectedPage == 'Offers'"></offers>
    <restaurants *ngIf="selectedPage == 'Eat'"></restaurants>
    <emergencies *ngIf="selectedPage == 'Emergencies'"></emergencies>
    <drink *ngIf="selectedPage == 'Drink'"></drink>
    <spa *ngIf="selectedPage == 'Spa'"></spa>
    <attractions *ngIf="selectedPage == 'Attractions'"></attractions>
    <beaches *ngIf="selectedPage == 'Beaches'"></beaches>
    <ion-row *ngIf="!selectedPage || selectedPage == 'DefaultPage'">
...


text:
Q: Resetting dask dataframe index to allow join Given http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.reset_index says dask doesn't support drop=True for reset_index() how do I join 2 dataframes together with different index (as viewed by head())

A: While my dask dataframe was small I was able to create a pandas dataframe from it, reset the index by dropping it
npdf = ddSample.compute()
npdf.reset_index(drop=True, inplace=True)
npdf.head()

after that I was able to use
ddmerged= dd.merge(npdf,df2)


text:
Q: Turbo C++ and Code blocks Why should I use namespaces and int main in Code blocks while there are no namespaces in turbo c++ and I can use void main without returning any value as I learnt in schools. Is the compiler different, Is the C++ version different?

A: First of all, Turbo C++ is a compiler bundled with an IDE targetting MS-Windows. Code Block is an IDE supporting several compilers and platforms. That is the main difference between these two tools, so you are not comparing exactly the same things.
Secondly, int is the standard return value for main, which is also standard by convention in C and C++ for program source code entry points (1). C++ compilers operating in standard mode expect programs to be written that way,  so your programs should conform these expectations, if you want to use conforming C++ compilers, which are what Code Block is supporting by default. However, I'm pretty sure that you code configure Code Block to use a specific compiler in a non compliant mode (or simply a non compliant compiler), since it is a flexible IDE; you might well be able to set it up to use Turbo C++, and thus make it compile non ANSI C++. That said, I don't think that Turbo C++ does not support ANSI C++.
Thirdly, Namespaces are a feature of C++, that you have to use if you want to use the standard C++ library, but nothing forces you to otherwise.

(1) the name is a convention, but the function itself is obviously necessary.

A: Possibly you worked on a very old version of compiler that doesn't implement the C++ specifications completely or in other words it is not conformant to C++. An old version written during dos era may allow you to do many nasty/non-standard things.
In C++ entire C++ standard library is defined within namespace std. You must use using and/or fully qualified name (with scope resolution) to access these.
main in C++ must return an int with either of the 2 signatures
int main();
int main(int argc, char *argv[]);

In short for your use cases turbo C++ is doing wrong while Codeblocks is correct.


text:
Q: has_one in a has_many I have an association I'm struggling with. I have a Department model, which can have many staff members, one of which is the manager.
I need to be able to call.
Department.staff - and get a collection of all staff including the manager.
Department.manager - and get the manager.
User.department - and get the users department, whether they are staff or manager.
User.is_manager - and get a boolean as to whether they manage a department or not.
User.manages - get the department they manage.
What is the best of setting up this association? I have currently started with something like this:
class User < ActiveRecord::Base
      belongs_to :department
      has_one :manages, :class_name => 'Department', :foreign_key => :manager_id
end

class Department < ActiveRecord::Base
      belongs_to :manager, :class_name => "User"
      has_many :staff, :class_name 'Users'
end

The problem that I have with this, is that I have to add the manager both as the manager and as a member of staff, which feels a little clumbsy - but perhaps I'm being picky?
Can anyone suggest some better options?

A: Try this association:
class Department < ActiveRecord::Base
  has_many :staffs, class_name: "User"
  has_one :manager, class_name: "User", foreign_key: "manager_id"
end

class User < ActiveRecord::Base
  belongs_to :department
end

Make sure your User table has a column called manager_id, and a column called department_id. If you have a boolean column called manager in your User table, you will have a method manager? to check whether user is manager or not.
To do what you want:
@department = Department.find(1) # Find department with id = 1
@department.staffs # Get all staffs of department

@department.manager.name # Get name of manager of department

@user = User.find(1) # Find user with id = 1
@user.department.name # Get name of department which user belongs to
@user.manager? # Return value of manager column


text:
Q: How to join every sublist to a single string in Python? How to join every sublist to a single string in Python?
Here is the list :
L=[['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]

My desired list would be :
 D=['11000','11110','00110']

A: L = [['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
D = [''.join(sub_list) for sub_list in L]

A: You can either use a list comprehension:
L = [
    ['1', '1', '0', '0', '0'],
    ['1', '1', '1', '1', '0'],
    ['0', '0', '1', '1', '0']
    ]

D = [''.join(l) for l in L]

or the map function:
D = map(''.join, L) # returns a generator in python3, cast it to list to get one

Note that the most pythonic way of doing this is the list comprehension.

A: flat list can be made through reduce easily.
All you need to use initializer - third argument in the reduce function.
reduce(
   lambda result, _list: result.append(''.join(_list)) or result,
   L,
   [])

or map and reduce in combination,
import operator
map(lambda l: reduce(operator.iconcat, l), L)

Above code works for both python2 and python3, but you need to import reduce module as from functools import reduce. Refer below link for details.

*

*for python2

*for python3


text:
Q: .htaccess internal redirect not working for subfolder I have a site that has another site inside of it in a sub folder. For example, www.domain.com and the sub folder would be www.domain.com/uk/. They both contain duplicate files, so even the .htaccess file is same. Now the problem is when I redirect users through .htaccess inside the uk subfolder to a file in the same directory it redirects them to the file in the parent site with the duplicate name.
This is the rule I have used in my .htaccess file:
RewriteRule ^category/[a-zA-Z0-9_-]+/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ final_final.php

I don't have much experience with mod_rewrite.

A: in the parent directory RewriteBase should be /
RewriteEngine On
RewriteBase /

in the subdirectory the RewriteBase should be /uk
RewriteEngine On
RewriteBase /uk

A: you can also specify concrete path in concrete redirect, it is not quite "clean" like Gustonez way but it may work too
in uk-htaccess redirect to uk base directory
RewriteRule ^category/(.*)$ /uk/$1 [L,R]

and in parent-htaccess redirect to base directory without /uk/
RewriteRule ^category/(.*)$ /$1 [L,R]

but redirect you have is weird i think
^category/[a-zA-Z0-9_-]+/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ final_final.php

do you really need all this parameters in url to redirect?
and when you redirect any of these parameters will be parsed on page
you just going to final_final.php page without sending parameters to this page
another thing is that you don't have [L] flag a the end of statement
you better tell exactly what you need because this redirect you have may be inadequate and may not work at all


text:
Q: Dynamic datagrid columns in Flex I have <mx:DataGrid> in my system like the following.
<mx:DataGrid id="testDG">
  <mx:columns>
    <mx:DataGridColumn headerText="name" dataField="name">
    <mx:DataGridColumn headerText="measure" dataField="measure">
  </mx:columns>
</mx:DataGrid>

It has two columns, name and measure. I want to add another number of columns and it's data in the datagrid as respect to measure.
So, it looks like:
name  measure  1-Aug  2-Aug   3-Aug ...

abc   ggggg    20      22      24   ...
xyz   fffff    21      19      20   ...
pqr   hhhhh    30      21      13   ...

...    ...     ...     ...     ...

I want to add date wise result followed by measure column dynamically.  So, is it possible? How can I add dynamic columns after measures in Flex?

A: How about this?
// Get current columns here.
var cols: Array = grid.columns;

var col1:DataGridColumn = new DataGridColumn();
col1.headerText = "1-Aug";
col1.dataField = "foo";
cols.push(col1);

var col2:DataGridColumn = new DataGridColumn();
col2.headerText = "2-Aug";
col2.dataField = "baz";
cols.push(col2);

grid.columns = cols;

If you want to add from 1-Aug to 31-Aug and these datafield is like val1~val31, how about this?
var cols: Array = grid.columns;
for (var i:int=1; i<=31;i++){
    var col:DataGridColumn = new DataGridColumn();
    col.headerText = i.toString()+"-Aug";
    col.dataField = "val"+i.toString();
    cols.push(col);
}
grid.columns = cols;

If you want to add other months, you should get from calendar instead of static 31 value.
Update: Oct 1 2015 16:40(JST)
For spark.DataGrid, there are different from mx.DataGrid a little.
Here is the code for spark.DataGrid.
// Get current columns here.
var list: ArrayList = grid.columns as ArrayList;
var cols: Array = list.source;

var col: GridColumn = new GridColumn();
col.headerText = "1-Aug";
col.dataField = "foo";
cols.push(col);

// Redefine columns.
grid.columns = new ArrayList(cols);

<s:DataGrid id="grid">
    <s:columns>
        <s:ArrayList>
            <s:GridColumn dataField="type" width="100"/>
            <s:GridColumn dataField="name" width="100"/>
        </s:ArrayList>
    </s:columns>
</s:DataGrid>

A: DataGrid has property columns. It can be used to set up columns dynamically. See example:
var columns:Array = [];
var nameColumn:DataGridColumn = new DataGridColumn("name");
nameColumn.dataField = "name";
columns.push(nameColumn);
var measureColumn:DataGridColumn = new DataGridColumn("measure");
measureColumn.dataField = "measure";
columns.push(measureColumn);
var newColumn:DataGridColumn = new DataGridColumn("1-Aug");
newColumn.dataField = "1AugValue";
columns.push(newColumn);
...
dataGrid.columns = columns;

As far as I know, when you need to change column structure while keeping columns, that are already present, you need to create new array and declare the already present columns again.


text:
Q: How sum column values and format cell using conditional formatting? I started to develop in React.js, and I'm using React-Bootstrap-Table.

*

*I need to get the sum of the total of a particular column (updates on every change in search field).

*I also want to add custom CSS for conditional formatting based on value     (example, if amount is less than average, need to be green
text    if amount is near average yellow,    if amount is above
average but less than maximum orange    else red).

*Also number field needs to be right aligned

Code can be viewed here

var DataTable = ReactDataComponents.DataTable;

// Generate random data
var names = ['201801003', '201801002', '201801004', '201801005', '201801006'];
var cities = ['2018', '2017', '2017', '2017', '2017', '2017'];
var addresses = ['Travancore', 'Sivagangai', 'Pudhukottai', 'Madurai'];
var states = ['1200', '350', '6400', '1700', '750'];

var data = [];
for (var i = 0; i < 1000; i++) {
  data.push({
    id: i,
    name: names[~~(Math.random() * names.length)],
    city: cities[~~(Math.random() * cities.length)],
    address: addresses[~~(Math.random() * addresses.length)],
    state: states[~~(Math.random() * states.length)]
  });
}

var columns = [{
  title: 'CID',
  prop: 'name'
}, {
  title: 'Area',
  prop: 'city'
}, {
  title: 'Authority',
  prop: 'address'
}, {
  title: 'Amount',
  prop: 'state'
}];

ReactDOM.render(React.createElement(DataTable, {
  className: 'container',
  keys: 'id',
  columns: columns,
  initialData: data,
  initialPageLength: 5,
  initialSortBy: {
    prop: 'city',
    order: 'descending'
  },
  pageLengthOptions: [5, 20, 50]
}), document.getElementById("root"));
<title>React Table</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css'>
<link rel='stylesheet prefetch' href='https://cdn.rawgit.com/carlosrocha/react-data-components/v1.0.0/css/table-twbs.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css'>

   Area

   Sum

Thank you

A: *

*For every row you make, add it to a counter in your state

*Do conditional css based on the value in the counter

*Align it to the right with css


text:
Q: How to prevent a process started by Process.Start() from exiting when my app exits? my method...
private static void RunAndExit(string command)
{
    var processInfo = new ProcessStartInfo
    {
        FileName = "cmd.exe",
        Arguments = "/c " + command,
        CreateNoWindow = false,
        UseShellExecute = true,
        RedirectStandardError = false,
        RedirectStandardOutput = false
     };
    }

I want the process started by RunAndExit() to continue to run after the app containing this method has exited. Thanks for any help!

A: Your code will already achieve that, so long as you actually start the new process. You are missing a call to Process.Start().
private static void RunAndExit(string command)
{
    var processInfo = new ProcessStartInfo
    {
        FileName = "cmd.exe",
        ....
    };
    Process.Start(processInfo); // add this line
}