text:
Q: Can I get a \widebar without using the mathabx package? One can use \bar to put a bar over a letter in math mode, but often the bar isn't wide enough. An alternative is \overline, but this isn't an accent, so it doesn't take into account the skew of the letter. In the following example, the bar extends too far to the left:

Now the mathabx package offers a \widebar accent, but this has several drawbacks:

*

*mathabx changes a lot of other things,

*The \widebar sits slightly higher than \bar and \overline,

*In previewers (checked with kpdf and acroread), the \widebar appears fuzzy, which \bar and \overline don't.
So my question is: How can I put a wide bar over a letter in math mode without the above drawbacks?

A: I confronted a similar problem with a need for a pretty bar over various characters with \mathbf, \mathcal, \mathfrak, etc. By "pretty," I mean that the bar seems very appropriate to the character shape and size, and this means adjusting the length and placement (left and right offsets) until it looks right. Further, the commands used must be compatible with MathJax in HTML after the TeX file is converted to XML for conversion to HTML on the Springer website.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%        Program for "manually" adjusting the bar over capital letters     %
%        or any other character to put a bar over. You specify the         %
%        character and two offset lengths. The program calculates the      %
%        the bar length such that the character with a bar has the same    %
%        same length as the character without a bar.                       %
%                                                                          %
%        Specify the character and initial offsets below. Produce a pdf    %
%        and zoom in to see the barred character full screen. Return to    %
%        the TeX file and change the offsets until you are happy with      %
%        with the resulting appearance. Then zoom out with the pdf viewer  %
%        and copy the command for pasting wherever you want to save it.    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[letterpaper]{article}
\usepackage[vmargin=0.25in]{geometry}
\usepackage[tbtags]{amsmath}
\usepackage{amsfonts,amssymb}
\usepackage{calc}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   If you want to use a character from another font (e.g., Euler)         %
%   then add the needed package above.                                     %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newlength{\charlength}
\newlength{\leftoffset}
\newlength{\rightoffset}
\newlength{\overlength}
\newlength{\backlength}                             %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                                    %      User settings          %
\newcommand{\testchar}{\mathcal{S}}                 % Set the character you want  %
\newcommand{\printchar}{\textbackslash mathcal\{S\}}% twice, slightly different.  %
\setlength{\leftoffset}{0.71pt}                     % Set the left offset and the %
\setlength{\rightoffset}{0.71pt}                    % right offset for the bar.   %
                                                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\settowidth{\charlength}{$\testchar$}
\setlength{\overlength}{\charlength - \leftoffset - \rightoffset}
\setlength{\backlength}{\charlength - \rightoffset}

\pagestyle{empty}
\begin{document}
\vspace*{25mm}

$\overset{\kern\leftoffset\underline{\kern\overlength}\kern\rightoffset}{\testchar}$

$\text{\textbackslash overset\{\textbackslash kern\the\leftoffset\textbackslash underline\{\textbackslash kern\the\overlength\}\textbackslash kern\the\rightoffset\}\{\printchar\}}$

\bigskip

$\kern\leftoffset\overline{\vphantom{\testchar}\kern\overlength}\kern-\backlength\testchar$

$\text{\textbackslash kern\the\leftoffset\textbackslash overline\{\textbackslash vphantom\{\printchar\}\textbackslash kern\the\overlength\}\textbackslash kern--\the\backlength\printchar}$

\end{document}

One drawback is that you must the character you want in the program twice in slightly different ways. For example, if you want a nice bar on \mathfrak{C},
then in the program, which is now set for \mathcal{S},  you must change S => C twice and change cal => frak twice.
But the payback for the double effort is that you get the command to save or put into another TeX file by copying the command from the pdf in your reader (I use SumatraPDF because the pdf file stays open in the reader while I change the TeX, and when I make the new pdf in WinEdt, it transfers me back to reader looking at the changed pdf in exactly the same place, etc., as when I left it to edit the TeX file).
The program gives two variants: with \overset and with \overline of a phantom. The separation from the character with \overset is about 20% greater than the separation with \overline. On my screen with the so-called \widebar{\mathcal{S}} occupying the full 23.5 cm height of the reader view, the separation is 3 cm for \overset and 2.5 cm for \overline.
Suppose you have adjusted the left and right offsets for a pretty \barfrakC, but you now need a double bar. What to do?
Copy the line \newcommand\barfrakC{...} and paste it in the TeX file, change the \mathfrak{C} test character (and print character) to \barfrakC, and so on to get what you need to paste into \newcommand\dbarfrakC{}.

A: Here's a new implementation of \widebar, based on \overline. It works by hacking into amsmath's accent placement, so it needs that package. Here's a comparison of \widebar (first line) and \overline (second line):

I think the placement of the bars in the first line is better, except for the \sin z, where there's no difference. Note that \widebar works well together with superscripts, but not necessarily with subscripts. (\overline has the same issue.) It also works well over combined symbols like AB in most cases.
\documentclass{article}
\usepackage{amsmath}
\makeatletter
\let\save@mathaccent\mathaccent
\newcommand*\if@single[3]{%
  \setbox0\hbox{${\mathaccent"0362{#1}}^H$}%
  \setbox2\hbox{${\mathaccent"0362{\kern0pt#1}}^H$}%
  \ifdim\ht0=\ht2 #3\else #2\fi
  }
%The bar will be moved to the right by a half of \macc@kerna, which is computed by amsmath:
\newcommand*\rel@kern[1]{\kern#1\dimexpr\macc@kerna}
%If there's a superscript following the bar, then no negative kern may follow the bar;
%an additional {} makes sure that the superscript is high enough in this case:
\newcommand*\widebar[1]{\@ifnextchar^{{\wide@bar{#1}{0}}}{\wide@bar{#1}{1}}}
%Use a separate algorithm for single symbols:
\newcommand*\wide@bar[2]{\if@single{#1}{\wide@bar@{#1}{#2}{1}}{\wide@bar@{#1}{#2}{2}}}
\newcommand*\wide@bar@[3]{%
  \begingroup
  \def\mathaccent##1##2{%
%Enable nesting of accents:
    \let\mathaccent\save@mathaccent
%If there's more than a single symbol, use the first character instead (see below):
    \if#32 \let\macc@nucleus\first@char \fi
%Determine the italic correction:
    \setbox\z@\hbox{$\macc@style{\macc@nucleus}_{}$}%
    \setbox\tw@\hbox{$\macc@style{\macc@nucleus}{}_{}$}%
    \dimen@\wd\tw@
    \advance\dimen@-\wd\z@
%Now \dimen@ is the italic correction of the symbol.
    \divide\dimen@ 3
    \@tempdima\wd\tw@
    \advance\@tempdima-\scriptspace
%Now \@tempdima is the width of the symbol.
    \divide\@tempdima 10
    \advance\dimen@-\@tempdima
%Now \dimen@ = (italic correction / 3) - (Breite / 10)
    \ifdim\dimen@>\z@ \dimen@0pt\fi
%The bar will be shortened in the case \dimen@<0 !
    \rel@kern{0.6}\kern-\dimen@
    \if#31
      \overline{\rel@kern{-0.6}\kern\dimen@\macc@nucleus\rel@kern{0.4}\kern\dimen@}%
      \advance\dimen@0.4\dimexpr\macc@kerna
%Place the combined final kern (-\dimen@) if it is >0 or if a superscript follows:
      \let\final@kern#2%
      \ifdim\dimen@<\z@ \let\final@kern1\fi
      \if\final@kern1 \kern-\dimen@\fi
    \else
      \overline{\rel@kern{-0.6}\kern\dimen@#1}%
    \fi
  }%
  \macc@depth\@ne
  \let\math@bgroup\@empty \let\math@egroup\macc@set@skewchar
  \mathsurround\z@ \frozen@everymath{\mathgroup\macc@group\relax}%
  \macc@set@skewchar\relax
  \let\mathaccentV\macc@nested@a
%The following initialises \macc@kerna and calls \mathaccent:
  \if#31
    \macc@nested@a\relax111{#1}%
  \else
%If the argument consists of more than one symbol, and if the first token is
%a letter, use that letter for the computations:
    \def\gobble@till@marker##1\endmarker{}%
    \futurelet\first@char\gobble@till@marker#1\endmarker
    \ifcat\noexpand\first@char A\else
      \def\first@char{}%
    \fi
    \macc@nested@a\relax111{\first@char}%
  \fi
  \endgroup
}
\makeatother
\newcommand\test[1]{%
$#1{M}$ $#1{A}$ $#1{g}$ $#1{\beta}$ $#1{\mathcal A}^q$
$#1{AB}^\sigma$ $#1{H}^C$ $#1{\sin z}$ $#1{W}_n$}

\begin{document}
\test\widebar

\test\overline
\end{document}

Here is my previous simpler implementation; the intended use is for single symbols. It also works when applied to several symbols, but then the placement of the bar may not be appropriate (see AW at the end). Moreover, subsequent superscripts may be placed too close to the bar.

\documentclass{article}
\usepackage{amsmath}
\makeatletter
\newcommand*\rel@kern[1]{\kern#1\dimexpr\macc@kerna}
\newcommand*\widebar[1]{%
  \begingroup
  \def\mathaccent##1##2{%
    \rel@kern{0.8}%
    \overline{\rel@kern{-0.8}\macc@nucleus\rel@kern{0.2}}%
    \rel@kern{-0.2}%
  }%
  \macc@depth\@ne
  \let\math@bgroup\@empty \let\math@egroup\macc@set@skewchar
  \mathsurround\z@ \frozen@everymath{\mathgroup\macc@group\relax}%
  \macc@set@skewchar\relax
  \let\mathaccentV\macc@nested@a
  \macc@nested@a\relax111{#1}%
  \endgroup
}
\makeatother
\begin{document}
$\widebar{M}$ $\widebar{A}$ $\widebar{\mathcal A}$ $\widebar{g}$ $\widebar{\beta}$
$\widebar{AB}$ $\widebar{AW}$

$\overline{M}$ $\overline{A}$ $\overline{\mathcal A}$ $\overline{g}$ $\overline{\beta}$
$\overline{AB}$ $\overline{AW}$
\end{document}

A: 1) You can use only \widebar through:
% from mathabx.sty and mathabx.dcl
\DeclareFontFamily{U}{mathx}{\hyphenchar\font45}
\DeclareFontShape{U}{mathx}{m}{n}{
      <5> <6> <7> <8> <9> <10>
      <10.95> <12> <14.4> <17.28> <20.74> <24.88>
      mathx10
      }{}
\DeclareSymbolFont{mathx}{U}{mathx}{m}{n}
\DeclareFontSubstitution{U}{mathx}{m}{n}
\DeclareMathAccent{\widebar}{0}{mathx}{"73}

or simpler (with example):
\documentclass{article}
\DeclareFontFamily{U}{mathx}{\hyphenchar\font45}
\DeclareFontShape{U}{mathx}{m}{n}{<-> mathx10}{}
\DeclareSymbolFont{mathx}{U}{mathx}{m}{n}
\DeclareMathAccent{\widebar}{0}{mathx}{"73}
\begin{document}
$\widebar M = \widebar{abcd}$
\end{document}

2) I don't think it matters much, \bar h is also higher than \bar a. Just remember not to use \bar M and \widebar M together.
3) Maybe bad hinting. I've no idea.

A: I show my solution for this problem for plain TeX, where amsmath.sty isn't loaded, because the first line of this macro file says: \NeedsTeXFormat{LaTeX2e}. I leaved the \skewchar calculation because this is more suitable for accents like dot. My \ẅidebar begins by left slanted border (by default) and ends at the same place as \overline. If the first token is non-letter then normal \overline is used.
But there are many exceptions for this rule declared in \widebarE macro. If you feel that you are able to do better look of \widebar, then you can simply re-define the \widecharE or add to this macro more exceptions for more characters.
\newcount\tmpnum \newdimen\tmpdim
{\lccode`\?=`\p \lccode`\!=`\t  \lowercase{\gdef\ignorept#1?!{#1}}}
\edef\widecharS{\expandafter\ignorept\the\fontdimen1\textfont1}

\def\widebar#1{\futurelet\next\widebarA#1\widebarA}
\def\widebarA#1\widebarA{%
   \def\tmp{0}\ifcat\noexpand\next A\def\tmp{1}\fi
   \widebarE
   \ifdim\tmp pt=0pt \overline{#1}%
   \else {\mathpalette\widebarB{#1}}\fi
}
\def\widebarB#1#2{%
   \setbox0=\hbox{$#1\overline{#2}$}%
   \tmpdim=\tmp\ht0 \advance\tmpdim by-.4pt
   \tmpdim=\widecharS\tmpdim
   \kern\tmpdim\overline{\kern-\tmpdim#2}%
}
\def\widebarC#1#2 {\ifx#1\end \else
   \ifx#1\next\def\tmp{#2}\widebarD
   \else\expandafter\expandafter\expandafter\widebarC
   \fi\fi
}
\def\widebarD#1\end. {\fi\fi}
\def\widebarE{\widebarC A1.4 J1.2 L.6 O.8 T.5 U.7 V.3 W.1 Y.2
   a.5 b.2 d1.1 h.5 i.5 k.5 l.3 m.4 n.4 o.6 p.4 r.5 t.4 v.7 w.7 x.8 y.8
   \alpha1 \beta1 \gamma.6 \delta.8 \epsilon.8 \varepsilon.8 \zeta.6 \eta.4
   \theta.8 \vartheta.8 \iota.5 \kappa.8 \lambda.5 \mu1 \nu.5 \xi.7 \pi.6
   \varpi.9 \rho1 \varrho1 \sigma.7 \varsigma.7 \tau.6 \upsilon.7 \phi1
   \varphi.6 \chi.7 \psi1 \omega.5 \cal1 \end. }

\def\test#1{$\let\.=#1 \.M, \.A, \.g, \.\beta, \.{\cal A}^q, \.{AB}^\sigma,
  \.H^C, \.{\sin z}, \.W_{\!n}$}

\test\widebar

\test\overline

\bye

First line shows the \widechar, second line is normal \overline.

A: I had to use the \bm command from the bm package and neither Hendrik Vogt nor wipet's answers worked with it (at least for me). Bill Everett's answer did the job, but it has some drawbacks, as he pointed out.
I would say that drawbacks #1 and #2 are mitigated by my answer, but I am not able to talk about the third one.
Note: It's a kludge, I admit, but it did the job for me without errors or warnings. I hope you can help someone.

The syntax is as follows:
\mybar{<scale factor>}{<right shift>}{<math expression>}

Then you can control the scale of the bar in relation to the size of the mathematical expression and also control the offset from left to right starting from the beginning of the mathematical expression.

\documentclass{article}

\usepackage{bm}         % <----- for '\bm' command (optional)
\usepackage{mathtools}  % <----- for '\mathrlap' command (necessary)

\newcommand{\mybar}[3]{%
    \mathrlap{\hspace{#2}\overline{\scalebox{#1}[1]{\phantom{\ensuremath{#3}}}}}\ensuremath{#3}
}

\begin{document}

    $\mybar{0.6}{3pt}{\bm{A}}$
    $\mybar{0.6}{3pt}{A}$
    $\mybar{0.5}{2.9pt}{A}$
    \enskip
    $\bm{A}_i^{t}$
    $\mybar{0.6}{3pt}{\bm{A}}_i^{t}$
    $\mybar{0.6}{3pt}{\bm{A}_i^{t}}$
    \enskip
    $\bm{A}_i^{\{t\}}$
    $\mybar{0.6}{3pt}{\bm{A}}_i^{\{t\}}$
    $\mybar{0.6}{3pt}{\bm{A}_i^{\{t\}}}$
    \enskip
    $\mybar{0.2}{0pt}{\bm{A}}$
    $\mybar{0.2}{5pt}{\bm{A}}$
    $\mybar{1}{0pt}{A}$
    $\mybar{2}{7pt}{A}$

\end{document}

If you are planning to use this command more often for a specific mathematical expression, you can use the following code to make things cleaner.
\mybar[<scale factor>][<right shift>]{<math expression>}

\documentclass{article}

\usepackage{bm}         % <--- for '\bm' command (optional)

\usepackage{mathtools}  % <----- for '\mathrlap' command (necessary)
\usepackage{xparse}     % <----- for '\NewDocumentCommand' command (necessary)

\NewDocumentCommand{\mybar}{ O{0.60} O{3pt} m }{%  <---- Set the default values here
    \mathrlap{\hspace{#2}\overline{\scalebox{#1}[1]{\phantom{\ensuremath{#3}}}}}\ensuremath{#3}
}

\begin{document}

    $\mybar{\bm{A}}$
    $\mybar{\bm{V}}$            % <---- bad result
    $\mybar[0.6][2pt]{\bm{V}}$  % <---- set manually
    $\mybar{\bm{E}}$
    $\mybar{\bm{P}}$
    $\mybar{\bm{W}}$
    $\mybar{A}$
    $\mybar{V}$             % <---- bad result
    $\mybar[0.6][2pt]{V}$   % <---- set manually
    $\mybar{E}$
    $\mybar{P}$
    $\mybar{W}$

\end{document}

Drawbacks

*

*It is not an automated command. If you want to use it with many
different symbols, your code will become very dense.

*As I've used the command \phantom, the line is not seen by the rest
of the text, so things like this can happen:

\documentclass{article}
\usepackage{bm}
\usepackage{mathtools}
\newcommand{\mybar}[3]{%
    \mathrlap{\hspace{#2}\overline{\scalebox{#1}[1]{\phantom{\ensuremath{#3}}}}}\ensuremath{#3}
}
\begin{document}

    text text text text text text text text

    $\bm{A}_i^{t}$
    $\mybar{0.6}{3pt}{\bm{A}}_i^{t}$
    $\mybar{0.6}{3pt}{\bm{A}_i^{t}}$
    \enskip
    $\bm{A}_i^{\{t\}}$
    $\mybar{0.6}{3pt}{\bm{A}}_i^{\{t\}}$
    $\mybar{0.6}{3pt}{\bm{A}_i^{\{t\}}}$  % <-------- very close to the top text
    \enskip
    $\mybar{2}{7pt}{A}$                   % <-------- overlap
    $\overline{\bm{A}_i^{t}}$

    text text text text text text text text

\end{document}


text:
Q: Pandas dropping column issue I'm trying to drop a column from my dataframe, but the problem is that whenever I drop the column (which works) my columns always get rearranged in different orders. Does anyone know why this might be? This is my code right now:
df=df.drop('column_name', axis=1)

A: One way to do it is:
df = df[[col1,col2,col4]] #if col3 is what you want to drop

This is useful when you have fewer columns.

A: I can not reproduce your problem. But I believe the following code can keep the order. It's the same idea as runzhi xiao's answer, but without typing all the remaining columns.
df = pd.DataFrame({
    'col1': [1, 2, 3, 4],
    'col2': ['a', 'e', 'i', 'o'],
    'col3': ['a', 'e', 'i', 'o'],
    'col4': [0.1, 0.2, 1, 2],
})
cols_to_drop = ['col2']
new_columns = df.columns.drop(cols_to_drop).to_list()
df[new_columns]

   col1 col3  col4
0     1    a   0.1
1     2    e   0.2
2     3    i   1.0
3     4    o   2.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python MQTT improving publish speed for image numpy array I currently have two scripts, one to capture footage and publish the numpy array values (servant.py) and the other script (master.py) to then process those values using opencv for later facial recognition implementations. Problem is that right now it is very slow since the internet packages being sent arrive very delayed to the master script. I was wondering if there was a better way of doing this? of course right now only one frame per second is being sent, so I need the scripts to be able to handle 24 frames per second.
Here are both scripts:
master.py
import paho.mqtt.client as mqtt
import numpy as np
import json
import PIL

MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"

def on_connect(client, userdata, flags, rc):
    print("connected with result code " + str(rc))
    client.subscribe(MQTT_PATH)

def on_message(client, userdata, msg):
    dtype = "uint8"
    dshape = (480, 640, 3)
    data = msg.payload
    img_array = np.fromstring(data, dtype=dtype).reshape(dshape)
    img = PIL.Image.fromarray(img_array)
    img.save("img.png")
    img.show()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, 1883, 60)

client.loop_forever()

servant.py
import paho.mqtt.client as mqtt
import time
import cv2
import numpy
import json

MQTT_SERVER = "iot.eclipse.org"
MQTT_PATH = "test_channel"

mqttc = mqtt.Client()
mqttc.connect(MQTT_SERVER, 1883, 60)

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    MQTT_MESSAGE = frame.tostring()
    mqttc.publish(MQTT_PATH, MQTT_MESSAGE)
    mqttc.loop()
    time.sleep(1)

A: I think your best bet would be to instead stream from the camera using something like cvlc, or gstreamer, and then connect to it from opencv simply (cap = cv2.VideoCapture("http://some_url:some_port") and then you should get a reasonable throughput depending always on the bandwidth, codec, etc.

A: Use WebcamVideoStream from imutils, compress the image in jpg, publish it as base64:
import base64
import cv2
from imutils.video import WebcamVideoStream

cap = WebcamVideoStream(0)
cap.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.start()

while True:
    frame = cap.read()
    if frame is None:
        print("Continue")
        continue

    retval, buffer = cv2.imencode('.jpg', frame)
    jpg_as_text = base64.b64encode(buffer).decode('utf-8')
    publish(jpg_as_text)


text:
Q: Gettext not working, what's wrong? I'm using gettext for adding different translations into my webpage. I've just installed it and I think it works fine. I also use Poedit for the .po files.
This is the code I have for my gettext testing:
<?php
// I18N support information here
$language = "en_US";
putenv("LANG=" . $language);
setlocale(LC_ALL, $language);

// Set the text domain as "messages"
$domain = "messages";
bindtextdomain($domain, "Locale");
bind_textdomain_codeset($domain, 'UTF-8');

textdomain($domain);
//
// test if gettext extension is installed with php
//

if (!function_exists("gettext"))
{
    echo "gettext is not installed\n";
}
else
{
    echo "gettext is supported\n";
}
echo '<br>';
echo _("HELLO WORLD");
echo _("TEST TRANSLATION");
?>

That code, returns me 'gettext is supported', but instead of showing me the translations, it shows me 'HELLO WORLD' and 'TEST TRANSLATION'.
This is my messages.po file:
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2014-03-22 14:45+0100\n"
"PO-Revision-Date: 2014-03-22 15:23+0100\n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
"X-Poedit-Basepath: .\n"
"X-Poedit-Language: English\n"
"X-Poedit-Country: UNITED STATES\n"
"X-Poedit-SourceCharset: utf-8\n"

# Test token 1
msgid "HELLO WORLD"
msgstr "Hello World!"

# Test token 2
msgid "TEST TRANSLATION"
msgstr "Testing translation..."

And it's inside my 'Locale/en_US/LC_MESSAGES' folder, with also a messages.mo file successfully converted. (I've hidden the info of the file, the name, the project, etc.)
What am I doing wrong?
Thanks!
EDIT: I also might add that I use Ubuntu with PHP, Apache and all this things installed.

A: I've been having headaches with this one too. I added this and it worked:
putenv('LANGUAGE=en_US');
Next to that I use the following:
$domain = 'woohoo';
setlocale(LC_ALL, 'en_US.utf8');
putenv('LANGUAGE=en_US');

if( ENV != 'live' ){
    // reset caching nocache is a simlink to "."
    bindtextdomain($domain, dirname(__FILE__) . '/../locale/nocache');
}

bindtextdomain($domain, dirname(__FILE__) . '/../locale');
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);

Also, in my setup it only started working when I added the iso code to the .po file:
msgid ""
msgstr ""
"Language: en_US\n"

A: For me, the solution was to use "en" for the directory name, rather than "en-US".
PHP 5.2, gettext 0.19.8.1, Ubuntu 18.04, apache2

A: Two things i would consider:

*

*check (e.g. by using locale -a) if the language you want to use is installed a more detailed description can be found here: here

*check if apache is caching your file, either "disable" it or restart apache to get the new file. more info on previous link and here

A: just add following line
putenv("LANGUAGE=en_US");


text:
Q: Mock a method of already instantiated object I writing unit tests and for testing I want to mock a method of already existing object.
But looks like with asyncio corutines it is not so simple as it looks.
I tried to use MagickMock but it just doesn't work. There is no errors or exceptions, but with debugger I can see that f() is never being called.
My tests and object I want to patch look like this:
from unittest.mock import patch, MagicMock

class Service(object):
   async def callback_handler(self, msg):
      pass

   async def handle(self, msg):
      await self.callback_handler(msg)

class TestCase(object):
    def setUp(self):
      self.service = Service()

    @patch('module.msg')
    def test_my_case(self, msg_mock):
      f_was_called = False

      async def f():
        global f_was_called
        f_was_called = True

      self.service.callback_handler = MagicMock(wraps=f) # here I try to mock
      await self.service.handle(msg_mock)
      assert f_was_called is True

How can I patch already instantiated object method with some custom one? Is there some issues with corutines?

A: Try using a context manager by replacing this line:
self.service.callback_handler = MagicMock(wraps=f) # here I try to mock

With this:
with mock.patch.object(self.service, 'callback_handler', side_effect=f) as mock_cb:
    ... # rest of code indented

A: I also faced the problem trying to mock asyncio and want into a lot of troubles,
I ended using pytest.asycio plugin .
@pytest.mark.asyncio
async def test_some_asyncio_code():
    res = await library.do_something()
    assert b'expected result' == res


text:
Q: JLayeredPane clicking on hidden layer widgets I am encountering a strange behaviour using a JLayeredPane. When I click on empty area of the topmost (displayed one) panel, Swing actually clicks on a button that is at that exact position but on a hidden layer.
Here is how I build the JLayeredPane:
    volatilityOptionsPane = new OptionsPane( this, optionsBo, mpp.getSkewParams() );
    volatilityOptionsPane.setBounds( 0, 0, 300, 750 );

    screenOptionsPane = new CScreenOptionsPanel( this, optionsBo );
    screenOptionsPane.setBounds( 0, 0, 300, 760 );

    divFwdOptionsPane = new DivFwdOptionsPanel( this, optionsBo );
    divFwdOptionsPane.setBounds( 0, 0, 300, 770 );

    emptyOptionsPane = new JPanel();
    emptyOptionsPane.setBounds( 0, 0, 300, 900 );

    layeredOptionPane.add( volatilityOptionsPane, new Integer( 3 ) );
    layeredOptionPane.add( emptyOptionsPane, new Integer( 2 ) );
    layeredOptionPane.add( divFwdOptionsPane, new Integer( 1 ) );
    layeredOptionPane.add( cscreenOptionsPane, new Integer( 0 ) );


text:
Q: How to create PDF of Report generate by Microsoft Dynamic CRM using WCF Service? I am working on Microsoft Dynamic CRM. I can create PDF from Report of the Order. But I want to create PDF from WCF Service. I have order Id. I want to create PDF of that orderId using WCF Service.
I can add order, retrieve order details, product list or order etc.
Can anybody suggest me how to create PDF of Order in Microsoft Dynamic CRM?

A: On-Premise, where you can "talk" directly to the server, you could bypass CRM and invoke the Reporting Service URL which would let you download the PDF.
Online, sadly, it cannot be done (no SSRS to talk to).


text:
Q: объясните работу кода JS - сдвоенный оператор !? Объясните пожалуйста работу сдвоенного оператора JS !!
Вот тут:
https://habr.com/ru/sandbox/44911/
автор пишет :
"!!" — является проверкой как определена ли переменная и является истиной, а "!!!" — как определена переменная и является ложью.

if(!!undefinedVar)
  alert("Not undefined");
else
  alert("Undefined");

Если запустить предлагаемый пример кода - то мы ничего не увидим ибо в консоли сразу вылетает Error: Uncaught ReferenceError: undefinedVar is not defined
Я подумал что пример устарел (2012 год)
Но вот тут (2018 год):
https://habr.com/ru/post/421817/
автор по прежнему использует тот же фрагмент кода:
className={cx('label', !!labelClass && labelClass)}

Объясните пожалуйста зачем используется сдвоенный оператор !!

A: допустим ситуацию, что переменная может быть не задана, т.е. undefined, так вот чтобы не было ошибок в коде, например, если у Вас проверка if(!!var) {...}, то первый ! превращает undefined в true, а второй ! впревращает в false, т.е. получается, что переменной нет и код работает, надеюсь понятно объяснил)

let x;
console.log(x);

if (!!x) {
  console.log('не сработает');
} else {
  console.log(!!x);
  console.log('сработает');
}


text:
Q: create a new column to increment value when value resets to 1 in another column in pyspark Logic and columnIn Pyspark DataFrame consider a column like [1,2,3,4,1,2,1,1,2,3,1,2,1,1,2]. Pyspark Column
create a new column to increment value when value resets to 1.
Expected output is[1,1,1,1,2,2,3,4,4,4,5,5,6,7,7]
i am bit new to pyspark, if anyone can help me it would be great for me.
written the logic as like below
def sequence(row_num):
    results = [1, ]
    flag = 1
    for col in range(0, len(row_num)-1):
        if row_num[col][0]>=row_num[col+1][0]:
            flag+=1
        results.append(flag)
    return results

but not able to pass a column through udf. please help me in this

A: Your Dataframe:
df  = spark.createDataFrame(
  [
('1','a'),
('2','b'),
('3','c'),
('4','d'),
('1','e'),
('2','f'),
('1','g'),
('1','h'),
('2','i'),
('3','j'),
('1','k'),
('2','l'),
('1','m'),
('1','n'),
('2','o')
  ], ['group','label']
)

+-----+-----+
|group|label|
+-----+-----+
|    1|    a|
|    2|    b|
|    3|    c|
|    4|    d|
|    1|    e|
|    2|    f|
|    1|    g|
|    1|    h|
|    2|    i|
|    3|    j|
|    1|    k|
|    2|    l|
|    1|    m|
|    1|    n|
|    2|    o|
+-----+-----+

You can create a flag and use a Window Function to calculate the cumulative sum. No need to use an UDF:
from pyspark.sql import Window as W
from pyspark.sql import functions as F

w = W.partitionBy().orderBy('label').rowsBetween(Window.unboundedPreceding, 0)

df\
    .withColumn('Flag', F.when(F.col('group') == 1, 1).otherwise(0))\
    .withColumn('Output', F.sum('Flag').over(w))\
    .show()

+-----+-----+----+------+
|group|label|Flag|Output|
+-----+-----+----+------+
|    1|    a|   1|     1|
|    2|    b|   0|     1|
|    3|    c|   0|     1|
|    4|    d|   0|     1|
|    1|    e|   1|     2|
|    2|    f|   0|     2|
|    1|    g|   1|     3|
|    1|    h|   1|     4|
|    2|    i|   0|     4|
|    3|    j|   0|     4|
|    1|    k|   1|     5|
|    2|    l|   0|     5|
|    1|    m|   1|     6|
|    1|    n|   1|     7|
|    2|    o|   0|     7|
+-----+-----+----+------+


text:
Q: Redirect after my login in my application Good morning, I need your help please:
What happens is that I'm programming in java with jboss server and am using jsf interface (primefaces), my question is because when I authenticate with a login in my application I get redirected to another page and not the one I want.
The url of the login page is:
...login.xhtml
Once my login is correct leads me to the following url:
...javax.faces.resource/primefaces.js.xhtml
What I wish when my login is correct is to take me to the following url:
...index.xhtml
Besides my web.xml file has the following code:
<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>

Also I noticed that when I remove dependencies on the file pom.xml primefaces ok, after loguearme directs me to the correct url:
...index.xhtml
Please kindly help me.

A: The container managed security will redirect to the last HTTP request which triggered the authentication check. In your case it's apparently the auto-included PrimeFaces JavaScript file. It look like that you've an overly generic URL pattern in your security constraint, such as /* or *.xhtml, covering not only the JSF pages, but also the CSS/JS/image resources. That primefaces.js file is apparently referenced in the login page. So when the login page is opened, the referenced primefaces.js file will trigger the authentication check once again and it will remember to use its URL to redirect after successful login.
You'd like to exclude the JSF resources from authentication checks. You could do that by excluding the common URL pattern /javax.faces.resource/* via a security constraint without an auth constraint:
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Allowed resources.</web-resource-name>
        <url-pattern>/javax.faces.resource/*</url-pattern>
    </web-resource-collection>
    <!-- No <auth-constraint>! -->
</security-constraint>


text:
Q: Using browser's HTTP stack I'm trying to solve somehow the problem described here:Silverlight 5 - Debugging npctrl.dll crash
They suggest two solutions. One of them is "Stop using the client networking stack".
Not sure what it means but in the app.xaml.cs we have the following line:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

Does this mean we use client networking stack? if so then how do I switch to browser http stack? I tried both to remove this line and change it to:
WebRequest.RegisterPrefix("http://", WebRequestCreator.BrowserHttp);

but in both ways when I execute an HTTP request I never get a response. Simply nothing happens.
Any suggestions?
SOME MORE DETAILS:
First of all it's an OOB application.
So I changed it to
WebRequest.RegisterPrefix("http://", WebRequestCreator.BrowserHttp);

as I explained above.
I try to execute an HTTP request in the following way:
m_restClient = new RestClient
    {
Authority = http://172.30.2.73:8182/;
    Timeout = TimeSpan.FromMinutes(2),
    Deserializer = deserializer,
    Serializer = serializer,
    GetErrorResponseEntityType = GetErrorResponseEntityType,
    Encoding = serializer.ContentEncoding
  };

var request = new RestRequest
    {
      Path = "emulation/parameters",
      Method = WebMethod.Get,
    };

m_restClient.BeginRequest<EmulationParametersResponse>(request, RestGetEmulationParamsCompleted);

In the fiddler it seems like I do get a response with status code 200 and I also can see the response there but I put a break point in the callback and deserializer and it doesn't stop there.


text:
Q: How to Add Prefix in XML in Python I have an xml like this
<eo-gateway>
<interface-code>AAA</interface-code>
<supplier-code>XXX</supplier-code>
<authors>
<author type="first">
<forename>John</forename>
<surname>Smith</surname>
</author>
</authors>
</eo-gateway>

I need to arrive to this kind of xml adding prefix "art" in each tag.
<art:eo-gateway>
<art:interface-code>AAA</art:interface-code>
<art:supplier-code>XXX</art:supplier-code>
<art:authors>
<art:author type="first">
<art:forename>John</art:forename>
<art:surname>Smith</art:surname>
</art:author>
</art:authors>
</art:eo-gateway>

Thanks for you help.

A: Use beautifulsoup :http://www.crummy.com/software/BeautifulSoup/bs4/doc/
from bs4 import BeautifulSoup
soup = BeautifulSoup('''<eo-gateway>
<interface-code>AAA</interface-code>
<supplier-code>XXX</supplier-code>
<authors>
<author type="first">
<forename>John</forename>
<surname>Smith</surname>
</author>
</authors>
</eo-gateway>''')

for i in soup.find_all():
    i.name = 'art:' + i.name

And if you don't want some tags you could do this:
except_these = ['art:body', 'art:html']

for i in soup.find_all():
    name = i.name
    if name not in except_these:
        i.name = 'art:' + i.name
print soup

Output:
<art:body>
<art:eo-gateway>
<art:interface-code>AAA</art:interface-code>
<art:supplier-code>XXX</art:supplier-code>
<art:authors>
<art:author type="first">
<art:forename>John</art:forename>
<art:surname>Smith</art:surname>
</art:author>
</art:authors>
</art:eo-gateway>
</art:body>

Or you could even check whether it already has 'art:' in front of it:
if !name.startswith('art:'):

A: I've already found the correct way to solve this using xml.etree that eliminates having extra tags like html and body tags from BeautifulSoup.
from xml.etree import ElementTree as etree

xml_content = """<eo-gateway>
    <interface-code>AAA</interface-code>
    <supplier-code>XXX</supplier-code>
    <authors>
    <author type="first">
    <forename>John</forename>
    <surname>Smith</surname>
    </author>
    </authors>
    </eo-gateway>"""

document_root = etree.ElementTree(etree.fromstring(xml_content))
for element in document_root.getiterator():
    element.tag = "art:" + element.tag
print etree.tostring(document_root.getroot())


text:
Q: Dynamically replicating a form textarea I am new to Javascript. And I am trying to create a page which is used for writing reviews. I am stuck at a certain point.
There should be a button to add a section which copies the whole sections div to allow the user to write another section.
Attached below is my code. I am using CKeditor plugin to allow the end user to format their text as they wish.
The current code , while creating a new section, doesn't allow the user to write into the text area created. Please guide me as to where I was mistaken.
    <?php
    include 'settings.php';

    if (!isset($dbc)){
        $dbc = new mysqli(DB_HOST , DB_USER , DB_PASSWORD , DB_NAME);
    }

    if ($dbc -> connect_error){
        die ("Cannot connect to the database");
    }

?>

        <title>Write a new Review.</title>

        <form id = "new_review" action = "form.php" method = "post">

 Header Section.

                Author : <input type = "text" id = "author">

                Title: <input type = "text" id = "title">

                Tagline: <input type = "text" id = "tagline" >

                Score: <input type = "text" id = "score" >

                Pros:   <textarea class = "ckeditor" id = "pros">
                            Please enter the pro's of the product here.
                        </textarea>
                Cons:   <textarea class = "ckeditor" id = "cons">
                            Please enter the cons of the product here.
                        </textarea>
                Verdict:<textarea class = "ckeditor" id = "verdict">
                            Enter your vedict here.
                        </textarea>

 Sections.

                <input type = "button" id="button" onclick="duplicate()">Add a section</button>

                    Section Icon: <input type="file" id="icon" accept="image/*">

                    Section Title: <input type = "text" id = "section_title" >

                    Section Text:   <textarea class = "ckeditor" id = "section_text">
                                    Enter you text here.
                                    </textarea>
                    Section Score: <input type = "text" id = "section_score">

 Conclusion:

                <textarea class = "ckeditor" id = "conclusions">
                    Enter your conclusion here.
                </textarea>

            <input type = "submit" value="submit">
        </form>

Below are the links from where I had the information to do what I did.
http://ckeditor.com/ckeditor_4.3_beta/samples/replacebyclass.html
How can i duplicate a div onclick with javascript?

A: Try your javascript as this

A: Seems like CKEditor got some issues with binding the controls for dynamically added elements. You can refer to this problem which contains discussion from people facing similar issues and their solutions.
CKEDITOR inline on dynamic created element ( droppable/sortable )
Also found this jsfiddle demo, which binds CKEditor inline
CKEDITOR.inline( el.get( 0 ) );

The guy has also written a nice tutorial on how to add inline ckeditor on dynamically created elements
See if it helps...


text:
Q: How to attach c and c++ modules? I have two moudles:
Module1: A C program, constructs two graphs.
Module2: A C++ program, checks equivalence of the two graphs produced by module1.
I want to feed output of module1 to module2.
Module2 uses structs only and are identical to ones used in module1, only difference is that module2 contains some function overloading etc.
One way to transfer the graphs is to write them to a file and re-read and parse in module2.
My Question is:
Is there a method available by which I can carry the instances of structs constructed in Module1 to Module2 directly, without going through this file read/write.
Abstract example of what I want to say:
// Module1:

struct s1 {
   int a;
};

void main (){
    struct s1 s;
    s.a = 10;
}

// Module2:
struct s1{
    int a;  // Note the same structure and variable name.
};

void print (struct s1 s){
    cout << s.a;
}

void main (){
    struct s1 s;
     print (s);
}

Question repharsed:
Is there a technique available by which I can feed the structure created in Module1 directly (via main memory only) to Module2; without writing to file first and then re-reading?

A: There is no reason the two modules can't be linked together into a single program. The main thing to remember is that the C function declarations (in the C header file module1.h) need to be marked as having C language linkage to the C++ compiler.
You can do that using __cplusplus guards:
module1.h
#ifndef MODULE_1_H
#define MODULE_1_H

// tell the C++ compiler this header is for
// a module written in C
#ifdef __cplusplus
extern "C" {
#endif

typedef struct
{
    int i;
    double d;
} Graph;

Graph construct_a_graph();

#ifdef __cplusplus
} // extern "C"
#endif

#endif // MODULE_1_H

module1.c
#include "module1.h"

Graph construct_a_graph()
{
    Graph g;
    g.i = 2;
    g.d = 7.9;

    return g;
}

module2.h
#ifndef MODULE_2_H
#define MODULE_2_H

#include "module1.h"

void process_graph(Graph g);

#endif // MODULE_2_H

module2.cpp
#include "module2.h"

void process_graph(Graph g)
{
    // do stuff in C++
}

main.cpp
#include "module1.h"
#include "module2.h"

int main()
{
    Graph g = construct_a_graph(); // C function

    process_graph(g); // C++ function
}

Compiling with GCC:
gcc -c -o module1.o module1.c // C module
g++ -c -o module2.o module2.cpp // C++ module
g++ -o main main.cpp module1.o module2.o // link fine

A: I think the easiest solution would be to make a library (.dll/.so/..) out of both, that contains the implementation of the class and provides a C- and a C++-interface for accessing it.
You can then either store the instances of your objects in the library and pass handles/copies to the user (depending on what you need) or use the shared memory and pass pointers between your modules.
Under VisualStudio the shared-memory-option is called "Multithreaded-DLL (\Md)", i don't know the exact option for other OS/Compilers.

A: As answered by @Galik, both modules can be linked to a single program. As an alternative, the message passing interface (MPI) can be used to communicate pieces of information from a program to another. Here is how it could be done in your case.

*

*CPP program module2 spawns a process calling module1.

*module1 sets the value of the member of a struct s1 s and sends the structure as a buffer to module2.

*module2 receives a copy of the buffer, puts it into a struct s1 and prints the value of the member.

Here is the c++ code of program module2, to be compiled by mpiCC module2.cpp -o module2:
#include <iostream>
using namespace std;

#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct s1{
    int a;  // Note the same structure and variable name.
};

void print (struct s1 s){
    cout << s.a;
}

int main (int argc, char *argv[])
{
    int  errcode;
    MPI_Comm intercomm,intracomm;
    MPI_Info info;
    MPI_Init( &argc, &argv );
    char command[15];
    sprintf(command,"%s","./module1");

    int ierr=MPI_Comm_spawn(command,MPI_ARGV_NULL,1,MPI_INFO_NULL,0,MPI_COMM_WORLD,&intercomm,&errcode);
    if (ierr != MPI_SUCCESS) {
        printf("spaw failed\n");
    }
    // intercomm has two group. One with the parent, one with the children
    MPI_Intercomm_merge(intercomm,0,&intracomm);
    int size, rank;
    MPI_Comm_size(intracomm, &size);
    MPI_Comm_rank(intracomm, &rank);
    cout<<"parent has rank "<<rank<<" in communicator of size "<<size<<endl;

    struct s1 s;
    MPI_Recv(&s,sizeof(struct s1),MPI_CHAR,1,0,intracomm,MPI_STATUS_IGNORE);
    MPI_Comm_disconnect(&intracomm); //disconnect after all communications
    MPI_Comm_disconnect(&intercomm);

    print (s);
    cout<<endl;
    MPI_Finalize();
    return 0;
}

Here is the c code of program module1, to be compiled by mpicc module1.c -o module1:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct s1 {
    int a;
};

int main(int argc,char *argv[])
{
    int rank,size;
    MPI_Comm parentcomm,intracomm;
    MPI_Init( &argc, &argv );

    //MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_get_parent( &parentcomm );
    if (parentcomm == MPI_COMM_NULL){fprintf(stderr,"module1 : i'm supposed to be the spawned process!");exit(1);}

    MPI_Intercomm_merge(parentcomm,1,&intracomm);

    MPI_Comm_size(intracomm, &size);
    MPI_Comm_rank(intracomm, &rank);
    printf("child had rank %d in communicator of size %d\n",rank,size);

    struct s1 s;
    s.a = 10;
    MPI_Send(&s,sizeof(struct s1),MPI_CHAR,0,0,intracomm);
    MPI_Comm_disconnect(&intracomm); //disconnect after all communications
    MPI_Comm_disconnect(&parentcomm);
    MPI_Finalize();
    return 0;
}

The whole thing is ran by mpirun -np 1 module2.


text:
Q: Update the list of default applications How can I have unity in ubuntu 11.10 to remove the names of deinstalled applications from the list of default applications?
I have removed all internet browser applications with software center. They dont disappear from the list of default applications in system information.
In Unity in ubuntu 11.10 there is a bottom for shutdown on the upper menuebar. There you can find system settings. inside that system settings menue there is an icon "system information", where you can find default applications. Application names dont disappear, when you deinstall an application. How can I let this names disappeare?

A: sudo update-alternatives --list <group>
sudo update-alternatives --remove <group> <app>

where  is the application you removed but still listed in , and  is the alternative name you want to change.


text:
Q: How use ReactJS with Craft CMS (mainly just looking to use on client side) I'm quite new to React, so this might just be down to inexperience.
Im looking to use React to replace the templates, css and js of a website built with Craft CMS. Does anyone have any experience with React and Craft CMS that can give me guidance in the process?
(I have guessed I'll need to get twig working in a React component file, and point the Craft CMS backend to both the development React and the build React.)

A: You can use the graphQL plugin or the element API and then get your CRAFT CMS content over an API request into your react app. Thats the way to separate backend from frontend.


text:
Q: how to host multiple wordpress website with different port as container inside EC2 I'm trying to host multiple small wordpress websites with different ports (81, 82 and 83) by using docker inside EC2. Problem is when I'm trying to map those ports in AWS ALB and ALB successfully forward to each instance and wordpress but wordpress redirect to its siteURL with each ports mapping as follow:
https://my-alb-00000000.ap-southeast-1.elb.amazonaws.com:81
https://my-alb-00000000.ap-southeast-1.elb.amazonaws.com:82
https://my-alb-00000000.ap-southeast-1.elb.amazonaws.com:83
So, I want to know how to fix that issue? Could I install nginx to make port mapping or anyway to prevent wordpress siteURL mapping configuration?

A: I've found a solution that we can create different wordpress docker containers with different ports, then mapped those ports to AWS ALB with different target groups or within same target group. The main key is we need to update subdomain or full domain in wordpress's siteURL. Thus whenever we want to access wordpress or its admin, we cannot browser with each IP and Port anymore. We can access with its subdomain or its full domain.


text:
Q: Why does shape of elements matter in finite elements analysis? I have used FEA for a couple of years now, but using it and using it correctly are two different things, safety factor is not the solution to everything. I have the feeling I won't be using it right unless I have a clear answer to that question:
I am aware elements must be close to their ideal shape (based on the Jacobian) in order to get accurate results.. But why? Since I understand it comes from a coordinate transform, unless two vectors of the element become colinear shouldn't the results be accurate no matter its shape?
A step-by-step answer based on n illustrated example (arbitrary stress distribution) would be really appreciated, especially given that it is a relatively common question (but never well answered from what I have seen).

A: There might be several reasons, some more obvious than others.

The quality of the cell (including its orthogonal quality, aspect ratio, and skewness) also has a significant impact on the accuracy of the numerical solution.

*

*Orthogonal quality is computed for cells using the vector from the cell centroid to each of its faces, the corresponding face area vector, and the vector from the cell centroid to the centroids of each of the adjacent cells (see Equation 5–1, Equation 5–2, and Figure 5.22: The Vectors Used to Compute Orthogonal Quality). The worst cells will have an orthogonal quality closer to 0, with the best cells closer to 1. The minimum orthogonal quality for all types of cells should be more than 0.01, with an average value that is significantly higher.

*Aspect ratio is a measure of the stretching of the cell. As discussed in Computational Expense, for highly anisotropic flows, extreme aspect ratios may yield accurate results with fewer cells. Generally, it is best to avoid sudden and large changes in cell aspect ratios in areas where the flow field exhibit large changes or strong gradients.

*Skewness is defined as the difference between the shape of the cell and the shape of an equilateral cell of equivalent volume. Highly skewed cells can decrease accuracy and destabilize the solution. For example, optimal quadrilateral meshes will have vertex angles close to 90 degrees, while triangular meshes should preferably have angles of close to 60 degrees and have all angles less than 90 degrees. A general rule is that the maximum skewness for a triangular/tetrahedral mesh in most flows should be kept below 0.95, with an average value that is significantly lower. A maximum value above 0.95 may lead to convergence difficulties and may require changing the solver controls, such as reducing under-relaxation factors and/or switching to the pressure-based coupled solver.

Source URL


text:
Q: Subdomains with .htaccess (PHP) I am looking to create a .htaccess file on my website to allow me enter "username.domain.com" as the url and it redirects me to "http://domain.com/index.php?a=profile&u=username"
eg: "john.domain.com" redirects to "http://domain.com/index.php?a=profile&u=john"
Thanks

A: This would not go into .htaccess, it would go into you httpd.conf file. Look into this question: VirtualHost with wildcard VirtualDocumentRoot
You would also need to setup a wildcard dns record for *.example.com to point to your server. In PHP you would have something like this as the index.php file for your wildcard.
<?php
    $domain = "test.example.com";
    $domain_parts = explode(".", $domain);
    $username = $domain_parts[0];
    header("location: http://example.com/".$username);
?>


text:
Q: Prove two matrices are similar (Frobenius normal form related)
Let $x^2+a_1x+a_0\in\mathbb{R}[x]$, irreducible polynomial.  It's roots are $\alpha \pm \beta i$. Show that $A=\left( {\matrix{
   0 & { - {a_0}}  \cr
   1 & { - {a_1}}  \cr
 } } \right)$ is similar to  $B= \left( {\matrix{
   \alpha & {  \beta}  \cr
   -\beta & {  \alpha}  \cr
 } } \right)$

I was guided to find an eigen vector of this matrix. So I looked at $\ker(B-(\alpha+i\beta)I_2)$ and found it's basis is $\left\{ (-i,1) \right\}$.
So we can take $v = -i +1$ as an eigen-vector. Now I was told to look at the real part and the imaginary part and figure out something, but I don't see how is it gonna help here.


text:
Q: Convert rows to columns using Twig - D8 I have a content type "Awards" that has data structured as below:

I want to group this data as below:
Want to group them on a "State" basis. So when I click on mysite.com/TXawards, it should show data grouped as below:

Similarly "/FLaward" page should show data grouped as above. I don't have a view created yet but the content type with data is ready. What would be the best way to achieve this? I was thinking to use a contextual filter but I click the link "/TXawards" which is hardcoded on a page. Any help on how to group this data? Thanks

UPDATE: I created a"Table" styled view and grouped the rows by Type and State. The view output looks as below.

Can someone help with twigging this output to 2 column format pls?

A: so this answer that I have doesn't go about transposing your table using the twig templates. What this does is just give you the data in the direct format from Views and then you can style and format it however you'd like.
Since I don't have your fields or project I can't really give you a view export, however I can walk you through a few steps to set it up.
EDIT: I figured that I might as well toss in the export of the mock-up view I made to make these screenshots. Also, this concept should be applicable for Drupal 7-9, but the export linked may only work for 9.x

Export of Drupal v9.3.12 View that was built as concept for answer.
Mark all fields hidden, except one

*

*All the fields you want to show, make them hidden.

*Whatever formatting you use will still be output for the each field (i.e. link, date format, etc.)

*I typically keep all the fields I plan on outputting hidden, and for the last field I add like an ID content field or something.

Set the one last non-hidden field to re-write with tokens

*

*You can style the overall format however you want it to rewrite.

*Your example is looking for a 2x4 table, so thats what I put in for mine.

*All the variables that are wrapped in double brackets are taken from the Replacement Patterns accordion below.

*Any field you included and set as hidden should be shown and be available as a token for rewrite.

*For my example I did just basic fields, title, user, date, etc.

Set the Format > Format to be Unformatted list instead of Table

*

*Now for this, if you really want, can make it any of the formats.

*I think Unformatted list will give you the easiest markup to work with

Preview the results

Lastly, configure the view and everything else as necessary. Hope this helps!


text:
Q: Point Sprite Alpha Blending Issue I'm trying to render a load of stars in 3D space using point sprites. My texture image is definitely 'good' as far as the alpha channel is concerned. It renders perfectly fine as a quad but when I render a lot of point sprites, I can see the square border of the image overwriting some of the images.

The above image shows the star being rendered nicely over the top of my cube. In the bottom right I would expect to see a continuous trail of star images in the 'flower' pattern that they're been drawn in.
What am I doing wrong?
Fragment shader:
#version 140

#extension GL_ARB_explicit_attrib_location : enable

precision mediump float;

uniform sampler2D uTexture;

void main( void )
{
  gl_FragColor = texture2D( uTexture, gl_PointCoord );
}

Vertex shader:
#version 140

#extension GL_ARB_explicit_attrib_location : enable

precision mediump float;

layout (location = 0) in float aTheta;

uniform float uK;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main( void )
{
  float x = cos( uK * aTheta ) * sin( aTheta );
  float y = cos( uK * aTheta ) * cos( aTheta );

  gl_Position  = projection * view * model * vec4( x, y, 0.0, 1.0 );
  gl_PointSize = 64.0;
}

Code:
void CPoint::Render( void )
{
  g_PointProgram.UseProgram();

  glEnable( GL_PROGRAM_POINT_SIZE );
  glEnable( GL_POINT_SPRITE );

  // Set the alpha blending function
  glEnable( GL_BLEND );
  glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
  glBlendEquation( GL_FUNC_ADD );

  glBindBuffer( GL_ARRAY_BUFFER, m_VBO );

  glm::mat4 Model = glm::mat4( 1.0 );

  Model = glm::translate( Model, glm::vec3( 2.0f, 0.0f, 4.0f ) );

  glm::mat4 Projection = g_Camera.GetProjection();
  glm::mat4 View       = g_Camera.GetView();

  g_PointProgram.SetUint( "uTexture", g_ImgStar.m_Texture );

  g_PointProgram.SetMatrix4fv( "model", Model );
  g_PointProgram.SetMatrix4fv( "view", View );
  g_PointProgram.SetMatrix4fv( "projection", Projection );

  g_PointProgram.SetFloat( "uK", m_Emitter.k );

  glActiveTexture( GL_TEXTURE0 );
  glBindTexture( GL_TEXTURE_2D, g_ImgStar.m_Texture );
  glEnable( GL_TEXTURE_2D );

  // Attributes
  glVertexAttribPointer( 0,                // 1st attribute array (only have 1)
                         1,                                        // One theta angle per particle
                         GL_FLOAT,                                 // Data is floating point type
                         GL_FALSE,                                 // No fixed point scaling
                         sizeof( Particle ),                       // No gaps in data
                         (void*) 0 );      // Start from "theta" offset within bound buffer

  glEnableVertexAttribArray( 0 );

  glDrawArrays( GL_POINTS, 0, NUM_PARTICLES );

  glDisableVertexAttribArray( 0 );
  glBindBuffer( GL_ARRAY_BUFFER, 0 );

  glDisable( GL_TEXTURE_2D );
}

A: Perhaps depth culling is playing tricks on you? Try glDepthMask(false) while rendering the sprites


text:
Q: UITableViewCell not updating after selection on iOS 7 So I am having a really weird issue.  My code works great on iOS 8 but doesn't on iOS 7 and I can't figure out why.
I have a tableview which has a list of items which when you select an item a checkmark is added to that item and if you select it again the checkmark is removed.  Pretty simple right? :-p  Like I said it works great on iOS 8, but when I run against iOS 7.1 the cell highlights, adds a checkmark, and removes the old title and replaces it with the default of Title.  Afterwards, no matter how many times I tap on the cell, it never changes (but the underlying data does change).
Before Selection

After Selection

If I leave the screen and come back to it, the rows are displayed properly.  I've verified that cellForRowAtIndexPath is being called and the correct values are being added to the cell.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [[parkFinderSingleton.data valueForKey:@"amenities"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"amenityFilterCell" forIndexPath:indexPath];

    Amenity *currentAmenity;
    NSArray *amenities = [parkFinderSingleton.data valueForKey:@"amenities"];

    if (amenities != nil) {
        currentAmenity = amenities[indexPath.row];
        cell.textLabel.text = currentAmenity.amenityTitle;
        NSLog(@"Cell Title %@", cell.textLabel.text);

        if (currentAmenity.amenitySelected) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"amenityFilterCell" forIndexPath:indexPath];

    Amenity *currentAmenity;
    NSArray *amenities = [parkFinderSingleton.data valueForKey:@"amenities"];

    if (amenities != nil) {
        currentAmenity = amenities[indexPath.row];

        if (currentAmenity.amenitySelected) {
            currentAmenity.amenitySelected = NO;
            cell.accessoryType = UITableViewCellAccessoryNone;
        } else {
            currentAmenity.amenitySelected = YES;
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }

    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];

}

Any thoughts as to what might be happening?

A: Normally, dequeueReusableCellWithIdentifier:forIndexPath: should not be called in tableView: didSelectRowAtIndexPath:. If you want the cell for a specific indexPath, use [tableView cellForRowAtIndexPath:indexPath].
For:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

If you just want to deselect a cell, use [tableView deselectRowAtIndexPath:animated:].


text:
Q: Express Static files on server not loading correctly but React Front end is loading correctly? I have a ReactJS project with Node/Express serving my server. On my front end (React) is serving port 3312 and on my server it's serving port (5000). When I load my front end through port 3312, everything looks great and my react router routes works fine. (My api's work everything is great). However, when I try and serve static files and see if I get the same result through my server (port 5000) I only see the styles on my page. (I have a background color) I don't see any of the html whatsoever that the static files should be serving?
I get no errors in the console when I look at localhost:5000. However, my css styles are displaying on the page correctly (cause I have a background color set on my body). However, I cannot see any of my front end React displaying html code. I went inside my index.html file and put a simple test in the root div and it's displaying but I don't understand why my React code isn't displaying on my server.
I most likely think the problem is with the express static files not serving my images or React Router code. I should also note that I'm not using create-react-app I'm using webpack dev server react no cli.
Also, I'm not using create-react-app I'm using no cli for custom webpack.
Here is my code:
(Node Server)

const express = require("express");
const path = require("path");
const router = express.Router();

const app = express();
const port = 5000;

// Serve static files on server
app.use("/public", express.static(__dirname + "/../public"));

app.get("*", function(request, response) {
  response.sendFile(path.join(__dirname + "/../public/index.html"));
});

if (app.get("env") === "development") {
  app.listen(port, () => {
    console.log(`Server started on port ${port}`);
  });
} else {
  app.listen(port, "171.33.4.126", () => {
    console.log(`Server started on port ${port}`);
  });
}

routes.js

import React from "react";

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import HomePage from "./components/homepage";
import AboutPage from "./components/aboutpage";
import Contactpage from "./components/contactpage";

export default (
  <Router>

      <Switch>
        <Route exact path="/" component={Landingpage} />
        <Route exact path="/about" component={AboutPage} />
        <Route exact path="/contact" component={Contactpage} />
      </Switch>

  </Router>
);

index.js

import React, { Component } from "react";
import ReactDOM from "react-dom";

import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Routes from "./routes";

ReactDOM.render(
{Routes}
, document.getElementById("root"));

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link
      href="/public/assets/css/styles.css"
      rel="stylesheet"
      type="text/css"
    />
    <title>Site</title>

Webpack Configuration Development

const webpack = require("webpack");
const path = require("path");
// const HtmlWebPackPlugin = require("html-webpack-plugin");
const BrowserSyncPlugin = require("browser-sync-webpack-plugin");

module.exports = {
  devServer: {
    historyApiFallback: true,
    port: 3312,
    proxy: {
      "/api": "http://localhost:5000"
    }
  },
  entry: ["babel-polyfill", __dirname + "/src/index.js"],
  output: {
    path: path.join(__dirname, "/public"),
    filename: "bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          query: {
            presets: ["react", "env", "stage-0"]
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" },
          { loader: "sass-loader" }
        ]
      }
    ]
  },
  plugins: [
    // new HtmlWebPackPlugin({
    //   template: "./public/index.html"
    // }),
    new BrowserSyncPlugin({
      host: "localhost",
      port: 3312,
      files: [
        "./public/*.html",
        "./public/assets/scss/*.scss",
        "./public/assets/variables/*.scss",
        "./public/assets/mixins/*.scss",
        "./public/assets/reset/*.scss"
      ],
      proxy: "http://localhost:3312/"
    })
  ]
};

Here is a screenshot of my folder structure:

Screenshot of network status in console:

A: Your react code is not showing up because index.html is not including it. Is public/bundle.js your transpiled react code? If so, add the following line to index.html, right after

:

If not, then change the path pointed by src to the correct one.
You can see your css styles just fine because you are already including those in index.html.
UPDATE: a couple of points based on your webpack config:

*

*Change the port in which you are running webpack-dev-server to 3000. You will also have to change BrowserSyncPlugin's proxy to http://localhost:3000/. You can then go to localhost:3312 in your browser and requests will be proxied to the webpack-dev-server running on port 3000.

*Correct me if I'm wrong, but you have not posted your index.html in its entirety. I'm guessing you already have a line that looks like  somewhere in that .html file -- based on your latest comment, it seems it is being added by HtmlWebPackPlugin. webpack-dev-server is serving bundle.js through /, the publicPath you've specified in webpack's output option. This works just fine as long as you access your site through localhost:3312 or localhost:3000. However, your express.js server running on port 5000 has no idea webpack-dev-server is serving bundle.js at /; as a result of that, you end up seeing none of your react code when you go to localhost:5000. As for the styles, you are already serving them correctly through /public/assets/css, which the express.js server understands because you've specified that in this line: app.use("/public", express.static(__dirname + "/../public")). The solution is to change the line  in your .html file to:

Also, in webpack's output option, change the publicPath to http://localhost:3312/. Now, as long as you have webpack-dev-server running (with BrowserSyncPlugin), you can access
your site at localhost:5000 and your bundle.js file should be
served just fine.
Try the following:
Webpack Config
module.exports = {
    devServer: {
        contentBase: path.join(__dirname, "/public"),
        historyApiFallback: true,
        port: 3000,
        proxy: {
            "/api": "http://localhost:5000"
        }
    },
    entry: ["babel-polyfill", __dirname + "/src/index.js"],
    output: {
        path: path.join(__dirname, "/public"),
        filename: "bundle.js",
        publicPath: "http://localhost:3312/"
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    query: {
                        presets: ["react", "env", "stage-0"]
                    }
                }
            },
            {
                test: /\.css$/,
                use: [
                    { loader: "style-loader" },
                    { loader: "css-loader" },
                    { loader: "sass-loader" }
                ]
            }
        ]
    },
    plugins: [
        new BrowserSyncPlugin({
            host: "localhost",
            port: 3312,
            files: [
                "./public/*.html",
                "./public/assets/scss/*.scss",
                "./public/assets/variables/*.scss",
                "./public/assets/mixins/*.scss",
                "./public/assets/reset/*.scss"
            ],
            proxy: "http://localhost:3000/"
        })
    ]
};

index.html
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <link
            href="/assets/css/styles.css"
            rel="stylesheet"
            type="text/css"
        />
        <title>Site</title>

A: Oh sorry, it looks like the problem is in index.js. Change {Routes} to <Routes />
import React, { Component } from "react";
import ReactDOM from "react-dom";

import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Routes from "./routes";

ReactDOM.render(
<Routes/>
, document.getElementById("root"));

You have another problem in routes.js. Export a component like
import React from "react";

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import HomePage from "./components/homepage";
import AboutPage from "./components/aboutpage";
import Contactpage from "./components/contactpage";

// make this a component
export default ()=>(
  <Router>
      <Switch>
        <Route exact path="/" component={Landingpage} />
        <Route exact path="/about" component={AboutPage} />
        <Route exact path="/contact" component={Contactpage} />
      </Switch>
  </Router>
);


text:
Q: Difference between "slip out of" and "slip off" I have a question about the preposition used with the verb "slip."
When you leave your bed quietly at night for a glass of water, I think you can say either of these sentences to describe your action.

I slipped out of my bed and went to the kitchen.
I slipped off my bed and went to the kitchen.

My question is, is there any difference in meaning between "slip out of" and "slip off"?

A: You lie in your bed, so you need to slip out of it.
When you would've been lying on your couch, you could slip off of it.
So you use 'slip out of' when you're in something, and 'slip off of' when you're on something.


text:
Q: Calculating conditional expectation with scipy.stats Let's suppose x ~ Poisson(2.5);  I would like to calculate something like E(x | x > 2).
I assumed that this could be done with the .dist.expect operator, i.e.:
D = stats.poisson(2.5)
cond_expect = D.dist.expect(lambda x: x, D.args,lb=2)

This evaluates to cond_expect = 2.29478750344
However, if I just calculate the mean of a random sample from that distribution
D = stats.poisson(2.5)
test = D.rvs(size = 100000)
empirical_expectation = np.mean(test[test>=2])

empirical_expectation evaluates to 3.20875563063.
If anyone could clarify what I'm misunderstanding about the API, it would be greatly appreciated.

A: The method expect takes a Boolean parameter conditional, which is False by default. Set it to True:
cond_expect = D.dist.expect(lambda x: x, D.args, lb=2, conditional=True)

returns 3.219839256818051 in agreement with empirical result.
What this does:

conditional : bool, optional
If true then the expectation is corrected by the conditional probability of the summation interval. The return value is the expectation of the function, func, conditional on being in the given interval (k such that ul <= k <= ub). Default is False.

So, if False then you get E(X if X >= 2 else 0) instead of conditional expectation, which is adjusted by division by P(X >= 2): E(X | X >= 2) = E(X if X >= 2 else 0) / P(X >= 2)
I don't know why you would ever want conditional=False when providing an upper or lower bound, but it's the default.


text:
Q: How to change password in Ubuntu 16? How to change the password in Ubuntu 16 using command?

A: Use command "passwd"
shrikant@shrikant-B250M-DS3H:~$ passwd
Changing password for shrikant.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully


text:
Q: Powering LEDs + a Controller with Lithium Ion Batteries I am trying to build a portable project with some form of RGB LED (probably APA102) and a controller such as a Raspberry Pi. I am trying to figure out what is required to safely power both the LEDs and the controller, but based on my calculations (which are probably incorrect), I am having trouble coming up with a way to do so:

*

*~200 APA102 LEDs (which, at most, should be drawing around 60 mA per RGB LED)

*Raspberry Pi (draws at the very most, 500-700 mA)

In total, this comes to ~12,000 mA maximum draw. Now, I am never going to have the Raspberry Pi or LEDs on full blast, so this figure is an absolute maximum. I can pretty easily add in software limits to prevent the LEDs from being completely lit at any one time.
But, even if this drops down to half (6A draw), this is way beyond what a standard AA/AAA battery pack can provide. So, the obvious choice is to use Lithium Ion.
Adafruit has a 6600 mAh battery pack (3 x 2200 mA: http://www.adafruit.com/products/353) with a stated max draw of ~13 A-- perfect for my situation, since I will rarely if ever be at that point. However, the voltage is only 3.7v when I need 5v.
So, then I would need a step up converter, correct? Is there a step up converter that even supports the 13 A peak draw (and probably around 3-4 A constant at very most)? Generally, I've only been able to find 500 mA to 1 A converters in my research.

A: Cheap 3.7V to 5V voltage boosters that can do 2.5A are readily available. You might be able run several of these boosters, each one supplying power to a part of the circuit.
However, while the Adafruit 6600mAh 3.7V li-ion battery can deliver a maximum of 13A (though not with the supplied cable and connector, which can only handle a mere 2 Amps!)  you need more. As the booster steps up voltage so its output current must drop proportionally. You want up to 12A @ 5V which equates to 60W. The booster cannot be 100% efficient, so it must draw more than 60W from the battery. For example a booster with 85% efficiency would draw 70.6W = 19A at 3.7V, way over the battery's rating. Also you will need thick wires and beefy connectors to carry this high current!
A better solution might be to use a higher voltage battery (eg. 7.4V) and step it down to 5V. That way the input current will be more manageable, and you can choose from a wide variety of high current buck mode regulators. At 7.4V you still want a battery that deliver at least 10A of real current. I would use an RC car lipo such as this 5000mAh 7.4V pack, which has 50% more energy storage capacity than the Adafruit 6600mAh 3.7V battery, and will have no trouble handling 10A.


text:
Q: How to speedup Excel formating from Delphi? I have Delphi (Delphi 2009) application, that uses Excel_TLB commands for writing into Excel file. I need not only write the data in the cells, but also assign custom format to the cells. It is done cell-by-cell bases and the typical code for one cell is:
    FWS.Cells.Item[CurrLine, 4].Value2:='some data';
    FWS.Cells.Item[CurrLine, 4].Font.Name:='Times New Roman';
    FWS.Cells.Item[CurrLine, 4].Font.Size:=9;
    FWS.Cells.Item[CurrLine, 4].Font.Bold:=True;
    FWS.Cells.Item[CurrLine, 4].Font.Italic:=True;
    FWS.Cells.Item[CurrLine, 4].HorizontalAlignment:=xlHAlignLeft;

I have approximately 6000*5 cells and such writing and formatting takes up to 1 minute of time. That is lot of time. The data writing itself is very fast, but formatting makes the most of time. I know that assignment of formats to the entire regions makes things faster, but that is not option for me.
My regions are very complex and not in one bulk.
Are there options for Excel to disable some processing during formatting so, that I can speed up my formatting? I do all the work in background/invisible state, then save the file to the disk and then I open it with ShellExecute.


text:
Q: Uploading image with DropZone and other values via AJAX but calling SweetAlert when Submit Data I have a form with some fields (first name, last name and profile picture) that looks like this:
<form>

            First Name:
            <input class="form-control" type="text" placeholder="Enter first name.." id="firstName">

            Last Name:
            <input class="form-control" type="text" placeholder="Enter last name.." id="lastName">

            profile picture:

                    <input name="file" type="file" multiple="multiple">

        <button type="button" class="btn btn-primary waves-effect waves-light" id="sweet-ajax">Submit Data</button>

</form>

When the user clicks on submit data I call a Sweet-Alert dialog that asks if the user is sure about the action he tries. If he clicks yes I want to submit the data via AJAX to an PHP script that does all the rest (storing the image on the server, save the data in my database and so on):

I also set up the DropZone on my site so that I can also have optional fields in my form (from here):
jQuery(document).ready(function() {

    $("div#profilbildDropzone").dropzone({
        //store images in this directory
        url: "../assets/images/uploads",
        dictDefaultMessage: "Drop image here or click.",
        autoProcessQueue: false,
        maxFiles: 1,
        uploadMultiple: true,
        parallelUploads: 100,

        // The setting up of the dropzone
        init: function() {
            var myDropzone = this;

            // First change the button to actually tell Dropzone to process the queue.
            this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
                // Make sure that the form isn't actually being sent.
                e.preventDefault();
                e.stopPropagation();
                myDropzone.processQueue();
            });

            // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
            // of the sending event because uploadMultiple is set to true.
            this.on("sendingmultiple", function() {
                // Gets triggered when the form is actually being sent.
                // Hide the success button or the complete form.
            });
            this.on("successmultiple", function(files, response) {
                // Gets triggered when the files have successfully been sent.
                // Redirect user or notify of success.
            });
            this.on("errormultiple", function(files, response) {
                // Gets triggered when there was an error sending the files.
                // Maybe show form again, and notify user of error
            });
        }
    });

});

But I do not get it how I upload the picture or give it so my php script.
In this line:
this.on("sendingmultiple", function() {
      // Gets triggered when the form is actually being sent.
      // Hide the success button or the complete form.
});

I'm supposed to upload the picture or what? Can I call this function inside my SWAL function or pass the data to my SWAL function where it gets send to the PHP script?
Sadly I haven't found any usable example that gives me a clear hint on how I could solve this specific problem.

A: You are not written logic send data via ajax to server side (i.e PHP). On click of the submit button you are telling Dropzone.js to processQueue(). But that itself will not post the data to the server via ajax.
On sendingmultiple event you need to get form data and assign it to formObject, then DropzoneJS will take care of posting data along file/image to the PHP.
init: function() {
    var myDropzone = this;

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
        // Make sure that the form isn't actually being sent.
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
    });

    // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
    // of the sending event because uploadMultiple is set to true.
    this.on("sendingmultiple", function() {
        // Append all form inputs to the formData Dropzone will POST
        var data = $form.serializeArray();
        $.each(data, function (key, el) {
            formData.append(el.name, el.value);
        });
    });
}

Next on the PHP server side get the posted data and files/images likes this.
<?php
    //get form data
    echo '
';print_r($_POST);echo '
';
    //get posted files
    echo '
';print_r($_FILES);echo '
';
    exit;

Next write your logic upload files/images and also updating the database with posted data.
Also check I have written detailed tutorials on how to upload images with form data on button click using DropzoneJS and PHP via ajax.
Ajax Image Upload Using Dropzone.js with Normal Form Fields On Button Click Using PHP


text:
Q: How do I install Realplayer to download FLV files? I need to be able to download .flv (flash video), and I know that the program "Real Player" can easily do that. How can I install it? I cant find the installer anywhere.

A: You can easily do that installing an add-on in firefox. Don't need to install any program for that. Open firefox, go to the website with the flash video and click in download.
Here is the link to the add-on.

A: if you mean downloading from youtube, you can install this extensionYouTube Downloader

A: This question has already been asked. I have no idea how to merge post or something. But this is the link to the question and answer: Is there any program or add-ons to download FLV from website?


text:
Q: Installing IIS 7.5 on Windows 7 Professional 64 bit Can you please assist me. I had installed IIS 7 on a Windows 7 professional 64 bit machine and I was getting errors when accessing my web pages, but now I decided to remove IIS to re-install it. The problem now is that I cannot see IIS manager in Admistrative Tools, even if I run CTLR + R (inetmgr) does not work. But when I browse http: //localhost on my browser I get the IIS7 default page as expected.
Can you please advise on what could be the problem? Thank you.

A: It is easy to overlook, but make sure you have the following option checked.
Internet Information Services -> Web Management Tools -> IIS Management Console

A: You need to verify that IIS is really is un-installed, and then either totally remove it or re-install it.
Open Control Panel
Program and Features
Turn Windows features on or off
Ensure that this is not checked to verify that it has been removed completely.


text:
Q: Vuetify Form Validation - defining ES6 rules for matching inputs I have a (Vuetify) form with an email input that uses ES6 & regex to check if it's a valid email. How would I set up another emailConfirmationRules ruleset to check if the emailConfirmation input matches the email input?
<template>
  <v-form v-model="valid">
       <v-text-field label="Email Address"
            v-model="email"
            :rules="emailRules"
            required></v-text-field>

       <v-text-field label="Confirm Email Address"
            v-model="emailConfirmation"
            :rules="emailConfirmationRules"
            required></v-text-field>
   </v-form>
 <template>

export default {
    data () {
      return {
         valid: false,
         email: '',
         emailConfirmation: '',
         emailRules: [
             (v) => !!v || 'E-mail is required',
             (v) => /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
        ],
        emailConfirmationRules: [
            (v) => !!v || 'Confirmation E-mail is required',
        ]   (v) => ??? || 'Confirmation E-mail does not match'
    }
}

A: Rules are not the proper way of handling field confirmation.
emailConfirmationRules are triggered only when emailConfirmation changes, but if you change email again, your fields won't match anymore without any break of rules.
You have to handle this manually:

methods: {
  emailMatchError () {
    return (this.email === this.emailConfirmation) ? '' : 'Email must match'
  }
}
<v-text-field v-model='emailConfirmation' :error-messages='emailMatchError()'></v-text-field>

There may be an alternative way of doing this with vee-validate too.

A: You can accomplish the same with a computed rule.
computed: {
    emailConfirmationRules() {
      return [
        () => (this.email === this.emailToMatch) || 'E-mail must match',
        v => !!v || 'Confirmation E-mail is required'
      ];
    },
}

A:   emailConfirmationRules: [
    (v) => !!v || 'Confirmation E-mail is required',
    (v) => v == this.email || 'E-mail must match'
  ],

A:   <template>
    <v-text-field
      v-model="employee.email"
      :rules="emailRules"
      required
      validate-on-blur
      />
</template>

<script>
data() {
    return {
    emailRules: [
        v => !!v || "E-mail is required",
        v =>
          /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
          "E-mail must be valid"
      ],
}
</script>

A: Check this post
https://stackoverflow.com/a/58883995/9169379

<template>
  <v-input  v-model="firstPassword" />
  <v-input :rules=[rules.equals(firstPassword)] v-model="secondPassword" />
</template>

<script>
  data() {
  firstPassword: '',
  secondPassword: '',
    rules: {
      equals(otherFieldValue) {
        return v =>  v === otherFieldValue || 'Not equals';
      }
    }
  }
</script>


text:
Q: Question on the transversality Let $f\colon N^n\to M^{2n}$ be an immersion. Then, we can extend $f$ to $\bar{f}\colon E(\nu_g)\to M$ of the total space of the normal bundle.
Let $s_0\colon N\to E(\nu_g)$ be a zero section and $s_1$ be the section which is zero at only a finite number of points. Define an isotopy $s_t\colon N\to E(\nu_g)$ between $s_0$ and $s_1$.
Let $f_t=\bar{f}\circ s_t\colon N\to M$. Then, $f_0=f$ by our construction.
Suppose that $f_0(x)=f_0(y)$ for $x\neq y$ is it ture that there exists a unique $y_1\in N$ in the neighborhood of $y\in N$ such that $f_0(x)=f_0(y)=f_1(y_1)$?


text:
Q: Invalid syntax python (defining vectors) #define the balls velocity
ball1.velocity=vector(85*cos(pi/9),85*sin(pi/69,0)
ball2.velocity=vector(85*cos((2*pi)/9),85*sin((2*pi)/9),0)
ball3.velocity=vector(85*cos((4*pi)/9),85*sin((4*pi)/9),0)

It is saying that there is invalid syntax for "ball.2".  This has worked in previous programs and works for the other two balls. Any idea what could be causing this?

A: You are missing a closing parenthesis in the ball1 line.


text:
Q: How to section a element with selenium & Appium that does not have a unique id, class, package, or resource id? I'm trying to detect if I get the expect response from a text message. so I need to access the text view of the received text. the problem I'm having is I cant figure out a way to let the driver know I need the received text rather than the sent text.
this first image of the ui selector shows that the sent text is highlighted here it shows the id, class, package, and resourse-id (which is out of frame)
in the second image of the ui selector shows that the received text is highlighted here it shows the id, class(out of frame), package, and resourse-id (which is out of frame)
all the attributes values match expect for the text value. how can i let appium know which one i need to check?
i was thinking something that accessed a element within another element, code id assume would be something like this:
await driver.waitForElementById('com.android.mms:id/msg_list_item_recv', 30000, function (err, data) {})
        .elementById('com.android.mms:id/text_view', function (err, data){})
        .textPresent('key text value', function (err, data) {});

Any help would be greatly appreciated.

A: If you can ask developers to update id of send text it will be best to do this, as currently there is same id for sent and received text . If this is not possible you can try this .

@FindBy(id = "com.android.mms:id/text_view")
    private List<WebElement> messagelist;

for (int i=0;i<messagelist.size();i++)
{
    if(messagelist.get(i).gettext().contentEquals("sendtext"))
    {
       // then i+1 is your received text
        messagelist.get(i+1).gettext().contentEquals("recievedText")
    }
}

A: What you can do to detect if message is received (left) or sent (right) is to compare with their bounds...
For my example I will use these two bounds:
Received message
Sent message
In Xpath with my example could be:
"//android.widget.TextView[@resource-id='com.android.mms:id/msg_list_item_recv' and contains(@bounds, '[163,')]"

If you have an element at [163,100][100,100] everything will be ok. But... The problem with this method is that if you have an element at [100,100][163,100] it will detect it as received when is not... So the next method could be better because there is no option...
Another way to get just left messages could be:
"//android.widget.TextView[@resource-id='com.android.mms:id/msg_list_item_recv' and not(contains(@bounds, '][942,'))]"

In the other hand this will return any textview that NOT contains "][942," so there can not be mistakes
Let me know if worked. I do it this way to know it.


text:
Q: How to display playback_count for a user using the SoundCloud API I am trying to display the total track views ("playback_count") for a specific SoundCloud user using the SoundCloud API.
According to the API documentation I get the info using the below function call:
http://api.soundcloud.com/tracks/13158665.json?client_id=YOUR_CLIENT_ID

This is fine because it displays the number "13158665".
What is this number? Is it the trackid?
I need to get the "playback_count" for a user using the users username.
I tried getting the UserId from the Username using this:
$soundcloud_playsAPI = "MY_SOUNDCLOUD_API_KEY";

/* Get the SoundCloud UserId from the username */
$json = wp_remote_get("http://api.soundcloud.com/users/jwagener.json?client_id=".$soundcloud_playsAPI);

$soundcloudData = json_decode($json['body'], true);
$soundcloud_userid = $soundcloudData['id'];

This returns the UserId: 3207181
Now I tried to substitute that response into the previous URL to get the "playback_count" but it failed.
$json = wp_remote_get("http://api.soundcloud.com/tracks/3207181.json?client_id=".$soundcloud_playsAPI);
$soundcloudPlaysData = json_decode($json['body'], true);
echo $soundcloudPlaysData['playback_count'];

Any guidance would be greatly appreciated.
Thanks.

A: The first number is the id of a track, the second number is the id of a user.
Now that you have the user id, you will need to fetch each of their tracks and tally how many times they have been played
First, get the id numbers for all tracks made by the user
GET:         /users/{id}/tracks:       list of tracks of the user
$json = wp_remote_get("http://api.soundcloud.com/users/3207181/tracks.json?client_id=".$soundcloud_playsAPI);

Now you have a list of track IDs so you will need to get each of those tracks and save the playback_count of each
$json = wp_remote_get("http://api.soundcloud.com/tracks/track-id-here.json?client_id=".$soundcloud_playsAPI);
$soundcloudPlaysData = json_decode($json['body'], true);
echo $soundcloudPlaysData['playback_count'];

A: Here is the full solution:
function listPlays()
    {SC.initialize({  client_id: 'YOUR ID HERE'});
    // Get the SoundCloud UserId from the username
    var userName="jwagener";
    SC.get("/users/"+userName,  function (users)
            {console.log(users.id);
            var myId=users.id;
            getTracks(myId);
            });

    var getTracks=function (myId)
        {var totalPlays=0;
        SC.get("/users/"+myId+"/tracks", function(getTracks)
            {for (var key in getTracks)    //get each track and look at it's playback_count
                {console.log(getTracks[key].title+"     "+getTracks[key].playback_count);
                totalPlays+=getTracks[key].playback_count;   //add the playback count for this track to the total
                }
            console.log("Total Plays for all tracks: "+totalPlays);

            });
        };

};


text:
Q: Is it possible to use the genitive with these expressions? Why don't we say "cat's food' but "cat food", is it because the owner is not a human? Can we say pets' food?

A: We use "cat food" because it's not a genitive. "Cat" is a descriptor. It's the equivalent of "blue house" -  a house that is blue.
A can of "cat food" is a can of food for cats - generally, not a specific cat.
You can definitely say "cat's food" but you wouldn't use it to describe the food generally, you use it to describe it particularly. Here's an example.

*

*My dog eats cat food.

*My dog eats the cat's food.

These mean different things.  Version 1 means that I, for some reason, feed my dog cat food instead of dog food. Version 2 means that I have both a cat and a dog and the dog eats the food that's put out for the cat.


text:
Q: Ripped edge pattern on div? The designer I'm working with has given me a monster of an implementation issue...
Page background is grey, and atop of it is a crumpled paper texture (non-repeating with painted design elements) for the first 600 pixels (by 1400 pixels across; currently centered as a non-repeating background). At the bottom is another div with more text on it -- with a dropshadow, complex line pattern for the background and ripped edges, hovered slightly above the top div.

*

*Saving the top part as a JPG and the bottom part as a transparent PNG leads to filesizes of +1mb.

*Saving the top part as a JPG and the bottom part as a JPG doesn't work very well due to the drop shadow. It would technically work to save the bottom part as a slice with elements of the top part underneath the dropshadow, but it would have to line up pixel-perfect always or else look crappy. And at that point, I might as well save the whole site as one big image...

*If the bottom part had a solid colour for the background, I could set each edge to have a different transparent PNG. However, the line pattern on the bottom part means that this wouldn't work.

My question is ultimately:
How the heck do people do ripped edges these days without making their site one big image?
Thanks!
Screengrab:

A: CSS3 does provide a border-image property, which should be able to help you with the ripped border effect (although even then, it would help if it was a repeating image).
See here for the W3 specification.
However it may not be much use to you, because browser support for this feature isn't great -- IE doesn't support it at all (not even IE9), and while most other browsers do support it, they all currently have gaps in their support and require a vendor prefix in the CSS property.
See CanIUse.com for a full browser support table for it.
To be honest, I think you should just go back to your designer and ask him to make it easier to work with -- he's probably just created something he thinks looks good, but is unaware of the limitations of the design he's put together; if you explain the issue to him, he may well be able to produce something a bit more usable for you.

A: There's really not a whole lot you can do here.
Page edges are ideally seamlessly repeated via repeat-y, and in your case it looks like the texture is one big image. You're either going to have to settle for sub-par performance or present the designer with your issues.
Check the archive of this blog for a good example.

A: You either have to fix the background images and use the entire image (or the top image AND the bottom image) and make the background non-scrolling. OR you have to get him to design a pattern that can repeat and then use a smaller PNG.

A: Clearly, your designer has a print background....
Ok, there's ways that will most likely theoretically work.  But theoretical isn't always practical.  I suspect your desire is to have cross-browser capability, as all of us should.  So, start by throwing most new CSS3 tricks out, thanks to legacy IE.  Forget box-shadow, forget crazy png tranparencies without hacks, etc.
What you're left with is doing a gigantic .jpg background.  That will load....eventually.....
In this case, you can see the storm on the horizon, so run for cover.  Go back to the designer, explain why this is about as smart an idea as texture layered over gradients, and help them understand why our buddies at Microsoft have made this virtually impossible.  Just like a fully-flashed out site, it can be done somehow....but it's probably not the best use of time and resources.  The web isn't print, it's dynamic...and when you put something "on a page" it's not going to stay put as it would in Illustrator, nor can you guarantee that your user is going it experience it in 100# glossy with a metallic overlay.  Yes, I was a designer before I was a developer.....
Sound like a cop-out?  Maybe it is.  But I've been in your shoes, building sites for credit cards.  My team was forced to waste thousands of dollars of the bank's money trying to make sites work with designs that probably shouldn't have been done on the web, thanks to print designers doing double-duty, getting designs approved prior to talking to the tech team....after, of course, we presented management with the options.  Ultimately, it got the boss fired for going over budget.

A: although this is untypical, I would recommend cutting a big square shaped hole in the center of the image so that you're only left with the edges themselves and a transparent center and saving to PNG. Then saving the center part itself as a jpeg and putting the jpeg directly on top of the PNG in the correct position.
This way, the majority of the very large PNG will contain very little data and be a very small file size. The rest of the data would then, obviously, be jpeg and therefore smaller.