text:
Q: Getting a window property in Angular 13 Trying to do this in Angular 13:
private _stripe:StripeFactory = window['Stripe']

And it creates this error:

Element implicitly has an 'any' type because index expression is not of type 'number'

Any ideas on how to fix this?
I added:
"suppressImplicitAnyIndexErrors": true,

To tsconfig.json, but the linting errors still persist.

A: Instead of
"suppressImplicitAnyIndexErrors": true,

in tscongfig.json, it's recommended to use an @ts-ignore comment on the preceding line in the .ts file:
// @ts-ignore
private _stripe:StripeFactory = window['Stripe']

But there is definitely a more 'Angular' way to do what you are trying to do, but I'm not quite sure what that is. Just extrapolating from the name of the type, I'd have a StripeFactory in the StripeService that calls a getStripe() method which has access to your Stripe configuration and key, using that to grab the global Stripe object. You'll have to load Stripe separately and inject the StripeService into the components that need it.
See this dev post for this Stripe specific solution in detail.
Or if you want to stick with window, you can add it to your provider array in the module:
providers: [
  { provide: Window, useValue: window }
]

Then you can inject it directly into your service:
constructor(private window: Window) {
  // ....do whatever you're gonna do
}


text:
Q: Не получается слинковать скомпилированный код на ассемблере Есть простая программа на ассемблере (синтаксических ошибок нет). Компилится в obj более-менее нормально, через один раз. Я использую nasm, но когда пытаюсь слинковать через golink — он отказывается работать и выдаёт ошибку:

При попытке сохранить текст программы в других различных кодировках (включая UTF-8 и остальные UTF-16) уже отказывается работать компилятор. Он просто не может прочитать текст. Иногда может, но его смущают некоторые символы и он выплёвывает ошибку undefined, конечно же, ничего не скомпилировав.

Я обращаюсь к вам за помощью здесь, потому что уже потратил несколько часов на попытки разобраться в этом с использованием информации в интернете. Помогите, пожалуйста, решить проблему с линковкой, или хотя бы посоветуйте, где можно скачать работающий линковщик.

Скомпилировал с другими параметрами, теперь линковщик ругается на отсутствие секций...я не понимаю, что происходит.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery click does not work Anyone have an idea why my jQuery click won't work?
It's attached to a hyperlink.
jQuery(function ($) {

    $(".delete").click(function(e) {
        alert("Hello");
    });

    var socket = io.connect();
    var $messageForm = $('#sendmessage');
    var $messageTitle = $('#title');
    var $messageBox = $('#message');
    var $chat = $('#chat');

    $messageForm.click(function (e) {
        if ($.trim($("#title").val()).length === 0) {
            alert('You must provide valid input');
            $messageTitle.val('');
            $messageBox.val('');
            return false;
        }
        if ($.trim($("#message").val()).length === 0) {
            alert('You must provide valid input');
            $messageTitle.val('');
            $messageBox.val('');
            return false;
        } else {
            e.preventDefault();
            socket.emit('send message',
               '' + $messageTitle.val() + '' + ' - '
               + $messageBox.val() + ' ' + '[' +
               'Delete' + ']');
            $messageTitle.val('');
            $messageBox.val('');
        }
    });

    socket.on('new message', function (data) {
        $chat.prepend(data + "
");
    });
});

A: Since the delete links are dynamically generated, you need to use event delegation:
$('#chat').on('click', '.delete', function(e) {
    alert("Hello");
});

A: Hello try to modify your jquery initialization like this:
(function($){ }(jQuery)

If your script still doesn't fire the click event, check if $messageForm exists, using console.log($messageForm). You can modify var $messageForm in var messageForm from what I seen that variable does not need a scope so wide. I hope this could help you


text:
Q: powershell weird output array index I have an array of numbers (larger than the example)
$ccheck = ("44729375","74729375")

for ( $i = 0; $i -lt $ccheck.Count; $i++ ) {
     cd $env:userprofile\desktop\CURL\
     $ccheck[$i]
     $curlexec ="curl -L ""https://server.net/$ccheck[$i]""";
     $curlexec
}

with a for loop I am iterating over an array. When asking for index with $ccheck[$i]  I am getting the first index which is 44729375. But from $curlexec variable I am getting the whole array and I just want the i index.
So I am getting this as as output  https://server.net/44729375 74729375 from the variable $curlexec. I don't know what's wrong.

A: Read Get-Help 'about_Quoting_Rules'.
Use either sub-expression syntax
 $curlexec ="curl -L ""https://server.net/$($ccheck[$i])""";
 ##### note the change                    $(           )

or an auxiliary variable
 $ccheckaux = $ccheck[$i]
 $curlexec ="curl -L ""https://server.net/$ccheckaux""";


text:
Q: How do I work with output data from BeatifulSoup? Specifically how do I split URL and anchor? I have this test code to extract backlinks from webpages. But I haven`t found a good solution to extract specifically URL and anchor, as well as additional attributes of the tag.
Allow me to explain more thorough. Let`s suppose I have 3 webpages I need to check. site.com/a/, site.com/b/ and site.com/c/. For each of the webpages I have the following output with this code:
1. [anchor-example-1]

2. [anchor-example-2]

3. [anchor-example-3]

What is the best way to split extraction so I have the following output for, let`s say, example #1?
Linked URL: https://example.com/
Anchor: anchor-example-1
Rel: nofollow

Also, as seen in the example #2 some websites tend to put some junk(?) in the code.
href="\'https://example.com/\'"

How do I get rid of things such as \' and other stuff that may corrupt output data at times?
from bs4 import BeautifulSoup
import requests
import re

with open('input.txt') as input_data:
    for line in input_data:
        check_url = line.rstrip('\n')
        data = requests.get(check_url, headers={'User-Agent': 'Mozilla/5.0'})
        data.encoding = 'ISO-8859-1'
        soup = BeautifulSoup(str(data.content), 'html.parser')
        backlink = soup.find_all('a', attrs={'href': re.compile('example.com')})
        print('Backlink: ', backlink, '\n')

Thanks in advance and have a happy holiday!

A: try some like this:
from bs4 import BeautifulSoup

html = """anchor-example-1
          anchor-example-2
          anchor-example-3
       """
soup = BeautifulSoup(html)

for n in soup.find_all('a'):
    print ('Linked : '+ n.get('href'))
    print ('Rel : '+''.join(n.get('rel')))
    print('Anchor : '+n.text)

Result :
Linked : https://example.com/
Rel : nofollow
Anchor : anchor-example-1
Linked : 'https://example.com/'
Rel : 'nofollow'
Anchor : anchor-example-2
Linked : https://example.com/
Rel : nofollow
Anchor : anchor-example-3


text:
Q: Is the following operator (related to the Dirac's delta) bounded? Consider $\eta \colon [-1,0] \to \mathbb{R}$ of bounded variation and define the (delay) operator $\Phi \colon \mathcal{C}[-1,0] \to \mathbb{R}$ by
$$\Phi f = \int_{-1}^{0} f d \eta$$
for $f \in \mathcal{C}[-1,0]$ where the integral is the Riemann-Stieltjes integral.
$\Phi$ is a bounded linear operator acting on $\mathcal{C}[-1,0]$ and so by continuous embeddings it is a bounded linear operator acting on the Sobolev space $W^{1,2}[-1,0]$.
Now [Bátkai, András, and Susanna Piazzera. Semigroups for delay equations. CRC Press, 2005.] p.69 example 3.28 claims that
$$\Phi f= f(-1), f \in W^{1,2}[-1,0]$$
is representable in the integral form before and it is a bounded linear operator.
But $\eta$ in this case should be the Dirac's delta in $-1$, i.e. $\eta = \delta_{-1}$.
It feels weird that it is a bounded linear operator on $W^{1,2}$ when usually distributions are defined as linear continuous functionals on $C_{0}^{\infty}$ which is a much smaller space? I mean ok this should be another way to define functionals from distributions right?
From the point of view of calcultions it seems like that:
$$|\Phi f|= |f(-1)| \leq |f|_{\mathcal{C}^0} \leq C |f|_{W^{1,2}}$$
where $|\cdot|_{\mathcal{C}^0}$ is the sup norm.
Anyway since $\eta= \delta_{-1}$ is not a function can you define the Riemann-Stieltjes integral correctly?

A: Actually, in terms of Stieltjes integral, the evaluation at a point is represented by the Heaviside function and not the Dirac delta. More precisely, if you have $H_{-1}(x) = \mathbf{1}_{x>-1}$ then
$$
f(-1) = \int_{-\infty}^\infty f(x)\,\mathrm d H_{-1}(x) = \int_{-\infty}^\infty f(x)\,\delta_{-1}(\mathrm d x)
$$
The Dirac delta $\delta_{-1}$ is only the derivative (in the sense of distributions) of your function of bounded variation $H_{-1}$ ... As I explained more precisely here, the ambiguity is due to the abusive notation $∫ f\,\mathrm d \mu$ when $\mu$ is a measure, which should rather be $∫ f\,\mu = ∫ f\,\mathrm d \eta$ or $∫ f(x)\,\mu(\mathrm d x) = ∫ f(x)\,\mathrm d \eta(x)$ to be coherent with the Stieltjes integral.
Distributions are usually defined on $C^\infty_c$ when one wants to be able to take a lot of derivatives. The distributions of order $0$ are isomorphic to measures, and so to every distribution of order $0$ one associates a measure such that the formula
$$
\langle\mu,\varphi\rangle = ∫ \varphi(x)\,\mu(\mathrm d x)
$$
holds for every test function in $C^\infty_c$. But the right hand-side can be defined through the usual measure and integration theory, so one can take any $\varphi\in L^1(\mu)$. And so in particular, any function $\varphi\in C^0$.
Still, it is indeed a bit weird here to use the fact that one can write $f(-1)$ as an integral to deduce the result, and your computation $|f(-1)| ≤ \|f\|_{C^0} ≤ C\|f\|_{W^{1,2}}$ makes much more sense.


text:
Q: Is a unitary representation always semisimple? I have been reading the online lecture notes by Fiona Murnaghan
http://www.math.toronto.edu/murnaghan/courses/mat1197/notes.pdf
The first lemma in p.35 says that every unitary representation of locally compact group $G$ is semisimple. In her notes, she defines a semisimple representation to be a representation which is a direct sum of irreducible representations.
On the other hand, people often say that the right regular representation of $G$ on $L^2(G)$, which is unitary, does not decompose into a direct sum of irreducible representations but it is a direct integral.
But if the above lemma by Murnaghan is correct, it seems that $L^2(G)$ must be a direct sum of irreducible representations.
I read the proof of the lemma in her note carefully, and noticed that even though she stated the lemma under the assumption that the group $G$ is $p$-adic and the representation is smooth, the proof goes through for any locally compact group and any uniterizable representation. Indeed, the proof only uses the property that any subrepresentation has the orthogonal complement and Zorn's lemma.
What am I missing?

A: Probably the version of "semi-simplicity" relevant in the context in those notes refers to a repn of $G$ that is admissible with respect to a compact subgroup $K$, in the sense that it is assumed to decompose with finite multiplicities over $K$. This assumption holds for repns induced from cuspidal repns on the compact itself, for example, as observed by Jacquet already in 1971. In such a context, the otherwise-too-glib remarks about complete-reducibility still reach a correct conclusion, even without completeness in a Hilbert-space sense.
The more down-to-earth situations, like $L^2(\mathbb R)$, or subspaces generated by rough functions on the circle, do not satisfy suitable "admissibility" conditions, perhaps-oddly.

A: $L^2(\mathbb{R})$ acted on by translation does decompose into a direct integral of one-dimensional representations. So in  general you have a direct integral if $G$ is not compact. If $G=SL_2(Q_p)$, you have the same issue. So no direct sum, but a direct integral.
You should look up type 1 groups, for various more complicated issues. The decomposition might not be unique otherwise.
I haven't time to read the full script. I seems that she is using it in the context of supercuspidal representations, which are in fact semisimple in the sense that they decompose into a direct sum (actually a finite sum). Here it is okay.
Murnagahan is certainly wrong if she means unitary = unitarizabile and smooth,e.g. it fails for $C_c^\infty(G)$. Unitary (being a unitary Hilbertspace representation and smooth) implies finite-dimensional, so isn't really interesting.

A: In the lemmas on semisimplicity, the representation is assumed to be smooth, which $L^2(G)$ is not.

A: The dimension. Every finite-dimensional unitary representation is a direct sum of irreducible representations (given an irreducible sub-representation, take the orthogonal, and go on…), but this is not true of an infinite-dimensional unitary representation -- you cannot go on forever, so you need a more elaborate notion of direct sum.

A: The proof does not go through. As far as I can tell, it is just false that $V = W \oplus W^{\perp}$ with only the hypotheses Murnaghan is using; the standard hypotheses are that $V$ is complete and that $W$ is closed. $W$ closed is necessary since the above implies $W = (W^{\perp})^{\perp}$, and on the other hand the earlier lemma to which the proof alludes needs complements for arbitrary $W$ to get semisimplicity.
For an easy counterexample let $V = L^2(\mathbb{Z})$ be the regular representation of $\mathbb{Z}$ (locally compact, Hausdorff, and totally disconnected as required) and let $W$ be the subspace of compactly supported functions. Then $W^{\perp} = 0$.
Edit: Noncompactness isn't even the issue here. For a compact counterexample let $V = L^2(S^1)$ be the regular representation of $S^1$ and let $W$ be the subspace spanned by translates of, say, a sawtooth wave. Here we don't get a direct sum of irreducibles but a Hilbert space direct sum of irreducibles. In general an infinite-dimensional Hilbert space can never be the orthogonal direct sum of any collection of its finite-dimensional subspaces.
I know nothing about $p$-adic representation theory but it seems like that whole section is disregarding the issue of topologies on $V$ and other hypotheses concerning only the structure of $V$. Is this standard?


text:
Q: How to get the physical_name of the secondary log shipping databases? The following query returns M:\data\db.mdf and L:\data\db.log. However, the server even doesn't have drive M: and L:.
SELECT * FROM sys.database_files

How to get the physical names of the disk files? I need to detach the database and make a copy of the database files to restore it on another machine since the secondary logshipping database cannot be backed up. What's the best way to make a copy of secondary db?


text:
Q: Get Integer between parenthesis using RegExp I'm trying to use regExp to get values between parenthesis:
for example:
<input type=\"button\" OnClick='FullScreen(1)' value=\" 1\" size=80>
<input type=\"button\" OnClick='FullScreen(2)' value=\" 1\" size=80>
<input type=\"button\" OnClick='FullScreen(3)' value=\" 1\" size=80>
<input type=\"button\" OnClick='FullScreen(4)' value=\" 1\" size=80>

I want to retrieve the values of the Fullscreen in this case 1,2,3 and 4
I try this regular expression:
    Pattern p = Pattern.compile("\\((.*?)\\)");

    Matcher m = p.matcher(String);
    if(m.find()){
        System.out.println("val = " +m.group(1));
    }

but this retrieves all the values between parenthesis how to I make to only get the values from the FullScreen string?
Thanks

A: Also add the  FullScreen prefix to your regex.
Pattern p = Pattern.compile("FullScreen\\((.*?)\\)");
Matcher m = p.matcher(String);
if(m.find()){
    System.out.println("val = " +m.group(1));
}


text:
Q: Why do I get a "Dimension is too large" error? \documentclass{article}
\usepackge{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{figure}[H]
\centering
\resizebox{0.80\textwidth}{!}{%
\begin{tikzpicture}
\begin{axis}[width=15cm,compat=1.5,height=9.5cm, legend columns=-1,
, axis line style=thick,
legend style={/tikz/every even column/.append style={column sep=6.15cm}, at={(0,0)}, mark
size=2.5pt, anchor=north east, at={(axis description cs:1.0,1.15)}, font=\small},
xlabel=\large periods, tick align=inside,
xtick={35,...,45},
ytick={0,10000,20000,...,1500000},
ylabel=\large Cases,
ymajorgrids=true,
grid style=dashed,
scaled x ticks=false,
        ]
\addplot[very thick,mark size=2.5pt,color=cyan,mark=x]
       plot coordinates {
                (37,205945.16)
                (38,262273.00)
                (39,334005.49)
                (40,425355.53)
                (41,541688.17)
                (42,689835.69)
                (43,878498.89)
                (44,1118758.08)
                (45,1424723.84)
        };
    \end{axis}
    \end{tikzpicture}
}
\end{figure}
\end{document}

A: It's the ytick part that offends. Typically, pgfplots has no problems handling these numbers but when you use <first>,<second>,...,<final> syntax, pgfplots uses the TikZ foreach hence the TeX based pgfmath capabilities which are limited up to 16384. Then it trips up. You can either spell out the ticks or use minor y tick num as a quicker fix. You can also turn on the grid for those too if you wish.
\documentclass{article}
\usepackge{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
  minor y tick num=5,
  ymajorgrids=true,
  grid style=dashed,
  scaled x ticks=false,
]

\addplot[very thick,mark size=2.5pt,color=cyan,mark=x]
    coordinates {
                (37,205945.16)
                (38,262273.00)
                (39,334005.49)
                (40,425355.53)
                (41,541688.17)
                (42,689835.69)
                (43,878498.89)
                (44,1118758.08)
                (45,1424723.84)
        };
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Writing wrappers for Python 3 vs Python 2 In Python, is there any difference in how one would write Python wrappers for c++ libraries if one aims to make it compatible with Py3 vs Py2?
Or should a wrapper originally written for Py2 work the same way for Py3 and visa versa? As I understand it, Python wrappers are written in c++ in a .cxx file which then have to be compiled.
Details
I ask because I'm wanting to install Aggdraw (wrapper for c++ Anti Grain Geometry drawing library), which works in Python 2.6-7, but results in errors on Python 3.4 (Windows 7 32-bit, via "PATH=C:/Python27[or Python34]" and "python setup.py install" in the command line). My hope is to revive this amazing wrapper module for Python 3, and was hoping anyone else here would be interesting in helping out.
I can get it compiled on Python 2.6 and 2.7 without any problems, and I have both Visual C++ 2008 and 2010 so it's not a compiler problem. The problem seems to be in the actual .cxx wrapper code.
Could it be that the Aggdraw wrapper was only written with Python 2x in mind (almost 10 years ago now), and so it didn't take into account problems that might arise in Python 3x? My best guess is that the wrapper fails to convert certain c++ objects/types over to Python due to deprecated and changed features in version 3.4.
I might be willing to go through the .cxx wrapper code to change the necessary parts, if someone can help me identify what the troubleparts are (see command line error codes below)? If we get it fixed then I'll update this post with a link to the "revived" wrapper code.
If there should´t be a difference between Python 2 and 3 wrappers, any idea why I´m getting the error codes below in Py3 but not Py2?
Thanks!
Original wrapper code: click here
C:\Users\BIGKIMO\Desktop\aggdraw-master>python setup.py build
=== freetype not available (edit setup.py to enable)
running install
running build
running build_ext
building 'aggdraw' extension
C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe /c /nologo /Ox /MD /
W3 /GS- /DNDEBUG -Iagg2/include -IC:\Python34\include -IC:\Python34\include /Tpa
ggdraw.cxx /Fobuild\temp.win32-3.4\Release\aggdraw.obj
aggdraw.cxx
aggdraw.cxx(124) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(126) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(128) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(142) : error C2440: 'initializing' : cannot convert from 'const char
 [4]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(144) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(161) : error C2440: 'initializing' : cannot convert from 'const char
 [6]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(163) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(187) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(189) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(191) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(207) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(209) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(211) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(488) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(489) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(575) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(583) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(584) : error C3861: 'PyString_GET_SIZE': identifier not found
aggdraw.cxx(730) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(730) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(731) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(731) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(735) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(735) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(736) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(736) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(742) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(742) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(745) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(745) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(759) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(760) : error C3861: 'PyInt_AsLong': identifier not found
aggdraw.cxx(763) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(765) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(788) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(789) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(1157) : error C3861: 'PyString_FromStringAndSize': identifier not fo
und
aggdraw.cxx(1289) : error C3861: 'PyString_FromString': identifier not found
aggdraw.cxx(1294) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1482) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1890) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1910) : error C3646: 'initaggdraw' : unknown override specifier
aggdraw.cxx(1911) : error C2091: function returns function
aggdraw.cxx(1911) : error C4430: missing type specifier - int assumed. Note: C++
 does not support default-int
aggdraw.cxx(1912) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1912) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1915) : error C3861: 'Py_InitModule': identifier not found
aggdraw.cxx(1940) : warning C4508: 'DL_EXPORT' : function should return a value;
 'void' return type assumed

A: The Python FFI library (ctype) has changes between each version of python. It would be up to you to go through the change list and see what exactly is different and why it isn't working.
For example, ssizet and strings are different between the two Python versions.
https://docs.python.org/3/whatsnew/3.2.html#ctypes
Differences in ctypes between Python 2 and 3

A: In the interest of expanding upon the previous answer, there are many functions which acted upon string in Py2.7 and now act upon bytes or unicode in Py3. Similarly, what referred to int may now refer to long. As just one example of this that caused a problem here, PyString_Check has been deprecated by pyBytes_Check. Read the following for more details:
https://docs.python.org/3/howto/cporting.html?highlight=pystring


text:
Q: How to change the name of table in SQL Server that is a keyword I used procedure as the name of a table in SQL Server. And I can't do anything now and get error.
I didn't know it is a reserved keyword.
What should I do ?

A: You can use reserved keywords for table and field names in SQL server when you surround them with square brackets.
So
drop table [procedure];

should solve the problem. The other option is to find the table dbo.procedure in Object Explorer, right click it, click Delete and choose OK.

A: You can use brackets [] or QUOTENAME() with dynamic SQL. But is bad practice at all to use RESERVED WORDS as tables, columns names.

A: You should Rename the Table to a non Reserved Keyword which reflects its usage. To Rename the table using something like this.
EXEC sp_rename '[procedure]','MyTable','OBJECT'

You can continue to use (Not Recommended) the existing name using [] in Static SQL like
SELECT <ColumnName> FROM [Procedure]
Or use QUOTENAME() where the table name needs to be manually added in case of Dynamic SQL. Something like this.
DECLARE @TableName NVARCHAR(10) = 'Procedure'
DECLARE @SQL NVARCHAR(500) = N'SELECT * FROM ' + QUOTENAME(@TableName)
EXEC sp_executesql @SQL

you can find the list of Reserved words here.


text:
Q: How to make git-diff and git log ignore new and deleted files? Sometimes there's a couple of changed files together with some new, deleted and/or renamed files. When doing git diff or git-log I'd like to omit them, so I can better spot the modifications.
Actually, listing the names of the new and deleted files without their content would be best. For "old" renamed to "new" I'd like to optionally get the difference between "old" and "new".

A:
Also, these upper-case letters can be downcased to exclude.
E.g. --diff-filter=ad excludes added and deleted paths.

In your case, git diff  --diff-filter=ad would work, but make sure to not use lower and upper letters in the same filter, unless you have Git 2.36 (Q2 2022).
"git diff --diff-filter=aR"(man) is now parsed correctly.
See commit 75408ca, commit 4d4d4ea, commit d843e31 (28 Jan 2022) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 9a16099, 16 Feb 2022)

diff-filter: be more careful when looking for negative bits
Signed-off-by: Johannes Schindelin

The --diff-filter=<bits> option allows to filter the diff by certain criteria, for example R to only show renamed files.
It also supports negating a filter via a down-cased letter, i.e.
r to show everything but renamed files.
However, the code is a bit overzealous when trying to figure out whether git diff(man) should start with all diff-filters turned on because the user provided a lower-case letter: if the --diff-filter argument starts with an upper-case letter, we must not start with all bits turned on.
Even worse, it is possible to specify the diff filters in multiple, separate options, e.g. --diff-filter=AM [...] --diff-filter=m.
Let's accumulate the include/exclude filters independently, and only special-case the "only exclude filters were specified" case after parsing the options altogether.

A: The --diff-filter option works with both diff and log.
I use --diff-filter=M a lot which restricts diff outputs to only content modifications.
To detect renames and copies and use these in the diff output, you can use -M and -C respectively, together with the R and C options to --diff-filter.

A: Official document:

--diff-filter=[(A|C|D|M|R|T|U|X|B)…[*]]
Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, …) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B).
Any combination of the filter characters (including none) can be used.
When * (All-or-none) is added to the combination, all paths are selected if there is any file that matches other criteria in the comparison; if there is no file that matches other criteria, nothing is selected.
Also, these upper-case letters can be downcased to exclude. E.g. --diff-filter=ad excludes added and deleted paths.

Example: show only added , changed, modified files exclude deleted files:
git diff --diff-filter=ACM

A: UPDATE: The accepted answer by Charles Bailey is the correct one; the desired functionality is already built into git.
I'll leave this answer here since it might provide ideas for things that aren't built into git.

git diff shows new and deleted files by comparing them to /dev/null.  It shouldn't be too difficult to write something (I'd use Perl myself) that looks for /dev/null and filters out the following lines up to the next diff.  Then git diff ... | the-filter.
Renamed files are a different matter; I don't (yet) have a good answer to that.


text:
Q: Is there an idiomatic way to assert a stream has only one element while yielding that element? Starting with this code:
public Thing thereCanBeOnlyOne(Stream<Thing> stream) {
  List<Thing> things = stream.collect(Collectors.toList());
  if(things.size() != 1) {
    throw new IllegalArgumentException();
  }
  return things.get(0);
}

Is there a more succint way to express the method body?
What I tried so far:
I read the documentation for Collector and reduce, but didn't find anything.

A: If using Guava is palatable to you, use MoreCollectors.onlyElement:
public Thing thereCanBeOnlyOne(Stream<Thing> stream) {
  return stream.collect(MoreCollectors.onlyElement());
}

Equivalents may well exist in other common libraries; I am just familiar with Guava.

A: How about
public static Thing thereCanBeOnlyOne(Stream<Thing> stream) {
    Object[] array = null;
    if((array = stream.limit(2).toArray()).length != 1) {
            throw new IllegalArgumentException();
    }
    return (Thing)array[0];
}

To me it seems like less overhead.


text:
Q: (13.04) lightdm crashing - black screen flashing cursor I am using the 13.04 x64 release of Ubuntu on my PC and at least it works so far as it should.  But suddenly the lightdm crashes during boot and even if I try to start it manually from terminal after switching to another tty.
I don't know what may cause the problems because I didn't even install any graphics-drivers for my nvidia card (because I just know those problems since years and skip those problems by not installing any of them).
It worked fine for some days after fresh install and updates, but now it just does not what it should.
Switching to gdm did solve the problem logging in to my computer with a gui but hell this lightdm should work I guess..
The logs aren't pretty much of help for me but maybe someone know what's up?
lightdm.log

 [+0.00s] DEBUG: Logging to /var/log/lightdm/lightdm.log [+0.00s]
 DEBUG: Starting Light Display Manager 1.6.0, UID=0 PID=7369 [+0.00s]
 DEBUG: Loaded configuration from /etc/lightdm/lightdm.conf [+0.00s]
 DEBUG: Using D-Bus name org.freedesktop.DisplayManager [+0.00s] DEBUG:
 Registered seat module xlocal [+0.00s] DEBUG: Registered seat module
 xremote [+0.00s] DEBUG: Adding default seat [+0.00s] DEBUG: Starting
 seat [+0.00s] DEBUG: Starting new display for greeter [+0.00s] DEBUG:
 Starting local X display [+0.00s] DEBUG: Using VT 7 [+0.00s] DEBUG:
 Activating VT 7 [+0.01s] DEBUG: Logging to /var/log/lightdm/x-1.log
 [+0.01s] DEBUG: Writing X server authority to /var/run/lightdm/root/:1
 [+0.01s] DEBUG: Launching X Server [+0.01s] DEBUG: Launching process
 7376: /usr/bin/X :1 -core -auth /var/run/lightdm/root/:1 -nolisten tcp
 vt7 -novtswitch [+0.01s] DEBUG: Waiting for ready signal from X server
 :1 [+0.01s] DEBUG: Acquired bus name org.freedesktop.DisplayManager
 [+0.01s] DEBUG: Registering seat with bus path
 /org/freedesktop/DisplayManager/Seat0 [+0.61s] DEBUG: Got signal 10
 from process 7376 [+0.61s] DEBUG: Got signal from X server :1 [+0.61s]
 DEBUG: Connecting to XServer :1 [+0.61s] DEBUG: Starting greeter
 [+0.62s] DEBUG: Started session 7385 with service 'lightdm-greeter',
 username 'lightdm' [+0.64s] DEBUG: Session 7385 authentication
 complete with return value 0: Success [+0.64s] DEBUG: Greeter
 authorized [+0.64s] DEBUG: Logging to /var/log/lightdm/x-1-greeter.log
 [+0.64s] DEBUG: Session 7385 running command
 /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter
 [+0.68s] DEBUG: Greeter closed communication channel [+0.68s] DEBUG:
 Session 7385 exited with return value 1 [+0.68s] DEBUG: Greeter quit
 [+0.68s] DEBUG: Failed to start greeter [+0.68s] DEBUG: Stopping
 display [+0.68s] DEBUG: Sending signal 15 to process 7376 [+0.82s]
 DEBUG: Process 7376 exited with return value 0 [+0.82s] DEBUG: X
 server stopped [+0.82s] DEBUG: Removing X server authority
 /var/run/lightdm/root/:1 [+0.82s] DEBUG: Releasing VT 7 [+0.82s]
 DEBUG: Display server stopped [+0.82s] DEBUG: Stopping seat, failed to
 start a display [+0.82s] DEBUG: Stopping seat [+0.82s] DEBUG: Seat
 stopped [+0.82s] DEBUG: Required seat has stopped [+0.82s] DEBUG:
 Stopping display manager [+0.82s] DEBUG: Display manager stopped
 [+0.82s] DEBUG: Stopping daemon [+0.82s] DEBUG: Exiting with return
 value 1

---

x-0-greeter.log

 Error writing X authority: Failed to write X authority
 /var/lib/lightdm/.Xauthority: Success

---

x-1-greeter.log

 Error writing X authority: Failed to write X authority
 /var/lib/lightdm/.Xauthority: Success /var/log/lightdm/x-1-greeter.log
 (END)

---

x0.log

 X.Org X Server 1.13.3 Release Date: 2013-03-07 X Protocol Version 11,
 Revision 0 Build Operating System: Linux 3.2.0-37-generic x86_64
 Ubuntu Current Operating System: Linux stefan-dev 3.8.0-30-generic
 #44-Ubuntu SMP Thu Aug 22 20:52:24 UTC 2013 x86_64 Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.8.0-30-generic
 root=UUID=6e9c6967-a55f-49b8-b690-7257b359ae8d ro quiet splash
 vt.handoff=7 Build Date: 17 April 2013  10:43:13PM xorg-server
 2:1.13.3-0ubuntu6 (For technical support please see
 http://www.ubuntu.com/support)  Current version of pixman: 0.28.2
Before reporting problems, check http://wiki.x.org
to make sure that you have the latest version. Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown. (==) Log file: "/var/log/Xorg.0.log", Time: Tue Sep 17 18:27:30 2013
 (==) Using system config directory "/usr/share/X11/xorg.conf.d"
 Initializing built-in extension Generic Event Extension Initializing
 built-in extension SHAPE Initializing built-in extension MIT-SHM
 Initializing built-in extension XInputExtension Initializing built-in
 extension XTEST Initializing built-in extension BIG-REQUESTS
 Initializing built-in extension SYNC Initializing built-in extension
 XKEYBOARD Initializing built-in extension XC-MISC Initializing
 built-in extension SECURITY Initializing built-in extension XINERAMA
 Initializing built-in extension XFIXES Initializing built-in extension
 RENDER Initializing built-in extension RANDR Initializing built-in
 extension COMPOSITE Initializing built-in extension DAMAGE
 Initializing built-in extension MIT-SCREEN-SAVER Initializing built-in
 extension DOUBLE-BUFFER Initializing built-in extension RECORD
 Initializing built-in extension DPMS Initializing built-in extension
 X-Resource Initializing built-in extension XVideo Initializing
 built-in extension XVideo-MotionCompensation Initializing built-in
 extension SELinux Initializing built-in extension
 XFree86-VidModeExtension Initializing built-in extension XFree86-DGA
 Initializing built-in extension XFree86-DRI Initializing built-in
 extension DRI2 Loading extension GLX resize called 1680 1050 Server
 terminated successfully (0). Closing log file.

A: Took me two days. Final solution:

*

*sudo dpkg-reconfigure gdm #select gdm

*sudo apt-get remove lightdm* --purge

*sudo reboot

*sudo apt-get install lightdm*

*sudo dpkg-reconfigure gdm #select lightdm

A: Lubuntu 15.x:
At the lightdm-greeter blackscreen, I switched to a virtual terminal (Alt2), logged in, then found the pid of lightdm-greeter with top -b -n 1 | grep 'lightdm', then I tried sudo kill -s SIGHUP [pid], then used top again to see if the greeter was still running, then tried sudo kill -s SIGTERM and used top again and the greeter was not running. Then I switched back to the graphical session/login.  It had a message that indicated that the session was locked and that I would be redirected to a login. I waited perhaps 7 seconds and the lightdm-greeter appeared. I was able to login. GUI session intact.

A: I've been having the same issue on Debian Sid and find removing the .Xauthority file rectifies it, although not a very reliable solution as I have had to do it every time I reboot, it's a workaround that enables me to get back to my gui.

*

*Rename  the file /var/lib/lightdm/.Xauthority to /var/lib/lightdm/.Xauthority-BAK with
sudo mv /var/lib/lightdm/.Xauthority /var/lib/lightdm/.Xauthority-BAK

*Restart lightdm service with
sudo service lightdm stop
sudo service lightdm start

A: I started experiencing this issue after applying the current lightdm patch last week. The greeter would fail to start due to lack of access to /var/lib/lightdm/.Xauthority, the result being a low graphic mode error which could only be resolved for one session by removing /var/lib/lightdm/.Xauthority. This issue seems to be caused by this new patch which gives the .Xauthority file much tighter permissions (600 rather than 664). See the following:

lightdm (1.6.0-0ubuntu3.1) raring-security; urgency=low

*

*SECURITY UPDATE: wrong permissions on .Xauthority file (LP: #1175023)

*

*debian/patches/07_xauthority_perms.patch: use g_open instead of
  g_file_set_contents in src/xauthority.c.

*debian/patches/08_xauthority_fix_perms.patch: fix incorrect
  permissions left behind by previous versions in src/xauthority.c.

*CVE-2013-4331

The suggested fix above seemed to work for about a half-hour until the old behavior returned, with the additional problem of stale .Xauthority files being left behind with 600 permissions in user home directories, causing graphical login loops.
To work around this issue, I have created a wrapper script for xfce-session-logout (I use XFCE) which removes .Xauthority from both user home directories and from /var/lib/lightdm. Since this script must use sudo to assume the correct authority to remove /var/lib/lightdm/.Xauthority, this is hardly ideal, although it works. Using gdm also avoids this issue. My situation is also complicated perhaps by the fact that I access the local system via the console and via xdmcp.
To address the security issue in the patch above, Ubuntu needs to patch whatever other programs (the greeters for example) need access to .Xauthority since currently by fixing the security issue, they have effectively broken lightdm. That is not very good.


text:
Q: Sudden networking problems in Ubuntu 18.04 Server This morning the networking in my Ubuntu 18.04 Server Edition is not working anymore :
marco@pc01:$ sudo lshw -class network
  *-network DISABLED
      description: Ethernet interface
      product: RTL8111/8168/8411 PCI Express
        Gigabit Ethernet Controller
  *-network DISABLED
      description: Wireles interface
      product: AR9227 Wireless Network Adapter
  *-network:0
       description: Ethernet interface
       physical id: 2
       logical name : docker0
  *-network:1
       description: Ethernet interface
       physical id: 3

sudo nano /etc/nework/interfaces :
iface eth0 inet static
    address 192.168.1.7
    netmask 255.255.255.0
    network 192.168.1.1
    broadcast 192.168.0.255
    post-up iptables-restore <
      /etc/iptables.up.rules
    gateway 192.168.1.1
    dns-nameservers 192.168.0.5 8.8.8.8

marco@pc01:$ sudo service network-manager restart
 Failed to restart network-manager.service: Unit network-manager.service
  not found

Even with sudo /etc/init.d/networking restart:
marco@pc01:$ sudo /etc/init.d/networking restart
[ok] Restarting networking (via systemctl):
 networking.service

marco@pc01:$ ping 192.168.1.4
 connect: Network is unreachable

marco@pc01:$ ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKOWN group
       default qlen 1000
   inet 27.0.0.1/8 scope host lo
     valid_lft forever preferred_lft forever
   inet6 ::1/128 scope host
     valid_lft forever preferred_lft forever
2: enp3s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group
       default qlen 1000
     link/ether 78:24:af:43:ef:5c brd ff:ff:ff:ff:ff:ff
3: wlp5s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group
       default qlen 1000
     link/ether c0:4a:00:09:0e:80 brd ff:ff:ff:ff:ff:ff
4: b3-4f9fe03b1a66: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc
       noqueue state DOWN group default
     link/ether 02:42:64:29:65:73 brd ff:ff:ff:ff:ff:ff
     inet 172.22.0.1/16 brd 172.22.255.255 scope global br-4f9fe03b1a66
       valid_lft forever preferred_lft forever
5: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue
      state DOWN group default
    link/Ether 02:42:01:ea:90:66 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scoper global docker0
      valid_lft forever preferred_lft forever

marco@pc01:$ ifconfig eth0 up eth0: ERROR while getting interface flags:
  eth0: ERROR while getting interface flgs: No such device
  eth0: Host name lookup failure

marco@pc01:$ ifconfig
br-4f9feo3b1a66: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
    inet 192.22.0.1 netmask 255.255.0.0 broadcast 172.22.255.255
    ether 02:42:4d:c4:bd:62 txqueuelen 0 (Ethernet)
    RX packets 0 bytes 0 (0.0B)
    RX errors 0 dropped 0 overruns 0 frame 0
    TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

docker0: flags=4099<,UP,BROADCAST,MULTICAST> mtue 1500
    inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
    ether 02:42:24:b9:3b:59 txqueuelen 0 (Ethernet)
    RX packets 0 bytes 0 (0.0 B)
    RX errors 0 dropped 0 overruns 0 frame 0
    TX packets 0 bytes 0 (0.0 B)
    TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

l0: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
    inet 127.0.0.1 netmask 255.0.0.0
    inet6 ::1 prefoxlen 128 scopeid 0x10<host>
    loop txqueuelen 1000 (Local Loopback)
    RX packets 258 bytes 32343 (32.3 KB)
    RX errors 0 dropped 0 overruns 0 frame 0
    TX packets 258 bytes 32343 (32.3 KB)
    TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

/etc/network/interfaces :

  auto lo
  iface lo inet loopback

4° Update:
  marco@pc01:$ uname -r
  4.15.0-55-generic

  marco@pc01:$ ls -al /etc/netplan
  total 20
  drwxr-xr-x 2 root root 4096 Jul 25 18:37
  drwxr-xr-x 128 root root 12288 Jul 25 12:51
  -rw-r--r-- 1 root root 616 Jul 25 18:37 30-cloun-init.yaml

   etc/netplan/50-cloud-init.yaml    :

     network:
         renderer: NetworkManager/ networkd
         ethernets:
           enp3s0:
               addresses: [192.168.1.7/24]
               gateway4: 192.168.1.1
               nameservers:
                   addresses: [8.8.8.8,8.8.4.4]
               dhcp4: no
         version: 2

 marco@pc01:$ sudo netplan apply
 sudo: netplan: command not found

For sudo llshw -c network : see above
What have I to do in order to make the network available again?
Looking forward to your kind help
Marco

A: It says "eth0: ERROR while getting interface flgs: No such device" right there. Perhaps a driver problem or deactivated/unusable hardware. Check system logs, especially the kernel. The other errors would be secondary or, in some cases, you may have mistyped commands (I am not familiar with Ubuntu).
(Linux has become soo complicated, also with networking...)


text:
Q: Does $\int_V f(s)ds=\int_U f(\varphi (t))|\det \varphi '(t))|dt$ hold if $f$ is measurable? Let $\varphi :U\to V$ a diffeomorphism where $U,V$ are open. If $f:\mathbb R\to \mathbb R$ is a Borel function integrable function, we have that $$\int_V f(s)ds=\int_U f(\varphi (t))|\det \varphi '(t)|dt.$$
Does this formulae still hold if $f$ is Lebesgue measurable and not only a Borel function ?


text:
Q: How can i printing all the cases in vscode console I don't understand. I wrote a "hello world" program and run it, console only shows up immediately and turns itself off.
You guys can help me please

I want to use vscode console to input the result then print it with the line "press any key to countinue" like DevC++. I want it to not turn itself off when I haven't entered all the cases

A: After your while loop, add: _getch();
std::cout << "press any key to countinue...";
int c = _getch();

Then the application will wait untill you press a key.
What's happening is when the caSe is zero the application leaves the loop. Then there is no code left and the application exits.

But please remove the second image and replace the first with your code. We love to copy your code to help you out. The programs output you should write out too, although in this case not needed when you write clearly what is happening. And state clearly what you want to do.

A: Try adding this in the last place.
system("pause");


text:
Q: While True - Go back to the top of the hierarchy while True:
    user_input_1 = input("")

    if user_input_1 == 'yes':
        print('Cont..')
        # Do something

        if checkcondition_1 == True:
            # Do something

            user_input_2 = input("")
            if user_input_2 == yes:
                # Do something
            if user_input_2 == no:
                # Do something

        else:
            print("Going back")
            continue

    if user_input_1 == 'no':

        user_input_3 = input("")

        if user_input_3 == 'yes':
            break
        if user_input_3 == 'no':
            # I need help to go back to "User_Input_1 == 'yes'
            Go all the way back to "user_input_1" =='yes' condition.
            Is it possible to go back like that?

As I have mentioned comments above, after user_input_3, if that condition equals to "no", I want to go all the way back up to user_input_1 == 'yes'.
When I say continue after that statement, it only goes back to user_input_1 == 'no'. How can I go back up one more in while statement? Any suggestion would be great.

A: You can do the process you want but not with while loop but can be done with function.
I have rewritten your code to get your desired result. Try it.
def user(user_input_1='yes'):
    if user_input_1 == 'yes':
        print('Cont..')
        # Do something
        if checkcondition_1 == True:
            # Do something
            user_input_2 = input("input_2")
            if user_input_2 == 'yes':
                pass
                # Do something
            if user_input_2 == 'no':
                pass
                # Do something

        else:
            print("Going back")
            user_input_1 = input("input_1")  # These two lines are equavalent to your continue.
            user(user_input_1)

    if user_input_1 == 'no':

        user_input_3 = input("input_3")

        if user_input_3 == 'yes':
            return None   # this is equivalent to break.
        if user_input_3 == 'no':
            # I need help to go back to "User_Input_1 == 'yes'
            #Go all the way back to "user_input_1" =='yes' condition.
            #Is it possible to go back like that?

            user()  # Calling user() function with default value, which is user_input_1 = 'yes'.

user_input_1 = input("input_1")
checkcondition_1 = True
user(user_input_1)

I hope it may help you.


text:
Q: Is there a way in oracle 11g to store temporary values in a table? I have a table type input+output(IO) variable in oracle(with 5 columns), i read values from it in a loop and and also perform validations, if there's an validation fired i put an error message in fifth column. if the fifth column is null i insert values in table. I have working code for this. But what i need is ,suppose i have 5 rows to be inserted, and if there's a validation fired for any row then data should not be inserted for other rows as well. I cannot raise exception as i still need error message for other rows.
I have 2 solutions for this. First..Perform validations first(without insert), if fifth column is empty then will again run loop and insert in table.
Second..Insert values in a temporary table, if no validation fired till last row then will select from temp table and insert in main table.
Is there a better way to handle this?

A: You can try to validate all rows before inserting and then use the command "INSERT SELECT" to insert all your rows into the table with the fifth column filled with error message or not (based on the prior validation you made).
Example:
BEGIN
    --DO SOME VALIDATION

    INSERT INTO <TABLE_NAME>
    SELECT COLUMN1, COLUMN2, COLUMN3, COLUMN4, 'ERROR OR NOT ERROR' COLUMN5
      FROM <OTHER_TABLE>;
END;

This way you wouldn't need a second loop, but you need to see if it suits your needs.


text:
Q: Dynamically passing db and table names using stored procedure in PostgreSQL I am creating a stored procedure in PostgreSQL which will first check on the basis of 'ID' if the data is present in the given table. If yes, then move it to some other table and insert the newest record in the given table name. I have a written a stored procedure where I tried it with hard-coded values and it works as I need but when I am trying to make it generic i.e creating variables and then passing those variables inside the queries then it throws an error. I referred below SO links and official documentation link and was able to modify my stored procedure:

*

*First SO link

*Second SO link
Below is my Stored Procedure:
CREATE OR REPLACE PROCEDURE compareDups(ab integer, b json, tablename varchar)
AS $$
DECLARE
  actualTableName varchar := 'testing.'||tablename;
  histTableName varchar:= actualTableName ||'_hist';
  job_id Integer:=0;
BEGIN --<<<< HERE
  EXECUTE 'SELECT id FROM '||actualTableName||' WHERE id =$1' INTO job_id USING ab;
  -- if there is data for id in the table then perform below operations
  IF job_id IS NOT NULL THEN
      EXECUTE FORMAT('INSERT INTO %I as select * from %L where id = $1',histTableName,actualTableName) USING ab;
      EXECUTE FORMAT('DELETE FROM %I where id = $1',actualTableName) USING ab;
      EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
  -- if id is not present then create a new record in the actualTable
  ELSE
      EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
  END IF;

END; --<<<< END HERE
$$
LANGUAGE plpgsql;

So, while creating variables I have used just EXECUTE option and while calling queries I have used EXECUTE FORMAT(...) option.
And when I try to call this, I am getting below error:
ERROR:  syntax error at or near "select"
LINE 1: INSERT INTO "testing.sampletesting_hist" as select * from 't...
                                                    ^
QUERY:  INSERT INTO "testing.sampletesting_hist" as select * from 'testing.sampletesting' where id = $1
CONTEXT:  PL/pgSQL function comparedups(integer,json,character varying) line 10 at EXECUTE
SQL state: 42601

What am I missing over here?

A: So, I would like to answer my own question maybe it can help someone like me. I was able to fix the above code by modifying the actualtablename string where I was setting up the schema name too. So, I added a SET statement inside the procedure for setting up schema names where the intended operations need to take place and it worked for me.
CREATE OR REPLACE PROCEDURE compareDups(ab integer, b json, tablename varchar)
AS $$
DECLARE
  actualTableName varchar := tablename;
  histTableName varchar:= actualTableName ||'_hist';
  job_id Integer:=0;
BEGIN --<<<< HERE
  SET search_path to testing; -- Set the schema name
  EXECUTE 'SELECT id FROM '||actualTableName||' WHERE id =$1' INTO job_id USING ab;
  -- if there is data for id in the table then perform below operations
  IF job_id IS NOT NULL THEN
      EXECUTE FORMAT('INSERT INTO %I select * from %I where id = $1',histTableName,actualTableName) USING ab;
      EXECUTE FORMAT('DELETE FROM %I where id = $1',actualTableName) USING ab;
      EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
  -- if id is not present then create a new record in the actualTable
  ELSE
      EXECUTE FORMAT('INSERT INTO %I values($1,$2)',actualTableName) USING ab,b;
  END IF;

END; --<<<< END HERE
$$
LANGUAGE plpgsql;

Somehow, this procedure is getting stored under the public schema. So, while calling it I have to use the below commands:
set search_path to public;
call compareDups(12,'{"name":"CTTT"}','sampletesting');


text:
Q: Field transformations I'm reading Maggiore's book "A modern introduction to quantum field theory" and I'm very confused by what he did in chapter 2.6 page 31 eq. (2.80). He basically wants to find the generators of the infinite representation of the Lorentz group (comparing how the Weyl spinor field change at equal coordinate). He writes:
$$\psi_L \rightarrow \psi'_L(x') = \Lambda_L \psi_L(x)$$
which is the finite dimensional representation. The coordinates transform as $x^{\mu} \rightarrow x'^{\mu} = x^{\mu}+\delta x^{\mu}$. Then in (2.80) he compares the field at equal coordinate:
\begin{align}
\delta_0 \psi_L &= \psi'_L(x) - \psi_L(x) \\
&=  \psi'_L(x'^{\mu}-\delta x^{\mu}) - \psi_L(x) \\
&= \psi'_L(x') - \delta x^{\mu}\partial_{\mu}\psi_L(x) - \psi_L(x) \\
&= (\Lambda_L - 1)\psi_L(x) - \delta x^{\mu}\partial_{\mu}\psi_L(x)
\end{align}
I don't understand why after the third equality the "primes" magically disappear from $\delta x^{\mu}\partial_{\mu}\psi_L(x)$. I would have written $\delta x^{\mu}\partial_{\mu}\psi'_L(x')$! Any idea?

A: He has just used
$$\psi_L \rightarrow \psi'_L(x') = \Lambda_L \psi_L(x)$$ and factored $\psi_L(x)$ from the first and third term in the third line of the expression.

A: If you look at equation (2.79) in the book, you could expand $ \Lambda_{L}$  in orders of the  parameters $ \omega_{\mu \nu}$. If you consider infinitesimal transformations, so we have infinitesimal parameters $\omega_{\mu\nu}$, you get
$$
\psi'_{L}(x') = (\mathbf{1} - \omega_{\mu\nu}S^{\mu\nu})\psi_{L}(x).
$$
Also $\delta x $ is proportional to $\omega_{\mu \nu}$ and by taking use of the previous result one gets
$$
\delta x^{\rho} \partial_{\rho} \psi'_{L}(x') =\delta x^{\rho} \partial_{\rho} \psi_{L}(x).
$$


text:
Q: Select Shock Size and Sign in Impulse Response Functions After running a VAR with 9 variables, I'm simply trying to obtain my impulse response functions through the irf() function.
However, I need to select the size of the shock as well its sign.
I know that this function from the VARS package uses by default a one standard error shock.
I'm also aware that I can simply multiply my IRFs by the size of the shock that I want.
Nevertheless, confidence bands obtained with bootstrapping cannot simply be multiplied by the desired value.
Therefore, how can I select the size of the shock and its sign, while computing the confidence bands through bootstrapping in my IRFs?
Thanks
library(vars)
vdewshi=VAR(dewshi, p=1, type = ('const'))

irfdewshi=irf(vdewshi, n.ahead = 10, ci=0.68, runs=1000, cumulative=TRUE)

plot(irfde$irf$factor1de[,1], type ='l',lwd=2,ylab= "", xlab="Steps", ylim=range(irfde$Lower$factor1de[,1],irfde$Upper$factor1de[,1]), main='Short-Term Rate')
lines(irfde$Upper$factor1de[,1], lty=2, col="red")
lines(irfde$Lower$factor1de[,1], lty=2, col="red")


text:
Q: android playing mp3 files from raw folder or from asset folder when more than 100 mp3 files I am creating 1 app that containing .mp3 playing functionality... my question is.. what is good to put my mp3 files in raw folder or to put files into assets folder? i have approx 100 mp3.
Right now i have puted that files in to raw folder.. it worked for 20 30 files but after 70 it says me Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE so what is better? is it problem remain same with asset folder also? it containing too much time to load
can anybody help me to find out the best solution?

A: If you really need supply this songs which your app use APK Expansion Files to do so. You songs will be download right after your app and then will be accessable.


text:
Q: What do these words mean in Git: Repository, fork, branch, clone, track? I'm honestly not clear on the semantics here.  They're all about copies/variants of a code+history unit, but past that I'm not sure I could say.  Is this logical structure explained somewhere?

A: This GoogleTechTalk is a fantastic introduction to Git to learn what is actually happening behind the scenes while learning the language also. It was given by a very early contributor to Git and he gave this talk in 2007 as a way of introduction into Git. If you watch this talk you will not only know what each word is, like repository, fork, branch, etc., but you will also know what is occurring behind the scenes when each of these are made, merged, etc.
The address is long but very informative. It also contrasts Git to other Version Control Systems so you get insight into why Git was created the way it was and what the comparative advantages of it are over other control systems. Even though the talk is old it is very helpful to get up and running. I would watch this before I jumped into the manuals. Things will make much more sense as a result, I believe.

A: A repository is simply a place where the history of your work is stored. It often lives in a .git subdirectory of your working copy - a copy of the most recent state of the files you're working on.
To fork a project (take the source from someone's repository at certain point in time, and apply your own diverging changes to it), you would clone the remote repository to create a copy of it, then do your own work in your local repository and commit changes.
Within a repository you have branches, which are effectively forks within your own repository. Your branches will have an ancestor commit in your repository, and will diverge from that commit with your changes. You can later merge your branch changes. Branches let you work on multiple disparate features at once.
You can also track individual branches in remote repositories. This allows you to pull in changes from another individual's branches and to merge them into a branch of your own. This may be useful if you and a friend are working on a new feature together.
There are lots of great git books online. Have a look at ProGit and Git Magic to get started, as well as the official tutorials and community book.

A: I'm going to answer my own question with an RTFM.
But, read this fine manual.  As the author puts it:

"The conclusion I draw from this is that you can only really use Git if you understand how Git works. Merely memorizing which commands you should run at what times will work in the short run, but it's only a matter of time before you get stuck or, worse, break something.
"Half of the existing resources on Git, unfortunately, take just that approach: they walk you through which commands to run when, and expect that you should do fine if you just mimic those commands. The other half does go through all the concepts, but from what I have seen, they explain Git in a manner that assumes you already understand how Git works."


text:
Q: how to use subquery or how to fetch data I use core-data and hava 2 embadded relationship to-many. Also i have a calendare, and I should dowload all medicines from all diseases at selected DATE. How I can do it with subquery  or using subquery?
Disease ->>Medicine->>Date

screenshot is here http://savepic.ru/4608231.png
Couild I search all medicine without binding with disease?
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"MyMedicine" inManagedObjectContext:objectContext]];
[request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(data == %@)", currentData]];

A: Assuming you initialize your NSFetchRequest like this:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"MyMedicine" inManagedObjectContext:objectContext]];
[request setSortDescriptors:[NSArray initWithObject:[[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]];

You may setup your predicate like this:
// Dates
[request setPredicate:[NSPredicate predicateWithFormat:@"date == %@", datesEntity]];

or
// NSDate
[request setPredicate:[NSPredicate predicateWithFormat:@"date.date == %@", date]];

As a default all the relations will be fetched as faults, if you need them to be fetched during this fetch you could configure relationship key paths to be fetched in this fetch like this:
NSArray* relationKeys = [NSArray arrayWithObject:@"disease"];
[request setRelationshipKeyPathsForPrefetching:relationKeys];

Using this approach all the related Disease entities will be fetched along with all matching Dates entities.


text:
Q: Send email with Gmail not work | codeigniter this is my code to send email with gmail but it is not work , I am try hard to make it work for 4 days but still not work.
please help me, it was work before 6 day , after that not work , the server told me to change PHPMailer to SMTP Gmail , I am changed but still not work ...
i am register in Amazon SES Email , but i do not know how to use it, so i have 2 option : make this run in my normal server or change to Amazon SES , if SES is better chance learn me how to use it .
my site to test

my Controller

 public function Send_Single_Email_Try ()
 {

 $email_config = Array(
        'protocol'  => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => '465',
        'smtp_user' => 'xx@gmail.com',
        'smtp_pass' => 'xx',
        'mailtype'  => 'html',
        'starttls'  => true,
        'newline'   => "\r\n"
    );

    $this->load->library('email', $email_config);
    $this->email->from('someuser@gmail.com', 'invoice');
    $this->email->to('test@test.com');
    $this->email->subject('Invoice');
    $this->email->message('Test');

    $this->email->send();
            if($send)
            {

                echo 1;
            }
            else
            {
                echo 0;

            }
}

my JS

   $(document).on('click','#SendEmailTry',function(e){
            e.preventDefault();

         $.ajax({

        url:"<?php echo
  base_url('Email/Send_Single_Email_Try/')?>",

        type: "POST",
        dataType: "text",

        success:function(data)
                  {
                     if (data == 1)
                      {
                        alert("send");
                      }
                      else
                      {
                         alert("notsend");
                      }

                  },
                    error: function (jqXHR, textStatus, errorThrown)
                 {

                          alert("error")

                 }

            });

});

A: Try this....

$this->load->library('email');
$config['protocol']    = 'smtp';
$config['smtp_host']    = 'ssl://smtp.gmail.com';
$config['smtp_port']    = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user']    = 'sender_mailid@gmail.com';
$config['smtp_pass']    = 'password';
$config['charset']    = 'utf-8';
$config['newline']    = "\r\n";
$config['mailtype'] = 'text'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$this->email->initialize($config);
$this->email->from('sender_mailid@gmail.com', 'sender_name');
  $this->email->to('recipient@gmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
echo $this->email->print_debugger();

A: *

*check and set your csrf protection from your site config file(yourproject/config/config.php) such as,

$config['csrf_protection'] = FALSE;

*your rewrite code:
public function Send_Single_Email_Try ()
{
$this->output->enable_profiler(FALSE);
$email_config = Array(
'protocol'  => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => '465',
'smtp_user' => 'xx@gmail.com',
'smtp_pass' => 'xx',
'mailtype'  => 'html',
'starttls'  => true,
'newline'   => "\r\n"
);

$this->load->library('email', $email_config);
$this->email->from('someuser@gmail.com', 'invoice');
$this->email->to('test@test.com');
$this->email->subject('Invoice');
$this->email->message('Test');

$send = $this->email->send();
if($send)
{

echo 1;
}
else
{
echo 0;
}
}


text:
Q: Paste images from MS Word to contenteditable div I've created a text editor, using a contenteditable div. The user can copy and paste text from word to the website. Only the images aren't working, because the src points to a local path.
I think I should encode the image to base64, before it is displayed, but the problem is, that the images cant be displayed, because they are local files.

A: Try using some remote server to hold the photos so that they can be utilized. Try something like picpaste.com, however they only hold files temporarily I presume.


text:
Q: Notify different parts of application if event is occured I have an onclick event and I need to update some views on a web page according to server response. What is the best way to implement this using listeners and handlers? I think that I should create clickListener and map it to a button, but I don't know how to notify views that they should render some data.
For example, I have one presenter (called Presenter) and 3 views (View1, View2, View3). And the first way is to do something like this:
public class Presenter {
    private View1 view1;
    private View3 view2;
    private View3 view3;
    private Button button;
    protected void doSmth() {
        button.setClickListener(new ClickListener() {
            view1.update();
            view2.update();
            view3.update();
        });
    }

}
But that's obviously bad approach. The good way (I think) is to do next:
public class Presenter {
    private Button button;
    protected void doSmth() {
        button.setClickListener(new ClickListener() {
            //push object that will trigger handlers in views.
        });
}
//this is the same for all views
public class View {
    protected void handleClickInPresenter() {
    //render the data
    }
}

But I can't understand how to implement this way. Ask for your help.Thanks.


text:
Q: Converting from signed char to unsigned char and back again? I'm working with JNI and have an array of type jbyte, where jbyte is represented as an signed char i.e. ranging from -128 to 127. The jbytes represent image pixels. For image processing, we usually want pixel components to range from 0 to 255. I therefore want to convert the jbyte value to the range 0 to 255 (i.e. the same range as unsigned char), do some calculations on the value and then store the result as a jbyte again.
How can I do these conversion safely?
I managed to get this code to work, where a pixel value is incremented by 30 but clamped to the value 255, but I don't understand if it's safe or portable:
 #define CLAMP255(v) (v > 255 ? 255 : (v < 0 ? 0 : v))

 jbyte pixel = ...
 pixel = CLAMP_255((unsigned char)pixel + 30);

I'm interested to know how to do this in both C and C++.

A: Yes this is safe.
The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

A: This is one of the reasons why C++ introduced the new cast style, which includes static_cast and reinterpret_cast
There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then CHAR_MAX+1 is added for a value of 128 and if it has a value of -1, then CHAR_MAX+1 is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value 0b10000000 it should evaluate to value 128, and 255 for bit value 0b11111111, this is accomplished with reinterpret_cast.
Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as 0b10000000 and -1 is represented as 0b11111111 and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the 0b10000000 bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the 0b11111111 bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.
I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.
The syntax boils down to the following:
signed char x = -100;
unsigned char y;

y = (unsigned char)x;                    // C static
y = *(unsigned char*)(&x);               // C reinterpret
y = static_cast<unsigned char>(x);       // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret

To do this in a nice C++ way with arrays:
jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);

or the C way:
unsigned char* pixels = (unsigned char*)memory_buffer;

A: Do you realize, that CLAMP255 returns 0 for v < 0 and 255 for v >= 0?
IMHO, CLAMP255 should be defined as:
#define CLAMP255(v) (v > 255 ? 255 : (v < 0 ? 0 : v))

Difference: If v is not greater than 255 and not less than 0: return v instead of 255

A: There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.
Assuming you mean the latter, the formally correct way is
signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;

which at least gcc properly recognizes as a no-op.

A: I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:

*

*convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate

*use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)

*when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
    // cast to unsigned char re-interprets values as 0-255
    // cast to int will make intermediate calculations safer
    return static_cast<int>(static_cast<unsigned char>(pixel));
}

inline jbyte fromInt(int pixel) {
    if(pixel < 0)
        pixel = 0;

    if(pixel > 255)
        pixel = 255;

    return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}

jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);


text:
Q: @Autowired variable is null when method in @Controller is final method In my Controller, I have a method like below:
@Autowired
StatisticsService statisticsService;

@GetMapping("statistic")
public final WebResponse<List<TierCpStatisticsDataDTO>> getStatisticsInfo(String var) {statisticsService.methodA();  ... ...)

With the 'final', statisticsService is null. statisticsService get the correct instance when I remove 'final'.
Can anybody explain why this happens?
Something wired is, when final exists, the controller is proxied like below:

But after I remove final, the controller is not proxied.

A: You can not use final in the field-based injection it is a drawback in field-based injection if you wish to use final use setter or constructor based injection final work with them.
reference: https://blog.marcnuri.com/field-injection-is-not-recommended/

A: Problem solved. I found AOP is used by @Validated. After I remove @Validated. The final method works.


text:
Q: Set default Send-As address using GAS Does GAS have the functionality to set the default Send-As address of a user to a sub-domain of a primary GApps domain, if the script is authorised by a Super Admin on the domain?
I have a signature script that's authorised using a token by a Super Admin on the domain, and was hoping something similar could be done to set the Send-As for users as they join.
We have several sub-domains, and users need their Send-As set related to the country they're in.

A: *

*If you are using MailApp.sendEmail(), you do not have a 'send as' option in Google Apps Script. However, you can set a combination of the name and replyTo options to simulate a 'Send As' option.

*If you use GmailApp.sendEmail() function, you have an additional option called from which you can use to specify the from email address


text:
Q: Android - How do I detect if user has chosen to share to Facebook or twitter using intent? I've created an application which shares to facebook, twitter etc. But I want to perform different functions dependent on who the user is sharing to, for instance if the user is sharing to Facebook do one thing but if the user shares to twitter do another.
How do I do this?
My code so far is below:
private void ShareSub() {
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(
            Intent.EXTRA_TEXT,
            "You've just shared "
                    + "Awesome");
    startActivity(i);
}

Further explanation of above code:
When the user presses the "menu_item_share" button in the action bar, the function above is triggered. This function then makes a box like the image below appear, which allows the user to select a particular option, e.g. Facebook or twitter. The Intent.EXTRA_TEXT is then shared to that particular app.
What I'm wanting is, when the user clicks for instance Facebook, a particular function is called e.g. Sharing via their (Facebook's) api etc.

I'm not using  ShareActionProvider like below:
   <item
        android:id="@+id/your_share_item"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:showAsAction="ifRoom"
        android:title="@string/share"/>

Instead, I've created a simple button which calls the function ShareSub:
<item
    android:id="@+id/menu_item_share"
    android:icon="@android:drawable/ic_menu_share"
    android:showAsAction="ifRoom"
    android:title="Share"/>

The reason I've chosen to do it this way is, I don't want the recently shared to button to appear, as in the image below. This is causing me problems when I attempt to use the code suggested below because I haven't used ShareActionProvider.

A:
Use presses a button in the action bar which triggers the above function.

If you used a ShareActionProvider instead, you could detect when a user selects a particular app from the list by implementing a ShareActionProvider.OnShareTargetSelectedListener. Otherwise you won't be able to detect which app is selected unless you implement your own activity chooser.
Here's an example:
menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/your_share_item"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:showAsAction="ifRoom"
        android:title="@string/share"/>

</menu>

Implementation
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate your menu
    getMenuInflater().inflate(R.menu.share, menu);

    // The Intent you want to share
    final Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_TEXT, "Test");

    // Set up your ShareActionProvider
    final ShareActionProvider shareActionProvider = (ShareActionProvider) menu.findItem(
            R.id.your_share_item).getActionProvider();
    shareActionProvider.setShareIntent(i);
    shareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {

        @Override
        public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
            final String packageName = intent.getComponent().getPackageName();
            if (packageName.equals("com.facebook.katana")) {
                // Do something for Facebook
            } else if (packageName.equals("com.twitter.android")) {
                // Do something for Twitter
            }
            return false;
        }

    });
    return super.onCreateOptionsMenu(menu);
}

A: You can't directly find out which app was chosen, but you can display your own Chooser dialog.
Instead of calling startActivity(i), get a list of all activities (facebook, twitter etc) that are registered to handle your intent using queryIntentActivities().
List<ResolveInfo> activities = getPackageManager().queryIntentActivities (i, 0);

Each ResolveInfo is an app that can handle your intent. Now you can show an AlertDialog containing a list of labels or icons. When the user selects a label from the list, you can handle what do to on an app-specific basis in the click handler for the dialog.
EDIT: Here's a full working example
private void ShareSub() {
    final Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_TEXT,"text");

    final List<ResolveInfo> activities = getPackageManager().queryIntentActivities (i, 0);

    List<String> appNames = new ArrayList<String>();
    for (ResolveInfo info : activities) {
        appNames.add(info.loadLabel(getPackageManager()).toString());
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Complete Action using...");
    builder.setItems(appNames.toArray(new CharSequence[appNames.size()]), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            ResolveInfo info = activities.get(item);
            if (info.activityInfo.packageName.equals("com.facebook.katana")) {
                // Facebook was chosen
            } else if (info.activityInfo.packageName.equals("com.twitter.android")) {
                // Twitter was chosen
            }

            // start the selected activity
            i.setPackage(info.activityInfo.packageName);
            startActivity(i);
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

A: Although this question has an accepted answer, things have changed, and now there is a better approach, which is the recommended way of achieving this.
Using "Android Sharesheet"
Here's the documentation:
https://developer.android.com/training/sharing/send#share-interaction-data
While creating the IntentChooser, you can pass a pending intent, which will trigger a broadcast receiver within your app.
The data provided by the onReceive method of that Broadcast Receiver will give you the name of the component that was used to handle the SEND intent.
Code for adding a pending intent to the SEND intent:
Intent share = new Intent(ACTION_SEND);
...
PendingIntent pi = PendingIntent.getBroadcast(myContext, requestCode,
        new Intent(myContext, MyBroadcastReceiver.class),
        PendingIntent.FLAG_UPDATE_CURRENT);
share = Intent.createChooser(share, null, pi.getIntentSender());

Code for retrieving the details of the component that was chosen by the user:
@Override public void onReceive(Context context, Intent intent) {
  ...
  ComponentName clickedComponent = intent.getParcelableExtra(EXTRA_CHOSEN_COMPONENT);
}

A: Try that answers:
here choose the define intent which you want:
Customize Android Intent.ACTION_SEND
Branching the Android Share Intent extras depending on which method they choose to share
Android - How to filter specific apps for ACTION_SEND intent


text:
Q: Mule MUnit test with Maven, mule.home property is not defined In our Mule projects we have a common properties file that is referenced from a number of Mule projects. To do this we put the file in the Mule installation directory and reference it in a flow in each project:
<spring:beans>
    <context:property-placeholder
    location="file:///${mule.home}/conf/common.properties" />
</spring:beans>

This works fine for running the projects in Mule and from Anypoint Studio as in both cases mule.home is defined. It also works for running the MUnit test suites defined in the project from Anypoint Studio.
However when running the tests from Maven mule.home is not defined and the tests fail. I've tried adding a definition to mule.home to the Maven settings.xml file, but that doesn't work.
Any suggestions on how I can run the tests from Maven and keep the mule.home reference in the property flow? Or perhaps is there a way to have an alternative configuration in the property flow for when the flow is called from the test suite?
Alternatively how should we reference a common property file from multiple Mule projects?
Versions:
Mule runtime: 3.6.2
Munit: 1.1.0
Maven 3.3.1

A: Try this:
mvn -Dmule.home=yourpath test

This should do the trick.
Hope this helps.

A: Alternatively you can set mule.home programmatically perhaps in a parent Abstract test class:
@BeforeClass
public static void setUp() {
    System.setProperty("mule.home", "whatever");
}


text:
Q: Stop urllib.request from raising exceptions on HTTP errors Python's urllib.request.urlopen() will raise an exception if the HTTP status code of the request is not OK (e.g., 404).
This is because the default opener uses the HTTPDefaultErrorHandler class:

A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions.

Even if you build your own opener, it (un)helpfully includes the HTTPDefaultErrorHandler for you implicitly.
If, however, you don't want Python to raise an exception if you get a non-OK response, it's unclear how to disable this behavior.

A: If you build your own opener with build_opener(), the documentation notes, emphasis added,

Instances of the following classes will be in front of the handlers, unless the handlers contain them, instances of them or subclasses of them: ... HTTPDefaultErrorHandler ...

Therefore, we need to make our own subclass of HTTPDefaultErrorHandler that does not raise an exception and simply passes the response through the pipeline unmodified. Then build_opener() will use our error handler instead of the default one.
import urllib.request

class NonRaisingHTTPErrorProcessor(urllib.request.HTTPErrorProcessor):
    http_response = https_response = lambda self, request, response: response

opener = urllib.request.build_opener(NonRaisingHTTPErrorProcessor)
response = opener.open('http://example.com/doesnt-exist')
print(response.status)  # prints 404

This answer (including the code sample) was not written by ChatGPT, but it did point out the solution.


text:
Q: MySQL FullText search returns 0 if multiple row matches Match / Against returns true if I pass unique value in query and returns 0 if I pass value, which exist in multiple row.
SELECT MATCH(b.branch_name)
AGAINST ('Men' IN NATURAL LANGUAGE MODE ), branch_name
FROM `branch` AS `b` WHERE 1

Table Data:
id   | branch_name
--------------------
1    | Men
2    | Beauty
3    | Women

If I pass MATCH(b.branch_name) AGAINST ('Men' IN NATURAL LANGUAGE MODE ) returns 0 for all row,
If I pass MATCH(b.branch_name) AGAINST ('Women' IN NATURAL LANGUAGE MODE ) returns > 0 value same for 'beauty'
Can anyone please help me where am I wrong?

A: There is a system variable called ft_min_word_len whose default value is 4 (see here).
That means that words of less than four letters are ignored -- not included in the index.  No entry in the index; no rows returned.
Reset the value and then rebuild the index so "men" will be in the index.  Then your query will work.