LUIS entity NOT getting detected after training with same utterance

Question: We have trained LUIS with same utterance for a particular intent having multiple entity. However one entity is not identified.
To improve the accuracy we have maintained a phrase list having the entity name bind to the list.
Step 1 - Adding Utterance

Step 2 - Adding Phrase List

Step 3 - Test Result
Comment: @Scuba try making sure to include more utterances that include the entity you're trying to detect. There should be AT LEAST 15 utterances. In addition, make sure the utterances are valuable in that they demonstrate different variations--whether that be with context (word order--beginning, middle, or end of utterance), or with the entity itself in word count (can the entity be 1 word? 2? 3?), and also make sure the utterances themselves vary in length
Answer: You LUIS model seems to be lacking some training data. LUIS supports up to 500 intents and 15.000 utterances, which means you can have 30 utterances for each intent if you have a model with all the 500 intents. If that's not the case you can have more example utterances for each intent, which can help you having a more accurate model.
Regarding your usage of phrase lists, that's the first time I've seen phrase lists used in this manner. It's like your using whole utterances as phrase list items. As per the Microsoft LUIS documentation, this is how prase lists are supposed to work:

You can add features to your LUIS app to improve its accuracy.
  Features help LUIS by providing hints that certain words and phrases
  are part of an app domain vocabulary.

Source: LUIS Docs on Phrase Lists
What I understand by that, and the way I have used phrase lists is to tell LUIS which words or expressions are interchangeable, which seems to be what you are trying to do, however with full utterances. I would advice you to replace these full utterances for keywords and expressions.
Again, keep in mind that creating an intent and providing the phrase list with the expression that should be detected as an intent it's not enough for LUIS to be able to recognize it. You must label a good amount of intents before LUIS can be able to automatically identify them.


What is c data type for python dictionary/object/json in Cython?

Question: I have a .pyx file. To implement the Cython, I must define the variable with cdef. So I replace the python version definition to cython one.
From this (.py file):
sql = """ SELECT * FROM vendors; """
conn = None
response = None

To this (.pyx file):
cdef char[120] sql = """ SELECT * FROM vendors; """
cdef ??????? conn = None
cdef ??????? response = None

I'm new in Cython. I don't know what are the c datatype for conn and response variables. Since the value of conn & response would be as we can see below.
conn = psycopg2.connect(**params)
response = json.dumps(items)

I tried the char[], struct, enum, but they caused me errors. What are the proper datatypes for conn and response? Could you give the reference about cython datatypes?
Answer: Both of these are Python functions returning Python objects. There is unlikely to be any advantage to specifying a type for either of them. It's also pretty likely that defining the type for sql is not helping (it'll be converted to a Python string anyway when it's passed to a Python function). You can either leave the Python code as is (it's still valid Cython code) or specify cdef object as the type.
If you insist of specifying a type then response is a Python string (cdef str response). This may allow some tiny optimizations is Cython, but is unlikely to give much.
conn is a Psycopg2 connection object which is actually defined in C. You could attempt to wrap that as an external extension type to gain direct access to its attributes. This is unlikely to be a useful thing to do - it won't give you any advantage unless you have specific attributes that you want to probe through Cython.

This is not the sort of code that benefits from Cython - it's manipulating Python objects through Python interfaces rather than numeric data - and therefore you should not be worrying about adding types.


Find the joint CDF of the smallest and largest order statistics $Y_1$ and $Y_n$

Question: Question: Find the joint cdf of $Y_1$ and $Y_n$ ($Y_1$ being the first order statistic and $Y_n$ being the maximum).
Find $P(Y_1 >u,Y_n ≤v)$  was given as a hint.
Comment: Any particular distribution?
Answer: $\Pr(Y_1 >u\ \&\ Y_n ≤v)$ is the probability that all of the $n$ independent identically distributed observations are in the interval $(u,v].$ Since they're independent, this is just the $n$th power of the probability that one of them is in that interval. That probabilty is $F(v) - F(u).$


Getting current country name

Question: I'm trying to get the country name where the phone is in. For instance if the user is in Germany it has to say Germany. I've tried several things to make this happen, but I haven't found any proper solution. I know I can use TelephonyManager, but that will give me the ISO, and I want the name of the country. I've also tried this getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();, but that always gives me "United States" even though I'm not there. I know this is possible as I've seen it in another application. Should I use the ISO somehow to accomplish what I what, or is there a smarter/easier way?
Please, don't vote this post as duplicate as I've already searched here on Stackoverflow, but there isn't any solution to get the name of the country :)
Comment: See: http://stackoverflow.com/questions/3659809/where-am-i-get-country
Comment: I've already seen that post, but is the country name recieved? Most of the solutions are how to get the ISO.
Comment: The ISO is a relatively static list, just add it to your app and lookup the full name.
Comment: Where should I look up and how?
Comment: How about: https://en.wikipedia.org/wiki/ISO_3166-1
Comment: Or use a prebuilt Java library: https://github.com/TakahikoKawasaki/nv-i18n
Comment: How do I look up when having the ISO code? I've the ISO code and want it to return the "English short name (upper/lower case)"
Answer: Where am I? - Get country
gives this code
/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}

Comment: Hmmm, wouldn't that be too "deep"? I mean to get the country name. Can't I use the ISO to get the name? `getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();` gave me "United States", I just want it to work properly (if it's possible)
Comment: are you testing `getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();` on the android emulator or an actual phone?
Comment: It gives me the ISO just with lowercase :(
Comment: `Locale loc = new Locale("","NL");
loc.getDisplayCountry();` @adadudu can get country name from ISO so just call that on ISO
Comment: I don't understand :(
Comment: @adadudu get the ISO from my method, then create a new Locale object using that string and get it's country by calling `getDisplayCountry()` on that new Locale object initialized with the countries ISO

Getting current country name


Biztalk gets MessageSecurityException with WCF-WsHTTP endpoint

Question: When Biztalk 2009 calls a regular ASP.NET webservice via an WS BasicHTTP adapter, it gets a System.ServiceModel.Security.MessageSecurityException: the HTTP request is unauthorized with client authentication scheme "Anonymous". The authentication header received from the server was : Negotiate NTLM".
The webservice is hosted in IIS (7.5), with anonymous access disabled, and Windows Authentication enabled.
Answer: Your send port needs to be configured to use NTLM security, as that appears to be what the web service requires.
Open the send port's configuration, open the transport type's (WCF-BasicHttp) configuration, and go to the Security tab. There, set the security mode to Transport. That will allow you to set the Transport client credential type to Ntlm.
This will cause BizTalk to authenticate to the web service using NTLM. It will use the account of the BizTalk host in which your send port is running. If that account does not have access to the web service, then you'll either need to grant it access or look at alternatives, such as switching from NTLM to Basic (which allows you to specify the credentials under that same Security tab). A discussion about this issue is here.
Of course, you did mention that you configured the web service for Windows Authentication, so you can also try setting the Transport client credential type to Windows. That should still use the BizTalk host process's account, though, just like NTLM.
Answer: FWIW here's a paste of a WCF basicHttpBinding exposed to BizTalk 2009
<services>
   <service ... >
       <endpoint address=""
        binding="basicHttpBinding"
        bindingConfiguration="binding4BizTalk"
        bindingNamespace="xxx"
... >

       </endpoint>

And then under the bindings
<bindings>
    <basicHttpBinding>
        <binding name="binding4BizTalk" ...>
            <security mode="None" />

Hope is of some use?
Comment: Sorry, but I did some edits there on my orginal post. The webservice is a regular ASP.NET webservice hosted in IIS. Biztalk 2009 and ESB is used and a static resolver is used and set to a wcf-basicHTTP transport...


Python: get pathname of files using regex pattern recursively

Question: If one want to get the (absolute) file paths (file listings) of all files with names of certain pattern how can this be done in Python (v 3.5 on unix). Something similar to the bash command find -regex 'pattern'. I have been looking as the os, glob, os.path  and this SO but cannot get it together.
Say you want absolute paths to the files that  matches /.*[pat.txt]$/ and you have the below diretories:
/home/me/dir1/dir1a/filepat.txt #1
/home/me/dir1/dir1a/file.txt
/home/me/dir1/dir1a/filepat.png
/home/me/dir2/filepat.txt #2
/home/me/dir3/dir3a/dir3ab/filepat
/home/me/dir3/dir3a/dir3ac/filepat.txt #3
/home/me/dir3/dir3a/dir3ac/filepat.png

Then you would get want the three indicated paths:
/home/me/dir1/dir1a/filepat.txt
/home/me/dir2/filepat.txt
/home/me/dir3/dir3a/dir3ac/filepat.txt

One try was:
import fnmatch
import os
start_path = "/home/me/"
for root, dirs, files in os.walk(start_path):
    for filename in fnmatch.filter(files, ".*pat.txt"):
        print(os.path.join(start_path, filename))

Comment: Python is misspelled in the post title  :-)
Comment: Embarrassing - but good catch
Comment: don't worry, I was in "debug mode"   ;-)
Answer: Here is one using regexes, but for the simple case I would go with akash`s answer using in operator
import re
pattern = re.compile(r'.*pat\.txt$')

import fnmatch
import os
start_path = "/home/me/"
for root, dirs, files in os.walk(start_path):
    for filename in files:
        if pattern.find(filename):
            print(os.path.join(start_path, filename))

Comment: I was close I see. I think yours is very general though (+1)
Answer: You can use basename and in operator
x = given list
>>> [i for i in x if 'pat.txt' in os.path.basename(i)]
['/home/me/dir1/dir1a/filepat.txt',
 '/home/me/dir2/filepat.txt',
 '/home/me/dir3/dir3a/dir3ac/filepat.txt']

Comment: However, this solution will also fetch files like `filepat.txt.bak`
Comment: - Yes, but then it would fail to fetch `FILEPAT.TXT`. - We may use `lower()`.
Comment: Oh I completely missed `basename`
Comment: To fix that, just use `i.endswith('pat.txt')`
Comment: @WiktorStribiżew , we can still achieve this using `endswith('pat.txt')` if required :)


Prove that $f$ is a homeomorphism

Question: Let $f: (M,d) \rightarrow (N,\rho)$ be a one-one and onto mapping. Prove that the following are equivalent:

$f$ is a homeomorphism.
$g: N\rightarrow \mathbb{R}$ is contiuous if and only if $gof: M
   \rightarrow \mathbb{R}$ is continuous.

To show $1 \implies 2$ I have proceeded in the following manner.
$f$ is a homeomorphism $\implies$ $f$ is continuous from $M \rightarrow  N$ $\implies$ For any sequence $(x_{n})$ in $M$ converging to $x$ we have $f(x_{n}) \rightarrow f(x)$. Let, $g$ is continuous from $N  \rightarrow \mathbb{R}$ Therefore, $g(f(x_{n}) \rightarrow g(f(x))$. Hence, $gof(x)$ is continuous in $M$.
Since, the statement 2 had an iff next, I assumed that $f$ is a homemomrphism and $gof$ is continuous and proved that $g$ is continuous.
Now, I am not sure how I have to show $2 \implies 1$
Source:Real Analysis by N.L Carothers Page 72, Problem 54
Comment: I wonder if one can start with, let $g$ be continuous!
Answer: A hint for $\ 2\implies 1\ $ is to take $\ g(y) = \rho\left(y,f(x_0)\right)\ $ for any fixed $\ x_0\in M\ $, and show that the continuity of $\ g\circ f\ $ implies the continuity of $\ f\ $ at $\ x_0\ $.
Edit: I originally missed the OP's statement that the proof of the continuity of $\ g\ $ following from $1$ and the continuity of $\ g\circ f\ $ had already been done.  So
I was incorrect in my earlier statement that this was still needed to complete the proof of $\ 1\implies 2\ $.
Answer: Let's generalise: let $f:X \to Y$ be a bijection between Tychonoff spaces. (all metrisable spaces are normal $T_1$ so Tychonoff, but we don't need the metric)
Let's show that 1 and 2 are equivalent :

$f$ is a homeomorphism.
For every $g: Y \to \Bbb R$: $g$ is continuous iff $g \circ f:X \to \Bbb R$ is continuous.

Assume that 1 holds. Then to show 2 we need to show an equivalence again. The left to right one is just using that the composition of continuous maps is continuous. If OTOH $ g \circ f$ is continuous, we can write $g = (g \circ f) \circ f^{-1}$ where the composition is continuous as $f^{-1}$ is continuous by assumption 1.
So 2. has been shown too, not using anything yet about our spaces.
Assume that 2. holds. We need to show 1, so $f$ is continuous and $f^{-1}$ is continuous (which exists because in all of this $f$ is a bijection) or alternatively, that $f$ is open.
To see that $f$ is continuous, let $O$ be open in $Y$ and we'll show that any $x \in f^{-1}[O]$ is an interior point of it, so take any $x \in f^{-1}[O]$; then $f(x) \in O$ and as $Y$ is Tychonoff, there is a continuous $g: Y \to \Bbb R$ such that
$g(f(x)) = 0$ and $g[Y\setminus O]=\{1\}$. Now apply 2.: as we know $g$ is continuous, $g \circ f$ must be continuous too. Define $U = (g \circ f)^{-1}[(-\frac12, \frac12)]$ which is continuous as the inverse image of an open set under the continuous $g \circ f$ and contains $x$. Also $U \subseteq f^{-1}[O]$ (as otherwise for some $x'$ with $g(f(x')) \in (-\frac12,\frac12)$ we'd have $f(x') \notin O$ which means $g(f(x'))=1$ by construction of $g$.). So $x$ is an interior point of $f^{-1}[O]$ and that set is open, and so $f$ is continuous.
To see that $f$ is open, let $O$ be open in $X$ and let $y\in f[O]$, so $y=f(x)$ for some $x \in O$. We can find some $h: X \to \Bbb R$ continuous with $h(x)=0$ and $h[X\setminus O]=\{1\}$ because $X$ is also Tychonoff. Define $g: Y \to \Bbb R$ by $g(y)=h(f^{-1}(y))$, using that $f$ is a bijection. Then $g \circ f = (h \circ f^{-1}) \circ f = h$ so we know that $g \circ f$ is continuous. It follows that $g$ is continuous too by using the other implication of 2., and now $U=g^{-1}[(-\frac12,\frac12)]$ is open in $Y$ and $g(y)=h(f^{-1}(y))=h(x)=0$ so $y \in U$ and if $y' \in U$ would be in $X\setminus f[O]$ then $f^{-1}(y') \in X\setminus O$ and so $g(y')=h(f^{-1}(y')) = 1$, contradicting $y' \in U$. So $y \in U \subseteq f[O]$ and each $y \in f[O]$ is an interior point and $f[O]$ is open. QED.
Sorry for the somewhat abstract argument, but this shows to what generality we can extend such results. The condition 2. is the so-called universal property for the initial topology wrt real-valued functions on $Y$, so if you have studied some more general topology, it's quite obvious to look to Tychonoff spaces to prove such a theorem in (which have the initial topology wrt real-valued maps), plus exploiting that a bijection to an initial topology will be a homeomorphism in many cases...
In a similar vein, we can replace $X$ and $Y$ by zero-dimensional (Hausdorff?) spaces and simultaneously $\Bbb R$ by $\{0,1\}$ in the discrete topology, e.g.

Prove that $f$ is a homeomorphism


When publishing database project from Visual Studio, error: "Rows were detected. The schema update is terminating because data loss might occur."

Question: I have an existing table in my database and as part of the enhancement, I am required to drop three columns in this table.
I have made the corresponding change in the SQL database project that I have in my Visual Studio 2022 where I have removed these columns from the table definition.
Now when I publish the project targeting my database, I get this error:
"Rows were detected. The schema update is terminating because data loss might occur."
Upon preliminary searching and checking with chatGPT, I got the setting in the project properties -> Debug -> Block incremental deployment if data loss might occur which had to be unchecked.

However, in spite of unchecking this setting, I continue to get this error.
Answer: Well, it turns out that the project level setting for does not take effect for the publish process. (Curious to know where this project level setting does apply). When publishing, you have to uncheck the value for a similar setting from the publish dialog box.
SQL Database project (right click) -> Publish -> Advanced -> Uncheck "Block incremental deployment if data loss might occur"
Very Important - If you are loading an existing publish profile, ensure that this checkbox is unchecked after you have loaded the publish profile.


Solving Recurrence relation $a_n = 3a_{n-1} + 5 \cdot 3^n$ for $n\geq 1, a_0=2$?

Question: How can I solve recurrence relation $a_n = 3a_{n-1} + 5 \cdot 3^n$ for $n \geq1 $ and $a_0 = 2$?
Comment: have you tried doing some values and finding a guess?
Answer: Hint: $$a_{n+1} - 3a_n = 5 \cdot 3^{n+1} = 3 (a_n-3a_{n-1})$$
Can you start from here?

 $$a_{n+1} - 6a_n + 9a_{n-1} = 0 \implies \frac{a_{n+1}}{3^{n+1}} - 2\frac{a_n}{3^n} + \frac{a_{n-1}}{3^{n-1}}=0$$ Let $a_n = 3^n b_n$ then $$b_{n+1} - 2b_n  + b_{n-1} = 0 \implies b_{n+1} - b_{n} = b_n-b_{n-1} = \cdots = b_1 - b_0 = 7 - 2 =5$$ Therefore $b_n=b_0+5n=5n+2, a_n = 3^n (5n+2). \blacksquare$
Comment: In this particular problem we can start with $a_n = 3^n b_n$ in the very beginning and derive $b_n$ as an arithmetic sequence. But if the coefficient is something else (e.g., $a_n=2a_{n-1}+5\cdot 3^n$) then it's better to make it homogeneous first.
Answer: Put
$$a_n=5.3^n.b_n$$
then
$$5.3^n.b_n=3.5.3^{n-1}.b_{n-1}+5.3^n$$
thus
$$b_n=b_{n-1}+1$$
So,
$$b_n=n+2,\; \; and \; \; a_n=5.3^n(n+2)$$
Answer: Let $ n\in\mathbb{N} $, we have for any $ k\leq n-1 $ the following : $$ a_{n-k}=3a_{n-k-1}+5\times 3^{n-k} $$
Thus : \begin{aligned}3^{k}a_{n-k}&=3^{k+1}a_{n-k-1}+5\times 3^{n}\\ \Longrightarrow \sum_{k=0}^{n-1}{\left(3^{k}a_{n-k}-3^{k+1}a_{n-k-1}\right)}&=5n\times 3^{n}\\ \iff \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ a_{n}-3^{n}a_{0}&=5n\times 3^{n}\\ \iff \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ a_{n}&=3^{n}\left(5n+2\right)\end{aligned}
Since $ n $ is arbitrary, the result stands for all $ n\in\mathbb{N} $.
Hope that helps.
Answer: When you have a first-order recurrence like this, you can often simply 'unwind' it:
$$\begin{align*}
a_n&=3a_{n-1}+5\cdot3^n\\
&=3(3a_{n-2}+5\cdot3^{n-1})+5\cdot3^n\\
&=3^2a_{n-2}+2\cdot5\cdot3^n)\\
&=3^2(3a_{n-3}+5\cdot3^{n-2})+2\cdot5\cdot3^n\\
&=\color{red}{3^3a_{n-3}+3\cdot5\cdot3^n}\\
&\;\;\vdots\\
&=\color{blue}{3^ka_{n-k}+k\cdot5\cdot3^n}\\
&\;\;\vdots\\
&=3^na_0+n\cdot5\cdot3^n\\
&=3^n(2+5n)
\end{align*}$$
By the time you get to the red line, the pattern should be pretty clear; I've expressed it in general terms in the blue line. Then you can jump to the end and simplify to get a closed form for $a_n$. The step from the red to the blue line isn't rigorous, so properly speaking you should prove by induction on $n$ that the formula $a_n=3^n(5n+2)$ really does satisfy the recurrence with the right initial condition, though in many cases, like this one, the pattern really is very clear.
Answer: general sequence is $a_n= (3^n)a_0 +n \times 5\times 3^n$
substitute $a(n-1)$ for $a(n-2)$ and check the pattern you can easily figure it out.


DBX Error in Delphi Berlin 64bit compiler: Driver could not be properly initialized. When connecting to a Oracle 12c DB Server

Question: I got the stopper error below in my apps. I used Delphi Berlin 64bit compiler. And also used the dbxora.dll as dbxpress driver default from embarcadero. Connected to Oracle 12c DB server using TSQLConnection component.

DBX Error: Driver could not be properly initialized. Client library may be missing, not installed properly, of the wrong version, or the driver may be missing from the system path.

How can I fix this?
Comment: Do you install 3rd party installers along with your application?
Comment: Do you have the 64-bit Oracle client installed?
Comment: @lrb - No, I don't.
Comment: @Ken White - Yes, we do. The 64-bit Oracle 12c installed already.
Answer: A DB Express driver is not always sufficient on it's own to connect to some data sources.  For certain data sources (most of them in fact) you also require the client drivers for that data source, usually provided by the database vendor themselves.
Oracle is one of these.
As well as the DB Express driver you also need to install the Oracle Client software provided by Oracle.  You also need to ensure that you install the correct version.
i.e. in your case since you indicate you are building a 64-bit application then you will need the 64-bit Oracle client.
If you (or your intended users) already have the 32-bit Oracle client installed then you might consider building your application as a 32-bit application instead, unless you absolutely need 64-bit capabilities.
Comment: @sandman yes, of course.  32-bit apps use 32-bit DLL's and 64-bit app's use 64-bit DLL's.  Neither one can use the other without some shenanigans going on inbetween.  e.g in the case of printer drivers, for example, the Windows provides 32 and 64-bit application drivers and takes care of mapping printer calls down to the underlying 64-bit printer drivers.  But for proprietary interfaces such as database drivers etc, it's up to the vendor to provide that sort of mapping (called "thunking") and if they don't then the 'bitness' of your apps **must** match the bitness of the driver.
Comment: @sandman probably not, simply because it doesn't *need* to be.  Unless of course a 64-bit OS removes support for 32-bit processes completely (looking at you Apple) then the decision as to whether to build for 32 or 64 bits (64-bits is not all gravy) comes down to whether a particular application really needs it.  Mostly that means server apps, not desktop/clients.  Whether to continue 32-bit support in an OS comes down to weighing the cost/complexity of continuing that support vs the #'s of apps/users/developers who will be inconvenienced for no direct benefit to them.
Comment: Yes, indeed. I installed the 64-bit Oracle 12c Client on this. All the environment 64bit already. And this issue is still emerging. Fyi, I used OCI access in this case.
Comment: And are you *certain* you are building (and running) an EXE for the Windows x64 target ?  If you are then the next thing I'd check is whether it is on the path, as required.  And of course first principles:  Can you successfully establish Oracle connections using *other* 64-bit apps on the same machine ?
Comment: This also happens, to my horror, if you install the 64 bit client software and you compile your Delphi project with 32 bit.
Comment: Most of our work environment evidently uses 32 bit legacy software, as lots of software broke when the 64 bit instantclient was tested.  Wonder if the world will ever be fully 64 bit compliant... sigh.


How to import unknown number of images with drupal feeds from xml file?

Question: I am trying to import a gallery of images for a specific content type. The XML file looks like this:
<code> <img1>
 https://xml.....
 </img1>
 <img2>
 https://xml.....
 </img2>
 <img3>
 https://xml.....
 </img3>
 <img4>
 https://xml.....
 </img4>
 <img5>
 https://xml.....
 </img5>
</code>
The node has a different and unknown number of images.
I'm using QueryPath's XML parser to import the contents to the node, but I don't know how to import all the images. Some nodes have up to 50 images.
Comment: Welcome to Drupal Answers! I don't understand specifically what you are asking or where it is that you are stuck.
Comment: When I mapping for a QueryPath XML source value, I use "img1" and parser imports image 1, but I don't know how many images they are for creating an exact number mappings.
Comment: I mean that the different nodes that need to be imported have different number of images and it's not clear where I should go with the mapping. The last can be img5 or img55.
Answer: I switched from QueryPath's XML parser to XPath, and used :
<code>//*[starts-with(local-name(), "img")]</code>
Thus, all images starting with 'img', regardless of the number after it, are imported without a problem.


The Distribution of max(X,1/X)

Question: If $X \sim \text{U}(0,1)$, what is the distribution of $Y = \max(X,1/X)$?
I know for this particular problem, $Y = \max(X,1/X) = 1/X$, whose distribution can be easily attained directly. However, I've been trying another approach by starting with this
$$P(Y \leq y) = P(X \leq y,\frac{1}{X} \leq y)=P(\frac{1}{X}\leq y| X \leq y)P(X \leq y),$$
and I've been stuck. I would be appreciate if someone could show me how it could be proceeded. Thank you very much.
Comment: Is $X$ really Uniform(0,1)? Because in that case, max($X, 1/X$) is always $1/X$.
Comment: If you tried $X \sim U(0,2)$, you could come up with a nice solution that might generalize (depending on what you want to generalize too).
Comment: Yes, I've mentioned that for this particular case, max(X,1/X) would be 1/X, but I'm trying a more general way to deal with this kind of problem.
Comment: @CliffAB so supposing that X~U(0,2), how can I derive the distribution of max(X,1/X)?
Answer: As you have acknowledged in your question, this problem is trivial in the case where $0 < X < 1$.  In the more general case (taking $\tfrac{1}{0} = +\infty$ for definiteness) you have:
$$Y = \max(X, \tfrac{1}{X}) = \begin{cases}
\tfrac{1}{X} & & \text{if }X < -1 \\[6pt]
X & & \text{if }-1 \leqslant X < 0 \\[6pt]
+\infty & & \text{if } X = 0 \\[6pt]
\tfrac{1}{X} & & \text{if }0 < X < 1 \\[6pt]
X & & \text{if }X \geqslant 1 \\[6pt]
\end{cases}$$
If you restrict this to the case where $X>0$ (which includes the last two categories), you have:
$$\begin{equation} \begin{aligned}
F_y(y) \equiv \mathbb{P}(Y \leqslant y)
&= \mathbb{P}(\max (X, \tfrac{1}{X}) \leqslant y) \\[6pt]
&= \mathbb{P}(X \geqslant \tfrac{1}{y}, 0 < X < 1) + \mathbb{P}(X \leqslant y, X \geqslant 1) \\[6pt]
&= \mathbb{P}(\tfrac{1}{y} \leqslant X < 1) + \mathbb{P}(1 \leqslant X \leqslant y). \\[6pt]
\end{aligned} \end{equation}$$
And of course, in the case where $0<y<1$ this probability is zero, as expected.

The Distribution of max(X,1/X)


Differential equations modelling rats factor of $e$

Question: I was given this question by a friend and I could not solve it.
a perfect environment, the population of Norway rat that breeds on the MIT campus increases by a factor of $e$ each year. Model this natural growth by a differential equation.
What is the growth rate k?
I know how to solve these questions normally. What I don't get is the part about factor of $e$. I know if it says it was proportional to the population number , I could find the de and solve it easily but what does a factor of $e$ even mean? Is it just a fancy way to say the number of rats can be modeled by a function of $e$?
Answer: If the population grows by a factor of $e$ each year then the population at time $t$ is given by
$$x(t) = x_0e^t$$
Where $x_0$ is the initial population and $t$ is measured in years. Therefor
$$\frac{dx}{dt} = k x, \quad x(0) = x_0$$
is your equation, with $k=1$


Can I create a listener in JS instead of repeatedly requesting a URL?

Question: I'm working on a tool that will require 'listening' for a response from the server.
Currently I've got the page using JQuery to request a URL and respond based on it's output.
I do that every couple seconds.
However, as there will likely be hundreds of people using the tool all at the same time, that could be a pretty big server load.
Is there a way I can create a 'listener' that will notify the loaded pages when a change happens instead of constantly querying the server?
I haven't really been able to find much on Google (probably not searching for the correct thing) so hopefully someone here will know exactly what I'm talking about.
Thanks in advance for your quick responses!
Comment: You'll probably want something like a comet or web sockets
Comment: socket io, web sockets. Node.js. CORS, postMessage.
Comment: Comet/server push is what you want here, but if you can't install that for some reason, don't forget that you can and should take advantage of caching and conditional headers (ETag and/or Last Modified) to reduce the amount of time servers need to spend on requests for stale data.
Answer: You are looking for technologies named Comet or server push. There are several different implementations of this problem, typically involving long-running, but idle HTTP connections. Check out Atmosphere (in Java) or various other libraries.
Also make sure to have a look at web sockets (new HTML5 technology).
See also

COMET javascript library
Comment: I think socket is the answer.
Comment: @Jun1st: do you mean (web) sockets?


How to compute $\lim\limits_{n\to\infty}\frac{1}{\sqrt{4n^2-1^2}}+\dots+\frac{1}{\sqrt{4n^2-n^2}}$.

Question: I want to compute $$\lim_{n\to\infty}\sum_{k=1}^n \frac1{\sqrt{4n^2-k^2}}.$$
I found it on this question and the exercise appears to be from previous years of a Latvian competition.
I tried writing $\frac1{\sqrt{4n^2-k^2}}=((2n-k)(2n+k))^\frac{-1}2$ and wanted to continue with partial fractions but the square root is annoying. Also, I thought about $$\frac1{\sqrt{4n^2-k^2}}=\frac{\sqrt{4n^2+k^2}}{\sqrt{16n^4-k^4}}$$ but I don't think that this can help me.
Answer: Using Riemann sums:
$$\lim_{n\to\infty}\sum_{k=1}^n \frac1{\sqrt{4n^2-k^2}} =\lim_{n\to\infty}\frac1n\sum_{k=1}^n \frac1{\sqrt{4-\left(\frac kn\right)^2}}
=\int_0^1 \frac1{\sqrt{4-x^2}}
=\arcsin\left(\frac x2\right)\bigg\vert_0^1
=\frac\pi6.
$$
Answer: $$\lim_{n\to\infty}\sum_{k=1}^n \frac1{\sqrt{4n^2-k^2}}=\lim_{n\to\infty}\sum_{k=1}^n \frac1{\sqrt{4-\left(\frac{k}{n}\right)^2}}\frac{1}{n}=\int\limits_0^1\frac{1}{\sqrt{4-x^2}}dx.$$
Can you end it now?
Answer: Since$$\sum_{k=1}^n\frac1{4n^2-k^2}=\sum_{k=1}^n\frac1n\times\frac1{\sqrt{4-\left(\frac kn\right)^2}},$$this is a Riemann sum. The limit is $\displaystyle\int_0^1\frac{\mathrm dx}{\sqrt{4-x^2}}=\frac\pi6$.
Answer: You can rewrite it to become $$\lim_{n\to\infty} \frac{1}{n}\sum_{k=1}^n \frac{n}{\sqrt{4n^2-k^2}} = \lim_{n\to\infty} \frac{1}{n}\sum_{k=1}^n \frac{1}{\sqrt{4-\left(\frac{k}{n}\right)^2}}$$
This is the Riemann sum for $\frac{1}{\sqrt{4-x^2}}$ from $0$ to $1$. Therefore, the limit of the sum is $$\int_0^1 \frac{1}{\sqrt{4-x^2}} dx$$
Integrating, we get $$\arcsin \left( \frac{x}{2} \right) \bigg\vert_0^1 = \arcsin\left(\frac{1}{2}\right) - \arcsin\left(\frac{0}{2} \right) = \frac{\pi}{6}$$


DNS: how to get local server to superimpose results over authoritative server?

Question: I've got a domain for which the DNS I control, and is hosted on the internet. I also have a NAT'd internal network (192.168.0.0/24) which has internet access, and which I also control. On this internal network, I also have a DNS resolver. DNS software on both is PowerDNS.
What I want to be able to do is for the DNS resolver on the internal network to be able to add/change records of queries and results that come down from the authoritative server. For example, the authoritative server might have a single record for animal.example.com:
animal.example.com.    IN    AAAA    2001:140:283::1

However, I'd like it so that when internal clients do a dns lookup for animal.example.com, they might get back the following:
animal.example.com.    IN    AAAA    2001:140:283::1
animal.example.com.    IN    A       192.168.0.2

Obviously, I could set up the internal DNS server to pretend to be authoritative for example.com, but that would require a fair bit of effort to keep the main DNS server and the internal DNS server in sync for the records which are the same between both. If the internal DNS server could somehow be made a slave of the main DNS server, but also have the provision to add its own results in, that would be ideal.
Is this possible?
Comment: Please note that if/when you implement DNSSEC on the example.com domain, this will become impossible.  (Well, unless you run a full authoritative DNS server internally using the same keys as the external server.  I'm also assuming you control example.com and aren't trying to mess with someone else's domain on your network.)
Comment: Are you going to transparently proxy WEB-requests at 192.168.0.2
? Also, IMHO, intercepting and spoofing of DNS results aint good idea.
Comment: I appreciate that spoofing DNS results falls into the realm of "bad", and that DNSSEC will make this impossible. We can assume I control example.com. I'm just trying to create a different DNS experience for internal clients, but one that includes the results that everyone else sees for that domain.
Answer: What I think you want is a split-horizon DNS setup, however PowerDNS doesn't directly support such (unlike Bind or DJBDNS).
The official response about it from the author is here:
http://mailman.powerdns.com/pipermail/pdns-users/2006-September/003779.html
I've never found split-horizon DNS to be particularly confusing, myself, especially if files are laid out clearly in the file system, e.g. ./master-interal/domain.com  ./master-external/domain.com
The only option they're suggesting is to have two different instances of PowerDNS running on a server listening on different ports. I guess you would then leverage iptables to redirect traffic to port 53 to whichever instance is relevant.
Comment: +1 for Twirrim's excellent explanation.  I stil don't like the idea of split horizon personally, but many people have pointed out that it's quite common.
Comment: I will read up further on split-horizon. It's annoying that PowerDNS doesn't support it, but I guess we can't have everything. Thanks for the pointer.
Answer: Actually if i had to do it i would use a Lua Script with the recursor that mangles with the data on postresolve.
Hoever i really do recommend something different: Simply use a seperate authoritative Zone like internal.example.com where you AXFR example.com from the authoritative Servers and simply append your local RFC1918 data.
This way you can still debug the authoritative Zone like it is on the internet from your LAN and use the internal data.
About PowerDNS Recursor Lua Scripting: http://doc.powerdns.com/recursor-scripting.html
Comment: ah yes, to be clear: Neither PowerDNS Server nor Recursor do support so called split horizon DNS by default but as Phil said it can be accomplished for the Auth Server by using the Pipe Backend and with Lua on the Recursor one can do just about everything anyways.
Answer: I strongly recommend that you don't go down this path as it is extremely confusing, complex, and difficult to manage.  Instead, you should set up a separate internal domain like inside.example.com.  Then, if your outside dns server is also on your inside network, you should set it up to be authoritative for both domains.  However if your external dns server isn't on your internal network, you should set up your inside dns server to be authoritative for inside.example.com.  Then your inside dns server should forward all other requests to the outside dns server.
I realize the downside of this is you have to change the domain on all your inside machines, but doing that up-front work now will save you a lot of confusion later on.
Answer: Split DNS via PowerDNS Recursor
After fumbling around for some time on my Fedora 20, I seem to have made it work. I haven't found a full how-to anywhere, so a short writeup for a minimal setup:

We want to resolve webserver.dyndns.org to access a web service on it, both from the Internet and the LAN.
From the Internet
Machine a on the Internet resolves webserver.dyndns.org to the IP address IPisp. Behing IPisp is a router with NAT, which port-forwards port 80 to LAN IP IPx, thus making a web service available on the Internet.
This is naturally done by registering IP address IPisp at the authoritative nameserver for domain dyndns.org, which, in the case of a service like DynDns, is done using ddclient running on the router or somewhere in the LAN, and thus of no further interest here.
From the LAN
Machine b on the LAN resolves webserver.dyndns.org to the IP address IPx, so that the web service becomes available on the LAN directly. Additionally, assuming all the machines on the LAN are named along the lines of bar.localdomain, the name webserver.localdomain should also resolve to IPx. We also want to have reverse lookup for good measure, resolving IPx to webserver.dyndns.orginside the LAN (on the Internet, IPx resolves of course to nothing and IPisp resolves to some arbitrary string generated by the ISP.)
We assume pdns-recursor is running on a separate machine with IP IPdns, but we could also have it running on the webserver (on the same IP address as IPx or on an alias), or have only a single machine on the LAN.
Machine "b" may be configured statically or dynamically via DHCP; see dhclient and dnsmasq and possibly avahi. NetworkManager also enters here because it may rewrite /etc/resolv.conf; for now, assume static configuration.
Also, assume:
IPx = 192.168.1.1
IPdns = 192.168.1.2
IPbar = 192.168.1.3

Then:
/etc/resolv.conf on any machine:
nameserver 192.168.1.2
domain localdomain

Configuration for pdns-recursor:
/etc/pdns-recursor/recursor.conf basically reduces to:
setuid=pdns-recursor
setgid=pdns-recursor
allow-from=127.0.0.0/8, 192.168.1.0/8, ::1/128, fe80::/10
auth-zones=webserver.dyndns.org=/etc/pdns-recursor/[webserver.dyndns.org].zone, localdomain=/etc/pdns-recursor/[localdomain].zone, 168.192.in-addr.arpa=/etc/pdns-recursor/[168.192.in-addr.arpa].zone
local-address=192.168.1.2

The above references very much cut-down zone files (their actual names are unimportant):
In /etc/pdns-recursor/[168.192.in-addr.arpa].zone (note the lack of a dot at the end of the record name - it is a relative name not an absolute one: 1.1 means 220.127.116.11.in-addr.arpa). This works with or without the "IN".
1.1   IN   PTR     webserver.dyndns.org.
2.1   IN   PTR     dns.localdomain.
3.1   IN   PTR     b.localdomain.

In /etc/pdns-recursor/[webserver.dyndns.org].zone (note the dot at the end of the record name - it is an absolute name not a relative one)
webserver.dyndns.org.  IN  A  192.168.1.1

In /etc/pdns-recursor/[localdomain].zone
webserver    IN  A  192.168.1.1
dns          IN  A  192.168.1.2
b            IN  A  192.168.1.3

After a restart of pdns-recursor, on can test using dig by running these commands:
PDNS=192.168.1.2

# Test unknwon domain resolution and webserver resolution
dig @$PDNS www.cnn.com | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS webserver.dyndns.org | grep -A1 ";; ANSWER SECTION:"

# Test responses for localdomain
dig @$PDNS unknown.localdomain | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS webserver.localdomain | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS b.localdomain | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS dns.localdomain A | grep -A1 ";; ANSWER SECTION:"

# Test responses for localdomain if the domain is omitted
dig +search @$PDNS webserver | grep -A1 ";; ANSWER SECTION:"

# Test reverse resolution
dig @$PDNS -x 192.168.1.1 | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS -x 192.168.1.2 | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS -x 192.168.1.3 | grep -A1 ";; ANSWER SECTION:"
dig @$PDNS -x 192.168.1.4 | grep -A1 ";; ANSWER SECTION:"

Answer: Use PipeBackend in PowerDNS. I created several systems on the Python.
PipeBackend:

The PipeBackend is primarily meant for
  allowing rapid development of new
  backends without tight integration
  with PowerDNS. It allows end-users to
  write PDNS backends in any language.


Javascript's onclick event causes the page to reload in IE8, but not in Firefox, Safari,Chrome and Opera?

Question: I have an onclick event attached to a button.
Clicking the button adds a text box to the target div.
The code is:
onclick="return addBlank("param1","param2");

The function addBlank does not have a return statement.
Clicking on the button behaves as intended in Firefox, Opera, Chrome and Safari - i.e., an empty text box is added to the target div and page is not reloaded.
Clicking on the button in IE8 forces a page reload and doesn't add anything to the target div.
Is there an onclick incompatibility that I'm missing here?
I appreciate your taking the time to read this doubt!
Answer: Why not add
return false;

to the end of the function then? It should prevent anything happening as a result of the onclick event.
Answer: IE is treating the button as a submit actor (i.e., clicking it submits the form)
The click handler needs to return false; to prevent this.
function addBlank( p1, p2 )
{
  // stuff
  return false;
}

Comment: That's not an IE method - IE would use `event.returnValue = false;`. In this case it's easier to just return false from the handler to prevent default behavior.
Comment: Hi,
I did try this - and it worked in 1 case only.
In the second case - with a similar function - the page still reloads.
I have tried onclick="return x();", onclick=x(); and x() has a return false statement, and both : onclick=return x(); with x() having a return false statement. None are working. Any thoughts?
Comment: I'm confused - you are saying this didn't work, but marked Geoff's answer (which is the same answer) as accepted?  So did you solve your problem or not?
Comment: I guess he must have missclicked or something. Cause `return: false;` isn't helping me with not reloading the page in IE8..
Comment: Btw I think you should update the answer with your comment - the `event.returnValue = false;` is working fine for me in IE ;) +1


Why can free throws be worth 2 or 3 points in the G League?

Question: When I am watching NBA G. League games, it is very surprising that they give only one free throw in a situation where two or three free throws should have been given. Instead, each throw was considered two or three points respectively.
What is the reason for this unique rule?
Answer: The reason is to speed up the game.
From a CBS Sports article by Sam Quinn in 2019 when the rule was introduced:

The goal of the new rule is to shave time off of games. Basketball
games typically have the shortest run-time among major professional
sports, but according to Lowe, G League officials estimate that this
move should cut around six to eight minutes from the league's average.
The rule is being tested in the G League now ostensibly to see if it
would be viable at the NBA level.
Answer: The NBA uses the G League to experiment with new rules. This free-throw rule is one of those experiments.
Comment: While this is true, it doesn't really answer the question which is _why_ this rule was introduced.


Show that $\text{rank}(A-B) = \text{rank}(A) - 1 \iff B = \frac{Axy^{T}A}{y^{T}Ax}$ where $\text{rank}(B)=1$.

Question: Let $m,n \in \mathbb{N}$ and $A,B \in \mathbb{R}^{m\times n}$ with $\text{rank}(B) = 1$. Show that $\text{rank}(A-B) = \text{rank}(A) - 1$ if and only if there exist vectors $x \in \mathbb{R}^n$ and $y \in \mathbb{R}^m$ such that $y^{T}Ax \neq 0$ and $B = \frac{Axy^{T}A}{y^{T}Ax}$.

I don't really know how to start this problem. I know that $y^{T}Ax$ is a scalar and that $B$ may be written as an outer product of two vectors $u^{T}v$. Other than that, I am pretty lost. I imagine that alternative characterizations of rank and the rank-nullity theorem might come in handy at some point.
Answer: Since $\operatorname{rank}(A-B)<\operatorname{rank}(A)$, we have
$\operatorname{nullity}(A-B)>\operatorname{nullity}(A)$. Hence there exists some vector $x\in\ker(A-B)\setminus\ker(A)$, meaning that $0\ne Ax=Bx$. If we consider the left null spaces of $A-B$ and $A$ instead, there also exists some $y$ such that $0\ne y^TA=y^TB$.
So, if we write $B=uv^T$, we have $0\ne Ax=Bx=uv^Tx=(v^Tx)u$ and likewise $0\ne y^TA=(y^Tu)v^T$. Thus $y^TAx=(y^Tu)(v^Tx)\ne0$ and
$$
B=uv^T=\frac{Ax}{v^Tx}\frac{y^TA}{y^Tu}
=\frac{Axy^TA}{(y^Tu)(v^Tx)}
=\frac{Axy^TA}{y^TAx}.
$$
The converse should be easy. Note that $\ker(A)\subsetneqq\ker(A-B)$ when $B=\frac{Axy^TA}{y^TAx}\ne0$.
Comment: It is a nice proof.
Comment: @TheSenate The rank inequality $\operatorname{rank}(X+Y)\le\operatorname{rank}(X)+\operatorname{rank}(Y)$ will be useful here.
Comment: I showed that $\ker(A) \subset \ker(A-B)$ (proper containment). From there you can reverse back into $\text{rank}(A-B) < \text{rank}(A)$. Any hints to get back to the final equality? I haven't yet used that $\text{rank}(B) = 1$. I'm sure that comes into play here. @user1551
Comment: Thank you very much @user1551! I finally had time to sit down and work out the details. Worked like a charm.


PDE for Wave Equation

Question: I have a boundary value problem

$u_{tt}$ + $u$ = $u_{xx}$ ; $0$ < $x$ < $\pi$,  $t$ > $0$
$u(0, t)$ = $u(\pi, t)$ = $0$
$u(x, 0) = 0, u(x, 4) = 0, 0 < x < 2$

I want to find the solution for this BVP using the method of separation of varables. In other BVP problems using the method to solve, their form was like $u_{tt} = u_{xx}$, so I was able to transform them into $X^{''} + \lambda X = 0$ and $T^{''} + \lambda T = 0$ by letting $u(x, t) = X(x)T(t)$. However, in the problem above, we have three terms, $u_{tt}, u, u_{xx}$, so I was not able to solve this problem using the method I suggested. How can I deal with that $u$ in the $u_{tt}$ + $u$ = $u_{xx}$?
Comment: What fails here? The same method still works.
Comment: You have it incorrect. Even the original equation without the extra $u$ would fail the way you have written it because you have introduced the $\lambda$ at the wrong time: $$XT'' = X''T = -\lambda$$ The $\lambda$ is supposed to come later, after you have divided everything by $XT$
Comment: @NinadMunshi I transformed the equation using the method of separation of variables, and the result was $XT^{''} + XT = X^{''}T = -\lambda$. How can I deal with that $XT$? I want to transform the equation into two $\lambda$ equations like I wrote above, $X^{''} + \lambda X = 0$ and the other for $T$.
Comment: @NinadMunshi Then I get $T^{''}/T = X^{''}/X = -\lambda - 1$. Before computing it, can I change $-\lambda - 1$ to $-\lambda ^{'}$ for simplicity?
Answer: Suppose there are functions $T$ and $X$ such that $u(x,t) = X(x)T(t)$ for all $t$ and $x$. Then $u_{tt}(x,t) = X(x)T''(t)$ and $u_{xx}(x,t) = X''(x)T(t)$, so the equation $u_{tt} + u = u_{xx}$ becomes
$$
XT'' + XT = X''T.
$$
Dividing this equation by $XT$, we get
$$
\frac{T''}{T} + 1 = \frac{X''}{X}.
$$
Note that the left-hand side is a function of $t$ only whereas the right-hand side is a function of $x$ only. Now $-$ this is the entire point of the separation of variables $-$ the only situation where a function of $t$ can be always equal to a function of $x$ up to a constant is when both functions are constants. Hence, we can introduce here a constant $\lambda$ such that
$$
\frac{T''}{T} + 1 = \frac{X''}{X} = \lambda.
$$
Now the partial differential equation becomes the system of ordinary differential equations
$$
\left\{ \begin{array}{l}
X'' - \lambda X = 0, \\
T'' - (\lambda - 1) T = 0,
\end{array} \right.
$$
which can be solved as usual.

PDE for Wave Equation


What's the name of this set theory property? $(A \subseteq B) \land (B \subseteq C) \implies (A \subseteq C)$

Question: What's the name of this property in set theory that states that $$(A \subseteq B) \land (B \subseteq C) \implies (A \subseteq C)?$$
Comment: Transitivity. $~$
Comment: FYI the "set theory" tag is used for more advanced topics in set theory - look at the tag descriptions.
Answer: This is transitivity. In general, a binary relation $R$ is transitive iff $$x R y\wedge yRz\implies xRz.$$

Other key properties of binary relations you should know are symmetry (= $xRy\implies yRx$) and reflexivity (= $xRx$). A relation which is transitive, symmetric, and reflexive is called an equivalence relation, and this is a fundamentally important notion. A relation which is transitive and symmetric - like $\subseteq$ - is called a partial order (or sometimes weak partial order - the term "partial order" is often reserved for transitive asymmetric relations).
While not related to your specific question here, I think this additional terminology is worth mentioning here since you'll likely run into it soon as well.
Comment: "a relation which is transitive and symmetric", I think you mean "reflexive"? Also, just having those properties would make it a pre-order, a partial order would involve some equality axiom.


How do I find the solutions of this equation?

Question:
How do I find the solutions of this equation:  $$\tan^2 (x)=-1$$
Answer: There is no solution since any real number squared is always positive.
Answer: (Edited after Julian's comment)
There might be complex solutions. In order to find these write
$$\tan z={1\over i}{e^{iz}-e^{-iz}\over e^{iz}+e^{-iz}}={1\over i}{u-1\over u+1}$$
with $u:=e^{2iz}$. With these conventions we have to solve the equation
$$-\left({u-1\over u+1}\right)^2=-1\ ,\quad{\rm i.e.}\quad {u-1\over u+1}=\pm 1\ .$$
As $(u-1)/(u+1)$ cannot be $1$ the last equation has the single  solution $u=0$, so that we now have to determine the solutions $z\in{\mathbb C}$ of the equation
$$e^{2iz}\ = 0\ ;$$
but there is no such $z$.
Comment: There is a $1/i$ missing in the formula for $\tan z$. This makes a great difference, since there are no solutions, real or complex. This can be seen from Chandrasekhar's answer, since $\sec x=0$ has no solution, real or complex.
Comment: @Julian Aguirre: How could I!
Comment: Thank you for your responses! could you help me in solving this following equation too,$$tanx=2x/(1-x^2 )$$
Answer: Hint: $$ \tan^{2}(x) = -1 \Rightarrow 1 + \tan^{2}(x) = 0 \Rightarrow \sec^{2}(x) = 0.$$
Oh, on the other hand note that $x^{2} = -1$ has no real solutions.
Answer: Notice that $\tan^2(0) = 0$ and for any other $x \neq 0$, $\tan^2(x) > 0$.
If you plot $\tan^2(x)$ and $-1$ you will see that those 2 curves never intersect, because $\tan^2(x) \geq 0$, $x\in{\mathbb R}$.

Therefore there are no real solutions.


Is it possible to run logrotate manually

Question: I created new files in
/etc/logrotate.d/

how run an iteration of logrotate manually to check these?
Comment: Top google result of "run logrotate" -> http://stackoverflow.com/questions/2117771/is-it-possible-to-run-one-logrotate-check-manually
Comment: This question is being voted for closure because the author has not performed a minimum amount of research into the question that is otherwise immediately solved by a basic search. In other words, ServerFault is not Google as a Service.
Answer: Try with:
logrotate --force $CONFIG_FILE

or you can run it in verbose and force mode:
logrotate -vf /etc/logrotate.conf

Answer: You can run logrotate in debug mode which will tell you what it would do without actually making changes.

-d, --debug
Turns on debug mode and implies -v. In debug mode, no changes will be made to the logs or to the logrotate state file.


solving complex numbers with powers algebraically

Question: Find algebraically the value of :$\left(2^{0.5} + 6^{0.5} - \left( 2^{0.5} - 6^{0.5} \right)i  \right)^4$
Below are my works
I try to simplify inside. but i found that i can't add $2^{0.5}$ and $6^{0.5}$ together.
Comment: 2^0.5 is square root of 2 btw
Comment: the answer sheet says the answer is 256i ... so the answer is wrong  ?
Comment: The real part of the expression in the question is not zero (on first glance).
Comment: WA apparently agrees with my answer: $\;128(1+\sqrt3\,i)\;$ ...http://www.wolframalpha.com/input/?i=%282%5E%281%2F2%29%2B6%5E%281%2F2%29-2%5E%281%2F2%29i%2B6%5E%281%2F2%29i%29%5E4
Comment: Oh, and btw: yes, that answer sheet's answer is wrong.
Answer: Simplify by manipulating the inner expression:
$$\begin{align}\sqrt{2} + \sqrt{6} - (\sqrt{2} - \sqrt{6})i &= (\sqrt{2} + \sqrt6i) + (\sqrt{6} - \sqrt2i)\\
&= (\sqrt{2} + \sqrt6i) - (\sqrt{2} + \sqrt6i)i
\\&= (\sqrt{2} + \sqrt6i)(1 - i)\end{align}$$
Now, let $$\begin{align}z &= (\sqrt{2} + \sqrt{6} - (\sqrt{2} - \sqrt{6})i)^4 \\
&= (\sqrt{2} + \sqrt6i)^4(1 - i)^4\end{align}$$
Then,
$$\begin{align}|z| &= |\sqrt{2} + \sqrt6i|^4\cdot|1 - i|^4 \\
&= (\sqrt{2 + 6})^4 \cdot (\sqrt{1 +1})^4 \\
&= 256\end{align}$$
On the other hand, $$\begin{align}\arg{z} &= 4\arg(\sqrt{2} + \sqrt6i) + 4 \arg(1 - i) \\
&= 4 \tan^{-1}\frac{\sqrt{6}}{\sqrt{2}} -4 \tan^{-1}1 \\
&= \frac{\pi}{3}\end{align}$$
Hence
$$z = 256e^{i\frac{\pi}{3}}$$
Answer: Set $\displaystyle\sqrt2+\sqrt6=R\cos\phi, \sqrt6-\sqrt2=R\sin\phi$ where real $R\ge0$
Squaring and adding we get $\displaystyle R^2=2(2+6)=16\implies R=4$
On division, $\displaystyle\tan\phi=\frac{R\sin\phi}{R\cos\phi}=\frac{\sqrt6-\sqrt2}{\sqrt6+\sqrt2}=\frac{\sqrt3-1}{\sqrt3+1}=2-\sqrt3$ which is $\tan15^\circ$ (Find here)
From the dentition of atan2, $\displaystyle\phi=15^\circ$
So, we have $\sqrt2+\sqrt6+(\sqrt6-\sqrt2)i=4(\cos15^\circ+i\sin15^\circ)$
Now apply de Moivre's Identity
Comment: I'll put in that if one didn't have the exact value for $ \tan 15º \ $ handy, one could use a right triangle (or trig identities) to establish that $ \ \sin \theta = \frac{2 - \sqrt{3}}{\sqrt{8 - 4 \sqrt{3}}} \ $ and $ \ \cos \theta = \frac{1}{\sqrt{8 - 4 \sqrt{3}}} \ . $  As horrible as this looks at the moment, the "double-angle formula" for sine produces $$ \sin 2 \theta \ = \ \frac{2 \cdot \ (2 - \sqrt{3}) \cdot 1}{8 - 4 \sqrt{3}} \ = \ \frac{4 - 2\sqrt{3}}{8 - 4 \sqrt{3}} \ = \ \frac{1}{2} \ . $$ Now we know where we are, and can get the angles we need for the fourth-power result.
Answer: Hints:
$$\sqrt2\pm\sqrt6=\sqrt2(1\pm\sqrt3)\implies \left(\sqrt2+\sqrt 6-(\sqrt2-\sqrt6)i\right)^4=$$
$$=4\left(1+\sqrt3-(1-\sqrt3)i\right)^4=4\left[(1+\sqrt3)^2-(1-\sqrt3)^2-2(1+\sqrt3)(1-\sqrt3)i\right]^2=$$
$$=4\left[4\sqrt3+4i\right]^2=64(\sqrt3+i)^2=64(2+2\sqrt3i)=\ldots$$


jQuery mouseenter simple effect

Question: I'm trying to fade a
 outand a
 in on hover, and when users hovers out I need to revert , fade out back and fade in front, however my
 does not fadeout on mouseleave.
Sorry the the newbie question but i'm not sure why this code isn't working. It is because I need to trigger the mouseenter on the back event when the front fades out?
http://jsfiddle.net/8xo8c5pn/
HTML

$(".front").mouseenter(function() {
    $(this).removeClass('on').addClass('off');
    $(this).next().removeClass('off').addClass('on');
});

$(".back").mouseleave(function() {
    $(this).removeClass('on').addClass('off');
    $(this).prev().removeClass('off').addClass('on');
});
.on{
    display:inherit;
}
.off{
    display:none;
}

Hello

im the back

Some text

Comment: try this as well: http://jsfiddle.net/8xo8c5pn/4/ I would suggest giving the item div a fixed height/width so that it doesn't keep resizing and messing up the mouseenter and mouseleave events
Answer: you have 2 element with class back so use .back.off  instead of just .back
try this
$( ".front" ).mouseenter(function() {
    $(this).removeClass('on').addClass('off');
    $(this).next('.back.off').removeClass('off').addClass('on');
});

$( ".back.off" ).mouseleave(function() {
    $(this).removeClass('on').addClass('off');
    $(this).prev('.front').removeClass('off').addClass('on');
});

DEMO
Answer:

$(document).ready(function() {
  $(".back").hide(); //hide back initially
  $(".front").mouseenter(function() {
    $(".back").show();
    $(this).hide();
  });

  $(".back").mouseleave(function() {
    $(".front").show();
    $(this).hide();
  });

});
.back,
.front {
  border: 1px solid red;
}

Hello

im the back

Some text

Comment: in addition, you need to ensure the elements are the exact same size.  when you move the mouse down, for example, the background div still shows
Answer: try this, Use hover function instead mouseenter and leave:

$( ".album" ).hover(
function() {  // IN
    $(this).find('.front').hide();
    $(this).find('.cover').show();
},function() { // OUT
    $(this).find('.front').show();
    $(this).find('.cover').hide();
});

jQuery mouseenter simple effect


Accessing a Table View IndexPath from prepareForSegue

Question: In the prepare segue function in my table view controller, I seem to be getting an error with the index Path.
 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "showView"){
        let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
        let indexPath = self.MainTableView.indexPathForSelectedRow!

        detailVC.test_label.text = names[indexPath.row]
        self.MainTableView.deselectRowAtIndexPath(indexPath, animated:
    }
}

For indexPath.row, it says "BAD_INSTRUCTION" . When I remove the line indexing the names array, it throws the BAD INSTRUCTION error on the line above (the indexPath definition line). When I change the ! After indexPathForSelectedRow to () , it says "Not a function" . I cannot figure out what to do to get the correct index path for the selected row! Anyone know what is going on?
--
The error in the console is:
        fatal error: unexpectedly found nil while unwrapping an Optional value
Comment: What line is it breaking on?
Comment: Can you show where MainTableView is defined in relation to this class?
Comment: @CodeBender       `class MainTableViewController: UITableViewController {

                               @IBOutlet var MainTableView: UITableView!`
Comment: @Amloelxer it is breaking on this line  `let indexPath = self.MainTableView.indexPathForSelectedRow!`
Comment: Look at this answer http://stackoverflow.com/a/24577892/5229157
Comment: @DanielOrmeño I had already looked and tried that solution, but it is still not working for me
Comment: Place a breakpoint on the let indexPath = ... line. See if the MainTableView object is nil or not, since you are likely crashing because it is force unwrapping a nil object. If it is nil, check your connections to your storyboard / xib file.
Comment: @CodeBender Thanks! That solved the problem, it was nil
Comment: Great, I posted it as an answer for future reference.
Answer: Here please find this code. This should work fine.

Or change ! to ? in your code.
//let indexPath = self.MainTableView.indexPathForSelectedRow?
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

{

 if(segue.identifier == "showView")

    {

   let detailVC = segue.destinationViewController as! ViewController2
            let path = tableView.indexPathForSelectedRow?.row
            detailVC.test_label.text = names[path]
     }
}

Answer: Place a breakpoint on the let indexPath = ... line. See if the MainTableView object is nil or not, since you are likely crashing because it is force unwrapping a nil object. If it is nil, check your connections to your storyboard / xib file.


The constrains of Butcher tableau

Question: Related posts(but did not answer the question):

deriving an implicit Runge Kutta method from its Butcher tableau

Understanding the Butcher tableau of implicit midpoint method

butcher tableau for given algorithm

butcher tableau runge kutta methods

One Wikipedia's webpage, Runge-Kutta methods could be generally described by Butcher tableau. However, it did not explain how to obtain the Butcher tableau.
There were several constrains

$\sum_{i=1}^s b_i=1$ for the consistence of Runge-Kutta method.

A "popular condition" for determining coefficients: $\sum_{j=1}^{i-1}a_{ij}=c_i$.

But then it left without comment as if one could just put any number there, but there was also example of generic second order and third order method which seemed to indicate further constrains on $b_i$, $c_i$, and $a_{ij}$.
My question was
1.a. how to obtain/calculate the Butcher tableau. What were the constrains exactly?
1.b. Especially, how was $a_ij$ being chosen under those constrains?(For example, how was "RK 3/8-rule" being read, since there were negative coefficients in $a_{ij}$)
1.c. Why was $\sum_{j=1}^{i-1}a_{ij}=c_i$ popular? Is this an explicit constrains or just a convention?
Answer: $\sum a_{ij}=c_i$: Consider the differential equation $\dot x(t)=1$, $x(0)=0$. Then it is quite reasonable to request that in the whole solution process the $x$ values are equal to the $t$ values. In general it should not make a difference if you consider a general ODE or its autonomous form.
If you can somewhat read German, go to the ultimate source, the article by M. Wilhelm Kutta "Beitrag zur näherungsweisen Lösung totaler Differentialgleichungen" is a quite explicit answer to your question. His approach for the low-order explicit methods is to completely solve the coefficient equations, then select a quadrature method for the $c_i$ and $b_i$,  symmetry constraints and zero coefficients. These then mostly determine the tableau.
For the higher-order explicit methods, where the number of stages is larger than the order, equations are added for structural constraints that simplify the order conditions, demands on the approximation orders of intermediate points, also in view of constructing a "dense output" interpolation, constructing an embedded method, first-same-as-last, and again zero patterns in the matrix. Then often some of the coefficients of the leading error term are selected for minimization, the system is solved. If possible, the solution is perturbed into a close-by rational solution.
With implicit methods one has even more freedom to add constraints. A common method is to use the collocation approach. Others are to make the matrix lower-triangular giving semi-implicit methods where each stage equation can be solved separately, then making the diagonal entries all the same, so that their simplified Newton methods can all use the same Jacobi matrix and its factorization.

The constrains of Butcher tableau


Mix static files into WordPress

Question: I'm migrating a previously-static site to WordPress 4.3.1. Most things are working fine, but I have one odd case: I need example.com/foo/ to be dynamic, but I need example.com/foo/bar/ to be static. I've created a /foo/bar/index.html to handle example.com/foo/bar/, but now example.com/foo/ is giving a 403 Forbidden code.
I also need example.com/foo/bar/ to show up in the menu, which I've accomplished by adding a dynamic example.com/foo/bar/ as well (deleting this doesn't help).
The example.com/foo/ page still exists and can be edited in admin. Why am I getting 403 and how can I fix it?
Comment: It is the default document on your web server who need to be configured, to get the correct answer we need server infos. It seems you don't have your old rewrite rules.
Answer: This happens because the WordPress Apache rewrite rules pass everything on to WordPress which does not exist as a file or a directory on the filesystem, which is what the two RewriteCond rules check for. But you do have a directory corresponding to /foo/ on the filesystem, causing Apache to handle it internally.
To resolve this, you'll need to tell Apache explicitly to pass this on to WordPress (and do this with any other URLs that might have directories masking them from the first rewrite rule).
Add a new section of directives just before the end of the IfModule:
RewriteCond %{REQUEST_URI} "/foo/" [OR]
RewriteCond %{REQUEST_URI} "/bar/" [OR]
RewriteCond %{REQUEST_URI} "/baz/"
RewriteRule . /index.php [L]

As for the WordPress menu, you shouldn't add blank pages to add entries to it. Instead, just create custom menu entries with the desired URLs to your static pages. Click on Custom Links in the menu editor and add the desired information.
Answer: I had to modify my DirectoryIndex configuration.
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

These is my /etc/workpresss/access rules for WordPress with mixed static content
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Content rewrites go here

    # Serve static content
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Use WordPress for rest of the content
    RewriteRule . /index.php [L]
</IfModule>

Edit: The 403 is a forbidden access message.  This may be an ACL in Apache or a permissions issue on the WordPress directories.  The reason for the 403 may be recorded in the Apache error log.
As you have an isolated directory tree, you should be able to use a Location or Directory directive for the static code. This is a variation on one I use.
<Location /foo/bar/>
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride None
    Require all granted
</Location>

Comment: This doesn't help. `DirectoryIndex` is probably irrelevant here because the static content is in `/foo/bar/` and I'm having trouble with `/foo/`. There is nothing in `/foo/` other than the `bar/` directory. Your rewrite rules don't help either (and are mostly the same as WordPress's default rules except that WordPress has one additional rule that rewrites `/index.php` to `/`).
Comment: @Viko See edit above.  My configuration doesn't rewrite `/index.php` to `/` as WordPress handles that.

Mix static files into WordPress


Is it possible to change the color component of a style?

Question: Say I have a class as follows:
.X {
   border:1px solid red;
   background-color: blue;
}

Is it possible to change, using script, the color of border and or background-color of class X without affecting all other properties?
Comment: Yes by jQuery/JavaScript, or some CSS that behave in a dynamic fashion. By other properties do you mean the other properties of other elements that have class `.X`?
Answer: To achieve this, you can use a little JavaScript.
var myElements = document.querySelectorAll(".X");

for (var i = 0; i < myElements.length; i++) {
    myElements[i].style.border = "1px solid red";
    myElements[i].style.backgroundColor = "blue";
}

Comment: It should be myElements[i].style.backgroundColor instead of myElements[i].style.background-color
Comment: Changing _color_ of border: `myElements[i].style.borderColor = "darkgreen";` is sufficient
Answer: Yes, you can indeed change the css properties of an element using Javascript or jQuery as suited.
Javascript way
document.getElementsByClassName("X")[0].style.border = "1px solid blue";

Read more about the HTMLElement.style property.
jQuery way
$(".X").css("border", "1px solid blue");

Read more about the jQuery.css() method.
Answer: As others have said it is possible to change the style definition, but do you really want to do that? I think you can achieve the same result just by adding another class
$('.X').addClass('blue');

and add this to you styles:
.X.blue {background-color:blue;}

Answer: Depending of the use case

// All elements with the class X
const elX = document.querySelectorAll('.X');
elX.forEach(i => i.setAttribute("style", "color: green; border:solid tomato"));

// First element with the class Y
const elY = document.querySelector('.Y');
// All at once
// elY.setAttribute("style", "color: tomato; border:solid tomato");

// Or you can set the styles individually
elY.style.color = "tomato";
elY.style.border = "solid tomato";

Yo!

Yo!

Yo!

Yo!


Can I exclude country specific users without breaking Google anayltics tracking?

Question: I really need to stop USA based visitors proceeding to buy products on our UK only website. We are getting a lot of fraud from USA based IP's. I have this nice solution ready to go live, but will it stop Google Analytics and any other USA based tracking scripts working on my website? Does anyone have a better solution?
<code>    // Cut non UK countries out of going any further:
$ip = $_SERVER['REMOTE_ADDR'];
$country = getCountryFromIP($ip, " NamE ");

if (strtolower($country) == "united states") {
    $pageOutput =  file_get_contents("country.exclusion.html");
    $pageOutput = str_replace("<quote:site-wide-footer-tracking.html>", file_get_contents("../static-includes/site-wide-footer-tracking.php"), $pageOutput );
</code>
Comment: You could also add a check for the UserAgent, and explicitly pass Googlebot.
Comment: IP address is not intended for user identification. You really should not block IPs, as one might use proxies, so you would bust legitimate users while this same technology allows any hacker to bypass your 'security'. User-Agent is even easier to forge. You have to accept that there will be requests the server must answer, and guard those operations that modify data, place orders, etc. with proper authentication schemes. To guard against overload, e.g. by a DoS attack, use a firewall. Otherwise you'll end up raking with your fork and eating with your rake...
Answer: I think a better way of doing this would be to prevent US based users from completing certain actions:

Stop them adding a product to basket
On the product page hide any 'Add to Cart' button and replace it with some simple 'This product is not available in your country' text.

This will prevent them from ever purchasing a product but still make sure Google and other US based entities can browse your site without restriction.
Comment: Good idea! I've removed my form from my results page but all tracking scripts remain!


What is it that brings a dance-like character in this Mozart rondo?

Question: So, while listening to the rondo movements of Mozart's piano sonatas, I found one that has a dance-like character to it, despite its development. That would be the rondo from Piano Sonata in Bb K 333. Here is what I know formally from listening to it a bunch of times with the score:

Bars 1-16 - A theme stated first quietly and then loudly as it arpeggiates to a cadence in Bb
Bars 16-40 - B theme with some of the motives from the A theme like for example the arpeggio motive at the beginning of the A theme
Bars 41-56 - A theme stated again
Bars 56-75 - Development of the B theme
Bars 76-84 - C theme, an example of important and new formal material in the development section before Beethoven(had this not had that C theme, it wouldn't feel as much like a rondo)
Bars 85-105 - Development of the A theme
106-111 - B theme used to retransition
Bars 112-127 - A theme again
Bars 127-163 - B theme that then twists around, leading to a cadenza
Bars 164-170 - End of B theme, sounds like A theme is going to come next
Bars 171-198 - Cadenza with some material from both the A and B themes, when is A going to arrive?
199-206 - Finally, at last the A theme, but this time it has the middle section of the theme cut out of it.
Bars 206-224 - Coda

So, basically, it is a rondo, but with the last B section so embellished that it sounds like it was split in half by a cadenza-like melody and with the Mozartian twist of not having the A section arrive when it sounds like it will.
Now why am I asking what it is about this rondo that gives it a dance-like character that other rondos I have listened to like for example Rondo in A minor K 511 or Rondo Alla Turka don't have? Well, it is because I had the idea to compose a Dance in Rondo, in other words a piece that on the one hand could be viewed as a dance and on the other hand is in rondo form. Most dances are in binary or ternary form. I know that I can't use just that single rondo to see how to go about writing my Dance in Rondo, I have to find at least a couple more rondos and compare them to dances like the Minuet and the Waltz and see where the similarities lie harmonically, rhythmically, and melodically and then apply those similarities to my own rondo themes. But, this rondo was the first that I found to have that dance like character.
Here is the video I kept listening to as well as the score(Rondo starts on page 13 of the PDF):

http://imslp.eu/files/imglnks/euimg/9/90/IMSLP456595-PMLP01849-Mozart,_Wofgang_Amadeus-NMA_09_25_2_04_KV_333_scan.pdf
So what is it about that Bb major rondo that I found that makes it have a dance like character despite all the development that occurs? Is it the bass not starting until the second beat, making the first beat sound like an anacrusis? Is it the rhythm? Harmonic rhythm? Melodic shape?
Comment: "Dance" character is almost entirely caused by rhythm rather than melody, form, or harmony. The reason is that dancing to music involves coordinating the *timing* of your steps with the beat of the music, but pitch, volume, harmony etc. have no direct equivalent in the dancer's performance.
Comment: @KiliannFoth Well, I figured that even if rhythm is the primary contributor, that the rate of harmonic change and the melodic contour would both play a role, as most dances I listen to have a harmonic rhythm of 1 chord per bar(Even Chopin's dance pieces tend to have this 1 chord per bar harmonic rhythm) or 1 chord per half-bar(like in a waltz that is written in 6/8). And as for melodic contour, again most dances that I know of stick to mostly stepwise motion in their melodies with some leaping by thirds and sixths. You will especially notice that melodic contour in Minuets from Bach to Mozart.
Answer:
Is it the bass not starting until the second beat, making the first beat sound like an anacrusis?

There is an anacrusis, but it's in the bass. There is also an elision. Beats 2-4 in bar 1, the bass, are the anacrusis. When that line continues to beat 1 of bar 3, it forms an elision...

...blue highlights elisions. First and second phrases in green and red.
I put a rest above beat 1 of bar 3 to show the elision is both the phrase ending F2 and a sort of implied rest beginning a second anacrusis phrase in the bass.

Is it the rhythm?

Yes. The phrasing is all about metrical placement which is an aspect of rhythm.

Harmonic rhythm?

I think is a factor. The harmonic rhythm - at least with the opening phrases - is one or two chords per bar. That's fairly lively.

Melodic shape?

I think contour alone doesn't matter. But if you think of the basic 2 bar phrase length as a short of shape aspect (small shapes, short lines) I think this adds to the lively feel.
You might also consider the anacrusis/elision/feminine endings elements part of shape. If you compared this to carpentry and wood joining, you have flush squared off endings complimented with overhanding edges. That's like shape, but not so much melodic contour.
So, short phrase lengths combined with skillful use of anacrusis and elision to reinforce the meter, with uncomplicated rhythmic figuration at a moderately fast tempo is probably what creates the dance quality you feel.

...other rondos I have listened to like for example Rondo in A minor K 511 or Rondo Alla Turka don't have

Personally, I think those other pieces have dance qualities, but different characters that K333. Those difference strike me first as a matter of tempo, and mode.
Comment: I have seen that term elision get thrown around often with numbers before it, but when I see it in text, I'm like "What does that mean?" Now that I have seen your visualization of the first few phrases of the rondo, I think I know what elision means, it's a seamless overlap between phrases, right?
Comment: And I never noticed a dance quality in K 511 or Rondo Alla Turka. What I hear primarily in Rondo Alla Turka is Mozart's version of triumph over struggle(A minor and F# minor vs A major). And in K 511, I hear a lot of slow melancholy and drama rivaling that of Beethoven. I don't typically hear slow melancholy in a dance piece, even if that dance piece is in minor outside of maybe the Sarabande in Baroque suites.
Comment: Yes, that's right about elision. I think you should look for elided phrases _inside_ the main sections of these larger works and then compare that the cadences ending those large sections where the music actually stops. So, in a first phrase group section of a sonata you might see lots of elision tightly knitting phrases together with continuous forward rhythmic motion, with cadence on the dominant is a clean break everything stop, no elision.
Comment: You can also see that in a lot of short binary pieces, like minuet sets. Within an 8 bar phrase there can be elision, anacrusis, but each 8 bar phrase ends with a cadence. Basically, I think the classical idea was to use these rhythmic devices to keep the motion moving forward, driving toward the 1 beat of the meter, only stopping at the cadences.


How to pass passphrase to private key when releasing with standard maven plugin

Question: I am trying to release my maven project using standard maven release plugin and Bitbucket pipelines. I've created my own docker image with private key protected with passphrase. My Bitbucket account allows commits from this docker image and Bitbucket pipeline is able to inject private key passphrase via environment variable when building.
The problem is that maven release plugin ignores everything and asks for passphrase which is an unacceptable manual step.
My settings.xml in /root/.m2 looks like
<server>
    <id>bitbucket.org</id>
    <privateKey>/root/.ssh/id_rsa</privateKey>
    <passphrase>${env.BB_PIPELINES_MAVEN_3_3_9_JDK_8_SSH_PASSPHRASE</passphrase>
</server>

I am using the latest release and scm plugins, respectively 2.5.3 and 1.9.5
In my pom.xml there is server property
<project.scm.id>bitbucket.org</project.scm.id>

and my scm url's are like
<scm>
    <url>https://bitbucket.org/user/repo</url>
    <developerConnection>scm:git:firstname.lastname@example.com:user/repo</developerConnection
    <connection>scm:git:email@example.com:user/repo</connection>
</scm>

I was trying to use ssh-agent, and it seems to work, but looks like ssh-agent doesn't allows to pass passphrase in command line as well.
Any ideas how can it be solved?
Answer: I managed to do some workaround using expect and ssh-agent.
In my .bashrc I've put
eval `ssh-agent -s`
/root/load-private-key.sh $BITBUCKET_PIPELINES_MAVEN_3_3_9_JDK_8_SSH_PASSPHRASE

and my load-private-key.sh file looks like
#!/usr/bin/expect -f
set password [lindex $argv 0];
set timeout 10
spawn ssh-add /root/.ssh/id_rsa
expect "Enter passphrase for /root/.ssh/id_rsa: "
sleep 1
send $password\n
expect "Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)"

Now every build session starts with loading into memory private key which can be used by standard maven release plugin.


ThreadPoolExecutor Not Using Multiple Workers When Being Called Inside a Function

Question: I'm trying to make a module that scans a given IP address and returns true or false for each port depending on it's current state. It works fine when the context manager is called by itself but when it's called within a function it stops using all of it's allocated threads. Here is my code:
import socket
import concurrent.futures

def _scan(ip, port):
    scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    scanner.settimeout(1)
    try:
        scanner.connect((ip, port))
        scanner.close()
        return True
    except:
        return False

def portScan(ip, workers, portNum):
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
        for port in range(portNum):
            future = executor.submit(_scan, ip, port + 1)
            print(future.result())

portScan("220.127.116.11", 100, 1000)

Answer: The problem is that you are waiting for each future to complete before submitting the next. You could use map instead. It will fan out the work to all of the threads and iterate the results in the same order as the parameters submitted.
import socket
import concurrent.futures

def _scan(params):
    ip, port = params
    scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    scanner.settimeout(1)
    try:
        scanner.connect((ip, port))
        scanner.close()
        return True
    except:
        return False

def portScan(ip, workers, portNum):
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
        for result in executor.map(_scan, ((ip, port) for port in range(portNum))):
            print(result)

portScan("127.0.0.1", 5, 22)


R - Identifying the most statistically significant variables that determine a target

Question: My dataframe looks something like this -
df <- data.frame(Speed_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE),
               Cleanliness_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE),
               Efficiency_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE),
               Variety_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE),
               Friendliness_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE),
               Overall_Satisfaction=sample(seq(from = 0, to = 1, by = 0.01), size = 1000, replace = TRUE))

My Objective
I'd like to determine which of my 5 variables is most important in determining Overall_Satisfaction for services provided in a restaurant. And rank these variables in order of their importance.
The satisfaction scores in my df are on a scale from 0 to 1, where 1 equals 100% satisfaction and 0 is 0% satisfaction.
My Approach
I chose to model my data using multiple linear regression (the lm function in R) to identify the most significant variables.
fit <- lm(Overall_Satisfaction ~ Speed_Satisfaction + Cleanliness_Satisfaction + Variety_Satisfaction + Friendliness_Satisfaction, data=df)

And the analyse the results using summary
This way, I can study the Estimates (negative or positive indicating the direction of the relationship with the target variable) and the P value to rank variables according to how statistically significant they are.
My Question
Is this the best approach for the problem I'm trying to solve with the data I have, or are there other methods that yield better results?
I am still exploring statistics and R, so your inputs will be greatly appreciated.
Answer: As John Coleman said in his comment, Cross Validated might be a better place to look for an answer, and you should ask there for more details. Also, in your idealized example above, most problems below don't apply since all the variables seem to have the same distribution, however you need to keep them in mind. For now, the main points would be:
1) In general, don't look at the estimates, because they are a function of the units in which they are measured. So for example, if you measure something in kilos and in grams, the latter coefficient will be 1000 larger, but without it being a better predictor. That being said, your variables are on the same scale, so the problem goes away.
2) p-values measure how likely you are to observe the estimated effect (or a more extreme one) under the null hypothesis. They are a function of your coefficient, the precision of the estimation (standard error), the sample size, and the null hypothesis. So again, not a great way to gauge importance.
Suggestions:
1) Look at standardized coefficients. In this case, you normalize your variables (subtract mean, divide by standard deviation) and the resulting coefficients are comparable. However, the interpretation changes. You can't say "a 1-unit increase in X, changes Y by ", but you can say "a 1-sd increase in X...". (In your example, the data are already standardized). You can implement this in R using the lm.beta package.
2) Remove the variables one by one, and see how the Adjusted  changes. So if you remove , and the Adjusted  decreases by , where , then you can say that  is the most important predictor. However, the results are not necessarily reliable, and that's why there is an extensive literature on variable selection methods (backwards, forward, best subset, LASSOs, Ridge Regressions, Elastic Nets etc.). However, with the basic example you gave, a basic application of backwards selection should be fine.
This is not by any means a complete discussion, but I think it hits some very basic points you should keep in mind.
Comment: While suggestion (2) is good to start with, I'd advise some caution in that your result will also depend on the *order* in which you remove variables. Incidentally, this is one of the reasons why stepwise regression methods can be very unreliable.
Comment: @MarcusCampbell, that's an excellent point! I was originally debating whether to get into it or not, and chose not to because of the simplicity of the OP's example. But I just edited the answer to capture the spirit of your comment. Thanks!
Comment: "p-values measure how likely you are to observe a coefficient under the null hypothesis"  doesn't seem totally exact. I would say "p-valuez measure how likely you are to observe the at least the estimated effect under the null hypothesis"
Comment: @denis fair point! I edited the answer
Answer: Variables such as satisfaction are usually best modeled with ordinal regression, e.g., the proportional odds model, because of the lack of interval scaling.  But to your question, the data are ill-equipped for telling you the importance of variables in prediction, especially if the variables are correlated.  I suggest using a method that is honest and exposes the difficulty of the task: using the bootstrap to compute 0.95 confidence limits for the ranks of the variables on their prediction ability.  This can be based on the log-likelihood that is explained by the predictors (partial $\chi^2$ Wald tests; likelihood ratio tests better).  A simple example of such a bootstrap exercise in a simulation of 12 predictors is in my RMS course notes.
If, when doing the bootstrap, one finds that the data are compatible with a certain variable being both the strongest and the weakest predictors, you have no basis for making a statement.
Background: look at a few regular bootstrap repetitions of model fits and see how the relative contributions of all the predictors are volatile.
Answer: I don't want to enter the whole discussion, I just want to point out a simple tool:
library(Hmisc)
rcorr(as.matrix(df))

It will give you the different correlations and the p-values associated. The strongest significant correlation would be a good start to determine your variable of interest


Accessing JS Class/Object Variables Via Instance Methods and This - Execution Contexts

Question: First Question: Why is the value for this in getXArrow() equal to the Solution object? Shouldn't it equal the this value of the solution object which called it, which would be the Window object?
Second Question: Shouldn't the JS Engine travel up the scope chain of each function to find the value of x? The scope of getX() and getXArrow() don't have x, so the JS engine would check their caller (the Solution object) and find x: 10, as declared in the constructor. Instead, it seems to jump up to the global scope?
let x = 5
class Solution {
    constructor() {
        this.x = 10
    }
    getX() {
        console.log(this);
        console.log(x);
    }
    getXArrow = () => {
        console.log(this);
        console.log(x);
    }
}

s.getXArrow() // Output: Solution
              //         5
s.getX()      // Output: Solution
              //         5

Thank you!
Comment: JS has lexical scope, it doesn't matter who the caller is. There is only one `x` variable in your script anyway - a property is not a variable.
Comment: A class method's `this` is the instance object itself, by default. class members are not hoisted into the lexical scope like they are in other langs; you have to use `this.x` to reach _that_ `x`
Comment: Please ask a single question per post only. Btw, your first question can be easily researched by looking for how arrow functions work.
Answer: getX just has two scopes accessible: It's own function scope and the global scope. Classes don't create a scope, and thus x cannot be accessed. You do however have access to the instance via this and can access its .x property.


Jquery after ajax loaded in view

Question: So I created a view listing all the users. I implement a search form with autosubmit function.
The autosubmit works with an ajax script.
Into my page view, I changed a few things in Jquery like this (main.js) :
<code>$(document).ready(function(){
    //code for others pages.....
});

$(document).ajaxComplete(function(){
   $('h2').text('filters');
});
</code>
But when I filter my list of users, the ajax script is loading and after that, Jquery changes do not appear due to ajax load.
Do you know a trick to keep Jquery changes when ajax script is loading ?
Thanks for your help !
Answer: Try this:
Add an ajaxComplete function
<code>   $( document ).ajaxComplete(function() {
      $('h2').text('filters');
    });
</code>
Comment: I edit my post btw, It does not work
Comment: @CorentinBranquet I assumed you were just focusing on the snipped rather than the entire code. Since I thought you got the document ready function to work.
Comment: It works for me.
Answer: Find the solution below:
<code>(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('#views-exposed-form-recherche-artiste-page', context).ajaxSuccess(function(){
         $('h2').text('filters');
      });
    }
  };
})(jQuery);
</code>
Comment: Tried your solution but it still not working for me. Should i change something else apart from my view ID? i'm using Views Load More, and my code doesn't work after getting more news in my view

Jquery after ajax loaded in view


Texto já escrito no textarea bloqueado

Question: Tenho o seguinte textarea já com uma parte do texto digitado:

<textarea class="form-control" id="text1" name="text" style="overflow: hidden; word-wrap: break-word; resize: none; height: 160px; width: 100%;">Estimado Familiar, pedimos que traga para o utente o seguinte produto: </textarea>

Pretendo que este texto digitado não seja possível elimina-lo, mas que permita acrescentar o nome do produto (acrescentar mais texto).
Neste caso permite acrescentar mais texto, mas o problema é que permite eliminar partes da frase ou a frase em completo
Comment: Por que não usa dois campos, com um deles acessível para o usuário digitar e junta tudo depois quando for enviar para o servidor?
Comment: Então não seria mais simples fazer um input text simples que a pessoa apenas insira o nome do produto? Se o texto é fixo, você pode inseri-lo quando for tratar as informações do formulário.
Comment: @Woss  pretendo que o texto fique visível para o utilizador. Eu já consegui fixar o texto com uma div, mas não fica como pretendo visualmente, veja aqui: [exemplo](https://i.stack.imgur.com/lB6iC.png), mas pretendia que o texto ficasse dentro das linhas da folha.
Comment: Cara a melhor forma de fazer isso, ou pelo menos a mais fácil, e fazer um text área falso... o texto vai parecer que está dentro, mas na verdade está fora... Ficaria tipo assim, sendo que a caixa de texto começa da linha vermelha para baixo http://prntscr.com/q3ak9c
Comment: @hugocsl e como posso fazer isso
Comment: Vou fazer uma resposta
Comment: @hugocsl  obrigado
Answer: Não é uma resposta super sofisticada, mas é algo que pode te ajudar de maneira bem simples, sem JS ou regex.
Eu fiz um box, imitando que é um textarea e a frase na verdade fica fora do textarea. Só tenha em mente que vc tem que fazer alguns ajustes de acessibilidade colocando role="textbox" na div para ela semanticamente fica mais coerente, o taxtarea continua sendo acessível pelo tab o que é bom, mas eu tive que "transferir" o outline do :focus da textarea para a div, para isso usei o css :focus-within, assim quando vc clica no textarea dentro do box, o box que vai receber o outline

Lembre de deixar tudo acessível com role e aria na div, e for na label que tem o texto do  textarea!
Segue o código da imagem acima

.box {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  padding: 0.2em;
  width: 600px;
  height: 200px;
}
.box:focus-within {
  box-shadow: 0px 0px 0px 2px cornflowerblue;
}
.box label {
  margin: 0;
  padding: 0;
  width: 100%;
}
.box textarea {
  resize: none;
  outline: none;
  padding: 0;
  margin: 0;
  border: none;
  width: 100%;
  height: 170px;
}

  Estimado Familiar, pedimos que traga para o utente o seguinte produto:
  <textarea name="" id="lista" ></textarea>

Comment: @Bruno Cara agora já estou no trabalho fica difícil fazer essas coisas. mas pelo que vi na imagem sua textarea está herdando alguns estilos do pai, da div que está dentro.... vc tem que limpar esses estilos de textarea, coloca background none nela, coloca tb outline none como eu fiz no exemplo, se precisar coloca position:relative no box pai, e na textarea alinha com bottom/left... Em último caso abre outra pergunta pedindo ajuda com esse alinhamento, explica a situação e coloca seu código mais atual e completo ok!!
Comment: já resolvi. Obrigado
Comment: era mesmo isso que procurava, mas estou a ter dificuldade em ajustar a label e textarea sem se perceber que são duas coisas diferentes, vê como fica: [o meu resultado](https://i.stack.imgur.com/7ItkB.png), podemos falar no chat só para ajustar o css que tinha com o css da box?
Comment: @Bruno boa jovem! legal que resolveu ai!

Texto já escrito no textarea bloqueado


Can I set up the server so that a leading slash in the filepath doesn't go to root?

Question: I'm working on a friend's site, which works fine live, but isn't working on my computer.  After tearing my hair out for a while, I figured out it's because he wrote all his links with a leading slash.
For example, if the file www.fruitsandstuff.com/apples/index.php was to link to www.fruitsandstuff.com/apples/images/redapple.jpg, then he would write .  On the live site that works, but on my computer, it goes to the root path and looks for the images folder there.
Is there something I can do to make all this code work on my computer, without going through 50+ files and changing the slash on every single link?
I'm using XAMPP.  I am also totally new at this and very confused.
Answer: The easiest thing would be to put his code in the root of the htdocs.  If you need to, it would be possible to modify the apache config so that there is a separate virtual host, and have his code be in the root of the document root of that virtual host.


How to store value from an sql query to a variable in node js?

Question: I'm using mysql with nodejs for the first time and I wish to enter the result from an sql query in my webpage through an asynchronous function. I am able to get the correct result but unable to store it within a variable and then use it as an input value.
I've tried using this but this doesn't provide a viable solution. I tried returning the value as well. Also will it be advisable to process the query outside the async function or inside it?
(async function Ahmedabad() {
      let i = 'select RegNumber from Details ORDER BY RegNumber DESC LIMIT 1;';
  await  con.query(i, [true], (error, results, fields) => {
    if (error) {
      return console.error(error.message);
    }
    let x = results[0].RegNumber;
    console.log(x);      // <------- Shows correct value
  });
  console.log(x);        // <------- Says x is not defined
})()

I want to store the value into a variable and then use it further.
Comment: "*I've tried using this but this doesn't provide a viable solution.*" Can you elaborate a bit as to why a near-exact duplicate of your question doesn't provide "a viable solution"?
Comment: Because there is only one answer to that question and that doesn't work either.
Comment: Can you elaborate on the statement "*doesn't work*"? It does point out the fact that the code should return a `Promise` object to be handled accordingly.
Comment: There is probably some error in the way the promises are handled in the answer provided, I keep getting "Cannot read property 'then' of undefined".
Answer: You've defined x in the callback scope, so it's not accessible out of the callback.
Try this:
(async function Ahmedabad() {
      let i = 'select RegNumber from Details ORDER BY RegNumber DESC LIMIT 1;';
  let x;
  await  con.query(i, [true], (error, results, fields) => {
    if (error) {
      return console.error(error.message);
    }
    x = results[0].RegNumber;
    console.log(x);      // <------- Shows correct value
  });
  console.log(x);        // <------- Says x is not defined
})()

But to be honest you should think about the whole design of your code))


TextBox mascara de valor de 2 até 4 casas decimais em WPF C#

Question: Gostaria que meu TextBox tivesse a seguinte "mascara"
Quando eu colocar duas casas depois da virgula:

0,00

ou quando eu colocar três:

0,000

ou quando eu colocar 4:

0,0000

Meu código no WPF C# e o seguinte:
<code> <TextBox  x:Name="ValorProdutoTextBox"
  Text="{Binding ValorProduto, NotifyOnValidationError=true,
  ValidatesOnExceptions=true,  ConverterCulture='pt-BR'}"
  UpdateSourceTrigger="ValorLostFocus"
   Height="20"
   Width="100" Margin="1" />
</code>
O resultado esta vindo sempre como determinado pelo 'Binding ValorProduto' que está no banco de dados (DECIMAL 15,4)

0,0000
Comment: Você tentou  adicionar um `StringFormat=N2` no seu binding?
Comment: @LeandroAngelo o n2 somente vai duas casa decimais.
Answer: Segue o exemplo do código:
<code><TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />
</code>
Resposta original: StackOverFlow Inglês


Find ISBN of a list with many books

Question: I have a list of books titles, and want to attach the ISBN to each one of those automatically. Each book is located in a .csv file. Any ideas if that is possible online?
Thanks!
Comment: Any ISBN version will do!
Comment: Different editions of a book have different ISBNs, so it is unlikely to find any accurate method to do this.
Comment: @OliverAmundsen did you do an app for this? I have need of a script/app for this.
Answer: Install the python package isbntools and you can use the command isbn_from_words "author title" to get the most probable ISBN.

Find ISBN of a list with many books