text:
Q: Hexagonal Card creation from what level up? I am trying to build a base on which to create hexagonally shaped cards, there a few questions I've found here that have been helpful but I'm searching for my own answers, while more importantly learning latex/tex/tikz/pgf
I have this so far, and maybe someone can nudge me in the right direction:
\usepackage{tikz}
\usetikzlibrary{scopes}
\usetikzlibrary{shapes}
\usetikzlibrary{shapes.geometric}

% 1:draw a hexagon
\newcommand{\hexagon}[1]{
    \begin{tikzpicture}
        \foreach \ang in {60,120,...,360}{
        \coordinate (\ang) at  (\ang:#1) ;}
        \draw (60) -- (120) -- (180) -- (240) -- (300) -- (360) -- cycle;
    \end{tikzpicture}
}

% 2:draw a hexagon from input radius
\newcommand{\hexagonTwo}[1]{
    \newdimen\R
    \R=#1
    \begin{tikzpicture}
        {[]
            \draw (0:\R) \foreach \x in {60,120,...,360} {
                    -- (\x:\R)
                }-- cycle (90:\R);
        }
    \end{tikzpicture}
}

\tikzset{
    hexStyle/.style={color=black,
                     draw,
                     fill=blue!50,
                     line width=1,
                     inner xsep=2.5cm,
                     inner ysep=0.5cm
                    }
}

% 3:build a hexagon shape
\newcommand{\hexagonThree}{
        \node[name=hx, shape=regular polygon, regular polygon sides=6, hexStyle]
            {};
        \foreach \anchor/\placement in
        {corner 1/above, corner 2/above, corner 3/left, corner 4/left, corner 5/right, corner 6/right,
         side 1/above, side 2/left, side 3/left, side 4/right, side 5/right, side 6/right,
         center/above, text/left, mid/right, base/below, 307/above,
         west/above, east/above, north/below, south/above,
         north east/below, south east/above, north west/below, south west/above}
        \draw[shift=(hx.\anchor)] plot[mark=x] coordinates{(0,0)}
            node[\placement] {\scriptsize\texttt{(hx.\anchor)}};
}

% 4:declare & build a hexagon from pgf
\pgfdeclareshape{rootHexagon}
{
    \savedmacro\sides{%
    \pgfmathtruncatemacro\sides{6}%
}
\savedmacro\anglestep{%
    \pgfmathdivide{360}{\sides}%
    \let\anglestep\pgfmathresult%
}
\savedmacro\calculateradii{%
    %
    % Get the node dimensions.
    %
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y.5\dp\pgfnodeparttextbox%
    \ifdim\pgf@y>\pgf@x%
        \pgf@x\pgf@y%
    \fi%
    %
    % Calculate i, the incircle radius
    %
    \pgf@x1.41421\pgf@x%
    %
    % Calculate r, the polygon radius
    %
    % r = i / cos(360 / s / 2)
    %
    % (s = polygon sides)
    %
    \pgfmathdivide{180}{\sides}%
    \pgfmathsec@{\pgfmathresult}%
    \pgf@x\pgfmathresult\pgf@x%
    %
    % Accommodate the minimum width/height.
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@ya>\pgf@xa%
        \pgf@xa\pgf@ya%
    \fi%
    \ifdim\pgf@x<.5\pgf@xa%
        \pgf@x.5\pgf@xa%
    \fi%
    \edef\radius{\the\pgf@x}%
    %
    % Now calculate the anchor radius from the outer sep.
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@ya>\pgf@xa%
        \pgf@xa\pgf@ya%
    \fi
    %
    % Take into account the miter length.
    %
    % m = o / sin (90 - (360 / s / 2))
    %
    % (o = outer sep, s = sides)
    %
    \pgfmathdivide{180}{\sides}%
    \pgfmathsubtract@{90}{\pgfmathresult}%
    \pgfmathcosec@{\pgfmathresult}%
    \advance\pgf@x\pgfmathresult\pgf@xa%
    \edef\anchorradius{\the\pgf@x}%
    %
    % Save both radii.
    %
    \addtosavedmacro{\radius}%
    \addtosavedmacro{\anchorradius}%
}
\savedmacro\startangle{%
    \pgfmathdivide{360}{\sides}%
    \let\anglestep\pgfmathresult%
    \pgfmathtruncatemacro\sides{\sides}%
    \pgfmathdivide@{\anglestep}{2}%
    \pgfmathsubtract@{90}{\pgfmathresult}%
    \pgfmathadd{\pgfmathresult}{\pgfkeysvalueof{/pgf/shape border rotate}}%
    \let\startangle\pgfmathresult%
}
%
% Saved anchors.
%
\savedanchor{\centerpoint}{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
}%
\savedanchor{\midpoint}{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+.5ex}%
}%
%
% Other anchors.
%
\anchor{center}{\centerpoint}%
\anchor{mid}{\midpoint}%
\anchor{base}{\centerpoint\pgf@y=0pt}%
\anchor{north}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{0pt}{\anchorradius}}}%
\anchor{south}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{0pt}{-\anchorradius}}}%
\anchor{east}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{\anchorradius}{0pt}}}%
\anchor{west}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{-\anchorradius}{0pt}}}%
\anchor{north east}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{\anchorradius}{\anchorradius}}}%
\anchor{north west}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{-\anchorradius}{\anchorradius}}}%
\anchor{south east}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{\anchorradius}{-\anchorradius}}}%
\anchor{south west}{%
    \calculateradii%
    \csname pgf@anchor@rootHex@border\endcsname{\pgfqpoint{-\anchorradius}{-\anchorradius}}}%
%
% Background path.
%
\backgroundpath{%
    \calculateradii%
    \pgfpathmoveto{%
        \pgfpointadd{\centerpoint}{\pgfqpointpolar{\startangle}{\radius}}%
    }%
    \let\angle\startangle%
    \pgfmathloop%
        \ifnum\pgfmathcounter=\sides\relax%
            \pgfpathclose%
        \else%
            \pgfmathadd@{\angle}{\anglestep}%
            \let\angle\pgfmathresult%
            \pgfpathlineto{%
                \pgfpointadd{\centerpoint}{\pgfqpointpolar{\angle}{\radius}}%
            }%
    \repeatpgfmathloop%
}%
\anchorborder{%
    %
    % Save x and y.
    %
    \edef\externalx{\the\pgf@x}%
    \edef\externaly{\the\pgf@y}%
    %
    % Adjust the location of the external
    % point relative to \centerpoint.
    %
    \centerpoint%
    \pgf@xa\externalx\relax%
    \pgf@ya\externaly\relax%
    \advance\pgf@xa\pgf@x%
    \advance\pgf@ya\pgf@y%
    \edef\externalx{\the\pgf@xa}%
    \edef\externaly{\the\pgf@ya}%
    %
    % Get the angle of the external point to the \centerpoint.
    %
    \pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
    %
    % Locate the appropriate sides on the polygon border...
    %
    \pgfmathsubtract@{\pgfmathresult}{\startangle}%
    \ifdim\pgfmathresult pt<0pt\relax%
        \pgfmathadd@{\pgfmathresult}{360}%
    \fi%
    \pgfmathdivide@{\pgfmathresult}{\anglestep}%
    \pgfmathfloor@{\pgfmathresult}%
    \pgfmathmultiply@{\pgfmathresult}{\anglestep}%
    \pgfmathadd@{\pgfmathresult}{\startangle}%
    \let\firstangle\pgfmathresult%
    \pgfmathadd@{\pgfmathresult}{\anglestep}%
    \let\secondangle\pgfmathresult%
    \calculateradii%
    %
    % ...and thus, the point on the polygon border.
    %
    \pgfpointintersectionoflines{\centerpoint}{\pgfpoint{+\externalx}{+\externaly}}%
        {%
            \pgfpointadd{\centerpoint}%
                {\pgfqpointpolar{+\firstangle}{+\anchorradius}}%
            }%
            {%
                \pgfpointadd{\centerpoint}%
                    {\pgfqpointpolar{+\secondangle}{+\anchorradius}}%
            }%
}
%
% More hackery for when the rootHex is positioned using
% a `corner <n+1>' or `side <n+1>' anchor, where n is the maximum
% number of sides of any previously drawn rootHex.
%
\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@rootHex\endcsname{%
    \c@pgf@counta\sides\relax%
    \pgfmathloop%
        \ifnum\c@pgf@counta>0\relax%
            \pgfutil@ifundefined{pgf@anchor@rootHex@corner\space\the\c@pgf@counta}{%
            %
            % ...(manually \xdef as \gdef is normally used by \anchor)...
            %
            \expandafter\xdef\csname pgf@anchor@rootHex@corner\space\the\c@pgf@counta\endcsname{%
                \noexpand\calculateradii%
                \noexpand\pgfmathsubtract@{\the\c@pgf@counta}{1}%
                \noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
                \noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
                \noexpand\let\noexpand\angle\noexpand\pgfmathresult%
                \noexpand\pgfpointadd{\noexpand\centerpoint}%
                    {\noexpand\pgfqpointpolar{\noexpand\angle}{\noexpand\anchorradius}}%
            }%
            \expandafter\xdef\csname pgf@anchor@rootHex@side\space\the\c@pgf@counta\endcsname{%
                \noexpand\calculateradii%
                \noexpand\pgfmathsubtract@{\the\c@pgf@counta}{1}%
                \noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
                \noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
                \noexpand\let\noexpand\firstangle\noexpand\pgfmathresult%
                \noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
                \noexpand\let\noexpand\secondangle\noexpand\pgfmathresult%
                \noexpand\pgfpointlineattime{0.5}%
                    {\noexpand\pgfpointadd{\noexpand\centerpoint}%
                        {\noexpand\pgfqpointpolar{\noexpand\firstangle}{\noexpand\anchorradius}}}%
                    {\noexpand\pgfpointadd{\noexpand\centerpoint}%
                        {\noexpand\pgfqpointpolar{\noexpand\secondangle}{\noexpand\anchorradius}}}%
            }%
        }{\c@pgf@counta0\relax}%
        \advance\c@pgf@counta-1\relax%
    \repeatpgfmathloop%
}%
}

1 & 2 are exercises in 'not much' and 3 is a start, the commented 4th I'm not at a point to actually do but think I should be moving toward. I need to build a hexagon card, and then get control over every point inside for node placement, etc.(i.e. import art, add text or other shapes, etc. but first things first). I need to control size, etc, which I cant seem to. My first step is building the actual thing, with actual measurements of sides and inside.
I'm mostly trying to establish first principles for something not 100% clear to me, any input appreciated.
EDIT:
After some effort, the 4th is taking shape, as a modified implementation of the regular polygon from the shapes library.

A: I normally wouldn't post a solution using asymptote when you've specifically tagged your question with tikz.  However, I see that you are not getting many responses to your questions.  Note that asymptote code can be embedded within Latex or can be compiled into PDF files independent of Latex.
If I were designing hexagonal cards, I would do something like the following code.  The pair anchor(...) function returns an anchor point with the hexagon as you requested in your other post.
I've also demonstrated how to import graphics and use clipping.
unitsize(1inch);
real height = 1.5;
real halfDiagonal = height / 2 / Cos(30);
path border = scale(halfDiagonal)*
    (dir(0)--dir(60)--dir(120)--dir(180)--dir(240)--dir(300)--cycle);

pair anchor(real degrees, real fractionFromCenter)
{
    path ray = rotate(degrees)*((0,0)--(2*height,0));
    return scale(fractionFromCenter)*intersectionpoint(ray,border);
}

fill(border, gray);
label(graphic("logs.eps","height=0.35in"), anchor(90,0.5));
layer();
label(graphic("lemons.eps","height=0.5in"), anchor(270,0.5));
layer();

dot(anchor(  0,0.0), black);
dot(anchor(  0,0.5), red);
dot(anchor( 30,0.5), blue);
dot(anchor(150,0.9), orange);

label(rotate(90)*"Hello", anchor(180,0.5), white);
filldraw(shift(anchor(330,0.9))*scale(0.2)*unitcircle, yellow, 3+red);
clip(border);


text:
Q: Parse error: syntax error, unexpected 'if' (T_IF), how to fix it? i was make a login script, and it's the index :
<?php
        session_start()
        if(isset($_POST['username'])&&!empty($_POST['username'])){
        header("location:login.php");
    }
    echo "selamat datang ".$_SESSION['username'];
    ?>

    Logout

when i try it, it show me :

Parse error: syntax error, unexpected 'if' (T_IF)

anyone know?

A: Space is improper and use ; after session_start
<?php
session_start();
if(isset($_POST['username']) && !empty($_POST['username'])){
    header("location:login.php");
}
echo "selamat datang ".$_SESSION['username'];
?>

Logout

A: MISSING ; AFTER session_start
<?php
        session_start();
        if(isset($_POST['username'])&&!empty($_POST['username'])){
        header("location:login.php");
    }
    echo "selamat datang ".$_SESSION['username'];
    ?>

    Logout

A: Try this...
<?php
        session_start(); //miss semicolon
        if(isset($_POST['username'])&&!empty($_POST['username'])){
        header("location:login.php");
    }
    echo "selamat datang ".$_SESSION['username'];
    ?>

    Logout

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA Excel - Open two word documents and add all the info from one to the end of the other I have a spreadsheet that I want to open two Word documents, do a bunch of stuff and then add all the contents of one to the end of the other. I've managed to figure out how to do the bunch of stuff, but for the life of me I can't seem to copy the contents of one to end of the other (which I thought would be the easiest part).
My code:
Sub Redate_OUT()

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.DisplayStatusBar = True

Dim sh As Worksheet

Set sh = ThisWorkbook.Sheets("Settings")

Dim pdf_path As String
Dim word_path As String
Dim Updated_path As String

pdf_path = sh.Range("E4").Value
Updated_path = sh.Range("E5").Value
word_path = "\\filestorage\cie\Operations\Results Team\Enquiries About Results\1.Series Folders\June 2022\4. Letters\OUT\Redater\Temporary Folder (Word)"

Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim MonthNo As Long
Dim MonthType As String
Dim Check As Boolean

Set fo = fso.GetFolder(pdf_path)

Dim wa As Object
Dim doc As Object
Dim FinalWording As Object

Set wa = CreateObject("word.application")
wa.Visible = True

Dim file_Count As Integer

Set FinalWording = wa.Documents.Open("\\filestorage\cie\Operations\Results Team\Enquiries About Results\1.Series Folders\June 2022\4. Letters\OUT\Redater\Final Wording.docx")

For Each f In fo.Files

    Application.StatusBar = "Converting - " & file_Count + 1 & "/" & fo.Files.Count
    Set doc = wa.Documents.Open(f.Path)
        doc.SaveAs2 (word_path & "\" & Replace(f.Name, ".pdf", ".docx"))
        doc.Close False

    Set doc = wa.Documents.Open(word_path & "\" & Replace(f.Name, ".pdf", ".docx"))

    For MonthNo = 12 To 1 Step -1

        MonthType = MonthName(MonthNo)

        With doc.Content.Find
              .Text = "?? " & MonthType & " 2022"
              .Replacement.Text = Format(Date, "dd") & " " & MonthName(Format(Date, "mm")) & " " & Format(Date, "yyyy")
              .MatchWildcards = True
              .MatchWholeWord = True
              .Execute Replace:=wdReplaceAll

            If .Found = True Then

                Check = True
                GoTo Done

            End If

        End With

    Next

Done:

    If Check = True Then

        With doc.Content.Find

            .Text = "If you believe we have not arrived at this outcome properly, * Enquiry About Results Team"
            .Replacement.Text = ""
            .MatchWildcards = True
            .MatchWholeWord = True
            .Execute Replace:=wdReplaceAll

        End With

        FinalWording.Content.WholeStory 'Select whole document
        Selection.Copy 'Copy your selection
        Documents(doc.Name).Activate 'Activate the other document
        Selection.EndKey wdStory 'Move to end of document
        Selection.PasteAndFormat wdPasteDefault 'Pastes in the content

        doc.ExportAsFixedFormat OutputFileName:=Updated_path & "/" & f.Name, ExportFormat:=wdExportFormatPDF, Range:=2
        doc.Close

    End If

    file_Count = file_Count + 1
Next

FinalWording.Close False

wa.Quit

Kill word_path & "\" & "*.docx"

MsgBox "All OUT Letters have been updated", vbInformation
Application.StatusBar = ""

End Sub

My main difficulty is with:
FinalWording.Content.WholeStory 'Select whole document
Selection.Copy 'Copy your selection
Documents(doc.Name).Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content

I get an error (Object does not support this property or method) with:
Selection.EndKey wdStory 'Move to end of document

I'm also not convinced that the contents of the FinalWording document is actually being copied, as when I try to paste this manually after that line of code has run, nothing happens.
On a side note, after the PDF is saved as a word document, I've been closing this and opening again to have a variable to use (doc). As I don't need to save the word document, if there's an easier way of doing this without having to close and open it, I would greatly appreciate that.
Many thanks.

A: You can replace this entire block:
FinalWording.Content.WholeStory 'Select whole document
Selection.Copy 'Copy your selection
Documents(doc.Name).Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content

With:
doc.Characters.Last.FormattedText = FinalWording.Content.FormattedText


text:
Q: Why is $\pi_1 (S^n) = 0$ for $n \ge 2$? You can geometrically show why it's like that for $S^2$, as every curve based in a point $x$ can be retracted to that point $x$, so the fundamental group is trivial hence equal to the point $0$.
But why is it true for $S^3, S^4, ...$ too?
It would be great to find an intuitive, geometrical way to explain it to others. I don't need a formal mathematical proof, but just the intuition behind it and why it makes geometrically sense.

A: Convince yourself inductively along the following lines. If I have a loop in $\mathbb{S}^{n}$, find a homotopy which contracts the loop to the equatorial sphere of a dimension lower. If the loop has become an interval, you're done, because this is contractible. If not, you can now continue the induction, forgetting the rest of the sphere and thinking now only within $\mathbb{S}^{n-1}$.


text:
Q: Let $X=\Bbb R$ endowed with the finite complement topology $T$. Is $X$ compact with respect to $T$? Let $X=\Bbb R$ endowed with the finite complement topology $T$. Is $X$ compact with respect to $T$?
Let $\{ T_a \}$ be an open cover. Let $[a,b]$ with the usual topology and $X$ be $[a,b]$ with the finite complement topology.
Let any single element of the cover $T_{a_0}$. The complement has finitely elements so there are only finitely many elements of $X$.
$x_1$, $x_2$, $x_3$,... , $x_n$ are not in this set and $T_{a_i}$ containing $x_i$ so that $X$ is a compact space with resect to $T$.
This is what I have but I'm unsure on correctness so would like to have it checked, please. Thank you in advance!

A: Your idea is correct but the proof is badly written. I  have no idea what $[a,b]$ is doing here. Here is a neat way of writing the proof: let $(U_i)$ be an open cover. Then $0 \in U_k$ for some $k$. Let $\mathbb R \setminus U_k =\{a_1,a_2,...,a_n\}$. Pick $i_1,i_2,..,i_n$ such that $a_j \in U_{i_j}$. Then $U_k$ together with $U_{i_j}, 1 \leq j \leq n$ is a finite subcover.


text:
Q: append dictionary to data frame I have a function, which returns a dictionary like this:
{'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116}

I am trying to append this dictionary to a dataframe like so:
output = pd.DataFrame()
output.append(dictionary, ignore_index=True)
print(output.head())

Unfortunately, the printing of the dataframe results in an empty dataframe. Any ideas?

A: The previous answer (user alex, answered Aug 9 2018 at 20:09) now triggers a warning saying that appending to a dataframe will be deprecated in a future version.
A way to do it is to transform the dictionary to a dataframe and the concatenate the dataframes:
output = pd.DataFrame()
df_dictionary = pd.DataFrame([dictionary])
output = pd.concat([output, df_dictionary], ignore_index=True)
print(output.head())

A: I always do it this way because this syntax is less confusing for me.
I believe concat method is recommended though.
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>>df
col1  col2
0     1     3
1     2     4

d={'col1': 5, 'col2': 6}
df.loc[len(df)]=d

>>>df
col1  col2
0     1     3
1     2     4
2     5     6

Note that iloc method won't work this way.

A: You don't assign the value to the result.
output = pd.DataFrame()
output = output.append(dictionary, ignore_index=True)
print(output.head())


text:
Q: Is Debian package ifenslave really necessary for bonding? This piece of Debian documentation states that package ifenslave is necessary for bonding:

First install the ifenslave package, necessary to enable bonding

Yet I know of two Debian 7.10 (wheezy) hosts where dpkg --get-selections | grep ifenslave returns ifenslave-2.6 install (i.e. package is not installed) and there are multiple entries /proc/net/bonding/* with MII Status: up.
So is package ifenslave really necessary for bonding or is it not?

A: No, the ifenslave package is not required on Debian systems. From that package's README.Debian (Debian 9 system):

[The] best way to configure bonding is via the files in /sys/class/net/$master/bonding/. This Debian package therefore does not contain the binary from the kernel sources, but provides a shell script with identical functionality.
  ...
You can also enslave interfaces using Debian's /etc/network/interfaces file:
...

Using the /etc/networking/interfaces approach results in bonding being configured by setting values in /sys. The ifenslave approach merely provides a shell script to make configuration easier.


text: Q: change length of each burst in multipart file upload in android Is there some way to limit the parts size that are sent on a MultipartEntity from the org.apache.http.entity.mime.MultipartEntity . I am using volley for network requests. I have tried extending the Volley request class and overriding the getbody() method.


text:
Q: Why is my maven surefire plugin getting ignored? I created a maven project in Netbeans 7.3 using the Maven Plugin for Netbeans (v4.20.1)
In my pom.xml, I try to explicitly define the surefire plugin, but no matter what I do it never picks it up.  It is pulling a different version of surefire (2.10), and I'm not sure from where.  All other plugins in the pom.xml work as expected. Any clues?
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>myGroup</groupId>
    <artifactId>myArtifact</artifactId>
    <version>myVersion</version>
    <packaging>jar</packaging>
    <name>myName</name>

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.build.timestamp.format>yyyy-MM-dd_HH:mm</maven.build.timestamp.format>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <!--etc...-->
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <!--etc...-->
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <!--etc...-->
            </plugin>

            <plugin>
                <groupId>org.apache.maven.surefire</groupId>
                <artifactId>surefire</artifactId>
                <!-- This invalid version should trigger a maven error, but doesn't -->
                <version>92.14</version>
                <!--etc...-->
            </plugin>

            <plugin>
                <groupId>com.google.code.maven-replacer-plugin</groupId>
                <artifactId>replacer</artifactId>
                <version>1.5.2</version>
                <!--etc...-->
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
            <!--etc...-->
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>2.5</version>
                <!--etc...-->
            </plugin>
        </plugins>

    </build>

    <profiles>
        <profile>
            <id>windows</id>
            <activation>
                <activeByDefault>true</activeByDefault>
                <os>
                    <family>windows</family>
                </os>
            </activation>
            <properties>
            <!--etc...-->
            </properties>
        </profile>
        <profile>
            <id>linux</id>
            <activation>
                <os>
                    <family>unix</family>
                </os>
            </activation>
            <properties>
            <!--etc...-->
            </properties>
        </profile>
    </profiles>

</project>

A: The artifact you referenced (org.apache.maven.surefire:surefire) is not a plugin, it's a POM.
You should change the declaration using :
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            ...
        </plugin>


text:
Q: How to format DOI in Rmd vignette so that correct in Rd? When I check my package on rhub with devtools::check_rhub(), I get notes that there are incorrectly formatted DOIs in the vignettes, e.g.

URL: doi:10.1029/2002GL016612
From: inst/doc/introduction-to-sedproxy.html
Message: Invalid URI scheme (use \doi for DOIs in Rd markup)

I am generating the vignettes from rmarkdown (.Rmd) files. How do I format DOIs in Rmd so that they will be correct in Rd?

A: From section 2.1.1 Documenting functions in https://cran.r-project.org/doc/manuals/r-devel/R-exts.html :
A section with references to the literature. Use \url{} or \href{}{} for web pointers, and \doi{} for DOIs (this needs R >= 3.3, see User-defined macros for more info).
Thus, it's recommended to use this for your reference as well (even if it works directly without the \doi{} by prefixing it with the https://doi.org/):
\doi{10.1029/2002GL016612}
This should not prompt a NOTE from running R CMD check with --as-cran. This seems to be the case also for vignettes / R markdown and not just Rd files.

A: I was struggling with this and found that using Rmarkdown to insert a link added it in this form
[Pui](https://doi.org/10.1080/02786828708959166)

This works locally anyway. I haven't tried getting it in a CRAN package yet.


text:
Q: How would I move variables from class to class For a final Project in our java class we can make anything. I am making a face creator, and I was wondering how would I make it so the Strings from the Questions class can move to the draw class. That's way I can make it so I can do if String is ... then draw...
public class FinalProjectQuestions
{
    public static void main(String []args)
    {
        Scanner in = new Scanner(System.in);

        System.out.println("We will design the stick face of your dreams");

        System.out.print("Choose gender M for Male, or F for Female: ");

        String gender = in.next();

        String hair = "";
        String haircolor = "";
        String eyecolor = "";
        String eyesize = "";
        String mouthsize = "";
        String m = "m";
        String m2 = "M";
        String femalehair = "";
        String femalehaircolor = "";
        String femaleeyecolor = "";
        String femaleeyesize = "";
        String femalemouthsize = "";
        String femalemakeup = "";
        if (gender.equals(m) || gender == "M")
        {
            System.out.print("Hair Length, Short, Mediuem, or Long: ");
            hair = in.next();
            System.out.print("Hair Color, Red, Brown, Blond, Blue, Black, or Purple: ");
            haircolor = in.next();
            System.out.print("Eye Color, Blue, Red, Brown, or Black: ");
            eyecolor = in.next();
            System.out.print("Eye size, Big, Small, or Mediuem: ");
            eyesize = in.next();
            System.out.print("Mouth Size, Big, Small, or Mediem: ");
            mouthsize = in.next();
        }

        else
        {
            System.out.print("Hair Length, Short, Mediuem, or Long: ");
            femalehair = in.next();
            System.out.print("Hair Color, Red, Brown, Blond, Blue, Black, or Purple: ");
            femalehaircolor = in.next();
            System.out.print("Eye Color, Blue, Red, Brown, or Black: ");
            femaleeyecolor = in.next();
            System.out.print("Eye size, Big, Small, or Mediuem: ");
            femaleeyesize = in.next();
            System.out.print("Mouth Size, Big, Small, or Mediem: ");
            femalemouthsize = in.next();
            System.out.print("MakeUp, None, Little, Average, or Tons: ");
            femalemakeup = in.next();
        }
    }
}

public class FinalProjectMale
{
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        Ellipse2D.Double faceshape = new Ellipse2D.Double(100,100,100,100);

        g2.draw(faceshape);
    }
}

A: That's a lot of parameters to pass to a new class, but there are some tricks to do this.  You could create a Face class that had all these attributes.  A best practice would be to use a Builder pattern to create the Face object.  The Face object could then be passed as a parameter to the Draw class, or the Face class could just have a function that allows it to draw itself.

A: Simply do like this: Here I just show you how to encapsulate data and pass it to the other classes for farther use. Hope this help you to know how to write your code
Create a person class
public class Person {
    private String hair;
    private String hairColor;
    private String eyeColor;
    private int eyeSize;
    private int mouthSize;
    private Gender gender = Gender.MALE; // default is male
    private String makeup;

    public String getHair() {
        return hair;
    }

    public void setHair(String hair) {
        this.hair = hair;
    }

    public String getHairColor() {
        return hairColor;
    }

    public void setHairColor(String hairColor) {
        this.hairColor = hairColor;
    }

    public String getEyeColor() {
        return eyeColor;
    }

    public void setEyeColor(String eyeColor) {
        this.eyeColor = eyeColor;
    }

    public int getEyeSize() {
        return eyeSize;
    }

    public void setEyeSize(int eyeSize) {
        this.eyeSize = eyeSize;
    }

    public int getMouthSize() {
        return mouthSize;
    }

    public void setMouthSize(int mouthSize) {
        this.mouthSize = mouthSize;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public String getMakeup() {
        return makeup;
    }

    public void setMakeup(String makeup) {
        this.makeup = makeup;
    }

    public enum Gender {
        MALE, FEMALE
    }
}

And Other class
class OtherClass {

    private Person person;

    public OtherClass(Person person) {
        this.person = person;
        if (person.getGender() == Person.Gender.FEMALE) {

        }
    }
}

and usage:
public static void main(String[] args) {
    Person male = new Person();
    male.setHair("HairColor");
    ...
    Person female = new Person();
    female.setHair("HairColor");
    ...

    // and pass it to the other class
    OtherClass otherClass = new OtherClass(male);
}


text:
Q: Confusion On How To Implement Chatbot To GUI I recently made a chatbot with Python and also GUI using Tkinter for my chatbot. But the problem is I have no idea on how to implement my chatbot into the GUI. Like I made the Chatbot and the GUI separately. I would really be grateful if you guys could help me. Here are Chatbot and GUI codes respectively below:
def start():
    print('start')
def second_window():
    root=Tk()
    root.title('welcome to metis')
    root.geometry('400x500')
    label2=Label(root,text='welcome to metis')
    button2=Button(root,text='hi').place(x=0,y=0)
    file_menu = Menu(root)
    main_menu = Menu(root)
    file_menu.add_command(label="New..")
    file_menu.add_command(label="Save As..")
    file_menu.add_command(label="Exit")
    main_menu.add_cascade(label="File", menu=file_menu)

    main_menu.add_command(label="Quit",command=root.quit)
    root.config(menu=main_menu)
    chatWindow = Text(root, bd=1, bg="black", width="50", height="8", font=("Arial", 23), foreground="#00ffff")
    chatWindow.place(x=6, y=6, height=385, width=370)
    messageWindow = Text(root, bd=0, bg="black", width="30", height="4", font=("Arial", 23), foreground="#00ffff")
    messageWindow.place(x=128, y=400, height=88, width=260)
    scrollbar = Scrollbar(root, command=chatWindow.yview, cursor="star")
    scrollbar.place(x=375, y=5, height=385)
    sendphoto=PhotoImage(file='send.png')
    Button3= Button(root, text="Send", width="12", height=5,command=send,
                    bd=0, bg="#0080ff", activebackground="#00bfff", foreground='#ffffff', font=("Arial", 12))
    Button3.place(x=6, y=400, height=88)
    root.mainloop()

window=Tk()
window.geometry('500x497')
window.title('metis')
window.config(bg='blue')
bg=PhotoImage(file='rob111.png')
myimage=ImageTk.PhotoImage(Image.open('png-format-16265000621410769899metis.png'))
label=Label(window,image=bg)
label.place(x=0,y=0)

icon=PhotoImage(file='rob111.png')
window.iconphoto(True,icon)
button1=Button(window,text='start',command=second_window).place(x=250,y=250)

window.mainloop()

A: You can use Tkinter module (python)
ex: label = Label(root, text="hi")
label.pack()
copy the tkinter snippet(available in google)


text:
Q: weird image while trying to compress YUV image to jpeg using libjpeg I am using Qt,OpenCV and libJpeg to compress a YUV422 image, but the output is not correct.

if I convert the yuv to rgb and then compress, I get a correct output, but what I understand that Jpeg is using YUV internally , that's why I want to remove redundancy.
Here is my code:
bool ipl2jpeg(IplImage *frame, unsigned char **outbuffer, long unsigned int *outlen) {
    unsigned char *outdata = (uchar *) frame->imageData;
    struct jpeg_compress_struct cinfo ;
    struct jpeg_error_mgr jerr;
    JSAMPROW row_ptr[1];
    int row_stride;

    *outbuffer = NULL;
    *outlen = 0;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_mem_dest(&cinfo, outbuffer, outlen);

    cinfo.image_width = frame->width;
    cinfo.image_height = frame->height;
    cinfo.input_components = frame->nChannels;
    cinfo.in_color_space = JCS_YCbCr;

    jpeg_set_defaults(&cinfo);
    jpeg_set_quality (&cinfo,100 , true);
    jpeg_start_compress(&cinfo, TRUE);
    row_stride = frame->width *2;// frame->nChannels;

    while (cinfo.next_scanline < cinfo.image_height) {
        /* jpeg_write_scanlines expects an array of pointers to scanlines.
         * Here the array is only one element long, but you could pass
         * more than one scanline at a time if that's more convenient.
         */
        row_ptr[0] = &outdata[cinfo.next_scanline * row_stride];
        (void) jpeg_write_scanlines(&cinfo, row_ptr, 1);
      }

    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);

    return true;

}

What is wrong ??
Here is the YUV image

A: the image file provided (frame-3.raw) is 640x480 in YUYV format
the following code
JSAMPROW row_pointer[1];
row_pointer[0] = row_buf;
while (cinfo.next_scanline < cinfo.image_height) {
    unsigned i, j;
    unsigned offset = cinfo.next_scanline * cinfo.image_width * 2;
    for (i = 0, j = 0; i < cinfo.image_width*2; i += 4, j += 6) {
        row_buf[j + 0] = buf[offset + i + 0]; // Y
        row_buf[j + 1] = buf[offset + i + 1]; // U
        row_buf[j + 2] = buf[offset + i + 3]; // V
        row_buf[j + 3] = buf[offset + i + 2]; // Y
        row_buf[j + 4] = buf[offset + i + 1]; // U
        row_buf[j + 5] = buf[offset + i + 3]; // V
    }
    jpeg_write_scanlines(&cinfo, row_pointer, 1);
}

to be put in between jpeg_start_compress() and jpeg_finish_compress() creates a JPEG file correctly without color space conversion (but with upsampling)
jason_s's code looks correct as well

A: I don't think libjpeg will accept subsampled image data as input. So, you'll have to un-subsample it first.
You could allocate a temporary row buffer, and convert each row, something like this:
for (i=0; i<frame->width; i++) {
    tmpbuf[i*3+0] = outdata[cinfo.next_scanline * row_stride + i*2];
    tmpbuf[i*3+1] = outdata[cinfo.next_scanline * row_stride + (i-i%2)*2+1];
    tmpbuf[i*3+2] = outdata[cinfo.next_scanline * row_stride + (i-i%2)*2+3];
}
row_ptr[0] = tmpbuf;


text:
Q: Instantiate a template class ? Here is my code :
template<typename T, template<typename = T,typename =std::allocator<typename = T> > class Container= std::vector>
 class stack
 {
     public:
     Container<T> cont;
     stack()
     {

     }
 };

If i replace the very first line of code to below code then it works :
template<typename T, template<typename elem= T,typename =std::allocator<elem> > class Container= std::vector>

but i want to ask that i've read when you don't use templates type parameter then you can write this : <typename=default_type> or <typename> . Also T in above code is visible in parameter list of template template parameter Container ( i.e type parameter T is visible in it's whole parameterization clause  ). so  all in all i think so it should work.
but it doesn't and gives the error :
error: expression '<erroneous-expression> = <erroneous-expression>' is not a constant-expression
error: template argument 1 and 2 are invalid

So can anyone explain why i am seeing these errors, what is erroneous-expression?

A: When a template parameter is itself a template, then its own template parameters are not used or relevant in the context of the outer template other than to define the "template signature" of the template-template parameter. Therefore, you don't need neither parameter names, as they are not usable or necessary. You can simply say this:
template <typename T, template<typename, typename> class Container = std::vector>
class stack
{
  typedef Container<T, std::allocator<T> > CT;
  // ...
};

Here template <typename, typename> is just the template signature of the Container template class that you expect.
In C++11 you can do better and allow more general containers by using variadic templates:
template <typename T, template<typename...> class Container = std::vector> class stack;

[For completeness:] Putting default types in the template parameter's parameter list also works, and it means you can omit those types later (as you already do):
template<typename = T, typename = std::allocator<T> > class Container

---> now we can say:

Container<T> x;  // use second default argument
Container<> y;   // use both default arguments

To answer your question: You want to specify a default type in
 template <typename = T, typename = std::allocator<typename> > class Container
                                    ^^^^^^^^^^^^^^^^^^^^^^^^
                                            Error!!

but std::allocator<typename> isn't a type -- it's not even legal syntax. You could either have a template parameter which once again is a template, i.e. template <typename> = std::allocator, but that wouldn't be matched by std::vector, or you have an actual type:
template <typename = T, typename = std::allocator<T> > class Container
                                   ^^^^^^^^^^^^^^^^^
                                   OK, this is a type

A: In the parameter-list of a class template, when you specify template template parameter , then template parameter of the template template parameter is not used (in fact, they cannot be used). As such, you can skip mentioning even their names.
So what you should be doing is this:
template<typename T, template<class,class> class Container= std::vector>
class stack
{
     Container<T, std::allocator<T> > cont;
};

That is, all that is required for the template template parameter is the number of parameter(s), and the information what their parameter(s) : type or value.
You can also write this for better readability:
template<typename T, template<class U,class Allocator> class Container= std::vector>
class stack
{
     Container<T, std::allocator<T> > cont;
};

As for why your first code is not working, because of std::allocator<typename = T> which should be simply std::allocator<T>. That is, this should work:
template<typename T, template<typename =T,typename =std::allocator<T> >  class Container= std::vector>

See it here : http://ideone.com/eO8qT
But then such default types of the template template parameter is not even considered. They're ignored.
Now you might ask why std::allocator<typename =T> doesn't work. Because its ill-formed. Do you think std::vector<typename =T> makes any sense?  Please note that std::allocator and std::vector both are class template, but Container is not a class template. Its a template template parameter of a class template. That is why, typename =T is allowed for this, while its not allowed for class templates such as std::allocator.


text:
Q: Sinatra: put some of my helpers in separate folder I have a Sinatra app and I have some helpers and they have their folder (helpers) in which I have website_helpers.rb and so on. I want to move some of this helpers in their own folder inside the helpers folder: to have helpers/subhelpers, bacause the files I want to put in the subhelpers folder are different from the others and it makes sense to have a different folder for them.
I tried adding this to my config.ru
Dir.glob('./helpers/subhelpers/*.rb').each { |file| require file }

And then in the controller I have:
helpers MyHelperFromSubHelpers

but I get an error uninitialized constant (NameError).
Any ideas how to fix this so that to have a clear structure?

A: TBH, it sounds like you're overdoing it, there's always Rails if you want to go in for a more Java like every-namespace-must-be-a-directory layout. Aside from that, usually, helpers in separate files are placed in the Sinatra namespace - see http://www.sinatrarb.com/extensions.html#extending-the-request-context-with-sinatrahelpers
Personally, I put them in:
project-root/
  lib/
    sinatra/
      name-of-extension.rb

Mainly because if the extension is really useful, I'll end up wanting to use it in another project, and this is the standard layout for a Sinatra gem, which makes it easy to extract it into one and with barely any change in the calling code.
Dir.glob will only return the file name and not the full path with each match, so you need to add the path:
Dir.glob('./helpers/subhelpers/*.rb').each do |file|
  require File.expand_path File.join( File.dirname(__FILE__), "./helpers/subhelpers/", file)
end

will probably fix it.


text:
Q: X509Certificate rawData I am working with X509Certificate (.pfx file) for jwt tokens. There is a parameters in the X509Certificate2 called as RawData. I understand that this contains the publicKey for sure and also some other metadata information about the certificate.
I wanted to know whether this rawData parameter contains any other critical information such as the PrivateKey. I am not able to find much documentation explaining these parameters. Can I get more documentation about this parameter, what it contains, and if it is safe to be shared.

A: Made an X509Certificate from the RawData of the X509Cetificate having the private key using this constructor. The new certificate created has HasPrivateKey as false and PrivateKey value as null.

A: let's say that X509Certificate certInstance is an instance of a Pfx certificate with all the goodies.
It depends on the content type when exporting the certificate. You can rebuild the certificate from that raw data. For example,
in C# if I use:
certInstance.Export(X509ContentType.Pfx);

Than the private key and public key will be in the raw data.
But if you export as cert or some other value, it can change.
If you export as:
certInstance.Export(X509ContentType.Cert);

It'll strip the certificate of sensitive information such as the private key. However if you use that same raw data and try to convert back to pfx, the private key data will be null.
If you wanted to change the content type of the certificate, you could do something along these lines.
byte[] certificateAsBytes = certInstance.Export(X509ContentType.Cert);
X509Certificate2 myNewCert = new X509Certificate2(certificateAsBytes);

Here's a link to the different content types that are available:
X509ContentTypes


text:
Q: While installing this code i am getting an error IP address not found I am using Ubuntu 10.04 LTS.
While using this code i am getting an error. why so?
sudo cp /usr/local/lib/libgraph.*/usr/lib

A: Andrea already answered in the comment.
The proper syntax for cp is cp <origin> <destination> and you only gave on argument, the origin.
Add a space between /usr/local/lib/libgraph.* and /usr/lib it'll work

A: You might be mixing up cd and cp.  The latter copies files:
$ cp file newfile

Now you have a copy of file named newfile in the same directory.  On the other hand, cd changes into a directory:
~/directory_1 $ cd directory_2/
~/directory_1/directory_2 $

which changes you from directory_1 to it's subdirectory, directory_2.
If you try to use cp with only one file name after it (like in your original post), you get
$ cp file
cp: missing destination file operand after 'file'
Try 'cp --help' for more information.

since cp doesn't know what the name of the new file (copy) is.


text:
Q: Firebase user creation is not working anymore I've been using the following code snippet in order to create a new user in Firebase/SimpleLogin for months:
var ref = new Firebase(FIREBASE_URL + user.id);
ref.once('value', function(snapshot) {
    if (snapshot.val() === null) {
        // User not found! Create new user
        ref.parent().update(meupontoFire.createNewUser(user.id), function(error) {
            // Nothing happens now...

But that code isn't working anymore! I noticed it yesterday. It seems like the update call is not working (the data is not being stored). Does anyone know why? What has changed?

A: I fixed the problem by changing the Object I pass and what is being updated:
ref.update(meupontoFire.createNewUser(), function(error) {

Now, instead of updating the reference's parent, I am updating the reference itself.


text:
Q: How to set MYSQLI_OPT_INT_AND_FLOAT_NATIVE option
I'm having troubles with the mysqli driver used by wordpress, where it is converting each and every integer value to a string within $wpdb->get_results("SELECT...").
I know that it is possible so use the the option MYSQLI_OPT_INT_AND_FLOAT_NATIVE with the mysqli driver ($mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);) but I don't seem to find a way to set this option in wordpress.
How do I do that?
Thank you
EDIT
Based on the comments below, I'b better further explain what I'm trying to achieve.
I'm developing a plugin to add reactive/responsive functionalities to wordpress both in the backend and in the frontend (exactly like Gutenberg).
In my plugin I need to access a variety of structures in the database, and I'm doing that using using AJAX along with VueJS which makes extensive use of observables.
Let's say, for example that I have a structure like this in the database:
CREATE TABLE IF NOT EXISTS `a_table` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(190) NOT NULL DEFAULT 'New name',
    `anInteger` INT NOT NULL DEFAULT '123',
    `aBoolean` BOOLEAN NOT NULL DEFAULT TRUE
    PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`));"

and that I'm accessing the table via AJAX to bind the data to something like this in Vue:
<template>
  <el-form
    :model="aTable"
    ref="tableForm">
    <el-row>
      <el-col :span="4">
        <el-form-item
          label="Name"
          prop="name">
          <el-input
            v-model="aTable.name">
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-form-item label="BoolVal" prop="aBoolean">
          <el-switch v-model="aTable.aBoolean"></el-switch>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="NumberVal" prop="anInteger">
          <el-input-number v-model="aTable.anInteger"></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
export default {
  props: {
    aTable: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
    };
  },
  methods: {
  }
};
</script>

//AJAX and other glue code omitted

With this set up, the input filed "name" is correctly bound and displays the string "new name", while the boolean switch shows always false (VueJS is expecting a boolean or, at least, an integer, and is getting a string instead!).
This forces me to manipulate the results I get from $wpdb before returning the dataset to the AJAX caller if I want VueJS understand correctly what I retrieve from the database, like this:
static function ajax_get_table()
{
    global $wpdb;
    $response = $wpdb->get_results("SELECT * FROM `a_table` WHERE 1=1 ORDER BY `id`");

    // MYSQLI_OPT_INT_AND_FLOAT_NATIVE Hack
    // mysql is returning each and every integer/boolean as a string
    // This hack is needed to retrieve correct data type
    array_walk($response, function(&$item, $key) {
        array_walk($item, function(&$subitem, $subkey) {
            // Integers
            if (in_array($subkey, ['id', 'anInteger'])) $subitem = intval($subitem);
            // Boolenas
            if (in_array($subkey, ['aBoolean'])) $subitem = boolval($subitem);
        });
    });

    // AJAX termination
    wp_send_json($response);
    die();
}

But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique.
That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3 limitation.

A:
That's why I'm wondering why is Wordpress stuck to this pre-PHP-5.3
  limitation.

Because WordPress has made the decision to support PHP 5.2 due to the large number of hosts that continue to use it. This is an ongoing debate and there's no point rehashing it all here.

But this means that I have to know in advance each end every data type returned from the MYSQL query, which is by far an anti-pattern programming technique.

What? MySQL in PHP, by default, only returns strings. So there you go. That's "each and every data type" that you need to know.
Regardless, you should know what your query is likely to return before outputting it to a page. And you should be verifying and escaping it before outputting it in the browser or an API response.
Most things like this have some sort of model that represents the data that sits between the front-end and the database. What is an anti-pattern is having your front-end so tightly coupled to the minutiae of how the data is stored.

A: This is how you do it:
$wpdb->dbh->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);

dbh is the native PHP mysqli object within ezSQL.


text:
Q: impdp: ORA-30036: unable to extend segment by 8 in undo tablespace 'UNDOTBS1' I'm trying to import a large database, and after a while I get:

ORA-30036: unable to extend segment by 8 in undo tablespace 'UNDOTBS1'

I know this has been asked before, but I can't find a clear answer other than "increase the size".
Tablespace is like this:

It's an autoextend, but that is meaningless since it can't grow past 32GB, therefore I can't "increase the size".
Does impdp try to do everything in one transaction?
I don't care what it's putting in UNDOTBS1, if I lost everything in there that would be fine, I just want the import to run successfully.
Can I flush it out?, Is there an impdp option that I can use to make it not crash after 2 hours of hoping it won't crash?
There is plenty of disk space.
Any advice appreciated


text:
Q: Calling a script (with no extension) in Windows to compile code I'm a complete newbie when it comes to this, apologies if this appears retarded - been searching for a while with no avail.
I have file in a folder called "quocGCC" and to compile the code I have to go into this directory and call the script called "go" (it has no extension).
THIS is where I'm stuck (embarrassing, I know), so how exactly do I call this script in windows?
I've been told that this invokes cmake with all necessary options and will create makefiles (cmake is installed), not sure about the GCC compiler (is this necessary to install or can I do with another compiler?).
Thank you very much in advance,
Peter


text:
Q: how to make a query to count, sum, and group by name? I want to make a report like this, but I'm having trouble making the query.

no
merk
tahun
departemen
lokasi
history 2020
history 2021
Total (2020+2021)

1
machine A
2014
Production
LA 1
1
1
2

2
machine B
2019
Production
LA 2
0
2
2

and here's my codes for make table.

                          NO
                          MERK
                          TAHUN
                          DEPARTEMEN
                          LOKASI
                          HISTORY 2020 (X)
                          HISTORY 2021 (X)
                          TOTAL

                      <?php
                      $sql    = "SELECT merk_tmf,tahun_tmf,dept_tmf,lokasi_tmf FROM tb_tmf GROUP BY merk_tmf";
                      $data20 = mysqli_query($connect,"SELECT merk_tmf FROM tb_tmf WHERE YEAR(waktu_tmf) = 2020 GROUP BY merk_tmf");
                      $data21 = mysqli_query($connect,"SELECT merk_tmf FROM tb_tmf WHERE YEAR(waktu_tmf) = 2021 GROUP BY merk_tmf");
                      $jumlah = mysqli_query($connect,"SELECT merk_tmf FROM tb_tmf GROUP BY merk_tmf");

                      $jumlah20 = mysqli_num_rows($data20);
                      $jumlah21 = mysqli_num_rows($data21);
                      $penjumlahan = mysqli_num_rows($jumlah);

                      $no= 1;
                      $query = $connect->query($sql);
                      while($row = $query->fetch_assoc()){
                        echo
                            "

                                ". $no++ ."
                                ".$row['merk_tmf']."
                                ".$row['tahun_tmf']."
                                ".$row['dept_tmf']."
                                ".$row['lokasi_tmf']."
                                ".$jumlah20."
                                ".$jumlah21."
                                ".$penjumlahan."

";
                            }
                        ?>

that data is from this table.

waktu_tmf
merk_tmf
tahun_tmf
dept_tmf
lokasi_tmf

2020-06-29
machine A
1987
Production
LA 1

2021-06-29
machine A
1987
Production
LA 1

2021-06-29
machine B
1990
Production
LA 2

2021-06-29
machine B
1990
Production
LA 2

I know that there is an error in the query, because I can't make it right.

A: Try to run this, I hope this can give you idea...
    select merk_tmf merk, tahun_tmf tahun, dept_tmf departemen, lokasi_tmf lokasi,
          sum(case when date_format(waktu_tmf, '%Y') = 2020 then 1 else 0 end) 'history 2020',
          sum(case when date_format(waktu_tmf, '%Y') = 2021 then 1 else 0 end) 'history 2021',
          sum((case when date_format(waktu_tmf, '%Y') = 2020 then 1 else 0 end) +
          (case when date_format(waktu_tmf, '%Y') = 2021 then 1 else 0 end)) 'Total (2020+2021)'
    from tb_tmf
    group by merk_tmf, lokasi_tmf


text:
Q: Using D3.js geom to scale a voronoi polygon with result in lat long, not coordinates in px I am trying to create voronoi polygons for a set of inputs points in lat/long. The problem is my input dataset can contain multiple points at the same location and hence the same voronoi polygons are returned for that point.
I would like to visually display the overlapping polygons (with each polygon slightly smaller than the previous) to demonstrate that there are multiple polygons at the same point as per the screenshot below.
From reading the documentation, it seems that you can scale projections but these projections are already in px, not my real world lat/long values.
So, how can I take an input polygon in lat/long and return a polygon that is shrunk by X%, with the output polygon in lat/long using d3.js-v3?
Example polygon input: [long1, lat1, long2, lat2, long3, lat3, long4, lat4]

edit: the above image is using a "clip" function to clip the polygons with ever shrinking clip radiuses, which gives the desired effect for edge polygons, but does not achieve the desired effect for internally bound polygons.

A: So the solution was quite easy in the end.
var p1 = d3.geom.polygon(polygonArray);
var centroid = p1.centroid();
var newPolygonArray = [];
p1.forEach(function(v, i) {
    var newLong = centroid[0] + (v[0] - centroid[0])*(0.9);
    var newLat = centroid[1] + (v[1] - centroid[1])*(0.9);
    newPolygonArray.push(newLong, newLat);
}.bind(this));

I spent far too long trying to use d3 functions and projections to transform, translate and scale the polygon, but as soon as I left work that day it hit me that all I needed to do was the simple maths procedure above.
The lesson is to take a break when you are stuck, fresh air can open your eyes.
concentric voronoi polygons


text:
Q: Tkinter Treeview Empty Row Is there a way to create an empty row in a Treeview for Tkinter. A row that other rows can be moved to?
Currently I have a treeview where rows can be moved.  When moved currently it switches the places of all the other rows to fill the gap.  I want an area where I can move a row to without affecting the other rows?


text:
Q: Quick Sort. C++ Доброго времени суток.
Изучаю алгоритмы и в качестве задания реализовал быструю сортировку(см. код ниже).
Сравниваю с алгоритмами в мировой паутине, ничем кардинально не отличается, но мой вызывает Stack Overflow, подскажите, почему?
void my_qsort(vector<int>& arr, int l, int r)
{
    int left = l;
    int right = r;
    int mid = left + (right - left) / 2;

    while (left <= right) {
        while (arr[left] < mid) {
            left++;
        }
        while (arr[right] > mid) {
            right--;
        }
        if (left <= right) {
            swap(arr[left++], arr[right++]);
        }
    }
    if (l < right) {
        my_qsort(arr, l, right);
    }
    if (r > left) {
        my_qsort(arr, r, left);
    }
}

A: void my_qsort(vector<int>& arr, int l, int r)
{
    int left = l;
    int right = r;
    int mid = arr[(left + right) / 2];

    while (left <= right) {
        while (arr[left] < mid) {
            left++;
        }
        while (arr[right] > mid) {
            right--;
        }
        if (left <= right) {
            swap(arr[left++], arr[right--]);
        }
    }
    if (l < right) {
        my_qsort(arr, l, right);
    }
    if (r > left) {
        my_qsort(arr, left, r);
    }
}


text:
Q: Random errors thrown by Bash shell: cannot open named pipe I have found that keeping a detailed log of every command I run, from which path I ran it from and which user I sudo'd from, is extremely valuable as the years go by and I'm trying to remember what I did. Some time ago, after browsing various articles on this site as well as others I came up with a solution that works really well.  Here is what I have in my .bashrc:
SUDOUSER=`who am i | awk '{print $1}'`
SUDOIP=`who am i | awk '{print $6}'`
DT=`date +"%Y%m%d%H%M%S"`

export HISTCONTROL=ignoredups
export HISTFILE=~/.history
DETAILHISTORY=~/.historydetail

echo $DT $SUDOUSER:$SUDOIP[$$] \|\|\| $(finger $SUDOUSER | head -1) logged in on $(date) \|\|\| >> $DETAILHISTORY
export PROMPT_COMMAND='trap "" 1 2 15; DT=`date +"%Y%m%d%H%M%S"`; history -a >(tee -a ~/.bash_history | while read line; do cwd=$(echo "$cwd" | sed "s|$HOME|~|g"); if [[ $line =~ ^#[0-9]*$ ]]       ; then continue; fi; echo "$DT $SUDOUSER:$SUDOIP[$$] {$cwd} $line" >> $DETAILHISTORY; done); if [[ $(history 1) == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; trap 1 2 15;'

I get output like this:
20180919150704 MyUsername:(192.168.24.207)[14090280] ||| Login name: MyUsername In real life: MyName logged in on Wed Sep 19 15:07:04 EDT 2018 |||
20180919150704 MyUsername:(192.168.24.207)[14090280] {~} clear
20180919150708 MyUsername:(192.168.24.207)[14090280] {~} cd user_scripts/
20180919150708 MyUsername:(192.168.24.207)[14090280] {~/user_scripts} ll
20180919150714 MyUsername:(192.168.24.207)[14090280] {~/user_scripts} cat file.sh
20180919151013 MyUsername:(192.168.24.207)[14090280] {~/user_scripts} cd
20180919151015 MyUsername:(192.168.24.207)[14090280] {~} cat .bashrc

Fantastic! It's saved my sanity so many times.
There is a down side however; every so often, out of the blue I'll get this message:
bash: cannot open named pipe /tmp//sh-np.5ARMam for reading: A system call received an interrupt.

and sometimes I'll get a whole bunch at once:
bash: cannot open named pipe /tmp//sh-np.4QRMal for reading: A system call received an interrupt.
bash: cannot open named pipe /tmp//sh-np.zqRMaj for reading: A system call received an interrupt.
bash: cannot open named pipe /tmp//sh-np.y7RMai for reading: A system call received an interrupt.
bash: cannot open named pipe /tmp//sh-np.6ARMan for reading: A system call received an interrupt.

I don't see any rhyme or reason for it; sometimes it happens when I adjust the size of the putty/terminal window, which I don't understand. This started happening when I added the detailed history logging (and stops when I disabled it).
Can anyone offer any guesses as to what portion of the history logging in PROMPT_COMMAND may be contributing to this issue, and even better how it might be prevented?


text:
Q: Como usar o bootstrap para websites com layout maior? Bom, eu sempre desenvolvi websites com bootstrap e nunca modifiquei o tamanho padrão do container que é de 1170px porque nunca houve necessidade. Agora tenho um layout de 1900 de largura.
Também uso sempre a sequencia col-md-12 col-sm-12 col-xs-12
Qual o procedimento correto para adaptar o container ao tamanho do meu layout? Tenho que usar o -lg- para desenvolver websites cujo a tela é maior que 1200px?

A: Use a biblioteca BootstrapXL (extra large ou extra grande).
É apropriada para telas com mais de 1600px de largura.
Link do GitHub: BootstrapXL

A: Se quiser modificar o layout apenas para telas grandes, pode adicionar em seu CSS o seguinte:
@media screen and (min-width: 1980px){
    .container{
        width: 1900px;
    }
}
A largura é 1980px é arbitrária. Eu coloquei este valor, mas você pode colocar outros. O ideal é que seja maior que 1900px, pra dar uma "folga" para o container.
Adicione esta regra em outro CSS para sobrepor o do Bootstrap. Não é aconselhável alterar o próprio arquivo do Bootstrap.


text:
Q: How to indent #if directives in code?
Possible Duplicate:
How to force indentation of C# conditional directives?
Can visual studio automatically indent / format preprocessing directives?

In the following sample code there is a #if directive but notice the lack of indentation:
                else
                {
#if DEBUG
    Debug.Print(ex.Message);
#endif
                    return null;
                }

I know this is probably like this for some pure development practice, but honestly within VS.NET I do not care and would prefer it to align with my code. Is there a way to allow # directives be auto indented inline with the rest of the code in VS.NET?
Thanks!

A: I'm not sure you can do it with Visual Studio natively. You might have to use a plugin like
StyleCop. See http://stylecop.codeplex.com/
I understand why you'd want the indentation done- because the conditional directives currently look quite messy. However, with the current indentation, the advantage is that it can be easily seen by someone who is reading your code. Since conditional directives can change the flow of your code by a great extent, it might be okay as it is right now. Otherwise, you have the plugin options :)

A: I tried to search something here:

Option -> Text Editor -> C#

but unfortunately it seems that visualstudio doesn't have anything built in which permit you to indent the preprocessor directives in that way. However googling I found this answer and it recommends to use StyleCop. Hope this helps you.

A: I don't know of anything, but the # pragmas shouldn't be indented anyway, as they are not affected by the code. It's fine to indent the Debug.Print of course.


text:
Q: remove parent element but keep the child element using jquery in HTML From the below HTML i want to remove the div and H2 tags but keep the UL tag using jquery.
Please advise how i can achieve this

<asp:Literal ID="categoryTitle" runat="server"></asp:Literal>

Thanks

A: You can use replaceWith()
$('.row').replaceWith(function() {
 return $('ul', this);
});

Working Demo

A: I stumbled across this page when simply trying to remove a parent element (whilst still keeping the children) - just in case it's useful to others I found unwrap to be exactly what I needed. For me it was a simple find-an-element-and-unwrap:
$('.target-child').unwrap();

However the addition of the h2 removal in this case makes things a little bit more involved:
$('.row h2').siblings('ul').unwrap().end().remove();

http://jsfiddle.net/t8uQ8/
The above should be more optimal as it doesn't rely on the use of an anonymous function creation and call.

A: You could use jQuery detach() function ?
This will remove the element (visually) but keep its code in a variable, then you can append it into another parent.

A: As @Silvain said, you could detach the element and save the reference to a variable.
var $ul = $('.row h2').siblings('ul').detach();

Then you could insert the ul after its parent and, later, remove the parent from DOM:
$('.row').after($ul).remove();


text:
Q: Whatsapi send image works on local machine but not online Hi I have a weird issue.
On my local machine I can send images no problem, when I upload (same code) , it does seem to send the image, but they actually never arrive at the destination.
Here is the debug: http://pastebin.com/TiMnpHxt
Any idea what might be the problem here?

A: In you local computer you are using xamp version 1.8.3 or upper version of that, and may be in your hosting server have a lower version of xamp or php version that is why


text:
Q: Access subform unbound control #Error I have a subform embedded in my main form as a datasheet. The subform's data gets populated after I select some filtering criteria and click "search" button. Everything works fine except one control I have in this subform. This is an unbound control and I will set its control source in the subform's onLoad event with values input from other controls of my subform. When I first load the main form and before select anything or click "search" button, the subform is displayed with an empty row of record. However, on the column of my unbound control, it shows as "#ERROR" while others are all blank. I know this will work fine after I do the search and my unbound control data gets populated, but is there anyway I can avoid showing the ugly "#ERROR" in my subform?
Part of my code is here.
Private Sub Form_Load()

Me.text_root_cause_field.ControlSource = "=getLatestRemark([plant], [shipment_no])"

End Sub

Public Function getLatestRemark(plant_code As String, shipment_no As String) As String

Dim db As Database
Dim srRS As Recordset

Set db = CurrentDb
Set srRS = db.OpenRecordset("SELECT TOP 1 root_cause FROM Shipment_Remark" _
                            & " WHERE plant = '" & plant_code & "'" _
                            & " AND shipment_no = '" & shipment_no & "'" _
                            & " ORDER BY update_time DESC", dbOpenDynaset)

If Not srRS Is Nothing Then
    If Not srRS.EOF Then
        getLatestRemark = srRS!root_cause
        srRS.Close
        Set srRS = Nothing
    End If
Else
    getLatestRemark = ""
End If

db.Close
Set db = Nothing

End Function

These are codes for my subform. text_root_cause_field is the unbound field I am talking about. Its control source depends on two other bound fields - [plant] and [shipment_no]. The field [plant] and [shipment_no], however, are only bound at run time after the user clicks search button in the main form and the subform's record source is set.
Thanks  for the help.

A: Thanks @Wayne G. Dunny for his helpful discussion with me. This helps me figure out the problem of my current implementation and a possible solution to it.
Here is the reason for the #ERROR shown in my unbound text box, text_root_cause_field. This text box is bound to a function call in my subform's Load Event with two other fields from my subform's record source as parameters. This will initially give me a value in text_root_cause_field text box because the record source of my subform has been set in the form property to be one of my queries, Shipment_cycle_time.
This works fine until the program hits my main form's Open Event. In the Open Event, I set the subform's record source to be NULL because I do not want to display any data on the form's startup. As the main form's Open Event happens after the subform's Load Event, I do not have any field present in the subform any more. So the function which my text_root_cause_field is bound to is retrieving values from two non-existent fields. This gives the #ERROR.
The solution is pretty simple after the cause is figured out. I can include the SQL output of my function to the SQL of my subform's record source. So the subform's record source becomes like
SELECT s.*, (SELECT TOP 1 root_cause FROM Shipment_Remark as r
                            WHERE r.plant = s.plant
                            AND r.shipment_no = s.shipment_no
                            ORDER BY r.update_time DESC) as root_cause
          FROM shipment_cycle_time AS s WHERE TRUE

In addition to all the fields in shipment_cycle_time query, the other field root_cause is selected from a different table based on the two shipment_cycle_time fields. This is exactly the same as what returns from the function. Instead of using a function, I set the controlsource of the text box text_root_cause_field to root_cause field.
Problem solved!

A: Since you are setting the value in the Form_Load event, why not just check if there are zero records, and if so, then don't set the value - let it be blank.


text:
Q: Plot with different line style when clicked I have a plots with many lines and would like to be able to highlight lines when clicked (or on mouseover). When the data plotted is small this works well
styles = {Automatic, Automatic};
Dynamic@ListStepPlot[
  MapIndexed[
    EventHandler[#,
      {"MouseClicked" :>
        (styles[[#2[[1]]]] =
           styles[[#2[[1]]]] /. {Thick -> Automatic, Automatic -> Thick})}] &,
    {{1, 2, 3}, {2, 3, 5}}],
  PlotStyle -> styles]

But my data is large and including the complete ListStepPlot inside Dynamic makes it very slow.
So I tried this, but it didn't work:
styles = {Automatic, Automatic};
ListStepPlot[
  MapIndexed[
    EventHandler[#,
      {"MouseClicked" :>
        (styles[[#2[[1]]]] =
           styles[[#2[[1]]]] /. {Thick -> Automatic, Automatic -> Thick})}] &,
    {{1, 2, 3}, {2, 3, 5}}],
  PlotStyle -> Dynamic[styles]]

I know that Dynamic can be used for some Plot options values but apparently not for PlotStyle. Is there a way to make this work efficiently for large data sets?

A: Edit: more efficient and more flexible solution:
ListStepPlot[
    {{1, 2, 3}, {2, 3, 5}}, BaseStyle -> Thick
] /. {styles__, l_Line} :> DynamicModule[
    {edge = Thin}
  , {styles
    , Dynamic @ edge
    , MouseAppearance[
          EventHandler[
              l
            , "MouseClicked" :> (edge = edge /. {Thick -> Thin, Thin -> Thick} )
          ]
        , "LinkHand"
      ]
    }
 ]

Here is the old fix. Not the best as it doubles the size of the GraphicsBox:
ListStepPlot[
    {{1, 2, 3}, {2, 3, 5}}, BaseStyle -> Thick
] /. {styles__, l_Line} :> {
    styles
  , MouseAppearance[Dynamic@Mouseover[{Thin, l}, {Thick, l}], "LinkHand"]
}

A: Here's a way to do it by post-processing the Plot:
styleFloops =
  Map[RandomColor[] &, Range[2]];
styles =
  Map[Directive[ColorData[97][#], Thickness@Medium] &, Range[2]];
ListStepPlot[
  MapIndexed[
   EventHandler[#, {"MouseClicked" :> (styles[[#2[[1]]]] =
         styles[[#2[[1]]]] /. {Thick -> Thickness@Medium,
           Thickness@Medium -> Thick})}] &, {{1, 2, 3}, {2, 3, 5}}],
  PlotStyle ->
   styleFloops
  ] /.
 MapIndexed[
  Directive[a___, #, b___] :>
    Dynamic[Directive[a, styles[[First@#2]], b]] &,
  styleFloops
  ]

It works under the assumption that RandomColor will never be the Axes color and will never intersect. I think that's reasonable.

A: You can also use FlipView to flip through a list of styles on each mouse click:
styles = {Thin, AbsoluteThickness[3], Directive[Thick, Dashed]};

ListStepPlot[{{1, 2, 3}, {2, 3, 5}}] /.
  l_Line :> MouseAppearance[FlipView @ Thread[{ styles, l}], "SampleStyle"] // Deploy


text:
Q: If I have that $Z$ is a random variable, and $f$ is a measurable function, how can I show that $E(f(Z)Y |Z) = f(Z)E(Y|Z)$? I have that $Z$ is a random variable, and that $f$ a measurable function, and would like to show that:
$$
E(f(Z)Y |Z) = f(Z)E(Y|Z)
$$
This was under wikipedia's expectation page under the "pulling out what is known" section. I am able to do this if I do not use measure theory, but I am unsure how to do this from a measure-theoretic standpoint. Would anyone have any hints? Thanks!

A: In general, if $X$ is $\sigma(Z)$-measurable and $\mathbb E[|XY|]<\infty$, then $$\mathbb E[XY\mid Z] = X\mathbb E[Y\mid Z]. \tag 1 $$ The proof uses the "standard machinery" of measure theory - prove $(1)$ for indicator random variables (i.e. $X=\mathsf 1_A$ where $A\in\sigma(Z)$), then for conical combinations of indicator random variaables, then for nonnegative random variables by monotone convergence, then passing to positive and negative parts.


text:
Q: Rails Association options I am new to Rails just been learning the last month or so. I have a question regarding setting up model associations. I have sort of hit a spot where I think I need to go back and make changes to what I've already done. Here is the scenario.
I am creating an application for bands to list upcoming events.
There are a few important factors

*

*There are multiple bands listing events

*Each band will have unique events but will also share some events with some of the other bands (i.e. when two bands using this system are playing the same venue together)

*There is certain information about each event which will be common to all bands on the event (i.e. venue, date, time, city, state, etc)

*There is certain information about each event that is specific to one band (i.e. specific VIP ticket purchase URLs, their own description of the event, etc)

Currently this is how its set up:
class Event < ActiveRecord::Base
  belongs_to :venue
  scope :upcoming, where('date >= ?', Date.today)
end

class Venue < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

I haven't really done much with the artist model yet as I was just focusing on getting the events in to the system and listed properly for 1 artist which was hardcoded in.
Essentially right now how it works is the user goes to the create an event form, they select the date and the next line is venue name. The venue name form autocompletes with the Venue Name + City from the DB. If the user is creating a event at a venue already in the system it essentially saves the Event info via the Venue model as a nested attribute. If the venue is not in the system additional input fields for location data appear and then a new venue is created and associated with that event.
It begins to get a bit tricky when I start to think about the best way to have artists share events and maintain particular details about events that are specific to that artist only. I could just treat every event as an individual event and it would be easy but then I am not sure how I would be able to say this artist is performing with this artists on this date aside from the artists inputting those names directly into 1 field. I also then lose a lot of the magic of the ActiveRecords with respect to which artists performed with which other artists where, etc.
As of now there is just 1 model for events, but i am thinking maybe it might be best to keep 1 central model for just the event basics that aren't shared by multiple bands like venue, city, state, etc and then link those to a secondary event_details model for band specific information.
Would you suggest the multiple models or is there a better way for me to link bands playing multiple events together than creating an event detail model linking back to the 1 main event that multiple artists share? Should I just create some type of unique event identifier on the events table so that I am treating an event with a different ID as the same event another band is playing? Only issue I see with that is then I am going to be doubling up on a lot of that data that is in my database...I essentially want to be able to while looking at event data say ok on this date the artist is playing this show, at this venue, with these other bands with out having to just simple make an "other_artists" column where the bands would simply list artists they are performing with.
sorry i hope that makes sense...thanks in advance for any advice!

A: I think your real issue here is that you are going to need to handle a many-to-many relationship between artists and events.  Events will have many artists booked, and artists will have many events on their schedule.
I would create a "Booking" class that specifically ties one artist to one event.  This booking will be a good place to hold any special requirements or special arrangements for that artist playing at that event.  Using ActiveRecord's "has_many :through" relationship will make this very straight forward and give you a lot of flexibility in how you can query the data.  Here is how I would do it:
class Event < ActiveRecord::Base
  belongs_to :venue
  has_many :artists, :through => :bookings
  scope :upcoming, where('date >= ?', Date.today)
end

class Venue < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

class Artist < ActiveRecord::Base
  has_many :events, :through => :bookings
end

class Booking < ActiveRecord::Base
  belongs_to :artist
  belongs_to :event
  attr_accessible :special_requirements, :special_arrangements
end

Some examples the flexibility you get in querying data via these relationships:
 @venue.events
 @venue.events.where(:id => specific_event.id).first.artists
 @event.artists
 @artist.events
 @event.bookings each do |b|
   b.artist
   b.special_requirements
 end

Hope this helps.


text:
Q: ASP.NET: Implementing a client server solution (for chats, iterative fights ect) I have a quite advanced application, where I need to add some client/server functionality. Some examples of functionalities is:

*

*Chat

*One vs. one fight in a browser game

*Draw people on a map

I am creating this application in ASP.NET and AJAX. I do not use Silverlight/Java Applet/Flash or anything else. If possible, I do not want to change this for other reasons.
I thought about creating some kind of game server, and then communicating either web services or TCP protocol: But I have NO idea if this is a good idea. Also, I don't know how to do this.
So my question is:
What's the best way to implement this? And is it even possible? And if it is, could you give a reference or two?
Thanks a lot,
Lars

A: For doing chat & multiplayer games, the crux of the problem is in getting the server to asynchronously send messages to the client. This can be accomplished by a method called reverse-Ajax (or commet). Here is a simple example for how to do reverse-Ajax with ASP.NET. This is a very involved concept (at least until we can use HTML5 WebSockets) with a lot of thought going into security concerns, et al. I assume that by asking this question you are already quite familiar with Ajax & browser scripting (if not, you have a lot of reading to do).

A: Tutorial on writing a basic chat server: (in c# no less)
http://www.dreamincode.net/forums/topic/33396-basic-clientserver-chat-application-in-c%23/
Sgive you a good foundation on server development.


text:
Q: How to replace a value of variable with different different values using notepad++ I have this:
"KeySchema" : [
      {
        "AttributeName" : "id",
        "KeyType" : "HASH"
      },
      {
        "AttributeName" : "chunk_id",
        "KeyType" : "RANGE"
      }
    ],
    "ProvisionedThroughput" : {
      "ReadCapacityUnits" :  "20",
      "WriteCapacityUnits" : "10"
    },
    "TableName" : "uat_appcast"

I want to change the value of "TableName" which is "uat_appcast" with another value say "qa_appcast_01"
I have got multiple instances of "TableName" in this file and each will have different value.


text:
Q: Solve the ODE $y'' = (y')^2$ I am asked in a past question paper to solve the following ODE: $$ y'' = (y')^{2}$$
To solve this, I began by equating $$y' = u$$
Differentiating both sides $w.r.t.x$ $$ \frac{d^{2}y}{dx^{2}} = \frac{du}{dx}$$
And therefore substituting back to out original equation I got:
$$  \frac{du}{dx} = u^{2}$$
Rearranging $$\frac{du}{u^{2}} = dx$$
Integrating $w.r.t.x$ I got
$$ \frac{-1}{u} = x+C$$ and substituting back $u$
$$ \frac{-dx}{dy} = x+C$$
$$ =x + \frac{dx}{dy} = C$$
$$=\frac{-dx}{x+c} = dy$$
$$ \log(\frac{1}{x+c}) = y$$
$$ -(x+c) = e^{y}$$
Is my answer and method correct?
EDIT As pointed out by @MtGlasser
We can re-write the D.E as $$ \frac{y''}{y'} = y'$$
Which is of the form :
$$(ln(y'))' = y'$$
Integrating on both sides we get
$$ ln (y') = y + c$$
And taking exponent on both sides and re-arranging we get
$$ e^{-1}e^{-y} dy = dx$$
Integrating we get the asnwer $$ e^{-(y+1)} - C = x$$

A: You could even do it faster switching variables
$$y'' = (y')^{2} \implies -\frac {x''}{[x']^3}=\frac {1}{[x']^2}\implies x''=-x'$$
Reduction of order
$$p'=-p \implies p=x'=c_1\,e^{-y}\implies x=-c_1 \,e^{-y}+c_2\implies y=\cdots$$

A: Your method is mostly correct, although the steps could be made more clear for the latter part and also you didn't include another constant of integrating after the last integration. Note you can stop once you have expressed $y$ in terms of $x$, unless it says in the question to express $x$ in terms of $y$.
We have
$$-\frac{dx}{dy}=x+C_{1}$$
$$\frac{dx}{dy}=-x-C_{1}$$
$$-\frac{dx}{x+C_{1}}=dy$$
$$\color{red}{C_{2}}-\ln(x+C_{1})=y$$
$$\implies y(x)=C_{2}-\ln(x+C_{1})$$


text:
Q: Summarize values in recursive function I have following permutation code
void permute(Matrix *m,int *array,int i,int length) {

     if (length == i){
         printA(array,4);
         return;
      }

     int j = i;
     for (j = i; j < length; j++) {
         swap(array+i,array+j);
         permute(m,array,i+1,length);
         swap(array+i,array+j);
     }
     return;
}

Its working fine but i want to execute a function to every permutation of array which return a value and add them together.
Example : [1 2 3 4] -> function(array) -> 12 , [1 3 2 4] -> function(array) -> 13 => 13+12 = 25 (This will be determinant calculator)
Tried this:
 double cnt = 0;
 if(lenght == i){
     cnt += function1(array,4);
 }

But it just show distinct values not summarize them. Where is should repair the function?

A: Since recursion calling function at every permutation i need to use static global counter to summarize values. So i just put somewhere static double cnt = 0; and working fine.


text:
Q: Power Up Issues with MacBook Pro A1278 First-off, let me preface this question by stating that I know nothing to very little about computers, especially Apple computers. That being said, I have a MacBook Pro A1278 model. About a month ago, smoke started coming out of the top row of keys on the keyboard (not good at all - that much I do know); so, I powered it down. Then it would not power up at all. This morning, I tried plugging in the adapter and, lo and behold, it started to fire up. However, the progress bar only moves about a third of the way across before it shuts down again. It does this whether or not the adapter is plugged in or not, so I am thinking that it is not the adapter or the battery. If I continue to hold down the power button, it was going into my Desktop. However, as soon as I release it, within about 2 seconds, it shuts down again. Also, now when I continue to hold the power button down, it only makes it about halfway and then shuts off again.
Could it be my power supply? something else? Any advice would be greatly appreciated as it is a work computer. Thanks.

A: The smoke coming out of your Macbook would lead anyone to conclude that the problem system had either an:

*

*Overheating battery (common on some model MBP's)

*Overheating CPU (not at all common unless there is a blockage or other external heat.)

As others have suggested, it is definitely time for you to triage and rescue whatever remains on the HDD and take it to the Apple Store for a further diagnosis. Here are some things you can do in the meantime

*

*Verify if the battery is the problem. Take a careful look at the chassis of the aluminum unibody. Does it seem swollen in some areas? If you use one finger to press on an edge of the MBP, does it rock? Swollen batteries are a common indicator of battery malfunction.

*If the battery is removable from the bottom of the MBP, go ahead and remove it. Attach the AC adapter and power on your MBP without the battery installed. This should mitigate your device from turning off because of the heat from a malfunctioning battery. Other things you can do is place your device on a cool, dry kitchen counter while running it without the battery. This will further allow you to use the computer without risk of running into the CPU thermal throttling timer (simple function: too hot -> turn off).

*Lastly, if the above tip worked, immediately move your HDD contents to a backup location.

Please report back on your findings and mark answered if this helps.


text:
Q: Quickest way to change endianness What is the quickest way to reverse the endianness of a 16 bit and 32 bit integer. I usually do something like (this coding was done in Visual Studio in C++):
union bytes4
{
    __int32 value;
    char ch[4];
};

union bytes2
{
    __int16 value;
    char ch[2];
};

__int16 changeEndianness16(__int16 val)
{
    bytes2 temp;
    temp.value=val;

    char x= temp.ch[0];
    temp.ch[0]=temp.ch[1];
    temp.ch[1]=x;
    return temp.value;
}

__int32 changeEndianness32(__int32 val)
{
    bytes4 temp;
    temp.value=val;
    char x;

    x= temp.ch[0];
    temp.ch[0]=temp.ch[1];
    temp.ch[1]=x;

    x= temp.ch[2];
    temp.ch[2]=temp.ch[3];
    temp.ch[3]=x;
    return temp.value;
}

Is there any faster way to do the same, in which I don't have to do so many calculations?

A: Why aren't you using the built-in swab function, which is likely optimized better than your code?
Beyond that, the usual bit-shift operations should be fast to begin with, and are so widely used they may be recognized by the optimizer and replaced by even better code.

Because other answers have serious bugs, I'll post a better implementation:
int16_t changeEndianness16(int16_t val)
{
    return (val << 8) |          // left-shift always fills with zeros
          ((val >> 8) & 0x00ff); // right-shift sign-extends, so force to zero
}

None of the compilers I tested generate rolw for this code, I think a slightly longer sequence (in terms of instruction count) is actually faster.  Benchmarks would be interesting.
For 32-bit, there are a few possible orders for the operations:
//version 1
int32_t changeEndianness32(int32_t val)
{
    return (val << 24) |
          ((val <<  8) & 0x00ff0000) |
          ((val >>  8) & 0x0000ff00) |
          ((val >> 24) & 0x000000ff);
}

//version 2, one less OR, but has data dependencies
int32_t changeEndianness32(int32_t val)
{
    int32_t tmp = (val << 16) |
                 ((val >> 16) & 0x00ffff);
    return ((tmp >> 8) & 0x00ff00ff) | ((tmp & 0x00ff00ff) << 8);
}

A: At least in Visual C++, you can use _byteswap_ulong() and friends: http://msdn.microsoft.com/en-us/library/a3140177.aspx
These functions are treated as intrinsics by the VC++ compiler, and will result in generated code that takes advantage of hardware support when available. With VC++ 10.0 SP1, I see the following generated code for x86:
return _byteswap_ulong(val);

mov     eax, DWORD PTR _val$[esp-4]
bswap   eax
ret     0

return _byteswap_ushort(val);

mov     ax, WORD PTR _val$[esp-4]
mov     ch, al
mov     cl, ah
mov     ax, cx
ret     0

A: Who says it does too many calculations?
out = changeEndianness16(in);

gcc 4.6.0

movzwl  -4(%rsp), %edx
movl    %edx, %eax
movsbl  %dh, %ecx
movb    %cl, %al
movb    %dl, %ah
movw    %ax, -2(%rsp)

clang++ 2.9

movw    -2(%rsp), %ax
rolw    $8, %ax
movw    %ax, -4(%rsp)

Intel C/C++ 11.1

movzwl    4(%rsp), %ecx
rolw      $8, %cx
xorl      %eax, %eax
movw      %cx, 6(%rsp)

What does your compiler produce?

A: I used the following code for the 16bit version swap function:
_int16 changeEndianness16(__int16 val)
{
    return ((val & 0x00ff) << 8) | ((val & 0xff00) >> 8);
}

With g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 the above code when compiled with g++ -O3 -S -fomit-frame-pointer test.cpp results in the following (non-inlined) assembler code:
movzwl  4(%esp), %eax
rolw    $8, %ax
ret

The next code is equivalent but g++ is not as good at optimizing it.
__int16 changeEndianness16_2(__int16 val)
{
    return ((val & 0xff) << 8) | (val >> 8);
}

Compiling it gives more asm code:
movzwl  4(%esp), %edx
movl    %edx, %eax
sarl    $8, %eax
sall    $8, %edx
orl     %edx, %eax
ret


text:
Q: Temporarily redirect PHP error_log destination (STDERR) I'm running a unit test with PHPUnit on a class that calls error_log internally (with message_type 0, so it's the "standard" error output for that PHP environment). When running the test on the command line, the output of error_log interrupts the PHPUnit output, because in a command line environment the output of error_log is STDERR. Is it possible to capture or redirect the output to STDERR for just one call inside my test code? In pseudocode:
function testSomethingHappens() {

    // TODO redirect STDERR
    $result = (new MyClass())->doSomething();
    // TODO restore STDERR

    $this->assertSame( 'OK', $result );
}


text:
Q: How to read multiple files from multiple remote servers in Python? I have a list of AWS ubuntu servers e.g
ubuntu@ec2-bla-95-blablabla-23.amazonaws.com
ubuntu@ec2-bla-95-blablabla-43.amazonaws.com
ubuntu@ec2-bla-95-blablabla-24.amazonaws.com
...

On each of these servers, I have a folder with variable number of files, the path is the same for each server e.g /roth/files/
I want to write a Python script that would fetch the contents of those files and merge them locally on my machine.
How do I go about fetching contents of those files on remote servers?
The way I login to these servers is
ssh -i  path/aws.pem ubuntu@ec2-bla-95-blablabla-23.amazonaws.com

e.g using a key
I found answer on similar question here
sftp_client = ssh_client.open_sftp()
remote_file = sftp_client.open('remote_filename')
try:
    for line in remote_file:
        # process line
finally:
    remote_file.close()

But I do not see where you provide a server name, and the key...
EDIT:
As a small correction to Ganesh's answer you need to do the following to fetch every file or otherwise you get an error complaining that you try to fetch directory:
lobj = sftp.listdir_attr(target_folder_remote)
    for o in lobj:
        name = o.filename
        sftp.get(os.path.join(target_folder_remote, name), os.path.join(target_folder_local, name))

A: aws_host_list = [] # Your list here

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dest_list = list()
for host in aws_host_list:
    client.connect(host, username=<User Name>, key_filename=<.PEM File path)
    sftp = client.open_sftp()
    lobj = sftp.listdir_attr(target_folder_remote)
    for o in lobj:
        name = o.filename
        sftp.get(os.path.join(target_folder_remote, name), os.path.join(target_folder_local, name))
        dest_list.append(os.path.join(target_folder_local, name))
    sftp.close()
    client.close()

# Then process you files
for f in dest_list:
    # Combine it


text:
Q: How to correct font adjustment button alignment I have updated my code  so that the buttons can be seen in the nav bar and only target p tags with the id of "content" feel free to update the name to anything else for a project if some one is looking for  simple font resizer code. It will also save to local storage to keep the same font size throughout the page reload.
Thanks to those who helped me solve my original problem.

    <input type="button" value="A+" onclick="resizeText(1)" id="plustext">
    <input type="button" value="A-" onclick="resizeText(-1)" id="minustext">

          WebSiteName

            Home

            Page 1

            Page 2

               Sign Up

               Login

    This text will be made bigger

A: You can add a container for the buttons and set it to flex and flex-start to align the buttons to the start the container element.

    <input type="button" value="A+" onclick="resizeText(1)" id="plustext">
    <input type="button" value="A-" onclick="resizeText(-1)" id="minustext">

    This text will be made bigger

A: I try to change your code, so that you can understand the changes:

  <input type="button" value="A+" onclick="resizeText(1)" id="plustext">
  <input type="button" value="A-" onclick="resizeText(-1)" id="minustext">

    This text will be made bigger

.button-div
{
  display:flex;
}

this will not let increase the space between 2 buttons
if not believes me, have a look on jsfiddle:
https://jsfiddle.net/dupinderdhiman/cg5mws0n/7/