If $(^0E)^0=E$ for every closed subspace $E\subset X^*$ then $X$ is reflexive.

Question: Let $X$ be a normed vector space, $X^*$ be its dual and $X^{**}$ be its bidual.
For every $E \subset X^*$ we define the left-annihilator of $E$ as
$$^0E=\{x \in X : f(x)=0 \ \forall f \in E\}.$$
And for every $F \subset X$ we define the annihilator of $F$ as
$$F^0=\{f \in X^*: f(x)=0 \ \forall x \in F\}.$$
It is easy to see that $E \subset (^0E)^0$.
Suppose that for every closed subspace $E \subset X^*$ we have
$$E = (^0E)^0.$$
I want to prove that it implies $X$ is reflexive.
So, we want to show that the natural isometric linear injection $J_X:X \to X^{**}$, $J_X(x)(\varphi)=\varphi(x)$, is surjective.
That is, given $\Psi \in X^{**}$ there is $x \in X$ such that for every $\varphi \in X^*$ we have
$$\Psi(x)(\varphi)=\varphi(x).$$
These are some ideas I had but I didn't know how to use them:
Define $E:=null(\Psi) \subset X^*$. I think we should consider the case $E\neq X^*$ and then pick the $x\neq 0$ in
$$\bigcap_{f \in E}null(f),$$
that is, $x \in (^0E)$.
I also know that we have a natural isometric isomorphism $\Phi: X^*/E \to (^0E)^*$, $\Phi([f])=f|_{(^0E)}$.
I appreciate any ideas or comments!
Answer: This should follow from the following facts:

$(^0E)^0 = E$ if and only if $E$ is weak-$\star$ closed
$\operatorname{null}(f)$ is closed if and only if $f$ is continuous
$\operatorname{null}(f)$ is weak-$\star$ closed if and only if $f$ is weak-$\star$ continuous if and only if $f$ belongs to the image of $J_X$.
Comment: This is sometimes known as the 'bipolar theorem' and often formulated in terms of topological vector spaces, see, e.g., Nonsmooth Analysis by Schirotzek, Prop. 2.3.3. It basically follows from the Hahn-Banach separation theorem (formulated in topological spaces).
Comment: Thanks for the answer! Can you explain or give some reference to this first result?


Collaborative remote music recording

Question: Is there a network of musicians who can record musical phrases/tracks for other musicians?
I an an amateur musician, I write and record songs (voice, guitar, and virtual instruments such as keyboards, drums, etc.). What would be really cool is to replace some virtual instruments with real ones. For instance in one of my recent tunes there is a musical phrase in chorus that would sound really good if played by brass instruments (instead of a synthesizer). I don't know anybody who plays brass instruments. But surely there are people on the globe that can play and are willing to record something for other people (and get something recorded for them if they need).
The process can be something like this:

Provide mp3 track with the draft of the tune (with the instrument to be recorded played using a virtual instrument).
Provide mp3 track without the melody.
Provide mp3 track of just the melody.
Receive recorded track.
Receive mp3 of recorded track merged with the original mp3 track without the melody.

So i thought is there an existing internet community of musicians who record and exchange music recording for production of their own music?
Comment: This is a really cool idea, and one in which I would definitely participate in if it existed.
Answer: There have been several Web-based businesses that have built up around this idea over the years. Some are for amateurs and some are for professional session musicians. It's been awhile  since I have looked into this; if I come up with references I will post them here.
By the way, all of them will use MP3s only to provide "proof copies" for evaluation, but will provide full-bandwidth audio files in high-resolution formats such as FLAC, AIFF or WAV for actual recording and mixing.
Answer: I think You may be interested in
http://www.indabamusic.com/
This is very active community. And i think that You find musicians within amator and better range.
They also sport some contest where You can hook up with pro's
They also have online DAW but i disliked it.
I think it's worth Your attention. It has free Basic subscription plan - so You can see around if You find there what You looking for.
Answer: http://www.kompoz.com seems to work pretty well, linking musicians from all over the world.

Collaborative remote music recording


Bootstrap 3 form not working on mobile devices

Question: I have created this website using your theme; however the form is not working on the mobile devices http://www.qli.co.in/?page_id=297 only the first field works and rest do not work per div.
Here is my code:

Contact Details

                        <input id="cmob" name="cmob" class="col-md-12" type="text" placeholder="Mobile Number" title="Please enter a valid mobile number" pattern="\d{10}" required />

                        <input id="landnum" name="landnum" class="col-md-12" type="text" placeholder="Landline Number" />

                        <input id="cemail" name="cemail" class="col-md-12" type="email" placeholder="Email Address" title="Please enter a valid email id" required />

                        <textarea id="address" name="address" class="col-md-12" rows="1" placeholder="Address" required></textarea>

EDIT:
The form tag has been included. When we focus on the input box in mobile browser the input keyboard does not appear automatically
Comment: What is "not working?" And I don't see a form tag.
Comment: The form tag has been included. When we focus on the input box in mobile browser the input keyboard does not appear automatically.
Comment: Would you please add this information to your quesition? It is pretty hard to guess what your actual problem is.
Answer: You have some issues on your floating elements, their parents aren't wrapping them.
You can see on the image that the next element is covering the input fields.

To fix this you need to do this on your css.
.form-inline span {
  display:block;
}

.form-inline span:after {
  content: "";
  clear: both;
  display: block;
}

.form-inline .col-lg-12 {
  clear:both;
}

Comment: Thanks a ton Robin.. Worked like charm. :)
Answer: It's a bit of a late response, but worth mentioning. I had this error a while back and although a little CSS trickery will do the job, I found the best solution is prevention - by structuring your page as the Twitter developers intended.
This issue happens when you fail to make good use of the row class. You must lay your page out a row at a time.

        // Here you can start building your columns

// now we start a new row

        // Here you can start building the columns for the second row

If you fail to structure your page in this way, bugs can appear in your code. One of the said bugs is where the inputs are overlayed by other elements, as the OP experienced here, thus preventing them from interacting with smaller devices.
I hope this helps someone in the future


MSA70 Upgrade options

Question: Recently I purchased MSA70. Unfortunately I did read specs properly.
In my project, I need as much I/O operations as possible.
MSA70 is only 3Gbps, so my question is: is it any possibility to upgrade it to 6gbps, by replacing/adding better controller to pcie slots maybe?
Comment: IOPs is not the same as bandwith. Check [this](https://stackoverflow.com/questions/15759571/iops-versus-throughput) for clarification.
Answer: No. There's no upgrade option with your existing hardware.

If you need 6Gbps, locate an HPE StorageWorks D2700 enclosure.
If you need 12Gbps, locate an HPE StorageWorks D3700 enclosure.
Comment: Thanks for clarification.

MSA70 Upgrade options


uncut files AWK : Random and strange

Question: By using AWK (1.3.3) for Windows, we encountered a problem random and strange
We use AWK to cut csv files to integrate more easily into our application. The files arrive in the import directory every 9 minutes and are cut and then loaded, during all the day. The problem is that sometimes the files are not cut. This can happen one or more times in the same day or never.
When we return again not cut files in the import directory, cutting works well!
Does anybody have already encountered this problem and has an idea of the cause?
We use awk in .bat file like this:
<code>REM arg1 = file to split
REM arg2 = max size
REM arg3 = destination folder
REM arg4 = AWK folder
REM If file arg1 size is smaller than arg2 then use column 1 else use column 3
cd %3 & if %~z1 LSS %2 (%4awk -F; "{print >> $1\".csv\"}" %1) else (%4awk -F; "{print >> $3\".csv\"}" %1)
</code>
Thank you in advance for your feedback
Answer: If by "the files are not cut" you mean that the whole lines are printed instead of just one column, then it might be a problem of file separator, for instance if some csv files have ',' as a file separator instead of ';' and you would have to change -F; by -F';|,'.
The best would be to see a problematic file individually.
Comment: Thank you for your response.

By "the files are not cut" I mean that nothing is happen, the target directory is empty.
I don't think that problem come from files, because when I return again not cut files in the import directory, cutting works well.
Comment: I don't know if there is a problem with an escape character. You could try replacing " by ' and \" by "... Otherwise, could it come from the batch script itself? You could test if you actually are in one of the "if" cases and see if awk doesn't give any output.

uncut files AWK : Random and strange


Using a "normal" constexpr function argument in a template

Question: Let's say I have this function:
constexpr void foo(size_t x)
{ }

And this template:
template<size_t X>
class bar;

Would it be possible to instantiate an instance of template bar with the constexpr size_t x inside the foo function if I know that I will always constexpr evaluate that function (C++17)?
Answer: If I understand you correctly you want this:
constexpr void foo(size_t x)
{
    bar<x> b{};
}

This is not possible because a constexpr function can be evaluated at runtime, in which case the argument x is not a compile time constant.
What you need to do is make the argument a template argument instead:
template <size_t X>
constexpr void foo()
{
    bar<x> b{};
}

// call it like this:
auto test()
{
     foo<24>();
}

Comment: That is not possible unfortunately because im calling the foo function from another constexpr function, which has it as a normal parameter.
Comment: @AndreasLoanjoe and what is the problem that prevents you to call `foo` like this?
Comment: I got the value passed into a constexpr function by value not as template parameter before I want to call foo. Lets say the test function above is also a constexpr function and got size_t as argument how would you do it then.
Comment: @AndreasLoanjoe you cannot use a function parameter for the reasons I told. You need to apply the same treatment up the call stack, i.e. make the `x` template argument all the way.
Comment: :( Will this change with constexpr bang functions or consteval in 20?
Comment: @AndreasLoanjoe I think consteval and constexpr bang were competing and since consteval made it into the standard I suppose constexpr bang is abandoned. I don't know if it should work with consteval, but both gcc and clang reject the code atm even in consteval function


Cross entropy loss function and division by zero

Question: I'm trying out the cross entropy loss function for neural network training, per the arguments at https://jamesmccaffrey.wordpress.com/2013/11/05/why-you-should-use-cross-entropy-error-instead-of-classification-error-or-mean-squared-error-for-neural-network-classifier-training/ as to why it's better than mean squared error.
However, I'm getting division by zero errors leading to infinite weights. Looking at the formula for it e.g. as implemented in the tiny-cnn library,
class cross_entropy_multiclass {
public:
    static float_t f(float_t y, float_t t) {
        return -t * std::log(y);
    }

    static float_t df(float_t y, float_t t) {
        return -t / y;
    }
};

in one sense this is not surprising, as it will give division by zero every time the current output of a neuron, y, happens to be zero.
In another sense it is surprising; if this were a known problem with cross entropy loss, I would expect it to be mentioned in some of the discussion I looked at.
Am I doing something wrong, or is there some sort of bug in tiny-cnn, or what else am I missing?
Answer: Your output neuron should be a sigmoid function (which ensures your values are between 0 and 1 exclusive)
Comment: Sigmoid can output zero or almost zero causing error in division when computing gradient.
Answer: You can compute gradient of cross-entropy loss and softmax activation combo or logistic loss and sigmoid activation combo in single step.
You will see no gradient between loss and activation of last layer but you will have simple gradient function for combo, like just (labels - predictions).


How to integrate Imebra v5 to a swift command line project

Question: I'm trying to import Imebra into a basic swift 5 command line project using Xcode 12. I followed the official steps but I failed. I can summarise the whole structure:
The structure of the project is just
./
├── main.swift
├── Data
   └── DX_0.dcm
├── Imebra
   └── CMakeLists.txt
   └── docs
   └── examples
   └── library
   └── test
   └── wrappers
   └── build_imebra_macos

The main swift file is
// main.swift

import Foundation

print("Hello, Imebra!")

do {
   let pDataSet = try ImebraCodecFactory.load(fromFile: "PathToDicomFileFromExecutable")
    let pImage = try pDataSet.getImageApplyModalityTransform(0)
   print("The image width is", pImage.width)
} catch {
   print(error)
}

Following the documentation, I compile the library by going to the build_imebra_macos folder and running
build_imebra_macos % cmake -GXcode -DCMAKE_BUILD_TYPE=Release ..
build_imebra_macos % cmake --build . --config Release

The build is successful and the new folder Release has the dynamic library. Now in Xcode project of the CL Swift application, SwiftyImebra.xcodeproj, I followed the next instruction "open the target Build Settings and under "Swift Compiler/ObjectiveC Bridging Header" specify the path to imebra_location/wrappers/objectivec/include/imebraobjc/imebra.h.", with Imebra_location changed to Imebra.
Then when I build I get the error
Showing All Messages
Undefined symbol: _OBJC_CLASS_$_ImebraCodecFactory

I'm new in Swift and I guess I need to specify somewhere in Xcode where the source or the dynamic library is. However, I am not sure about this either as we have generated a cpp dynamic library so this can only interact with objective-C (?). I apologise if this is a basic question...
In addition, I'd like to learn how to use Imebra as a static library with swift.
Answer: The imebra dynamic library must be added to the project.
Drag the imebra.dylib (generated into your build folder build_imebra_macos) into your project.
Additionally, specify the folder containing the dylib into the "Library search path" in the compiler options.
Comment: Hi Paolo! After dragging the generated .dylib files into "Link Binary With Libraries" (Build Phases) and specifying the Library Path I got at runtime:
```dyld: Library not loaded: @rpath/libimebra.5.dylib
  Referenced from:
PathToDerivedDataFolder
  Reason: no suitable image found.  Did find:
 /usr/local/lib/libimebra.5.dylib: code signature in (/usr/local/lib/libimebra.5.dylib) not valid for use in process using Library Validation: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?)
```
Comment: I would not like to remove the validation layer. I checked the signatures again and they are in development.
Comment: Move the library to the location where the executable is so it can find it when it runs, or configure xcode to copy the dll to the executable location.
Comment: I found out that the dylib must be also build with Team ID. It didn't need to copy/move the dll to the executable as long as the folder was specified in "Library Search Paths". Xcode12 seems to be more restrictive
Comment: A better way though, would be to use XCODE_EMBED_FRAMEWORKS and set the target PROPERTY `XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY` to TRUE. Could you maybe add this hints as well to your answer and I will accept it?
Comment: The hardcoded, not recommended, way was to change the Imebra's main project CMakeList.txt file with
```cmake
project("imebra")
# Signing & Capabilities
set(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM   "YOURTEAM")
set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Development")
```
and then generate and build as in the Description of this question.


Merge-Sort implementation / suspecting mistake in recursive call or while merging

Question: any help with this mess is appreciated. The task here is to sort an array of integers that differ from zero. I think i made two mistakes which i cant manage to solve.
first: i think i made a mistake at the recursive call. The bounds seem to be set the wrong way while merging
second: i also think the sorting process has several errors too
<code>    static void mergeSort(int[] init, int lower, int upper) {
    if (lower < upper) {

        int mid = (lower + upper) / 2;
        mergeSort(init, lower, mid);
        mergeSort(init, mid+1, upper);
        merge(init, lower, mid, upper);
    }
}

static void merge(int[] init, int lower, int mid, int upper) {
    int length1 = mid - lower;      //length of first subarray
    int length2 = upper - mid;      //length of second subarray

    int[] leftArray = new int[length1+1];     //creating left subArray
    int[] rightArray = new int[length2+1];    //creating right subArray

    for (int i = 0; i < length1; i++) {       //copying positions from left partition to left subArray
        leftArray[i] = init[lower + i];
    }

    for (int i = 0; i < length2; i++) {       //copying positions from right partition to right subArray
        rightArray[i] = init[mid+i];
    }

    int i = 0;                                //sorting
    int j = 0;
    for (int k = lower; k < upper; k++) {
        if (leftArray[i] <= rightArray[j]) {
            init[k] = leftArray[i];
            i++;
        } else {
            init[k] = rightArray[j];
            j++;
        }
    }
}
</code>
Answer: Wasn't this the recommended way to do the merge sort step-by-step using static methods:
<code>public static void mergeSort(int[] init, int arrayLength) {
    if (arrayLength < 2) {
        return;
    }
    int mid = arrayLength / 2;
    int[] left = new int[mid];
    int[] right = new int[arrayLength - mid];

    for (int i = 0; i < mid; i++) {
        left[i] = init[i];
    }
    for (int i = mid; i < arrayLength; i++) {
        right[i - mid] = init[i];
    }
    mergeSort(left, mid);
    mergeSort(right, arrayLength - mid);

    merge(init, left, right, mid, arrayLength - mid);
}

public static void merge(
  int[] init, int[] left, int[] right, int leftLength, int rightLength) {

    int i = 0, j = 0, k = 0;
    while (i < leftLength && j < rightLength) {
        if (left[i] <= right[j]) {
            init[k++] = left[i++];
        }
        else {
            init[k++] = right[j++];
        }
    }
    while (i < leftLength) {
        init[k++] = left[i++];
    }
    while (j < rightLength) {
        init[k++] = right[j++];
    }
}
</code>
Call "mergeSort" with the 1st parameter being the array to be sorted and the 2nd parameter being it's length.
Cheers!


convergence in probability to a constant

Question: I have a sequence of random variables $X_n$ defined on $\Omega =[0,1]$ by $X_n(\omega)=\omega n$. Let $\mathbb{P}$ be the Lebesgue measure on $[0,1]$.
Does $X_n \rightarrow 0$ in probability?
I know that if $X_n$ converges in probability to a constant then $ \lim_{n \to \infty}\mathbb{P}(|X_n-c|\gt\epsilon) = 0$
I am confused on the next step for proving or disproving this.
Thank you
Comment: First, note that convergence in probability suppose you have a probability on your space, and depends on that probability. What is the probability $\mathbb{P}$ ? The lebesgue measure ?
Comment: Yes the lebesgue measure
Answer: Hint : if you want to show that $X_n$ doesn't converge in probability to $0$, all you have to do is make sure that $\mathbf{P}(|X_n|>\epsilon)$ does not goes to zero. But
$$\mathbf{P}(|X_n|> \epsilon) = \mathbf{P}(\omega : |\omega n| > \epsilon ) = \mathbf{P}(\omega : \omega > \epsilon / n)$$ which can be computed : if $\mathbf{P}$ is the Lebesgue measure, then
$$\mathbf{P}(\omega : \omega > \epsilon / n) = 1- \frac{\epsilon}{n} $$
Comment: Ah yes. Thank you. Do you mind elaborating a bit on the steps you took to arrive at last statment LHS=RHS wise, sorry I am a bit rusty.
Comment: It's the basic property of the Lebesgue measure : if $a \epsilon) = \mathbf{P}(\omega > \epsilon^{\frac{1}{n}}) = 1 -  \epsilon^{\frac{1}{n}}$. As $n \to \infty$, you have $1/n \to 0$ and $\epsilon^{\frac{1}{n}} \to 1$, so the overall thing goes to zero.


where does the actual parameter go in the closure function?

Question: I am doing my 1.1 learning ( means very basic ) on Javascript, now i am stuck in the chapter of "the closure function", here are my codes..

function a() {
  let n = 0;

  function b(m) {
    n = m + n;
    return n
  }
  return b
}

let c = a();
console.log(c(3)); // result: 3
console.log(c(3)); // result: 6
console.log(c(3)); // result: 9
console.log(c(3)); // result: 12

so, I know when i give an actual parameter 3 to c, that at same time means give the actual parameter 3 to function a, like a(3), but how it goes automatically to add itself to formal parameter of function b to add itself again and again and end up being 6,9,12......etc. ?
in other word, I didn't set any formal parameter in function a to catch the given actual parameter, how did all these happen ?
thanks a lot !
Comment: At the moment `c` is not a function (so your code will throw an error). Did you mean to `return b` in your example?
Comment: `let c = a()` here `a()` returns function `b()` which has closure to `n`,  now when you do `c(3)` you're actually passing value to `b(3)` and inside `b` you're doing `n = m + n` so it increases value of `n` by passed parameter everytime you call it
Comment: hey, sorry I did a typo, in the end of function a, it should be return b, NOT return b(),
Comment: since "c is not a function " was said, but how did c(3) works, i was taught that everytime you want to use a function just put () after, (roughly),
Comment: @CodeManiac  I got it ! thanks bro!
Answer:
I know when i give an actual parameter 3 to c, that at same time means
give the actual parameter 3 to function a, like a(3)

This is not the case, when you give the actual parameter 3 to c, it becomes the formal parameter of the function b. Here's why:
When you return b, you're returning a function, which is yet to be called. So, you can visualize the line let c = a() as so:
let c = function b(m) {
  n = m + 0; // m + n becomes n + 0, because `n` is set to `0` initially in `a`
  return n
}

So, when you later call c(3), you're actually calling the function returned by a (ie: function b). This means, 3 becomes the formal parameter of b, which is then used as the value of m in your function.
And so, each time you perform an increment on n (by doing n = m + n), your value for n the next time you call c will be the sum of previous values passed through into c.
Answer: let c = a()

here a() returns function b() which has closure to n, now when you do c(3) you're actually passing value to b(3) and inside b you're doing n = m + n so it increases value of n by passed parameter to c() every time you call it

Watch out the debugger section of image to see what actually c has clsoures

function a() {
  let n = 0;

  function b(m) {
    n = m + n;
    return n
  }
  return b
}

let c = a();

console.log(c(3)); // result: 3
console.log(c(3)); // result: 6
console.log(c(3)); // result: 9
console.log(c(3)); // result: 12
Answer: When you are calling c(3) it basically calls b function with parameter 3. When you are calling a() it creates a new instance of the function, and the n variable equals 0. Calling c(3) will change the value to 3, cause it updates the n value with the calculated expression (0 + 3). And so on. Calling another c(3), will update n param of your instance of function with 3 + 3. I hope it helps u understand it.


Nfc-V tag reading example?

Question: Could somebody provide an NFC-V tag reading example code?
Android Development Guide provides only the NFCDemo code that is for NDEF tag only. There are no resources for all the other kinds of tags. Thanks!
Answer: Reading block 0 demo working for an 15693 i-code sli
<code>ByteArrayOutputStream out = new ByteArrayOutputStream();

out.write(new byte[] { (byte)0x20, (byte)0x20 }); //addressed mode,  read single blocks,
out.write(nfcV_tag.getTag().getId()); //address
out.write(new byte[] { (byte)blockIndex }); //block 0

byte errorcode_and_block0[] = nfcV_tag.transceive(out.toByteArray());
//1st byte should be 0 if everything is ok. next 4 bytes are block 0
</code>
Answer: Well - With Android 2.3.4 you can use the ordinary NDEF format and use the usual android API to write to the tag just like any other ndef complient tag. NFC-V has been the major feature for Android 2.3.4 after all.
If you otherwise want to communicate with the NFC-V tag: It's nothing more then the ISO 15693 standard. You should be able to find the PDUs that this tag understands with a google-search and then you can roll your own implementation if you really want.

Nfc-V tag reading example?


Does anyone used a zoom g1x four with bias fx?

Question: So I always wanted to cover marooned by pink floyd but it never hit home for me since I don't own a pitch shifter pedal I only use bias fx2 via my audio interface I was keen to buy this cheap zoom multi effects so I can use it's built in pitch shifter but then I realized that you can only put up to 5 block of units in your signal chain, so with a amp and cab it only left you with 3 other effect which isn't enough if you are going to get that tone
I was wondering that does anyone ever used this multi effect with bias fx? Without messing up the guitar tone or signals?
In theory you should be able to use noise gate/comp/drive/amp/cabin on zoom and get your reverb and echo on the bias fx
But I'm not sure if it will work out alright in reality
Edit: in case of me not being clear enough with my question since both of these devices (bias and zoom) are digitally manipulating the signal from your guitar I was wondering the result (the quality of the sound and tone of your guitar) would be usable for recording at home  or live performance or we will get a very thin weak unsatisfying sound at the end
I know the quality of your tone and sound of your guitar is subjective matter  but I was hopeful to find someone who used these 2 together and ask him about the end result
Comment: Could you perhaps make your title more reflective of what you are actually trying to achieve, rather than asking if anyone else uses something? That just not searchable for future visitors. One would assume that the answer, if any, will come from someone who does use it, as opposed to someone who has never heard of it.
Answer: They will work beautifully together. The signals don't know that one is digital and one is analog. You can mix any digital with any analog and any digital with digital. It's just sound waves passing through your cables. So there's no compatibility issue. As long as the cable ends match, you're good. It really comes down to the quality of your effects.


VAR - ARCH LM Test results are conflicting

Question: I'm using the R package vars to model multivariate series with VAR of order p = 5. The multivariate series is:
$$
Y_t = \{y_{1,t}; y_{2,t}; y_{3,t}\}^\top
$$
In order to stabilize the time series, I calculated the relative differences (return) of each element:
$$
x_{i, t} = \frac{y_{t} - y_{t-1}}{y_{t-1}}
$$
When I test the residuals for heteroskedasticity with the function arch.test, which implements an ARCH-LM test, I get conflicting results.
For example, with arch.test(data.var, lags.multi = 1), I get:
> ht <- arch.test(data.var, lags.multi = 1)
> ht

   ARCH (multivariate)

data:  Residuals of VAR object data.var
Chi-squared = 27.663, df = 36, p-value = 0.839

which tells me to accept the null hypothesis. But when I run arch.test(data.var, lags.multi = 2), then I get:
> ht <- arch.test(data.var, lags.multi = 2)
> ht

   ARCH (multivariate)

data:  Residuals of VAR object data.var
Chi-squared = 295.84, df = 72, p-value < 2.2e-16

now the result is that I should reject the null hypothesis and hence my multivariate time series is heteroskedastic. If I continue increasing the lags.multi parameter, the p-value closes to zero.
Why different test lags result in a different result? Should I use another method to stabilize my time series?
Answer: The ARCH-LM test (be it multivariate or univariate) with $q$ lags tests whether there are ARCH effects at lags from 1 up to $q$. It tests the joint significance of coefficients $\alpha_1,\dotsc,\alpha_q$ in the equation
$$ x_t^2 = \alpha_0 + \alpha_1 x_{t-1}^2 + \dotsc + \alpha_q x_{t-q}^2 + \varepsilon_t $$
(I use different notation than in the Wikipedia article linked to above to stress that the dependent variable need not be a residual from an ARIMA model and to match your notation).
For $q=1$, it tests for ARCH effects at lag 1: $\text{H}_0:\alpha_1=0$.
For $q=2$, it tests for ARCH effects at lags 1 and 2 jointly: $\text{H}_0:\alpha_1=\alpha_2=0$.
These are different hypotheses so one could not say the result of the first test is in conflict with the result of the second test.
In your case, you do not find an ARCH effect at lag 1 but you do find them at lags 1 and 2 jointly. That suggests that the squared time series is autocorrelated at lag 2 but not lag 1.

If I continue increasing the lags.multi parameter, the p-value closes to zero.

That suggests the squared series has significant partial autocorrelations (significant ARCH effects) at higher lag orders as well; if that was not the case and the only significant autocorrelation was at lag 2, the $p$-values of the ARCH-LM test would decrease with increasing lag order as the single effect would be "diluted" in a test of joint significance of an increasing number of coefficients.
In sum, you seem to have an ARCH effect at lag 2 and likely higher lag orders, which means your data is conditionally heteroskedastic.


Condição onde si for encontrado o nome "teste" imprimi OK se nao imprimir NO

Question: este e o código que estou querendo resolver e seu resultado!
awk '{if ($0 ~ "teste") { print "ok"} else {print "no" }}' arquivo.txt
no
ok
no
no
no

como pode ver ele verificou cada linha si tinha o nome teste
e imprimiu ok e nas linhas que nao tinha imprimiu no !!
sei que o awk trabalha linha por linha!
queria q ele apenas me dissesse OK si tiver a expressão q eu busco ou NO caso nao exista!
Answer: Em awk:
awk '/teste/ {visto=1; exit} END {print visto ? "OK" : "NO"}' arquivo.txt

Explicação:

/teste/ { cosas } quando Awk encontra o texto "teste", executa o código em {}.
visto=1; exit} nesse caso, define uma variável booleana visto.
END {print visto ? "OK" : "NO"} quando termina, mira se a variável es 1 o no. Si ela é 1, imprime "OK"; de outra forma, imprime "NO".

Mai eu prefiro Bash:
if grep -q "teste" arquivo.txt; then
   echo "OK"
else
   echo "NO"
fi

Em una línea:
if grep -q teste archivo.txt; then echo "OK"; else echo "NO"; fi

Comment: muito obrigado mano! era isso mesmo que queria! com bash eu sabia fazer mais queria so com awk!  mais pod me explica como funciona não intendi algumas partes!
Comment: @socketplus claro!  Atualizada
Comment: muito obg! @fedorqui


Setting up a large Xcode project

Question: I have a large exiting C++ project involving:

4 applications
50+ libraries
20+ third party libraries

It all builds fine on Windows using VS8, Linux using QMake (project uses Qt a lot). I also build it on OS X using QMake but I was wanting to setup an Xcode project to handle it in an IDE. I'm struggling to setup proper configuration to easily define dependencies, both to internal libraries and to the third party. I can do property sheets and .pri files in my (disturbed) sleep, but would appreciate some advice on building such large projects in Xcode.
I've been experiencing with Xcode configuration files and #including one from another but it does not seem to work as I would expect, especially when defining standard locations for header files etc.
Is there some good book describing the process of setting up Xcode (remember it's C++, I'm not wanting to learn ObjC at this time)?
Or maybe a good open source project I could learn from?
Thanks!
Answer: Step in to Xcode may be the book you're looking for. It's got a whole section devoted to using AppleScript to automate configuration includes. I've been going through the book myself on O'Reilly Safari as I've found myself in a situation similar to yourself!
Comment: Be forewarned though, The applescript implementation in XCode4 is currently horribly broken. (I'm assuming that book was written in the XCode3 era)

Setting up a large Xcode project


Buddypress members area in blank in my live server

Question: Buddypress member area is showing blank in my live server but it is showing fine in my localhost. I have tried debugging it is not showing any bug. how can i get the members area back live.
I am using a windows server with PHP 5.6 and WordPress 4.9.8
Comment: Hey there, it seems you are making a statement, but I'm missing the question. Perhaps have a look at this! https://stackoverflow.com/help/how-to-ask
Comment: Where is the code you are having issues with?
Comment: its in live server. the code with local host is working fine
Answer: Please check the URL for the members list.
Localhost URL are not case sensitive but server URL are.
eg.

URL: abc.com/xyz/test.php
URL you keep in your code: abc.com/XYZ/test.php
abc.com/XYZ/test.php Works in local but fails on server


is there any identities on cotangent on a triangle inside two parallel lines?

Question: I came across some engineering paper and equation in the paper doesn't seem to make sense unless cot(A)=cot(-B) in the image below.
But I never heard of such identity before.
Can cot(A)=cot(-B) be true or it can't be true in general?
Comment: Just from the figure, we can vary $\angle A$ for fixed $\angle B$. Hence for fixed $\cot(-\angle B)$, we can have arbitrary values of $\cot(\angle A)$. Hence what you are claiming is not true in general, unless some other conditions are present.
Answer: $\cot A=-\cot B$ if $A+B=180°$
This is impossible because of the basic external theorem in triangles which asserts that external angle $(180°-B)$ is strictly larger than internal angles $A$ and the third on the top.
Send other detail on your equation. Maybe the problem is elsewhere
Hope this helps
Answer: No, it's only true in that diagram if B = 180° - A, and then you have two parallel lines, not a triangle.


Connect React/AJAX to custom module

Question: I am trying to create a mini-CRUD component on the Drupal 8 site. I am fetching data from an external source, and rendering it using ReactJS.
I wish to update the database when a user clicks a button in the React component.
<button
    onClick={() =>
        $.ajax({
            type: "POST",
            url: "../path-to-file/script.php",
            data: { id: 'some data' },
        })}
>
    click me
</button>

I have written the React component (index.js),
I have connected the React component to a custom PHP script with an AJAX script (script.php).
I have written a custom Drupal 8 module to handle the database updates (mymodule.module).

However, I can't figure out how to connect the custom PHP script (script.php) to the module (mymodule.module) to perform the updates.
Any help would be greatly appreciated!
Comment: It's unclear what you want to do.  When do you want to execute the script?  Find a drupal hook that executes at the desired timing, and use that hook in the module to execute the script.
Comment: Thank you Patrick, I want to execute the script when a user clicks a button. I have updated my question above to include that!
Answer: Using AJAX to let the user arbitrarily insert data into your database via a custom PHP script seems like a really bad idea because it opens a backdoor into Drupal by circumventing Drupal's security.
To do this the "Drupal" way, you can use the JSON:API module in core to handle CRUD operations.  This is way too broad a topic to describe in depth here, but Drupalize.me has a good (paid) tutorial.
This allows you to use JSON:API do CRUD on Drupal entities (nodes, media, taxonomy terms, and so on) using the same access permissions as the Drupal website.
To use this approach, you will need to configure the entities within Drupal so that they receive the data correctly when updated via JSON:API.
Instead of using a custom PHP script, I would create a new JSON:API Resource, which lets you do whatever kind of processing you want via a custom JSON:API endpoint.  By doing it this way, you get all the data sanitization benefits that are built into Drupal core.

Connect React/AJAX to custom module


Does a 2*2 chi-square test give the same results as a binomial test?

Question: This is a conceptual question. Suppose we have an experimental design with two grouping variables (e.g., the subjects are either male or female) and the variable we are measuring is a binary variable, like whether they are smokers or not - and we are interested in seeing whether the prevalence of smoking depends on gender.
I feel like both a binomial test and a 2*2 chi-square test would work in this case. For example, we could look at the proportion of yes responses in women and in men, and then compare whether one proportion was significantly different from the other (i.e., the binomial test). Alternatively, we could have a 2*2 contingency table with male/female and smoker/non-smoker and we could do a chi-square test.
My question is, would these two tests give the same results?
What would be the principled way of deciding which test to use in this situation?
Comment: Can you be more explicit about the binomial test you intend? For some of the things you might mean the answer to the title question may be 'yes', for others, 'no'
Answer: The basic concept is that they should be the same.
However, different statistical programs use slight variations
that give different answers. Several variations are illustrated here. I have chosen data for which
there is no significant effect. (In my experience, P-values vary less
in the case of significant effects.)
My fake data are as follows:
Gender\Smoke  Y   N   Tot
F            60  40   100
M           130  70   200

Output from R: Chi-squared test with Yates continuity correction.
a = c(60,40); b = c(130,70)
DTA = cbind(a,b); DTA
      a   b
[1,] 60 130
[2,] 40  70
chisq.test(DTA)

        Pearson's Chi-squared test with
         Yates' continuity correction

data:  DTA
X-squared = 0.51854, df = 1, p-value = 0.4715

Without continuity correction:
chisq.test(DTA, cor=F)

        Pearson's Chi-squared test

data:  DTA
X-squared = 0.7177, df = 1, p-value = 0.3969

Test of two proportions (two-sided alternative), with continuity correction:
prop.test(c(60,130), c(100,200))

        2-sample test for equality of proportions
        with continuity correction

data:  c(60, 130) out of c(100, 200)
X-squared = 0.51854, df = 1, p-value = 0.4715
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.17407255  0.07407255
sample estimates:
prop 1 prop 2
  0.60   0.65

And without:
prop.test(c(60,130), c(100,200), cor=F)

        2-sample test for equality of proportions
        without continuity correction

data:  c(60, 130) out of c(100, 200)
X-squared = 0.7177, df = 1, p-value = 0.3969
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.16657255  0.06657255
sample estimates:
prop 1 prop 2
  0.60   0.65

Output from Minitab,
Chi-squared test:
Chi-Square Test for Association

            Y       N  All

A          60     130  190
        63.33  126.67
       0.1754  0.0877

B          40      70  110
        36.67   73.33
       0.3030  0.1515

All       100     200  300

Cell Contents:      Count
                    Expected count
                    Contribution to Chi-square

Pearson Chi-Square = 0.718, DF = 1,
    P-Value = 0.397
Likelihood Ratio Chi-Square = 0.714, DF = 1,
    P-Value = 0.398

Test of two proportions (two-sided alternative).
MTB > PTwo 100 60 200 130;
SUBC>   Confidence 95.0;
SUBC>   Test 0.0;
SUBC>   Alternative 0;
SUBC>   Pooled.
        # Pooled estimate of common probability

Test and CI for Two Proportions

Sample    X    N  Sample p
1        60  100  0.600000
2       130  200  0.650000

Difference = p (1) - p (2)
Estimate for difference:  -0.05
95% CI for difference:  (-0.166573, 0.0665726)
Test for difference = 0 (vs ≠ 0):
   Z = -0.85  P-Value = 0.397

Fisher's exact test (two-sided alternative):
   P-Value = 0.446

.
MTB > PTwo 100 60 200 130;
SUBC>   Confidence 95.0;
SUBC>   Test 0.0;
SUBC>   Alternative 0.
      # Standard error uses 2 separate estimates

Test and CI for Two Proportions

Sample    X    N  Sample p
1        60  100  0.600000
2       130  200  0.650000

 Difference = p (1) - p (2)
 Estimate for difference:  -0.05
 95% CI for difference:  (-0.166573, 0.0665726)
 Test for difference = 0 (vs ≠ 0):
     Z = -0.84  P-Value = 0.401

 Fisher's exact test: P-Value = 0.446

Notes: [1]  Because of the squaring involved in computing the chi-squared test statistic, all chi-squared tests are inherently two-sided (even though one rejects in the right tail of the chi-squared distribution). [2] The likelihood ratio test uses an asymptotic chi-squared distribution. Pearson's chi-squared test uses a different approximation to a chi-squared distribution. [3] Fisher's exact test uses an exact hypergeometric distribution for one-sided tests; most computer
implementations double the P-value for a two-sided test (as shown here).
[4] Be careful to understand how each program expects data to be entered. For 'tests of two proportions', some programs expect you to
enter counts of 'success' and 'failures'; other expect 'successes' and 'total trials'.
Comment: This was a brilliant answer, and thanks for taking the time to generate a sample data set and to run the different tests on it!


C# .NET: Problems with query strings with character references

Question: I'm having problems creating a query string and sending it to another webpage.
The text I'm trying to send is long and has special characters. Here is an example:
Represent a fraction 1/𝘣 on a number line diagram by defining the interval from 0 to 1 as the whole and partitioning it into 𝘣 equal parts. Recognize that each part has size 1/𝘣 and that the endpoint of the part based at 0 locates the number 1/𝘣 on the number line.
I can send this just fine if I hand code it:

        Link Text

This goes through without any problems, and I can read the entire Query String on the other side.
But if I am creating the link programmatically, my query string gets cut off right before the first character reference. I am using the following setup in a helper function:
string url = "Default.cshtml";
url += "?standardText=" + standard.text;
Link Text

When I use this, I only get "Understand a Fraction as 1/" and then it stops.
When I look at the page source, the only difference in the links is that one has actual ampersands and the second is having those turned into &
<a href="Default.cshtml?standardText=Understand a fraction 1/&#120355; as the quantity formed by 1 part when a whole is partitioned into &#120355; equal parts; understand a fraction &#120354;/&#119887; as the quantity formed by &#120354; parts of size 1/&#120355;."

So the problem is not really the spaces, but the fact that the & is being interpreted as starting a new query string parameter.
I have tried various things [using HttpUtility.UrlEncode, HttpUtility.UrlEncodeUnicode, Html.Raw, trying to replace spaces with "+"], but the problem isn't with the spaces, its with how the character references are being handled.  When I tried HttpUtility.urlEncode I got a double-encoding security error.
On the advice of OmG I tried replacing all the &s, #s, and /s using:
url = url.Replace("&","%26");
url = url.Replace("#","%23");
url = url.Replace("/","%2F");

This led to the following link:
    All Items

And now when I click on the link I get a different security warning/error:
A potentially dangerous Request.QueryString value was detected from the client (standardText="...raction 1/𝘣 as the qua...").
I don't see why it is so hard to send character references through a QueryString. Is there a way to prevent Razor from converting all my &s to the &amp ; ? The address works fine when it is just plain "&"s.
Update: using URLDecode() on the string does not affect its character entity references, so when I try to decode the string then re-encode it, I still get the double-escape security warning.
Update: on the suggestion of @MikeMcCaughan, I tried using JS, but I am not very knowledgeable about mixing JS and Razor.  I tried creating a link by dropping a script into the body like so:

But no link showed up, so I'm obviously doing it wrong.
For reference, when I try to use @Html.Raw(url),
Link Text

The &s are still turned into &amp ;s. the link renders as:
Link text

Comment: Are you doing this in Web Forms or MVC?
Comment: Never mind, I saw the mention of Razor. You can use `@Html.Raw(url)` to get it to not convert `&` to `&`, IIRC.
Comment: @MikeMcCaughan, using @HTML.Raw() was one of the first things I did, and it works fine if I am just outputting the value of the string to the page, but when I try to use it inside the link with text, the &s are still converted to & ;s.
Comment: From my experimentation, the URL that ends up there, while it has `&` in the attribute, still passes `&` when you click on the URL. Is that not the case?
Comment: One question is, what is in `standard.text`? Does it have "" or "𝘣" in it?
Comment: It has 𝘣

The link is to another cshtml page that has

string standardText = Request.QueryString["standardText"];

and when I use @Html.Raw(url) as the link and then try to display it on the next page using

@Html.Raw(standardText)

The string is cut off. So I'm assuming that the value of QueryString["standardText"] is being truncated due to the &
Comment: A friend who worked as a .NET developer for many years indicated that I need to use "\u" instead of "&#x" to escape unicode strings... but unfortunately, that only works for hexadecimal strings.

When I replace 𝘣 with \U0001d623, it works great. [\U for 8-digit hex]
Answer: One simple solution is replacing the special characters by their encoding which can be accessed from here.
As you can find, replace in the string & with %26 using .replace for string. Also, replace / with %2F, # with %23, ; with %3B, and space with %20.
Also, You can do these in C# by the following function:
Server.URLEncode("<The Url>")

and in Javascript by the following function:
encodeURI("<The Url>")

Also, as you know the double-encoding is this. To prevent the double-encoding, you should have not encoded some part of the string before passing the string into the Server.URLEncode function.
Comment: When using Server.URLEncode(), I get the same double-encoding character error as I get with HttpUtilityUrlEncode().

When I try to replace & with "%26", the receiving page no longer is able to parse the query string at all. Request.QueryString["standardText"] returns an empty string.
Comment: See my update on the post: "Also, as you know the double-encoding is this. To prevent the double-encoding, you should have not encoded some part of the string before passing the string into the Server.URLEncode function."
Comment: I did not do the encoding. The data is provided to me.

Any idea why encoding &'s prevents query string from being readable?
Comment: Okay, actually I made an error when replacing the &s, but it did not fix the problem. I then tried replacing &s, #s, and \s, and I got an other security error: "A potentially dangerous Request.QueryString value was detected from the client..."
Comment: @DavidR So, you should apply `Server.URLDecode` on the string, then apply the encoder.
Comment: I tried that. Server.URLDecode does not appear to change character entity references, so I still get the same double-encoding error. The output of Server.URLDecode(url) still has entity references in it like 𝘣
Comment: One should typically use [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) rather than [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI), since the latter does not encode things like `&`.
Comment: @MikeMcCaughan, thanks for the note... sadly I'm not very good at combining Javascript with Razor.  I edited the main post with what I tried without success.


Practical Way Of Writing Natural Deduction Proofs

Question: Natural deduction has "natural" rules of deduction but has very "unnatural" and inpractical way of writing proofs as a trees. Is there some decently formalized way of writing natural deduction proofs that is useful in structuring everyday mathematical proofs?
Comment: To understand how natural deduction proofs are formally represented, you'd have to learn lambda calculus and the curry howard isomorphism.
Answer: What's unnatural about trees? They're an elegant way of capturing the structure of the proof: each node of the tree is labeled by a sentence and the deduction rule used to conclude that sentence, and the children of the node are the premises used by the rule.
If you just want to be able to arrange your proof on paper in a more efficient way, you can just make a numbered list of sentences, and next to each one indicate the rule used to conclude it, together with the numbers of the premises used. As long as you make sure that each item on the list (except the conclusion of the proof) is used as a premise for exactly one later item on this list, such a list captures exactly the same information as a proof tree.
In a comment to Bram28's answer, you write "I was thinking about paper friendly way of writing natural deduction rules (or very similar rules) so I can use it in my everyday work". If your everyday work is proof theory, then I can see the need for an efficient way of writing down formal proofs. But if your everyday work is doing (ordinary) mathematics, I'll suggest a much more efficient way of writing proofs, that mathematicians have been effectively using for centuries: natural language.
Answer: I find the Fitch notation that has very explicit subproof structures, and that have to be strictly nested inside each other to be most like 'natural' deduction. It certainly looks very different from the Wikipedia page on Natural Deduction, which is probably what you are looking at. The Wikipedia page does refer to several different sequential representations rather than trees, and one of those is the Fitch notation.  But please note that there are also sequential notations, such as the Lemmon System (System L), where assumptions can be discharged in any order ... which in my eyes is less 'natural' than the Fitch notation: when we do a mathematical proof, for example, we tend to discharge assumptions in the reverse order in which we introduce them, and that is exactly what the Fitch notation does. So again, in my eyes that is a much more 'natural' deductive system, even as there are many systems of 'natural deduction'.
Finally, I should mention that Fitch systems are characterized by having exactly one Introduction and one Elimination rule for each operator which, while mathematically elegant, does not always make for the most user-friendly system in terms of elementary inferences. For example, you won't find handy inference principles like Modus Tollens, Disjunctive Syllogism in a typical Fitch system. Also, Fitch systems typically don't have equivalence principles, such as DeMorgan or Distribution as part of their inference rules.  So, there are some systems, the best known one of which is probably Copi's system (with Conditional Proof (CP) and Indirect Proof (with IP), that have some of those additional inference rules, but that have these strictly nested subproof structures as well.
Comment: I was thinking about paper friendly way of writing natural deduction rules (or very similar rules) so I can use it in my everyday work. It looks like fitch has it's own deduction rules, which is not exactly what I wanted.
Comment: @Trismegistos I see.  Well, I still think the systems I listed still push you a little bit more in that direction than the tree format, so I think it might be a good place for you to start.  And please let me know what you come up with: I myself am always looking for more user-friendly systems of logic as well!


Running atop in a docker stack

Question: atop is a tool I install on all my servers to go and check out what was happening on a machine when debugging site events. Is there a nice "docker" way to run atop in your fleet, or should I just get atop running in the os below docker?
Related to this is all the other tools I love having to debug issues: strace, iotop, htop, tcpdump, perf, etc. What are people doing in production to cover this niche.
Answer: You can achieve this by running the container with --pid=host (See the Docker Run Reference;

In certain cases you want your container to share the host's process namespace, basically allowing processes within the container to see all of the processes on the system. For example, you could build a container with debugging tools like strace or gdb, but want to use these tools when debugging processes within the container.

An example of a Dockerfile to run htop created by one of the Docker Maintainers can be found here; https://github.com/jfrazelle/dockerfiles/blob/master/htop/Dockerfile (and many more great examples in that repository). An automated build of that image can be found on Docker Hub here; https://hub.docker.com/r/jess/htop/
Run it like this;
docker run --rm -it --pid host jess/htop

Comment: I guess one doesn't want to do that continuously, only for launching a special-purpose debugging container?

Running atop in a docker stack


Localization by a non-nilpotent as a polynomial quotient

Question: In Dummit and Foote, Exercise 15.18 (p. 727 3rd edition) one is asked to prove that for a commutative ring with unity $R$, and $f$ a non-nilpotent element of $R$, that the localization $R_f$ is isomorphic to $R[x]/(xf - 1)$.
I have done this, using the strategy outlined in the problem, using the universal property of $R_f$ proved in Theorem 36. The problem I have is this:
If $R_f \cong R[x]/(xf - 1)$ and $\phi:R[x] \to R_f$ is a surjective homomorphism, it stands to reason that $\text{ker}(\phi)$ should be $(xf - 1)$. I cannot show this directly. The surjective homomorphism I have in mind is, for:
$p(x) = a_0 + a_1x + \cdots + a_mx^m$
$\phi(p) = \dfrac{a_0}{1} + \dfrac{a_1}{f} + \cdots + \dfrac{a_m}{f^m}$
It is clear to me that $\phi$ annihilates $(xf - 1)$, so that ideal is contained in the kernel. What I cannot show is the other containment, or equivalently:
If $\phi(g) = 0_{R_f}$ then $g(x) \in (xf - 1)$. The trouble I am running into is that $R$ might be a "bad" ring, containing a lot of zero-divisors, $f$ might even be a zero-divisor (being non-nilpotent is a considerably weaker property), so the usual polynomial tricks of the division algorithm or using the irreducibility of $xf - 1$ aren't much use, here.
I feel I am missing something obvious....what is it?
Comment: I don't quite see why you "it stands to reason" should be true for an arbitrary such $\phi$. For the specific one you should be right, though I am still trying to think of a nice argument for it.
Comment: That is my problem exactly. I would (just for education's sake) be interesting in seeing an example of a surjective homomorphism $\phi$ that preserves unity between 2 commutative rings $R,S$ where $S \cong R/I$ for some ideal $I$ which is NOT $\text{ker}(\phi)$. Do you have a counter-example in mind?
Comment: Just take $R\times R$ to $R$ given by projecting on either factor.
Answer: The assumption, that $f$ is not nilpotent, is not needed and should be erased.
Instead of working with elements, you should work with morphisms (this is a general idea of category theory), because this simplifies things a lot and you won't have to calculate anything.
We have a canonical homomorphism $R \to R[x] \to R[x]/(xf-1)$ which sends $f$ to an invertible element (the class of $x$). Hence, by the universal property of localizations, it lifts uniquely to a homomorphism $R_f \to R[x]/(xf-1)$.
Conversely, consider the element $1/f \in R_f$. By the universal property of $R[x]$ there is a homomorphism $R[x] \to R_f$ extending $R \to R_f$ and mapping $x$ to $1/f$. This homomorphism kills $xf-1$ by construction, hence lifts to a homomorphism $R[x]/(xf-1) \to R_f$.
These homomorphisms are easily seen to be inverse to each other (again using the universal properties, but also using elements if you want to).
If you know the Yoneda Lemma, we can even give a shorter and slicker proof (following essentially the same argument): Let $S$ be a commutative ring. We have natural bijections
$$\hom(R[x]/(xf-1),S) \cong \{\phi \in \hom(R[x],S) : \phi(x) \phi(f)=1\}$$
$$\cong \{(\psi,s) : \psi \in \hom(R,S), s \in S, s \psi(f)=1\}$$
$$ \cong \{\psi \in \hom(R,S) : \psi(f) \in S^*\} \cong \hom(R_f,S).$$
Hence, $R[x]/(xf-1) \cong R_f$.
EDIT:
For a direct proof that the kernel of $R[x] \to R_f$ is precisely $(xf-1)$, see Rings of fractions the hard way by F. Voloch.
Comment: @DavidWheeler It's in Rotman as well as Voloch, as I mentioned [on 12/6/23,](http://math.stackexchange.com/a/162037/242) with a simplification. See also [other discussions here.](http://www.google.com/search?q=site:math.stackexchange.com+voloch)
Comment: They probably included the assumption of not being nilpotent to avoid getting something trivial.
Comment: Yes, I know that, and this wish is absolutely unnatural. In fact, there are rings in which you cannot really decide a priori if some element is zero (or nilpotent) or not.
Comment: I agree completely.
Comment: @MartinBrandenburg It may not be clear from my post, but I *did* prove it in essentially the same way you outlined it. If we call $(xf - 1) = I$, it is clear that $f$ becomes a unit in $R[x]/I$ with $x + I$ as its inverse. That's not my question, I want to know if it CAN be shown directly. The condition of non-nilpotency of $f$ doesn't affect the "morphism" flow, and is something introduced in D&F to prevent triviality, presumably for illustrative purposes.
Comment: Alright, see my Edit.
Comment: Thank you for the edit, it was what I was looking for :)


Import Values of an Array into a Variable

Question: I'm very new in PHP or Programing at all and i have a problem which i can't solve alone.
I made a Test Website where i can upload songs (Filename = artist&song), and the uploaded songs are shown in a table with the artist.
So i created an array from my music folder where i uploaded my songs.
function displayfilename($artist, $song) {
$songarray = array_slice(scandir('music/mp3'), 2);
}

The Array looks like this:
Array
(
[0] => hello&adele.mp3
[1] => hotline&drake.mp3
)

What i need to do is to save the first part of the value in a variable named $song and the second part of the value in a value named $artist, and then display them in a table (i guess with a for each).
I would appreciate it if you could try to help me with this problem^^
bye
Comment: Take a look at the `explode()` function. You could use `&` as delimiter
Answer: Loop your $songarray, exploding your values by your separator, &
echo '
';
foreach($songarray as $sa)
{
    $exp = explode("&", $sa);
    $song = $exp[0]; $artist = $exp[1];
    echo '
';
    echo '    ' . $song . '	';
    echo '    ' . $artist . '	';
    echo '
';
}
echo '
';


How do I 'reset' a theme completely?

Question: I think I have deleted some .css theme files in my local directory by accident and when I delete All the theme's files to re-install and get the original files back, they still aren't there. Is there a way to reset the whole theme folder?
Comment: Why WAS the "theming" tag not appropriate for this question ... And why is "files" (still) a relevant tag (looking at its wiki excerpt)?
Answer: If it's a core/contrib theme, just download the original and replace the modified version with it.
If it's a custom theme, just restore from whatever backup you have available (or from Trash or your OS's equivalent feature).
If you're wondering if Drupal somehow keeps track of file system changes and might be able to help you restore deleted files - it doesn't (I've yet to come across a framework that would do this).
Comment: To some extent, [Hacked!](https://www.drupal.org/project/hacked) may be used for this purpose. One needs to define source for his theme, and keep unmodified version there. And voila, list of changes available. Not great, and not module's main purpose, but doable. And sometimes less effort than using git properly.
Answer: If you're using GIT, just compare your current branch with whatever you have available to get more details about what happened, and then perform the appropriate GIT action (command) to get back to that "reset" point you're looking for.
As a variation, the Hacked! module might be of some help also (if this question is about a contributed module). I.e to find out what is "currently different from the module on drupal.org. Some details about it (from its project page):

This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

As per your "I think I have deleted": make sure that you also cleared the appropriate caches  ... it doesn't hurt, but sometimes it helps (and turns out to be "the" solution).
PS: if you're NOT using GIT, then consider the issue you suffer now as a great lesson why you should ...

How do I 'reset' a theme completely?


Como impedir que uma função seja executada quando uma condição for alcançada e reativá-la quando necessário?

Question: Estou numa peleja aqui para tentar fazer com que uma função seja interrompida quando determinada condição for alcançada e reabilitá-la, caso determinado botão seja clicado.
No meu caso, tenho uma texto e botões que alteram o tamanho da fonte (além dos botões também estou usando cookies e atalhos no teclado, mas isso é outra história). Minha dificuldade está sendo em bloquear o botão de aumentar a fonte, caso essa esteja com 25px; e bloquear o de diminuir, caso a fonte esteja com 13px. É possível?
Detalhe: eu já utilizei os métodos show e hide para esses botões e até que funciona, entretanto eu não conseguia deixar esses valores ocultos em um cookie. Também usei o prevent.default, mas sem êxito.
Além do código inserido abaixo, também tenho o mesmo no Codepen.

$(".dec-font").click($.diminuiFonte = function() {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) - 3.0;
  $("#body-post").animate({
    'font-size': size + 'px'
  });
  console.log(size);
  return (false);
});

$(".inc-font").click($.aumentaFonte = function() {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) + 3.0;
  $("#body-post").animate({
    'font-size': size + 'px'
  });
  console.log(size);
  return (false);
});

$(".res-font").click($.resetaFonte = function() {
  var size = '16';
  size = size.replace('px', '');
  size = parseInt(size);
  $("#body-post").animate({
    'font-size': size + 'px'
  });
  console.log(size);
  return (false);
});
.acess li {
  display: inline-block;
  margin-right: -4px!important;
  border: 1px solid #bbb;
  cursor: pointer
}

.acess li a {
  font-size: 10px;
  padding: 6px;
  display: block;
  font-family: Open Sans;
  text-transform: uppercase
}

#body-post {
  font-size: 16px
}

A-

Tamanho Normal

A+

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer viverra nulla quis velit pretium, in lacinia enim rutrum. Proin molestie magna in ullamcorper pulvinar. Sed ac finibus metus. Quisque placerat posuere elit. Cras tempus faucibus est, at
  aliquam nisi pulvinar non. Vestibulum nunc lacus, mattis ac molestie quis, facilisis a elit. Cras auctor maximus urna eget ultricies. Nunc rhoncus imperdiet dui, in fringilla purus fringilla venenatis. Cras commodo, odio ut accumsan eleifend, nulla
  dolor vestibulum lacus, elementum posuere eros dolor non dui. Nulla sed ligula eleifend, blandit mi eget, iaculis nisl. In ut augue sed arcu tincidunt auctor ac quis lectus. Fusce ac purus turpis. Duis ultrices purus non massa ultricies, id sagittis
  sapien tempor. Nam erat libero, accumsan et commodo et, vulputate nec metus. Duis pretium tortor sed condimentum facilisis. Aliquam non elit ac lectus luctus rhoncus vitae a arcu. Vestibulum vulputate rutrum maximus. Donec arcu quam, ultricies finibus
  arcu nec, dapibus semper neque. Etiam bibendum sem non tristique cursus. Duis sed porta quam. Nam faucibus placerat mattis. Sed interdum sapien ex, non elementum augue scelerisque non. Quisque porta mi at eros suscipit varius. Proin et efficitur ante,
  ac faucibus diam. Cras vehicula sagittis metus, in suscipit lacus dapibus posuere. Morbi odio felis, dapibus in urna vitae, pretium sodales dui. Cras ornare risus et dolor feugiat pellentesque. Donec volutpat, eros non feugiat tempus, ex leo vulputate
  velit, a aliquet felis nunc sed turpis. Pellentesque et velit vel massa sodales tincidunt. Proin suscipit mauris arcu, sed euismod sapien pharetra in. Nam eget hendrerit ex.

Answer: Se você não deseja que a função seja executada por completo, basta verificar o valor da variável size conforme suas regras de tamanho máximo e mínimo:
$(".dec-font").click($.diminuiFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) - 3.0;

  if (size >= 13) {
    $("#body-post").animate({'font-size' : size + 'px'});
  }
});

$(".inc-font").click($.aumentaFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) + 3.0;

  if (size <= 25) {
    $("#body-post").animate({'font-size' : size + 'px'});
  }
});

Perceba que agora a animação no tamanho das letras está condicional e nem sempre será executada.
Com isso, seu código completo ficaria mais ou menos da seguinte forma:

$(".dec-font").click($.diminuiFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) - 3.0;

  if (size >= 13) {
    $("#body-post").animate({'font-size' : size + 'px'});
  }
});

$(".inc-font").click($.aumentaFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) + 3.0;

  if (size <= 25) {
    $("#body-post").animate({'font-size' : size + 'px'});
  }
});

$(".res-font").click($.resetaFonte = function () {
  var size = '16'; size = size.replace('px', '');
  size = parseInt(size);
  $("#body-post").animate({'font-size' : size + 'px'});
});
.acess li {
  display:inline-block;
  margin-right:-4px!important;
  border:1px solid #bbb; cursor:pointer
}

.acess li a {
  font-size:10px; padding:6px;
  display:block; font-family:Open Sans;
  text-transform:uppercase
}

#body-post {
  font-size:16px
}

A-

Tamanho Normal

A+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer viverra nulla quis velit pretium, in lacinia enim rutrum. Proin molestie magna in ullamcorper pulvinar. Sed ac finibus metus. Quisque placerat posuere elit. Cras tempus faucibus est, at aliquam nisi pulvinar non. Vestibulum nunc lacus, mattis ac molestie quis, facilisis a elit. Cras auctor maximus urna eget ultricies. Nunc rhoncus imperdiet dui, in fringilla purus fringilla venenatis. Cras commodo, odio ut accumsan eleifend, nulla dolor vestibulum lacus, elementum posuere eros dolor non dui. Nulla sed ligula eleifend, blandit mi eget, iaculis nisl. In ut augue sed arcu tincidunt auctor ac quis lectus. Fusce ac purus turpis. Duis ultrices purus non massa ultricies, id sagittis sapien tempor. Nam erat libero, accumsan et commodo et, vulputate nec metus. Duis pretium tortor sed condimentum facilisis.

Aliquam non elit ac lectus luctus rhoncus vitae a arcu. Vestibulum vulputate rutrum maximus. Donec arcu quam, ultricies finibus arcu nec, dapibus semper neque. Etiam bibendum sem non tristique cursus. Duis sed porta quam. Nam faucibus placerat mattis. Sed interdum sapien ex, non elementum augue scelerisque non. Quisque porta mi at eros suscipit varius. Proin et efficitur ante, ac faucibus diam. Cras vehicula sagittis metus, in suscipit lacus dapibus posuere. Morbi odio felis, dapibus in urna vitae, pretium sodales dui. Cras ornare risus et dolor feugiat pellentesque. Donec volutpat, eros non feugiat tempus, ex leo vulputate velit, a aliquet felis nunc sed turpis. Pellentesque et velit vel massa sodales tincidunt. Proin suscipit mauris arcu, sed euismod sapien pharetra in. Nam eget hendrerit ex.

Uma outra opção, é criar uma classe css que desative a sua li, por exemplo:
.disabled {
  pointer-events: none;
  opacity:0.4;
}

Assim, sempre que uma das opções for clicada, você verifica o tamanho e adiciona ou remove essa classe utilizando addClass ou removeClass do JQuery:
Para desativar, seria assim:
$(".dec-font").removeClass("disabled");

Para ativar, seria dessa forma:
$(".dec-font").addClass("disabled");

O código completo, ficaria mais ou menos da seguinte forma:

$(".dec-font").click($.diminuiFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) - 3.0;
  $("#body-post").animate({'font-size' : size + 'px'});
  bloqueiaBotoes(size);
});

$(".inc-font").click($.aumentaFonte = function () {
  var size = $("#body-post").css('font-size');
  size = size.replace('px', '');
  size = parseInt(size) + 3.0;
  $("#body-post").animate({'font-size' : size + 'px'});
  bloqueiaBotoes(size);
});

$(".res-font").click($.resetaFonte = function () {
  var size = '16'; size = size.replace('px', ''); size = parseInt(size); $("#body-post").animate({'font-size' : size + 'px'});
  allEnabled();
});

function bloqueiaBotoes(size) {
  if (size <= 13) {
    $(".dec-font").addClass("disabled");
    $(".inc-font").removeClass("disabled");
  } else if (size >= 25) {
    $(".inc-font").addClass("disabled");
    $(".dec-font").removeClass("disabled");
  } else {
    allEnabled();
  }
}

function allEnabled() {
  $(".dec-font").removeClass("disabled");
  $(".inc-font").removeClass("disabled");
}
.acess li {
  display:inline-block;
  margin-right:-4px!important;
  border:1px solid #bbb; cursor:pointer
}

.acess li a {
  font-size:10px; padding:6px;
  display:block; font-family:Open Sans;
  text-transform:uppercase
}

#body-post {
  font-size:16px
}

.disabled {
  pointer-events: none;
  opacity:0.4;
}

A-

Tamanho Normal

A+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer viverra nulla quis velit pretium, in lacinia enim rutrum. Proin molestie magna in ullamcorper pulvinar. Sed ac finibus metus. Quisque placerat posuere elit. Cras tempus faucibus est, at aliquam nisi pulvinar non. Vestibulum nunc lacus, mattis ac molestie quis, facilisis a elit. Cras auctor maximus urna eget ultricies. Nunc rhoncus imperdiet dui, in fringilla purus fringilla venenatis. Cras commodo, odio ut accumsan eleifend, nulla dolor vestibulum lacus, elementum posuere eros dolor non dui. Nulla sed ligula eleifend, blandit mi eget, iaculis nisl. In ut augue sed arcu tincidunt auctor ac quis lectus. Fusce ac purus turpis. Duis ultrices purus non massa ultricies, id sagittis sapien tempor. Nam erat libero, accumsan et commodo et, vulputate nec metus. Duis pretium tortor sed condimentum facilisis.

Aliquam non elit ac lectus luctus rhoncus vitae a arcu. Vestibulum vulputate rutrum maximus. Donec arcu quam, ultricies finibus arcu nec, dapibus semper neque. Etiam bibendum sem non tristique cursus. Duis sed porta quam. Nam faucibus placerat mattis. Sed interdum sapien ex, non elementum augue scelerisque non. Quisque porta mi at eros suscipit varius. Proin et efficitur ante, ac faucibus diam. Cras vehicula sagittis metus, in suscipit lacus dapibus posuere. Morbi odio felis, dapibus in urna vitae, pretium sodales dui. Cras ornare risus et dolor feugiat pellentesque. Donec volutpat, eros non feugiat tempus, ex leo vulputate velit, a aliquet felis nunc sed turpis. Pellentesque et velit vel massa sodales tincidunt. Proin suscipit mauris arcu, sed euismod sapien pharetra in. Nam eget hendrerit ex.

Comment: Funcionou perfeitamente, Daniel! Acabei optando pela segunda dica, até pela sugestão visual de que o botão está desabilitado. Veio muito bem a calhar! Muito obrigado, meu caro!
Answer: Mantendo a mesma estrutura que você está usando basta fazer assim:
$(".inc-font").click($.aumentaFonte = function () {

  var size = $("#body-post").css('font-size').replace('px','');

   //aqui você verifica se o tamanho é menor que os 25, faz o incremento caso
   //seja não há a necessidade de colocar um else, pois se o valor for maior
   //não irá incrementar

   if(size < 25){
    size = parseInt(size) + 3.0;

    //então basta colocar na div
      $("#body-post").animate({'font-size' : size + 'px'});
   }
  return (false);
 });

para a função que diminui a fonte basta usar a mesma lógica.
Comment: Oi, Eliton! Grato pelo retorno, cara. Acabei ficando com a resposta do Daniel, mas muito obrigado pela sugestão!


Upload Word File to extract Text via TIKA REST

Question: I am trying to call Apache-TIKA via their REST API.  I have successfully been able to upload a PDF document and return the document's text via CURL
curl -X PUT --data-binary @<filename>.pdf http://localhost:9998/tika --header "Content-type: application/pdf"
That translated to INDY like so:
function GetPDFText(const FileName: String): String;
var
  IdHTTP:  TIdHTTP;
  Params: TIdMultiPartFormDataStream;
begin
  IdHTTP := TIdTTP.Create;
  try
    Params := TIdMultiPartFormDataStream.Create;
    try
      Params.Add('file', FileName, 'application/pdf')
      Result := IdHTTP.PUT('http://localhost:9998/tika', Params);
    finally
      Params.Free;
    end;
  finally
    IdHTTP.Free;
  end;
end;

Now I want to upload a word document (.docx)
I assumed that all I would need to do is change the content Type when I add my file to Params, but that doesn't seem to produce any results, although I get no error reported back.  I was able to get the following CURL command to work correctly
CURL -T <myDOCXfile>.docx http://localhost:9998/tika --header "Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document"

How do I modify my HTTP call from CURL -X PUT to CURL -T?
Answer: There are at least two issues in your implementation:

Your translation from CURL -X PUT to TIdHTTP is wrong.
You don't specify Accept HTTP header to retrieve the extracted text in specific format.

How to translate curl -X PUT to Indy?
At first, lets make it clear that curl -X PUT --data-binary @<filename> <url> is the same as curl -T <filename> <url> when:

<url>'s scheme is HTTP or HTTPS
<url> does not end with /

Therefore using one or the other shouldn't matter in your case. See also curl documentation.
Secondly, TIdMultiPartFormDataStream is designed for use with POST verb, however nothing can stop you from passing it to TIdHTTP.Put, because it is indirectly derived from TStream. There even is a dedicated invariant of TIdHTTP.Post method that accepts TIdMultiPartFormDataStream:

function Post(AURL: string; ASource: TIdMultiPartFormDataStream): string; overload;

To upload file to the service just use TIdHTTP.Put method with TFileStream as an argument while providing proper content type of the file being uploaded in HTTP header.
And finally you're trying to extract plain text from the document, but you didn't specify content type that the service should return. This is done via Accept HTTP header. Default instance of TIdHTTP has property IdHTTP.Request.Accept initialized to 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (this may vary depending on Indy version). Therefore by default Tika will return HTML formatted text. To get the plain text you should change it to 'text/plain; charset=utf-8'.
Fixed implementation:
uses IdGlobal, IdHTTP;

function GetDocumentText(const FileName, ContentType: string): string;
var
  IdHTTP: TIdHTTP;
  Stream: TIdReadFileExclusiveStream;
begin
  IdHTTP := TIdHTTP.Create;
  try
    IdHTTP.Request.Accept := 'text/plain; charset=utf-8';
    IdHTTP.Request.ContentType := ContentType;
    Stream := TIdReadFileExclusiveStream.Create(FileName);
    try
      Result := IdHTTP.Put('http://localhost:9998/tika', Stream);
    finally
      Stream.Free;
    end;
  finally
    IdHTTP.Free;
  end;
end;

function GetPDFText(const FileName: string): string;
const
  PDFContentType = 'application/pdf';
begin
  Result := GetDocumentText(FileName, PDFContentType);
end;

function GetDOCXText(const FileName: string): string;
const
  DOCXContentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
begin
  Result := GetDocumentText(FileName, DOCXContentType);
end;

According to the Tika's documentation it also supports posting multipart form data. If you insist on using this approach, then you should change the target resource to /tika/form and switch to Post method in your implementation:
function GetDocumentText(const FileName, ContentType: string): string;
var
  IdHTTP: TIdHTTP;
  FormData: TIdMultiPartFormDataStream;
begin
  IdHTTP := TIdHTTP.Create;
  try
    IdHTTP.Request.Accept := 'text/plain; charset=utf-8';
    FormData := TIdMultiPartFormDataStream.Create;
    try
      FormData.AddFile('file', FileName, ContentType); { older Indy versions: FormData.Add(...) }
      Result := IdHTTP.Post('http://localhost:9998/tika/form', FormData);
    finally
      FormData.Free;
    end;
  finally
    IdHTTP.Free;
  end;
end;

Why does the original implementation in question work with PDF files?
When you Post multipart form data via TIdHTTP, Indy automatically sets content type of the request to 'multipart/form-data; boundary=...whatever...'. This is not the case when you Put (unless you set it manually before performing the request) data and therefore TIdHttp.Request.ContentType remains blank. Now I can only guess that when Tika sees empty content type it falls back to some default type which could be PDF and it's still somehow able to read the document from multipart request.
Comment: Well said.  Much better than [the answer I posted](https://forum.lazarus.freepascal.org/index.php/topic,48604.msg350239.html#msg350239) to the [same question](https://forum.lazarus.freepascal.org/index.php/topic,48604.0.html) on the FreePascal forum.
Comment: -Peter Wolf, thanks for this great answer.  -Remy Lebeau, I read your reply in the other forum, thanks, I posted there because a few days passed without an answer on this question in SO.


Accesing Identity Profile Management

Question: I'm stuck with this problem for over 2 hours and can't find the answer anywhere.
I have a project that uses Identity. I have created a register and login not using Identity scaffolded items from the beginning.
Next, I added custom fields to user identity using ApplicationUser:IdentityUSer.
Now I want to allow users to manage their profiles. I wanted to use the default Identity Manager and then customize it. I didn't have it though so I added a new scaffolded Identity with only "Identity/Pages/Account/Manage" item. It has created an area.
The problem is that I don't know how to access the Index page inside this area in my _LoginPartial view.
Part of _LoginPartial code:
 @if (SignInManager.IsSignedIn(User))
 {

             Hello, @User.Identity.Name

             Logout

 }
 else
 {

 }

My project structure:
Is this a good way to manage user profile though?
Answer: To have your first  tag link to your new Account | Manage page, you can include the asp-area, asp-controller and asp-action attributes. (similar to what you already have on your second  tag).
Try changing the line to this:
Hello, @User.Identity.Name

Accesing Identity Profile Management


Could it be that a object has no mapping to its image by the endofunctor?

Question: I got confused when I saw $LR \to I$ in an Adjunction. The same goes for Comonad. For any object $a$ in Category $C$, $F a$ is the image of $a$ by endofunctor $F$.
Could a morphism $a \to F a$, not exist?
I know that a endofunctor maps all source objects in a domain. Then, for any object $a$, shouldn't $a \to F a$, which is the image of $a$ of endofunctor $F$, always exist?
Comment: Welcome to mse! I'm fairly confused by your question. A functor is a map between two categories, so $F : \mathcal{C} \to \mathcal{D}$. Since $a \in \mathcal{C}$ is an object in $\mathcal{C}$, it doesn't make sense to ask for an arrow $a \to Fa$, since $Fa \in \mathcal{D}$. That said, in a programming context, often the word "functor" is used to mean in particular a functor $\mathcal{C} \to \mathcal{C}$, where $\mathcal{C}$ is the syntactic category of some type theory. In that case it makes sense to ask for an arrow $a \to F a$, but there's no reason for it to exist in general.
Comment: With all this in mind, would you please clarify what it is you're looking for?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Sorry for writing without thinking. Functor in my question means endofunctor. I got confusion from Adjunction I -> R L , L R -> I . For L R -> I, L R c -> c exists. For L R c to exist, there would be a Functor L R mapping c to L R c for any c. Therefore, c -> L R c exists and I -> L R is automatically established. What could be wrong?
Answer: Take the category of the ordered set $\mathbb{Z}$. The objects are the integers, and if $a$ and $b$ are integers, then the set of arrows from $a$ to $b$ is a singleton if $a\leq b$, and empty otherwise.
Let $F$ be the endofunctor mapping every integer $a$ to $a-1$. Then there is never an arrow from $a$ to $Fa$.


Remove Side Menus on certain pages in Drupal 7

Question: I realize that this question might be the result of a fundamental misunderstanding of how things work.  So I apologize in advance if this is just me being a dope.
I am creating a webpage for a festival.  On each page there is a left side menu bar with about 6 menus in it.  I want that there most of the time, so that is good.
I've now created the ability for users to add events to the festival so others can see what's going on.  I've created a content type called Event, added the fields I want to it and exposed it to registered users.  I then create a table view and calendar view with all the events broken down by date/time with a few filters.
All that is working fine.  The part I'm now struggling with is, I want all the menus on the left to go away, any time I am working with the events. Which means when I'm adding, editing, viewing the content, and when I'm viewing the Event views I want access to the entire width of the site, except for a small menu on the right with Add Event, View Events, View Calendar.
I thought a sub-theme would get me what I want, so I created a subtheme with the menus the way I want it and the page the way I want it.  But I can't for the life of me figure out how to get the content to show in the sub-theme.
Any help would be appreciated.  Please keep in mind I am very new to drupal so as much detail as you can go into would be appreciated.
Thanks,
PJ
Answer: Did you added the menu on the left side menu bar using blocks or printing directly from the template?
On the first case you can hide the blocks on specific pages in many ways. The easiest is to configure the visibility from the blocks configuration (Administration > structure > blocks). On every block settings you can specify in which pages hide or show the block.
If you're printing the menus from the template you've to use some php in order to select when print them, like "if current page is x, then print" or something similar.
:-)
Comment: I tried that.  I went into the block, and checked every content type except the type I didn't want displayed.  When i did that the block was removed on every page.
Comment: EDIT: I was incorrect.  I have views setup to display a teaser list of certain content type.  For example, cicking on Theme Camps brings me up a list of Theme Camp Articles.  On this page, the block is not being displayed.  However if I click on one of the teasers the block appears.

This issue is it's not showing on the main page or any of the views.  I need to be able to control the blocks for my views as well.
Comment: @TheMad Hatter...if you can upload some screenshots that would be great
Comment: You've to correctly set the visibility from the block settings or you can also follow the solution suggested by @adaptordie (using context module)
Answer: Check out the Context module - http://drupal.org/project/context.
That should help you show the menus/sidebar on pages you want (i.e. adding, editing, viewing the Event content type) and not on the others.
Answer: One solution would be to create another content type for your Events pages. Then once you have that content type, you can create a separate template for it in your theme, which will be named page--YOUR_CONTENT_TYPE_MACHINE_NAME.tpl.php. In this template you can rearrange your content as needed, ie omit the sidebar-first element, add a top menu, etc. For more info, you can refer to this tutorial.


Get text from tree structure SQL

Question: i have category table with tree structure
every row has text for description Like below:

nodeid
parentid
description

1
0
root description

2
1
sub category description

3
2

4
3

5
4
last description

I want to show all the description from the root to the last category, like below:
Description:
root description.
sub category description.
last description
how can I do this?
thanks a lot
Comment: You want a recusive query. Tag your DBMS, the feature is product specific.
Comment: you need only in list of `description` right ?
Comment: @PiyushKachhadiya yes i need only description for show.
Comment: waht is `tree` explain in your equation properly.
Comment: If i understand your equation is it's simple select query like this `select   description from tablename where description <> '' `
Comment: @PiyushKachhadiya A tree is a tree structure of categories and subsets.
This is an example I wrote, I have over 2000 categories and subcategories in the table
Comment: @PiyushKachhadiya I know how to write a SELECT query, i want when condition is nid=5 result like this : root description.
sub category description.
last description
Comment: @PiyushKachhadiya my DBMS is 2016
Comment: So, its SQL Server :-)
Comment: @rajorshi i know
Answer: Here is the SQL (MS SQLServer) dbfiddle link:
<code>WITH q
AS
(
  select nodeid,parentid,description from category where parentid=0
  union all
  select c.nodeid,c.parentid,c.description from category c inner join  q on q.nodeid=c.parentid
)
select description from q where description is not null;
</code>
PostgreSQL : dbfiddle link
Oracle : dbfiddle link

Get text from tree structure SQL


Incluir Loading em Botão - Bootstrap v4 - JSP

Question: Olá, estou tentando alterar um botão onde, quando for clicado. Seu conteúdo seja alterado para mostrar um "loading" e apos o carregamento da pagina o botão volte ao estado anterior. Já tentei de varias formas mas sem sucesso, não sei se é conflito; poderiam me ajudar por gentileza?
O front end do projeto é em JSP, usamos bootstrap 4.4.
O codigo do botão que quero alterar é:
 Pesquisar

/*Codigo que quero alterar*/

    <button class="btn btn-sm btn-primary" name="Pesquisar" type="submit">Pesquisar</button>

Eu tentei da forma abaixo passar os dados usando ID na DIV, pq possuem outros class "button" na pagina que não quero incluir o Loading.
HTML:
  Carregando">Pesquisar

JS/JQ:
 $('#load').click(function () {
                var btn = $(this)
                btn.button('loading')
                setTimeout(function () {
                    btn.button('reset')
                }, 9000)
            });

/*codigo que tentei*/

    <button type="submit" class="btn btn-sm
        btn-primary" id="load" data-loading-text=" Carregando">Pesquisar</button>

Comment: não coloque imagens de código, coloque o próprio código para que podemos testar (use o JsFiddle) no caso
Answer: Boa tarde pessoal,
No meu caso consegui resolver conforme abaixo; meu problema é que utilizo no projeto bootstrap 4.0, e os o efeitos que queria utilizar nos botões "class='fa fa-spinner fa-spin" por exemplo, estão disponíveis apenas no bootstrap 4.4. Como não posso atualizar a versão do bootstrap utilizado no projeto, resolvi achando as classes CSS dos efeitos que estão apenas na versão que não posso usar e inclui os mesmo no projeto. no meu caso foram os CSS's abaixo:

  <button type="submit" id="load" class="btn btn-sm btn-            primary">Pesquisar</button>


Estimation of a uniform distribution corrupted by Gaussian noise

Question: Problem definition
I have a dataset composed by $m$ observations $y^{(1)},\dots,y^{(m)} \in \mathbb{R}^2$ generated as follow
\begin{equation*}\begin{aligned}
y &= z + v \newline
z & \sim\mathcal{U}([a,b]) \newline
v & \sim\mathcal{N}(0_{2\times1}, \sigma_v^2 I_2)
\end{aligned}
\end{equation*}
here $z$ is uniformely distributed over the line connecting the vertices $[\begin{array}{cc}a & 0 \end{array}]$, $[\begin{array}{cc}b & 0\end{array}]$ with $b>a$, while $v$ is a zero-mean Gaussian variable with isotropic covariance $\sigma_v^2 I_2$ ($I_2$  is the $2\times 2$ identity matrix). The two components $z$ and $v$ are independent.
Given the dataset $y^{(1)},\dots, y^{(m)}$, I would like to estimate the parameters $a$ and $b$ that define the segment generating $z$.
My attempt
For $\sigma_v\triangleq 0$, i.e. no Gaussian noise, if I'm not wrong the maximum likelihood estimates of $a$ and $b$ should be
\begin{equation}\begin{aligned}
\hat{\alpha} &\triangleq \min_{j=1,\dots,m} [\begin{array}{cc} 1 & 0 \end{array}] y^{(j)} \newline
\hat{\beta} &\triangleq \max_{j=1,\dots,m} [\begin{array}{cc} 1 & 0 \end{array}] y^{(j)}
\end{aligned}
\tag{$\star$}
\end{equation}
Now, if $\sigma_v$ is "small" compared to the segment length $b-a$, then the estimates above should work pretty well. As $\sigma_v$ becomes comparable with $b-a$, I expect a degradation of the estimate accuracy.
I'm thinking about a sort of heuristic correction as follows
\begin{equation*}\begin{aligned}
\hat{\alpha} &\triangleq \min_{j=1,\dots,m} [\begin{array}{cc} 1 & 0 \end{array}] y^{(j)} +\sigma_v\newline
\hat{\beta} &\triangleq \max_{j=1,\dots,m} [\begin{array}{cc} 1 & 0 \end{array}] y^{(j)} -\sigma_v
\end{aligned}
\end{equation*}
because due to the Gaussian noise $v$ the minimum and the maximum can overshoot $a$ and $b$.
Question
My solution is far from rigorous and I'm not even sure if it makes sense. My questions are the following:

Based on some solid principle, is it possible to correct the estimates $(\star)$  in order to take into account the effect of $v$?
If my approach cannot work, how do we estimate $a$, $b$?
Comment: In that case you can ignore the second dimension.
Comment: Do you know $\sigma_v$ or are you estimating it from the data?
Comment: I know $\sigma_v$
Answer: When you add Gaussian noise, the smallest and largest observations are no longer sufficient for and MLEs of $a,b$.
Instead consider the likelihood which, in the usual way, is given by the product of the density of each $\mathbf{y}_i$, in this case given by
\begin{align}
f(\mathbf{y})&=\int_a^b f(\mathbf{y}|z)f(z)dz
\\&=\frac1{2\pi\sigma_v^2}\int_a^b e^{-\frac1{2\sigma_v^2}[(y_1-z)^2+y_2^2]}\frac1{b-a}dz
\\&=\frac1{\sqrt{2\pi}\sigma_u}e^{-\frac{y_2^2}{2\sigma_u^2}}\frac{\Phi(\frac{y_1-a}{\sigma_u})-\Phi(\frac{y_1-b}{\sigma_u})}{b-a},
\end{align}
where $\Phi$ is the standard normal cdf.
The resulting likelihood (or its log) should be straightforward to maximise numerically with respect to $a, b, \sigma_u^2$.
I would expect the MLEs of $a$ and $b$ to be biased, however, just like in the case of uniform observations without Gaussian noise, so some form of bias correction may be needed.
An alternative is Bayesian inference, perhaps using an improper uniform prior $\pi(\theta_1)\propto 1$ on $\theta_1=\frac{a+b}2$ and an independent scale prior $\pi(\sigma_u)\propto \frac1{\sigma_u}$ on $\sigma_u$.  It would be tempting to use an independent, improper scale prior also on $\theta_2=b-a$ but I believe this would make the posterior improper (as in Hobert (1996)) as the likelihood tends to a positive limit as $\theta_2 \rightarrow 0$.  A sensible way around this would be to assume that $\sigma_u$ and $\theta_2$ instead are of similar orders of magnitude, e.g. by letting $\pi(\theta_2|\sigma_u)$ be lognormal with a suitable variance.
The argument for the conditional informative prior $\pi(\theta_2|\sigma_u)$ also applies if $\sigma_u$ is known.  Thus, completely "objective" Bayesian inference does not seem feasible for this model.


Common websites displaying "Server's certificate is not trusted" on new Server 2012 R2 image

Question: I've recently been tasked with migrating one of our company's web app servers from Server 2008 to Server 2012 R2. While on the new server and trying to download some apps to set it up I keep getting greeted by warning pages. In Chrome many of the trusted sites I visit normally (e.g. Any msdn, technet, or github page), it brings up the warning page "Your connection is not private" and the padlock in the address bar shows:

"The identity of this website has not been verified.

Server's certificate is not trusted."

I might add my role is a developer, not network/server admin so there might be something obvious to others in such a role that I haven't learned yet.
From what I read in this Microsoft post the trusted certificates should be updated automatically. Am I missing something?
Comment: Do you have an internet proxy configured on the new server? Without that the CRL validation is likely to fail and that could lead to cert issues.
Answer: If a certificate was issued by an authority that is part of the Microsoft Trusted Root CA program, Windows should attempt to download the certificate of the CA in the chain - at the time they are needed. If the server is unable to download the certificate(s) in the chain or the feature is disallowed by policy, this will not work as expected.  You may also want to try using Internet Explorer to see if the auto-download works as expected.  You can get more information about certificate issues by enabling the CAPI2 event log.
You can also install the required root/issuing certificates in the appropriate stores yourself and not rely on this behavior.  (Note that you should not attempt to import all ~350 certificates as that would cause problems for your server.)
For Chrome, if the certificate is an EV certificate, additional restrictions apply.
Google Chrome Root Certificate Policy
http://dev.chromium.org/Home/chromium-security/root-ca-policy
Current Microsoft Trusted Root CA list is published here:
http://social.technet.microsoft.com/wiki/contents/articles/31634.microsoft-trusted-root-certificate-program-participants.aspx
Microsoft Trusted Root CA deployment notices published here:
http://social.technet.microsoft.com/wiki/contents/articles/31680.microsoft-trusted-root-certificate-program-updates.aspx


Manual set cookies using accesstoken/AuthenticationResult -like UseCookieAuthentication() owin middleware

Question: In an Action in a Controller, we have the AuthenticationResult which contains AccessToken.
We would like to do a manual login with this token that is equal to the UserCookieAuthentication owin middleware. Is that possible?
<code>public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
                {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            },
            });
    }
}
</code>
I have been looking at HttpContext.GetOwinContext().Authentication.SignIn() but that doesn't take any Tokens.
Answer: Looking in the Katana/Owin Github project the following TokenHelper solved it along with using the AuthenticationResponseGrant method:
<code>                result = await authContext.AcquireTokenAsync(resource, clientId, uc);

                var principal = await new TokenHelper().GetValidatedClaimsPrincipalAsync(result.AccessToken);

                var claimsIdentity = new ClaimsIdentity(principal.Claims, CookieAuthenticationDefaults.AuthenticationType);

                var properties = new AuthenticationProperties();

                HttpContext.GetOwinContext().Authentication.AuthenticationResponseGrant =
                    new AuthenticationResponseGrant(claimsIdentity, properties);
</code>