How to delete a file in C using a file-descriptor?

Question: In my code, I create a file with a random name using mkstemp() function (Im on Linux). What this function returns is an int being a file descriptor.
int fd;
char temp[] = "tempXXXXXX";

fd = mkstemp(temp);

Later I can access the file using fdopen() through that int file descriptor.
FILE *file_ptr = NULL;

file_ptr = fdopen(fd);

But at the end of my program, I would like to see if the file still exists with the random name it was given when I created it (the program should change that file name if successful). I can set a flag if the rename() function run on that file is successful, but I still don't know how to delete it when I only have its file descriptor.
if rename files => remove the temp file

How can I do that? Or is there a way to get the files name if I have its file descriptor?
Comment: @KamilCuk `unlink` requires a filename, which `mkstemp` doesn't provide.
Comment: Does this answer your question? [Retrieve filename from file descriptor in C](https://stackoverflow.com/questions/1188757/retrieve-filename-from-file-descriptor-in-c)
Comment: I don't think you can. Names get deleted, not files. A file may have multiple names, or none - how does Linux know which name to delete?
Comment: @John mkstemp modifies the template string so the filename is returned.
Comment: `mkstemp` already has the filename - it's `mkstemp(char *template)`. Just `mkstemp(template); unlink(template)`.
Comment: @KamilCuk it has a template for that file name for example "tempXXXXXX" where those Xs are to be filled with random characters
Comment: Do you want to get the filename or delete the file? Why not have the file deleted automatically by calling `unlink`?
Comment: @stark & KamilCuk wow okay, now I see, it really does modify that string! Please if you write that as an answer I will select it as the solution
Answer: Neither C nor POSIX (since you are using POSIX library functions) defines a way to delete a file via an open file descriptor.  And that makes sense, because the kind of deletion you're talking about is actually to remove a directory entry, not the file itself.  The same file can be hard linked into the directory tree in multiple places, with multiple names.  The OS takes care of removing its data from storage, or at least marking it as available for reuse, after the last hard link to it is removed from the directory tree and no process any longer has it open.
A file descriptor is associated directly with a file, not with any particular path, notwithstanding the fact that under many circumstances, you obtain one via a path.  This has several consequences, among them that once a process opens a file, that file cannot be pulled out from under it by manipulating the directory tree.  And that is the basis for one of the standard approaches to your problem: unlink (delete) it immediately after opening it, before losing its name.  Example:
#include <stdlib.h>
#include <unistd.h>

int make_temp_file() {
    char filename[] = "my_temp_file_XXXXXX";
    int fd;

    fd = mkstemp(filename);
    if (fd == -1) {
        // handle failure to open ...
    } else {
        // file successfully opened, now unlink it
        int result = unlink(filename);
        // ... check for and handle error conditions ...
    }

    return fd;
}

Not only does that (nearly) ensure that the temp file does not outlive the need for it, but it also prevents the contents from being accessible to users and processes to which the owning process does not explicitly grant access.
Answer: Even though this doesn't exactly answer the question you're asking about mkstemp, consider creating a temporary file that will automatically be deleted, unless you rename it.
Instead of mkstemp you could call open combined with the creation flag O_TMPFILE to create a temporary, unnamed file that is automatically deleted when file is closed.
See open(2):
O_TMPFILE (since Linux 3.11)
    Create an unnamed temporary regular file.  The pathname argu‐
    ment specifies a directory; an unnamed inode will be created
    in that directory's filesystem.  Anything written to the
    resulting file will be lost when the last file descriptor is
    closed, unless the file is given a name.

Instead of a filename, you call open with the path where you prefer to place the temporary file, like:
temp_fd = open("/path/to/dir", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);

If you like to give the temporary file a permanent location/name, you can call linkat on it later:
linkat(temp_fd, NULL, AT_FDCWD, "/path/for/file", AT_EMPTY_PATH);

Note: Filesystem support is required for O_TMPFILE, but mainstream Linux filesystems do support it.
Comment: @John well... s/e//
Comment: I dont know why it doesnt recognize `O_TEMPFILE` flag, also should there be something instead of "AT_EMPTY_PATH"?
Answer: readlink provide you the name of your file depending of the file descriptor if you use the path /proc/self/fd/ adding you fd.
Then use remove for deleting the file passing the name readlink gave you
ssize_t readlink(const char *path, char *buf, size_t bufsiz); (also load ernno)
int remove(const char *filename); (returns zero is successful, otherwise nonzero)
I hope something like that could helped you ?

⚠ Don't copy/past this you must edit "filename"; _BUFFER, _BUFSIZE ⚠
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>

int delete_file(int fd) {
   char *str_fd = itoa(fd, str_fd, 10);
   char *path = strcat("/proc/self/fd/", str_fd);

   if (read_link(path, buffer, bufsize) == -1)
        return -1;

   int del = remove(filename);
   if (!del)
      printf("The file is Deleted successfully");
   else
      printf("The file is not Deleted");
   return 0;
}

(feel free to edit this, i didn't test the code and i let you handel the buffer and buffer size)
Comment: What kind of a buffer should there be?
Comment: Names that begin with an underscore and an upper-case letter, like `_BUFFER` and `_BUFSIZE`, are reserved identifiers and should not be used in your code.  See [**7.1.3 Reserved identifiers**](https://port70.net/~nsz/c/c11/n1570.html#7.1.3)
Comment: @john it's a char *


Discord.py não tô conseguindo implementar o ''Else'' no meu comando

Question: Bom, eu estou tentando criar um comando de "avatar", porém só mostra o icon, e eu queria fazer que meu comando mostrasse gif também. Só que eu queria implementar o "else" no comando, mas fica dando erro de "Syntax", se alguém puder ajudar a ajeitar o meu código, etc
Meu código:
@commands.command()
    async def avatar(self, ctx, user: discord.Member=None):
        if user == None:
            user = ctx.author
        icon_url2 = user.avatar_url_as
        icon_url = user.avatar_url

        avatarEmbed = discord.Embed(title=f'{user.name}\nClique no icon para baixá-lo.', timestamp=datetime.datetime.utcnow(),color=discord.Color.dark_blue())
        avatarEmbed.set_image(url=f'{icon_url}')

        await ctx.send(embed=avatarEmbed)

Se eu coloco "Else" abaixo do await, aparece isso:
SyntaxError: invalid syntax (talks.py, line 346)
Answer: Pelo que eu entendi você quer fazer o seguinte:
@commands.command()
async def avatar(self, ctx, user: discord.Member=None):
    if user == None:
        user = ctx.author
    icon_url2 = user.avatar_url_as
    icon_url = user.avatar_url

    avatarEmbed = discord.Embed(title=f'{user.name}\nClique no icon para baixá-lo.', timestamp=datetime.datetime.utcnow(),color=discord.Color.dark_blue())
    avatarEmbed.set_image(url=f'{icon_url}')

    await ctx.send(embed=avatarEmbed)
    else:
        #seu codigo aqui

Porem em estruturas condicionais o else deve estar diretamente após o if, exemplo:
@commands.command()
async def avatar(self, ctx, user: discord.Member=None):
    if user == None:
        user = ctx.author
    else:
        #seu codigo aqui
    icon_url2 = user.avatar_url_as
    icon_url = user.avatar_url

    avatarEmbed = discord.Embed(title=f'{user.name}\nClique no icon para baixá-lo.', timestamp=datetime.datetime.utcnow(),color=discord.Color.dark_blue())
    avatarEmbed.set_image(url=f'{icon_url}')

    await ctx.send(embed=avatarEmbed)

Isso deve funcionar, qualquer duvida só perguntar.
Comment: Obrigado amigo, ajudou muito.
Answer: Não necessita-se colocar um else:nesse código, já usei no meu Bot sem o else: em comandos de ship, userinfo e perfil e deu certo


The dual version of trichotomy of cardinality without AC

Question: Let $A$, $B$ be sets and denote by $A\leq^* B$ an assertion that if $A$ is non-empty, then there's a surjection from $B$ onto $A$.
This might be understood as a dual definition of cardinality. (Typically we use injections to capture the notion of A not being bigger than B. The $\leq^*$ notation is to be read as B not being smaller than A.)
Is this relation trichotomous without using the axiom of choice? Meaning for every two sets $A$ and $B$, it holds $A\leq^* B$ or $B\leq^* A$. (I would be surprised). Would trichotomy imply some interesting extra-ZF axiom?
More broadly, is there anything to be said about $\leq^*$? For example how does it relate to the usual comparisons of cardinality by injections?
I suspect there's no clear answer, since it is somehow reminiscent of Partition Principle ($A\leq^* B \implies A\leq B$) and Weak Partition Principle ($A\leq^* B \implies B\not< A $) which both are independent of ZF.
Comment: I read below that you find an almost exact duplicate. It can be closed as such without it being deleted, and it would fulfill the purposes you state in your comment (that's how duplicates are useful).
Answer: Not even a little bit.
If $\leq^*$ satisfies the trichotomy, then the axiom of choice holds.

Theorem. (Lindenbaum) If $X$ is a set, then there is an ordinal $\alpha$ such that $\alpha\nleq^*X$.

(Proof. If $\alpha\leq^*X$, then $\alpha$ injects into $\mathcal P(X)$; apply Hartogs' theorem.)
Let us denote the least such (non-zero) ordinal as $\aleph^*(X)$ and name it the Lindenbaum number of $X$.

Theorem. If $X\leq^*\alpha$ for an ordinal $\alpha$, then $X$ can be well-ordered.

(Proof. If $X$ is empty, we're done; otherwise fix a surjection from $\alpha$ onto $X$, and for every $x\in X$ let $\beta_x$ be the least $\beta<\alpha$ mapped to $x$. Then $x\prec y\iff\beta_x<\beta_y$ is a well-ordering of $X$.)

Theorem. If $\leq^*$ satisfies trichotomy, then the axiom of choice holds.

Proof. Compare $X$ and $\aleph^*(X)$, it has to be the case that $X<^*\aleph^*(X)$, and therefore $X$ can be well-ordered.

Now, what can we say about $\leq^*$ in general? Not too much.
It does not have to be anti-symmetric; but if it is anti-symmetric then there are no Dedekind-finite sets.
Comment: thanks, Asaf. Great answer as usual! Googling this topic I've found your [blogpost](http://karagila.org/2014/on-the-partition-principle/). After asking this, I've found an [almost-duplicate](https://math.stackexchange.com/questions/499066/in-zf-how-would-the-structure-of-the-cardinal-numbers-change-by-adopting-this-d?rq=1), where you've posted a thorough answer as well. I'm leaving it here for it might help possible future readers.


How to apply latitude and longitude resolution to image mosaic in geoserver based on zoom level

Question: How we can skip points in the raster layer (created using image mosaic) based on zoom?
I think it's called latitude/longitude resolution or sometimes grid step.
Tried Point symbolizer/ filters in SLD, but not sure how to use filters to skip points.
Edit -
I created store and layers as mentioned in below link
https://geoserver.geo-solutions.it/multidim/multidim/mosaic_config/netcdf_mosaic.html
Everything works fine. Now the issue is all data is shown.
The default netcdf spatial resolution is 0.4 and I want to change this as per zoom levels. for ex for zoom 1-5=1, zoom 5-10=0.75 and so on
Comment: rasters have pixels not points - may be you can [edit] your question to make what you are trying to do clear.
Answer: Found the solution, It's not what I need but still solves the issue.
The solution is to use wms_scale_denominator & Categories.
SLD block -
<code><ogc:Function name="parameter">
    <ogc:Literal>scale</ogc:Literal>
    <ogc:Function name="Categorize">
        <ogc:Function name="env">
            <ogc:Literal>wms_scale_denominator</ogc:Literal>
        </ogc:Function>
        <ogc:Literal>16</ogc:Literal>
        <ogc:Literal>100000</ogc:Literal>
        <ogc:Literal>8</ogc:Literal>
        <ogc:Literal>500000</ogc:Literal>
        <ogc:Literal>2</ogc:Literal>
        <ogc:Literal>1000000</ogc:Literal>
        <ogc:Literal>0.5</ogc:Literal>
        <ogc:Literal>5000000</ogc:Literal>
        <ogc:Literal>0.2</ogc:Literal>
        <ogc:Literal>10000000</ogc:Literal>
        <ogc:Literal>0.1</ogc:Literal>
        <ogc:Literal>20000000</ogc:Literal>
        <ogc:Literal>0.05</ogc:Literal>
        <ogc:Literal>60000000</ogc:Literal>
        <ogc:Literal>0.02</ogc:Literal>
    </ogc:Function>
</ogc:Function>
</code>


How can I do it Dropdown sorting options? I want to sort with Dropdown sorting options

Question: I'm new to React Native. I'm making a movie app. I want to sort with Dropdown sorting options. I pulled my data from the URL. How can I do it Dropdown sorting options? I want to sort.
"Sort by new - Sort by old - Sort by Random"
import React, { useState } from 'react';
import { View, TextInput, FlatList, ActivityIndicator, Text } from 'react-native';
import useFetch from '../../components/Hooks/useFetch';
import styles from './Sorting.style';
import { SelectList } from 'react-native-dropdown-select-list'

const Sorting = () => {
  const {data, loading} = useFetch();
  const [list, setList] = useState(data);

  const handleFilter = text => {
    const filteredList = data.filter(search => {
    const searchedText = text.toLowerCase();
    const currentTitle = search.title.toLowerCase();
    return currentTitle.indexOf(searchedText) > -1;
})
setList(filteredList);
}

if (loading) {
    return <ActivityIndicator style={{flex: 1, justifyContent: "center"}} size="large" />
}

const renderMovies = ({item}) => <Text>{item.title}</Text>

    return (
        <View style={styles.container}>
            <SelectList
                placeholder='Sırala'
                onSelect={handleFilter}
                setSelected={setList}
                data={list}
            />
            <FlatList
                numColumns={2}
                horizontal={false}
                data={data}
                renderItem={renderMovies}
            />
        </View>
    )
}

export default Sorting;

Comment: I think your problem is that `react-native-dropdown-list` doesnt give you access to the current value of the text input, so I would recommend disabling search and using your own text input to do filters
Answer: The onSelect prop in react-native-dropdown-list doesnt have any parameters  because the setSelect prop ensures that you already have access to what the selected is. I believe the search bar in the component is only meant to be used to filter options, rather than the list itself.
Here's what I've put together (demo)
import React, { useState, useCallback, useEffect } from 'react';
import {
  View,
  FlatList,
  ActivityIndicator,
  Text,
  StyleSheet,
} from 'react-native';
import { TextInput } from 'react-native-paper';
import { SelectList } from 'react-native-dropdown-select-list';
import useFetch, { formatDate } from './components/Hooks/useFetch';

const SORT_TYPES = ['default', 'newest', 'oldest', 'random'];
const SORT_FUNCTIONS = {
  oldest: (a, b) => a.creationTime - b.creationTime,
  newest: (b, a) => a.creationTime - b.creationTime,
  random: () => Math.random(),
};

const Sorting = () => {
  const { data, loading } = useFetch();
  const [list, setList] = useState([]);
  const [sortType, setSortType] = useState(SORT_TYPES[0]);
  const [filter, setFilter] = useState('');
  const [filteredList, setFilteredList] = useState([]);

  const handleSort = useCallback(() => {
    if (!data) return;
    if (sortType == 'default') setList(data);
    const sortFunction = SORT_FUNCTIONS[sortType]
      setList((prev) => {
        const newList = [...prev];
        return newList.sort(sortFunction);
      });

  }, [data, sortType]);
  // data initial value will be null/undefined when it changes update other values
  useEffect(() => {
    if (data) {
      setList(data);
      setFilteredList(data);
    }
  }, [data]);
  // when filter changes update list
  useEffect(() => {
    if (filter.length < 1) setFilteredList(list);
    else
      setFilteredList((prev) =>
        prev.filter((search) => {
          const searchedText = filter.toLowerCase();
          const currentTitle = search.title.toLowerCase();
          return currentTitle.indexOf(searchedText) > -1;
        })
      );
  }, [filter, list]);

  if (loading) {
    return (
      <ActivityIndicator
        style={{ flex: 1, justifyContent: 'center' }}
        size="large"
      />
    );
  }

  const renderMovies = ({ item }) => (
    <View style={styles.itemContainer}>
      <View style={styles.textContainer}>
        <Text>
          {item.title}
          {'\n'}
        </Text>
        <Text>Date:{formatDate(item.creationTime)}</Text>
      </View>
    </View>
  );

  return (
    <View style={styles.container}>
      <SelectList
        onSelect={handleSort}
        setSelected={setSortType}
        data={SORT_TYPES}
        search={false}
      />
      <FlatList
        numColumns={2}
        horizontal={false}
        data={filteredList}
        renderItem={renderMovies}
        stickyHeaderIndices={[0]}
        ListHeaderComponent={
          <TextInput
            mode="outlined"
            label="Filter list"
            onChangeText={setFilter}
            value={filter}
            dense
          />
        }
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 8,
  },
  itemContainer: {
    width: '50%',
    borderWidth: 1,
    alignItems: 'center',
    padding: 4,
    margin: 4,
    flexWrap: 'wrap',
  },
  textContainer: {
    margin: 4,
    flexWrap: 'wrap',
  },
});
export default Sorting;

Comment: Thnak you. It works very well.


Find the x for the minimum area of triangle

Question: Triangle area = f(x) = $$\frac{{(4+a^2)}^2}{-4a}$$
So, to find min area, i take the derivative and equals to 0
$$f'(x) = 16 -8a^2-3a^4$$
$$0 = 16 -8a^2-3a^4$$
How to factorize it? Thanks
Comment: $3(a^2)^2+8(a^2)-16=0\therefore(3a^2-4)(a^2+4)=0$
Comment: Thanks i should have realized it
Answer: Hint: $3a^4+8a^2-16$ is in quadratic form, and you can also factor it. The factoring would be $(a^2+4)(3a^2-4)$=0, or $(a+2i)(a-2i)(\sqrt{3}+2)(\sqrt{3}-2)$.
Answer: At the risk of being pedantic, even if you arrive to the correct equation, you must know that your derivative if wrong.
$$f(x)=-\frac{\left(a^2+4\right)^2}{4 a}\implies f'(x)=-a^2-4+\frac{\left(a^2+4\right)^2}{4 a^2}=-\frac{3 a^2}{4}+\frac{4}{a^2}-2$$ What you wrote, as $f'(x)$ is in fact $4a^2 f'(x)$ assuming that $a\neq 0$.
Now, to get the solution of $f'(x)=0$, you need to solve $$-\frac{3 a^2}{4}+\frac{4}{a^2}-2=0$$ Let $x=a^2$ to make the equation
$$-\frac{3 x}{4}+\frac{4}{x}-2=0\implies 3 x^2+8 x-16=0$$ which is a quadratic in $x$; its solutions are
$x_1=-4$ and $x_2=\frac 43$. $x_1$ must be discarded since $x=a^2>0$ and the only root is then $a^2=x_2=\frac 43$.


Complex numbers singularites

Question: I was recently watching a video about residue theorem, and I got confused on one part which he didn't explain in details
how does this
$$z^4+1=0$$
lead to that $$z=e^{i(\frac{\pi}{4}+\frac{\pi}{2}n)}$$
where $n=0,1,2,3$
Comment: Does it have anything to do with eulners identity? since $z^4=-1$ so we can write it as $e^{i\pi}=-1$?
Comment: $z^4=-1$ says that $z^8=1$, so $z$ is an $8$-th root of unity, i.e., a power of $e^{2\pi i/8}$. Then use $\ker(\exp))=2\pi i \mathbb{Z}$.
Answer: From $|z|=1$, let $z=\cos\theta+i\sin\theta$ then $z^4=\cos4\theta+i\sin4\theta=-1$ which shows $\cos4\theta=-1$ or $4\theta=2k\pi+\pi$ and then
$$\theta=\dfrac{k\pi}{2}+\dfrac{\pi}{4}$$
so
$$z=e^{i\left(\frac{k\pi}{2}+\frac{\pi}{4}\right)}$$
where $k=0,1,2,3$.

Complex numbers singularites


Prove that following recursively defined sequence converges and its limit is 1/2

Question:
\begin{cases}a_1 = 1\\ \\ \displaystyle a_{1+n} = \sqrt{\sum_{i=1}^n a_i}\end{cases}
Prove that $\{\frac{a_n}{n}\}$ is convergent and its limit is $\frac12$

My proof:   We can recursively define relation between $a_{1+n}$ & $a_n$ as
$a_{1+n} = \sqrt{a_n^2+a_n}$
Also, it is evident that $a_{1+n} > a_n > 1$
Thus, $a_{n}^2 - a_{n-1}^2 + a_{n} - a_{n-1} = a_{n} > 1 > 1/4$
Thus,  $a_{n+1} = \sqrt{a_{n}^2  + a_{n}} > \sqrt{a_{n-1}^2+a_{n-1}+1/4} = a_{n-1} + 1/2  $
Similarly, we can show $a_{n+1} = \sqrt{a_{n}^2  + a_n} < a_n + 1/2$
So, we have  $a_1 + \frac{n-1}2 < a_{n+1} < a_1 + \frac{n+1}2$
Using Sandwich Theorem we got limit of $\frac{a_n}n$ as $\frac12$
Is my proof correct.
I will be grateful if you can provide alternative proofs
Answer: As pointed out in question, the sequence satisfy the recurrence relation $a_{n+1} = \sqrt{a_n^2 + a_n}$.
From this, it is easy to see $a_n$ is strictly increasing and positive.
One consequence of this is $a_n$ cannot be bounded.
Assume the contrary, then $a_n$ converges to some finite value $M > 0$. Since the map $x \mapsto \sqrt{x(x+1)}$ is continuous, the "limit" $M$ will then satisfy $M = \sqrt{M^2 + M} > M$ which is absurd.
Another consequence is
$$a_n < a_{n+1} < \sqrt{a_n^2 + a_n + \frac14} = a_n + \frac12
\quad\implies\quad 1 < \frac{a_{n+1}}{a_n} < 1 + \frac1{2a_n}$$
Since $a_n$ is unbounded, this leads to
$\displaystyle\;\lim_{n\to\infty}\frac{a_{n+1}}{a_n} = 1$ and hence
$$\lim_{n\to\infty} \frac{a_{n+1}-a_{n}}{(n+1)-n} =
\lim_{n\to\infty}\frac{a_{n+1}^2-a_n^2}{a_{n+1}+a_n}
= \lim_{n\to\infty}\frac{a_n}{a_n + a_{n+1}}
= \lim_{n\to\infty}\frac{1}{1 + \frac{a_{n+1}}{a_n}}
= \frac{1}{1+1} = \frac12$$
By Stolz-Cesàro, we can conclude
$$\lim_{n\to\infty} \frac{a_n}{n} \quad\text{exists and equals to}\quad \lim_{n\to\infty}\frac{a_{n+1}-a_n}{(n+1)-n} = \frac12$$
Answer: Try showing via induction that $(a_n)_{n \in \mathbb{N}}$ is monotone and bounded and the solve the fixed point equation (aka $\lim\limits_{n \to \infty} a_n = \lim\limits_{n \to \infty} a_{n+1}$).
Comment: Monotone is obvious but how to show boundedness?
Answer: You have shown that $a_{n+1}-a_{n-1} \gt \frac 12$  but that is a step of $2$ in the index.  You therefore can only conclude that $a_{n+1} \gt a_1+\frac n4$ and the squeeze fails.


Show that $\det(A+A^t)\neq p$ where $p$ is a prime number and $A \in M_{p \times p}(\mathbb{Z})$

Question: I've stumbled across the above question. Usually, I don't spend my time on such problems, though it's a nice question in my opinion.
My idea:
Case $p=2$ is easy, follows from $x^2 \equiv 2 \;\;\; (\text{mod} \;\; 4)$ has no integer solution.
Assume the contrary and $p$ is an odd prime number. Since, $A+A^t$ is symmetric, then is has only real eigenvalues, so if $\det(xI-(A+A^t)) \in \mathbb{Z}[x]$ is the characteristic polynomial, it factors $(x-\lambda_1) \cdots (x-\lambda_p)$ where $\lambda_i$'s are real numbers. By rational root test, if any of $\lambda_i$ is rational, then it will be an integer. Therefore, if we show that non of them is irrational (hence, all $\lambda_i$ are integers), we may then conclude as follows;
$\sum_i \lambda_i=-tr(A+A^t)=2k$ where $k \in \mathbb{Z},$ and $\lambda_1 \cdots \lambda_p=-p.$ Now, $p$ is odd, then wlog,

$\lambda_p=-p$ and $\lambda_1=\cdots=\lambda_{2t}=-1$ and $\lambda_{2t}=\cdots=\lambda_{p-1}=1,$ but $\sum_i \lambda_i=-2t+p-1-2t-p$ which is odd,
$\lambda_p=p$ and $\lambda_1= \cdots=\lambda_{2t+1}=-1$ and $\lambda_{2t+1}=\cdots=\lambda_{p-1}=1,$ but again $\sum_i \lambda_i=-2t-1+p-1-2t-1+p$ which is odd,

hence contradiction.
Now, we're left to show that (in my words)
Lemma: Given $p$ integers and irrational numbers, where $p$ is an odd prime number. We have that
$$\sum_i\lambda_i=2k \in \mathbb{Z}, $$
$$\sum_{i<j}\lambda_i\lambda_j \in \mathbb{Z},$$
$$.$$
$$.$$
$$.$$
$$\lambda_1\cdots \lambda_p=-p \in \mathbb{Z}.$$
Then, non of the $\lambda_i$ is irrational.
An idea to prove the lamma: Since any symmetric polynomial in $p$ variables $\lambda_i$ with integer coefficient can be expressed in terms of elementary symmetric polynomials above, then any symmetric (polynomial with integer coefficient) expression of $\lambda_i$'s will be an integer.

Is it possible to conclude from here that non of the $\lambda_i$ is irrational?

P.S. I'd appreciate any other ideas for solving it.
Answer: If $p$ is odd, the determinant of the skew-symmetric $p\times p$ matrix $A^t-A$ is zero. But
$$
A+A^t\equiv A^t-A\pmod2,
$$
so
$$
\det(A+A^t)\equiv\det(A^t-A)\equiv 0\pmod2.
$$
Thus $\det(A+A^t)$ is an even integer, and hence $\neq p$.
Answer: Or straight from a definition of the determinant: Let $A$ be a symmetric square integer matrix with odd dimension and even entries on the diagonal.  Then
$$
\det(A) = \sum_{\sigma}\textrm{sgn}(\sigma)\prod_iA_{i\sigma(i)}.
$$
Now $\sigma$ and $\sigma^{-1}$ have equal sign and
$$
\prod_iA_{i\sigma^{-1}(i)} = \prod_iA_{\sigma(i)i} = \prod_iA_{i\sigma(i)}.
$$
So if $\sigma \neq \sigma^{-1}$ then their combined contribution to the determinant is even.  If $\sigma = \sigma^{-1}$ then $\sigma$ has a fixed point and so its contribution is also even.  Therefore $\det(A)$ is even.
Comment: yes, a lot easier way!


Show that if $L(u_i)=v_i$ for some finite set, and span$(u_i) \cap \ker(L)=0,$ then the set of v_i are independent.

Question: I get that, if $c_1v_1 + ... + c_nv_n = 0,$ applying L to both sides gives that, $c_1u_1 + ... + c_nu_n \in \ker(L),$ so $c_1u_1 + ... + c_nu_n = 0$ but since we don't know if the $u_i$'s are independent or not, I'm not seeing why this implies that the $v_i$'s are independent.
Comment: What did you try?
Comment: Well I tried showing they are independent by showing that the sum of the u_i's is in the kernel, but I get stuck at this point.
Comment: I also tried showing that if the u_i's are dependent that more than one thing is in the kernel, but I can't seem to make this work either.
Answer: I don't think you've offered enough conditions. I'll assume $L$ is linear mapping, at least $\Bbb Z$-linear map, and $\{u_i\mid i\in I\}$ is linear independent.
Then, if there exists $c_i$ such that $\sum_{i\in F}c_iv_i=0$. ($F\subseteq I$ is finite set.)
Then $u=\sum_{i\in F}c_iu_i$ is the element of $\text{span}(u_i)$, and $\ker L$. Why?

 $L(u)=L(\sum_{i\in F}c_iu_i)=\sum_{i\in F}c_iL(u_i)=\sum_{i\in F}c_iv_i=0$.

So $u=0$, because $\ker L\cap\text{span}(u_i)=0$. That means $\forall i\in F, c_i=0$.
Every non-trivial linear combination of $\{v_i\mid i\in I\}$ is non-zero. So $\{v_i\mid i\in I\}$ is linear independent.
Comment: Thank you! But isn't this only true if the set of u_i's is independent? We do not know this for sure in the problem I was given.


What is an attack hit in volleyball?

Question: What exactly constitutes an attack hit in volleyball?
For example, if I set the ball to someone else for an attack hit, and the set goes too far and it is blocked by someone on the opposing team with their hands over my side of the net, is that legal? Would my hit have been counted an attack hit?
Comment: See also http://sports.stackexchange.com/a/3944/96
Answer: This is specifically defined in section 13 of the official rules:

13.1.1 All actions which direct the ball towards the opponent, with the
  exception of service and block, are considered as attack hits.

Your set directed the ball towards the opponent, therefore it is an attack hit and therefore it can be blocked. You may also wish to refer to 14.3:

14.3 In blocking, the player may place his/her hands and arms beyond the
  net, provided that this action does not interfere with the opponent's
  play. Thus, it is not permitted to touch the ball beyond the net until an
  opponent has executed an attack hit.
Answer: 14.3 is the key,  and the answer isn't as crystal clear as the excepted answer states.   The actual answer really depends on what you mean by the phrase, "the set goes too far."
Even though the set was "too far", did you still have a player on your team that could have made a play on the ball prior to it going over the net? If so, it is a fault for the defensive player to reach over the net and interfere with your player's play on the ball.
Comment: -1. The rules have been directly quoted, and they do not support your interpretation. In particular, "could have played it" is not nearly the same thing as "actually did or attempted to play it".
Comment: @Nij the interpretation in this answer is correct; a blocker may not prevent a poster attempting to play the ball within their space, even if the ball is heading over the net.
Comment: But the answer doesn't say anything about an attempt. It only says "could have" and I have pointed out the problem with that equivocation already.
Comment: @Nij It's still right - this may not be clear from the section I've quoted in the rulebook, but it *is* how the game is played. This is specfically covered by Case 9.1 in the [2016 Casebook](http://www.fivb.org/EN/Refereeing-Rules/Documents/2016_Volleyball_Rules_Casebook.pdf).
Answer: The attack-hit is the action of a player to direct the ball towards the opponents court. When the ball is contacted by the blocker or crosses the vertical plane of the net then it is considered as completed.
Comment: Welcome to Sports SE, Please check [How do I write a good answer?](https://sports.stackexchange.com/help/how-to-answer) and improve your answer by adding references to your answer.

What is an attack hit in volleyball?


How to disambiguate instructions from data in the .text segment of a PE file?

Question: I have a PE file and I try to disassemble it in order to get it's instructions. However I noticed that .text segment contains not only instructions but also some data (I used IDA to notice that). Here's the example:
.text:004037E4                 jmp     ds:__CxxFrameHandler3
.text:004037EA ; [00000006 BYTES: COLLAPSED FUNCTION _CxxThrowException. PRESS KEYPAD "+" TO EXPAND]
.text:004037F0 ;
.text:004037F0                 mov     ecx, [ebp-10h]
.text:004037F3                 jmp     ds:??1exception@std@@UAE@XZ ; std::exception::~exception(void)
.text:004037F3 ;
.text:004037F9 byte_4037F9     db 8Bh, 54h, 24h        ; DATA XREF: sub_401440+2o
.text:004037FC                 dd 0F4428D08h, 33F04A8Bh, 0F6B2E8C8h, 0C4B8FFFFh, 0E9004047h
.text:004037FC                 dd 0FFFFFFD0h, 3 dup(0CCCCCCCCh), 0E904458Bh, 0FFFFD9B8h
.text:00403828 dword_403828    dd 824548Bh, 8BFC428Dh, 0C833F84Ah, 0FFF683E8h, 47F0B8FFh
.text:00403828                                         ; DATA XREF: sub_4010D0+2o
.text:00403828                                         ; .text:00401162o
.text:00403828                 dd 0A1E90040h, 0CCFFFFFFh, 3 dup(0CCCCCCCCh), 50E0458Dh
.text:00403828                 dd 0FFD907E8h, 458DC3FFh, 0D97EE9E0h
.text:00403860                 db 2 dup(0FFh)
.text:00403862 word_403862     dw 548Bh

How can I distinct such data from instructions? My solution to this problem was to find simply the first instruction (enter address) and visit each instruction and all called functions. Unfortunatelly it occured that there are some blocks of code which are not directly called but their addresses are in .rdata segment among some data and I have no idea how distinct valid instruction addresses from data.
To sum up: is there any way to decide whether some address in .text segment contains data or instructions? Or maybe is there any way to decide which potential addresses in .rdata should be interpreted as instructions addresses and which as data?
Answer: You cannot, in general. The .text section of a PE file can mix up code and constants any way the author likes. Programs like IDA try to make sense of this by starting with the entrypoints and then disassembling, and seeing which addresses are targets of jumps, and which of reads. But devious programs can 'pun' between instructions and data.
Comment: So the only instructions which I can be sure that are properly disassembled are those which are accessible from the entry point?
Comment: @AdamSznajder: the only instructions you can be *sure of* are those that are actually *exectuted* by the CPU on a specific run of the program. For everything else you have to make assumptions.


Python BeautifulSoup: How to return the html tag that the html text comes from?

Question: I am hoping to iterate through a list of urls to find specific information about various stocks. However, I need to find the html tag where specific text came from. For example, take text on this AMZN stock ticker:
The text shows "Market Cap". I want to find where this comes from and return it. By inspecting element, I find the html tag says: Market Cap. I am hoping to have it return the previously bolded text and the tag above it: Market Cap
I tried to do something the like following:
parent_tag = soup.find(text="Market Cap")
print(parent_tag)
It just returned "Market Cap".
Comment: I don't fully understand your problem, could you clarify what you're trying to receive as the output?
Answer: If your goal is to find parents, you can try BS4's find_parent and find_parents which are both very straightforward. See the docs for those two methods, and their example:
a_string = soup.find(string="Lacie")
a_string
# 'Lacie'

a_string.find_parents("a")
# [Lacie]

a_string.find_parent("p")
#
Once upon a time there were three little sisters; and their names were
#  Elsie,
#  Lacie and
#  Tillie;
#  and they lived at the bottom of a well.

a_string.find_parents("p", class_="title")
# []


Docker + nginx + Php-FPM 502 Bad Gateway

Question: I'm trying to install php-fpm and nginx via docker and I have a problem with nginx which returns me a 502 Bad gateway error, however when I try to go on any HTML file only displays correctly. What must I do to a php file works correctly with this system?
Nginx config site:
server {
        listen      80;
        server_name  api.local.dev;
        access_log  /var/log/nginx/api.access.log;
        error_log   /var/log/nginx/api.error.log;
        root        /www;
        charset     utf-8;
        index  index.php index.html index.htm;
        location / {
                index  index.php index.html index.htm;
        }

        location ~ \.php$ {
                include fastcgi_params;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
}

Dockerfile
FROM ubuntu:13.10

# Keep upstart from complaining
RUN dpkg-divert --local --rename --add /sbin/initctl
RUN ln -sf /bin/true /sbin/initctl

# Let the conatiner know that there is no tty
ENV DEBIAN_FRONTEND noninteractive

RUN locale-gen en_US.UTF-8
ENV LANG       en_US.UTF-8
ENV LC_ALL     en_US.UTF-8

RUN apt-get update && apt-get upgrade -y

RUN apt-get -y install nginx php5-fpm php5-mysql php-apc pwgen python-setuptools curl git unzip
RUN apt-get -y install php5-curl php5-gd php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-sqlite php5-tidy php5-xmlrpc

VOLUME  ["/var/log/nginx"]

CMD echo "127.0.0.1      api.local.dev" >> /etc/hosts
EXPOSE 80

RUN mkdir /www
RUN chown www-data:www-data -R /www
RUN echo "<?php phpinfo()  ?>" > /www/index.php
RUN cat /www/index.php

RUN mkdir /docker
ADD nginx /docker/nginx

RUN mkdir -p /var/log/nginx

RUN chown www-data:www-data /var/log/nginx
RUN sed -i -e"s/keepalive_timeout\s*65/keepalive_timeout 2/" /etc/nginx/nginx.conf
RUN sed -i -e"s/keepalive_timeout 2/keepalive_timeout 2;\n\tclient_max_body_size 100m/" /etc/nginx/nginx.conf

RUN sed -i -e "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g" /etc/php5/fpm/php.ini
RUN sed -i -e "s/upload_max_filesize\s*=\s*2M/upload_max_filesize = 100M/g" /etc/php5/fpm/php.ini
RUN sed -i -e "s/post_max_size\s*=\s*8M/post_max_size = 100M/g" /etc/php5/fpm/php.ini
RUN sed -i -e "s/;daemonize\s*=\s*yes/daemonize = no/g" /etc/php5/fpm/php-fpm.conf
RUN sed -i -e "s/;catch_workers_output\s*=\s*yes/catch_workers_output = yes/g" /etc/php5/fpm/pool.d/www.conf
RUN cat /etc/php5/fpm/pool.d/www.conf
RUN find /etc/php5/cli/conf.d/ -name "*.ini" -exec sed -i -re 's/^(\s*)#(.*)/\1;\2/g' {} \;

RUN echo "cgi.fix_pathinfo = 0;" >> /etc/php5/fpm/php.ini

RUN cat /docker/nginx/api.local.dev >  /etc/nginx/sites-available/api.local.dev
RUN ln -s /etc/nginx/sites-available/api/local.dev /etc/nginx/sites-enabled/api/local.dev

RUN echo "daemon off;" >> /etc/nginx/nginx.conf

CMD ["nginx"]

nginx.conf
user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;
    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # nginx-naxsi config
    ##
    # Uncomment it if you installed nginx-naxsi
    ##

    #include /etc/nginx/naxsi_core.rules;

    ##
    # nginx-passenger config
    ##
    # Uncomment it if you installed nginx-passenger
    ##

    #passenger_root /usr;
    #passenger_ruby /usr/bin/ruby;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Comment: did you see anything interesting in nginx's logs ? in php-fpm logs ?
Comment: And what does `netstat -lntp` output ?
Comment: **Nginx log**

    connect() to unix:/var/run/php5-fpm.sock failed (111: Connection refused)
or according to my tests

    failed (2: No such file or directory) while connecting to upstream
Comment: **netstat** Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      -
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     1820188  -                   /var/run/php5-fpm.sock
Comment: Don't use comments for this, update your question. And you can answer your own question if you have the solution.
Answer: Ok,
I solved my problem, that's how I did it:
docker run -i -t ubuntu /bin/bash

Then I looked at the nginx logs that indicated a problem with the upstream php fpm server as shown above
tail -f /var/log/nginx/*

Finally I restart the php5-fpm service
service php5-fpm restart

So finally my problem is that during the installation of container service was launched but with php misconfiguration and thus restarting the service has reloaded the php5-fpm configuration
Answer: You are making the faulty assumption that a docker container is just another machine or vm. With Docker should always try to run one thing only per container. You are then supposed to use links and volumes to make them talk together.
CMD should start the program directly and the daemon should instead be configured to run in the foreground, thus not as a service. Logs should preferably also be forwarded to docker but that is a bit beyond me (see the official app builds on github).
Also make sure that certain things are not run as root, because Docker does not offer proper security isolation features at this time.
In the end your issue is resolved by taking a look at their newly improved documentation and learning the essentials.


Visual Studio - How to search in pending changes files?

Question: I've made plenty of changes in my solution, using TFS, and I want to search for something only in the files which I edited (which appear in the "Pending Changes").
There is only an option to search in specific directories of the solution but not in the edited files.
Maybe there is some extension that can help with it?
For example, I want to search for TODO comments but only in the files edited by me, without seeing TODOs of other developers.
Answer: Press ctrl + shift + f
In Result options, select Find results Table

Press find all and then, in the find window filter by select Changed Documents.
Comment: Great! that's exactly what I wanted!
Comment: If aynone got advice how to make this work when having multiple external solutions checked out, please let me know. It doesn't detect any 'Changed documents' when I search all files (cause Entire solution doesn't cover it) Using 'All files' and typing in words in the filter works, but it's still not as efficient than the 'Changed documents' feature.
Answer: This is not the answer for searching in pending changes in general, but it is possible to get list of TODOS only from changed files by using Task list window.
Open Task list window and use the filter for only Changed documents:
Comment: That's nice option, and I can edit the task tokens in `Tools -> Options -> Environment -> Task List`, it will show them in this list... Thanks, but this solution only for search in comments of changed documents.
Answer: It doesnt look like there is a way to do this directly but I am able to do it via a work around that might work for you.

Shelve your pending changes
Delete all local items
Unshelve your changes (this should now bring down only the files you have edited to
your local)
Perform your search on the parent folder of all the edited items.
Comment: Oh, it would work, but it is too much effort... Looking for an easier way. Thanks
Comment: This looks promising but I have not tried it.  Doesnt look like its exactly what you are looking for, but I have not seen an extension with quite that capability.
Here is the extension: https://marketplace.visualstudio.com/items?itemName=EntrianSolutions-RichieHindle.EntrianSourceSearchAfulltextindexsearchengineforyo#overview.  And
http://entrian.com/source-search/doc-searching.html  is the manual page which talks about search filtering
Comment: I've tried these options, but it's not what i'm looking for.
Answer: It's super hacky but you could write a quick console/win forms application to:

Scan your project directory for files with a last modified date greater than your last check in
Copy them to a separate temp folder
Use the visual studio's find in files feature to search that temp directory.
Comment: Too much effort, I'm sure there is more elegant way to do it.
Answer: Not the exact answer for this question but go to View/Task List to search for the TODO
Apply the technics explained in the other answers.
To get a list of tokens, go to Tools/Options/Environment/TaskList
Comment: Apply the technics explained in the other answers?! What technics?


Javascript regex for validating filenames

Question: I have a regexp to validate file names. Here is it:
/[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/

It should allow file names like this:
aaa
aaa.ext
a#
A9#.ext

The following characters are not allowed \ / : * ? \" < > |
The problem is that file names like *.txt or /\kk passes the validation. I am doing validation with keyup event. So when I put one extra character after not allowed one it shows that everything is correct.
Comment: the accepted answer fixed your regex, but your regex is not correct for checking Windows filenames. [see here](https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file)
Answer: For Windows names.
var isValid=(function(){
  var rg1=/^[^\\/:\*\?"<>\|]+$/; // forbidden characters \ / : * ? " < > |
  var rg2=/^\./; // cannot start with dot (.)
  var rg3=/^(nul|prn|con|lpt[0-9]|com[0-9])(\.|$)/i; // forbidden file names
  return function isValid(fname){
    return rg1.test(fname)&&!rg2.test(fname)&&!rg3.test(fname);
  }
})();

isValid('file name');

Comment: Escape / with \ in rg1. At least, VS 2010 thinks so.
Comment: It should be return !rg1.test(fname) && !rg2.test(fname) && !rg3.test(fname); I guess.
Comment: AUX is missing, COM0 is actually valid, starting with "." is actually valid... [ref](https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file)
Comment: ^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|\*\?\\:<>/$"]*[^\.\|\*\?\\:<>/$"]+$
Comment: Thanks @RyanWilliams for comment. But I know way to create file in Windows with long file name that contains dot in the end of file name and without extention :)
Comment: Hi @Andrew D. If you want to permit filenames ending in a dot, try this one instead ^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|*\?\\:<>/$"]+$  if you wish to allow filenames starting with a . then simply remove the (?!\.) part.
Comment: @mav3n You are wrong. _rg1.test(...)_ does not require _logical not_ operator. Check _isValid("foo.txt")_ and _isValid("fo:o.txt")_
Answer: You need to anchor the expression by using ^ and $. For example:
/^[-\w^&'@{}[\],$=!#().%+~ ]+$/

Note that you need to escape - in a character class, or place it first/last.
Comment: Can you tell a bit what this regex does?
Answer: You need to add a starting anchor:
/^[0-9a-zA-Z ... ]+$/

This tells the engine to match from the start of the input all the way to the end of the input, whereas for your original expression it only needs to match at the end of the input.
Answer: /^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|\*\?\\:<>/$"]*[^\.\|\*\?\\:<>/$"]+$/

Must not be empty.
Must not start with .
Must not be com0-com9, con, lpt0-lpt9, nul, prn
Must not contain | * ? \ : < > $
Must not end with .

Comment: / (forward slash) is missing, AUX is missing, COM0 is actually valid, starting with "." is actually valid....  [ref](https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file)
Answer: Since this post (regex-for-windows-file-name) redirects to this question, I assume its about windows file names.
And based on the comment and reference by @Leon on the answer by @AndrewD, I made this regular expression and it works for me.
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig

According to the naming-conventions (see reference above), I agree that "com0" should be a valid file name, but its not working if you try to name a file "com0" on windows, so I guess thats missing in the article.
So this regular expression would be more safe
/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$|([<>:"\/\\|?*])|(\.|\s)$/ig

Comment: shortened: /^(con|prn|aux|nul|((com|lpt)[0-9]))$|([<>:"\/\\|?*])|(\.|\s)$/ig
Answer: I would try something with this Regex (you can even make a validation attribute for ASP.NET MVC with it!):
@"^[^\u0022\u003C\u003E\u007C\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000A\u000B\u000C\u000D\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\u003A\u002A\u003F\u005C\u002F]*$"

If it matches the input, it is valid filename (at least on Windows).
Answer: try this:
^[0-9a-z_\-]{3,255}\.([a-z0-9]{2,5})$

its for any filename with minimum 3 chars and max length from 255 and an extension from 2 till 5 chars... the chars of the filename itself allowed for numbers, chars and minus sign and underscore ... maybe its helpful.


How to change format of a number in sql?

Question: I have a MySQL table with hours:
10:30
11:00
9:00

how to format the numbers in PHP output and order them ASC?
I suppose, I need to change the format of the numbers to something like this?
09:00
10:30
11:00

Comment: Do you want the format to be changed in PHP os SQL?
Comment: The best way is to store minutes and hours in 2 columns, then you will be able to order (ORDER BY hour, minute ASC)
Comment: You'll need the date function in PHP.... True Story.
Comment: @putvande I need to change the format in PHP as I can not alter the database
Answer: i think you should change your field type for a "time" format. For ordering it's the best
Answer: $times_array = array();
$times = array("10:30","11:00","9:00");
foreach($times as $time){
    $times_array[strtotime($time)] = $time;
}

ksort($times_array);
print_r($times_array);

Answer: Here's an idea...
Store the time (PHP time() function), that way you'll be able to do whatever you want easily.
$strTime = time();
INSERT INTO tablename (time) VALUES ('$time');

Then you'll be able to sort easily...
// For example - simple query
SELECT time FROM table ORDER BY time ASC

or
SELECT HOUR(time), MINUTE(time) FROM table ORDER BY HOUR(time), MINUTE(TIME) ASC;

Displaying in PHP...
$strTimeFromDB = $arrDBResult['time'];

// Displaying the time e.g.: 11:00
echo date("H:i", $strTimeFromDB);


O que faz o "delete" na frente do construtor?

Question: O que significa esse delete na frente do construtor?
Grap& operator=(const Grab &g) = delete;

Answer: Note que isso é um operador de atribuição e não um construtor.
Ele está invalidando essa operação. Todo tipo em C++ tem o operador de atribuição criado automaticamente pelo compilador se nenhum for fornecido. Quando o seu tipo não pode permitir que atribuições sejam feitas com ele, esse é o jeito de impedir que o compilador crie o operador por você.
É possível fazer o mesmo com o operador de cópia.
Só está disponível a partir do C++11.


How does this function concatenate work with first order functions?

Question: let concat (l : string list) : string = fold_right (fun a x -> a ^ x) l ""

so to go through it, I see that

let concat takes a list with strings, and returns a string.
fold right takes 3 parameters,

1 the first being a function that concatenates two strings, it takes a and x, and then concatenates them using ^.
2 the second argument is the list,
3 and finally the third is the accumulator that gets each pass added to it.

BUT, how does the func a x know that a is the first element of the list, and x is the second.
And when it passes through again, how does it know that a is the third element of the list, and x is the fourth, and so forth?
Answer: The accumulator is the first argument, a, to the fold function, and x is set to each element of the list in turn as the fold walks over it.
The return value of the fold function is the new value of the accumulator.
The initial value of the accumulator is the empty string, so the result of the first concatenation, which becomes the new accumulator, is the same value as the first element of the list.
Then the next element is concatenated to that, and so on until the end of the list is reached, at which point the fold returns final value of the accumulator, the fully concatenated string.
Comment: Just a small comment: for `List.fold_right` the accumulator is the *second* argument of the folded function. For `^` it doesn't matter so much. For `List.fold_left` the accumulator is the first argument.


How to resolve the 403 error when creating a new node via RESTful module?

Question: I'm trying to create a new node through REST on Drupal 8 with no success and a 403 (Forbidden) error. I'm using REST UI module to enable permissions with the following config for Content resources:

GET authentication: basic_auth formats: hal_json, json
POST authentication: basic_auth formats: hal_json, json

After many failed tries I installed a fresh copy of Drupal 8.2.3 to discard it had to be with the recent core upgrade on my original site. The big surprise is on the fresh site there are no other RESTful module permissions than Administer REST resource configuration, no permissions to grant DELETE, GET, PATCH or POST to each role.
I'm using Postman for testing purposes as follows:

Request body:
{
    "_links": {
        "type": {
            "href": "http://fischer.dev:81/rest/type/node/article"
        }
    },
    "title": [
        {
            "value":"My article"
        }
    ],
    "type": [
        {
            "target_id":"article"
        }
    ]
}

User role is granted permissions to create Article nodes. I tried even with the admin credentials with no success. The GET method for retrieving an existing node is woking fine.
I don't know if there was any change on the latest Drupal release since the official documentation page for this module appears to be outdated. Am I missing something?
Answer: For headers you only need Content-Type and Authorization.
Your POST url needs to be http://fischer.dev:80/entity/node (this is only for POST).
If you are going to PATCH or DELETE, the url would then be the url of the node, Ex: http://fischer.dev:80/node/1 that you want to update (patch) or delete.

PS: Not really sure why you have port numbers in your url, and why you were using port 81 instead of 80, using http://fischer.dev/entity/node should be good enough.


Reference for working knowledge of abstract algebra

Question: I am a graduate student in Economics, and I'm looking for a text which can give me a good working understanding of abstract algebra. I am specifically interested in those topics that are used in algebraic topology and lattice theory.
PS I do not have any background in abstract algebra, while I have a pretty good understanding of real analysis, general topology, and linear algebra (at the same level as an undergraduate degree in math).
Answer: This is tough, because abstract algebra is very broad. I might recommend "A First Course in Abstract Algebra" by Fraleigh.
Comment: Looks pretty good,, thanks! It does talk about simplicial complexes like I wanted, and the chapter dependence schematic at the beginning of the book is quite helpful.


Access derived class property that is visible during runtime

Question: I wasn't sure how to title this question so maybe the description will help.
I am new to coding and want to use Inheritance to minimize my code.
I have two base class and two derived classes I am using:
Base Class 1:
public class TDXInput
{
    public SCContext SCContext { get; set; }
    public ToolContext ToolContext { get; set; }
    public WaferContainer WaferContainer { get; set; }
}

Derived Class 1:
public class CURTDXInput : TDXInput
{

}

Base Class 2:
public class WaferContainer
{
    public WaferContext WaferContext = new WaferContext();
    public List<WaferImage> ImageList = new List<WaferImage>();
    public List<WaferDieResults> WaferResultList = new List<WaferDieResults>();
    public List<WaferDieMeasurements> WaferMeasurementList = new List<WaferDieMeasurements>();
    public List<DieData> DieDataList = new List<DieData>();
}

Derived Class 2:
public class CURWaferContainer : WaferContainer
{
    //public CURWaferContext WaferContext = new CURWaferContext();
    public List<CURWaferImage> CURImageList = new List<CURWaferImage>();
    public List<CURWaferDieResults> CURWaferResultList = new List<CURWaferDieResults>();
    public List<CURWaferDieMeasurements> CURWaferMeasurementList = new List<CURWaferDieMeasurements>();
    public List<CURDieData> CurDieDataList = new List<CURDieData>();

}

The idea is that there is an umbrella format called TDXinput that has 3 main sections, SCCOntext, ToolCOntext,  and WaferContainer.
However there are tools that have their own uniqueness for these 3 section but also have a few similarities. Because of this I started to use inheritance.
A big goal is to be able to pass in an input like CURTDXInput to a general function that takes in the base class TDXInput so I don't have to rewrite that function each time a new TDXInput tool comes in:
public static TDX2KlarfResult CheckTDXInput(TDXInput input, TDX2KlarfResult result)
{
    if (input.ToolContext == null)
    {
        result.success = false;
        return result;

    }

    if (input.WaferContainer == null)
    {

        Logger.Warn("Missing Wafer Container Skipping the file");
        result.success = false;
        return result;
    }
    return result;
}

For the implementation above it does work but then I run into issues I am forced to use the base class instead of the derived class like so:
List<CURDieData> dieDataList = input.WaferContainer.DieDataList.OfType<CURDieData>().ToList();

When I inspect input during debugging in Visual studio I can see the value for CurDieDataList (which I want) from the CURWaferContainer class but I only can reference DieDataList from the WaferContainer class  which I then have to cast to CURDieData List. Is there a way for me to access CurDieDataList?
Also am I using inheritance correctly or is there a way I can get around not having to overload CheckTDXInput(TDXInput input, TDX2KlarfResult result) for each TDXInput derived type.
Comment: Re. your side question: [Inheritance is not a mechanism for code reuse.](https://www.arhohuttunen.com/misconceptions-about-code-reuse/) IMO, inheritance is one of the last concepts that new coders should be introduced to. The only topic that causes more confusion and brain damage is threads.
Comment: @KevinKrumwiede Is there any way to write a function that can handle different classes/types that have similar properties like I am trying to do with that CheckTDXInput function?
Answer: in that function you have a TDXInput. That gives you a WeferContainer.Fine but it not guaranteed what type that WaferContainer is
The simple thing to do is
 if(input.WaferContainer is CURWaferContainer){
    var cwc = input.WaferContainer as CURWaferContainer;
    // you now have the CURWaferContainer instance and can get at its data

Is this optimal?. Its hard to say, your object model is pretty complex. Testing objects for their type is a classic 'code smell'. A common solution would be for WaferContainer to have a virtual method called, say, GetMainDieList.
Its hard to say whats best tho
Comment: I am not familiar with the "as" clause in C#. I think I will roll back the inheritance model. What this means now is I'd have to rewrite that function each time for each derived class of TDXInput. Is there a way to make a generic function that can handle different classes with similar fields?
Comment: @Datboydozy https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator
Comment: Ok I see. The only issue with your logic there is that it always will be WaferContainer since it's only seeing the local TDXInput before runtime and during runtime, it still only searches for TDXinput's member properties which CURWaferContainer is not a part of @pm100


How to slow down the doing background in asynctask when internet connection down

Question: i use asynctask to do the GET request to server, and What i want to do is when the internet connection down ( no internet connection ) i want my AsynTask sleep abit then start send request again in the same asynctask , How can i do that
THx
Answer: Documentation says:
**Threading rules**
There are a few threading rules that must be followed for this class to work properly:
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Try using Handler, do the fetching HTTP stuff in Thread (you can make thread sleep for some amount of time using Thread.sleep(time); when you think you are ready to proceed call .sendMessage(message); and do the updates on the ui from the handler (handleMessage() or runOnUiThread() methods) if that is needed.
Comment: so you means i have to use manual thread rather AsysnTask to deal with my problem>??>
Answer: A logical thing to do would be listen to connectivity change broadcast and cancel the task when no connection available and restart it when the connection gets available again. You could check this Q to get the BroadcastReceiver ready.


Mac Post Events to specific background windows

Question: I am trying to create an accessibility app that will type in multiple windows at once, neither of which are owned by my app. For instance, let's say you have two Microsoft word documents open. When you hit a keystroke I want the command to go to both windows.
I have tried using Quartz events services, but it looks like it will only allow you to post to events either on a global or process level. But if two windows are running for the same process, how do I post to a specific window?
There's also the issue of the person typing in one window, while the content is being copied to the next.
Is it possible to post to a single window?
PS I know it's possible to do this in Windows
Comment: Have you tried using NSNotificationCenter? https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html
Comment: You're talking about interfering with the event/input dispatch of another process. That doesn't sound like a great idea, and I doubt there's going to be any built-in, system facility for that. It would be possible using some kind of code injection, however.
Comment: I know in Windows, you can post events like mouse clicks and keyboard presses to specific windows http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx
Answer: MacOS X includes a few tools which may be helpful. You should look into the Accessibility framework, Automator actions, and AppleScript. You should also be aware of application-specific solutions; in the case of Word, for example, you might look at VBA (Visual Basic for Applications). All of these tools provide ways that you can modify the content of other applications. Unfortunately, the level of support for each one varies from one application to another, and the way they're used also varies. So, it's unlikely that you'll find a single solution that works for all applications.
It's unlikely that you'll find a way to insert events directly into another process's event queue. That'd be a huge security hole, for one thing. Even if you could do that, you really wouldn't be able to target specific windows with your events. Mac applications use a responder chain that sends keystrokes to the "first responder", usually a component of the active window.


Ignore NAN value and compare the cell values and return true or false

Question: I would appreciate if someone can advise on how to solve this using pandas library. as I am newbie to programing.
I want to compare each the value on each raw ignoring NAN
Note: last raw also true.

Col_1 Col_2 Col_3 Col_4 Col_5 Col_6

A01 NaN A01 NaN A02 NaN
A02 A02 A02 A02 A02 A02
A03 A03 NaN NaN NaN A03
A04 A01 NaN A04 NaN NaN
A05 A05 A05 A05 NaN NaN
A06 NaN NaN NaN NaN NaN

I want the result to be as showing on below dataframe

Col_1   Col_2   Col_3   Col_4   Col_5   Col_6   results
A01 NaN A01 NaN A02 NaN FALSE
A02 A02 A02 A02 A02 A02 TRUE
A03 A03 NaN NaN NaN A03 TRUE
A04 A01 NaN A04 NaN NaN FALSE
A05 A05 A05 A05 NaN NaN TRUE
A06 NaN NaN NaN NaN NaN TRUE
Answer: Use DataFrame.nunique because method omit missing values:
df['results'] = df.nunique(axis=1).eq(1)
print (df)
  Col_1 Col_2 Col_3 Col_4 Col_5 Col_6  results
0   A01   NaN   A01   NaN   A02   NaN    False
1   A02   A02   A02   A02   A02   A02     True
2   A03   A03   NaN   NaN   NaN   A03     True
3   A04   A01   NaN   A04   NaN   NaN    False
4   A05   A05   A05   A05   NaN   NaN     True
5   A06   NaN   NaN   NaN   NaN   NaN     True


Use batch script to insert a string at a particular line in XML

Question: i am new to programming.
Can some1 kindly teach me how to insert a new line in an XML file using batch script?
Current file has first 2 lines:
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:xxxxxxxxx

I want to add a format string on Line 2 so it has:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:xxxxxxxxxx

It has to be using batch-file as the rest of the file is built with it.
Cheers,
Alan
Answer: @echo off
    setlocal enableextensions disabledelayedexpansion
    set "secondLine=^<?mso-application progid="Excel.Sheet"?^>"
    (for /f "delims=" %%a in (input.xml) do (
        echo(%%a
        if defined secondLine (
            echo(%secondLine%
            set "secondLine="
        )
    )) > output.xml

Comment: so how do i make this work for other line numbers? what if i want to insert into the 12th or the 23rd line how would I accomplish that?
Answer: I assume you are on Windows. If you do not already have Unix Utils, I would recommend grabbing that first and adding it to your PATH.
You can then do
 sed "1 a <?mso-application progid=\"Excel.Sheet\"?>" Input.xml > Output.xml
 move Output.xml Input.xml

Note that the Windows version of sed may not support the -i option, but if it does, you can shorten this to
sed -i "1 a <?mso-application progid=\"Excel.Sheet\"?>" Input.xml

Comment: thx Merlin, yes, I am using Window 7 on company PC, but it seems it automatically delete the files after I downloaded and extracted them.


Handle multiple gmail accounts

Question: I am using Google Calendar JavaScript API.It works fine for single account.Problem is when user is logged-in into two of my gmail accounts, It asks user every time to select which account user want to use.
I want API to remember my last selection at least for the session or most preferably till user disconnect himself.
Here is my JS file.

var clientId = $("#CalendarClientId").val();

var scopes = 'https://www.googleapis.com/auth/calendar';
var objEventList = [];
var calendarIdAtt;

function InitilizeCalendarAPI() {
    // Step 2: Reference the API key
    window.setTimeout(checkAuth, 5);
}
function CheckGoogleCalAuth() {

    gapi.auth.authorize({ client_id: clientId, scope: scopes }, HandleAuthCallBack);
}
function checkAuth() {
    gapi.auth.authorize({ client_id: clientId, scope: scopes }, HandelCalAuthResult);
}
function CheckAuthentication() {
    gapi.auth.checkSessionState({ client_id: clientId }, CheckAuthCallback);
}
function CheckAuthCallback(loginDataCallback) {

    if (loginDataCallback == false) {

        checkAuth();
        $("#googleAuthorize-Button").hide();
    }
}
function HandelCalAuthResult(authResult) {
    if (authResult && !authResult.error) {
        /*authorizeButton.style.visibility = 'hidden';*/
        $("#googleAuthorize-Button").hide();
        if ($("#googleConnected").length > 0) {
            $("#googleConnected").show();
        }
        /*bind listing of google calendar name in addevent page*/
        if ($("#divGoogleCalendarNameList").length > 0) {
            GetListOfCalendarNameFromGoogle();
        }
    } else {
        $("#googleAuthorize-Button").show();
        /*authorizeButton.style.visibility = '';*/
        if ($("#googleConnected").length > 0) {
            $("#googleConnected").hide();
        }
    }
    if ($('#googleAuthorized-Button').length > 0) {
        $("#googleAuthorize-Button").hide();
        $('#googleAuthorized-Button').show();
        $('#calenderSettingIcon').attr('data-original-title', 'Connected To Google');
    }
}

function CheckAutheForEventList() {

    gapi.auth.checkSessionState({ client_id: clientId }, CheckAuthCallbackListEvent);
}

function CheckAuthCallbackListEvent(loginDataCallback)
{
     gapi.auth.authorize({ client_id: clientId, scope: scopes }, LoadEventListinAPI);
}

function checkAuthEventList() {
    ConfirmConnectionToGoogleCalendar(function (isConnect) {
            if (isConnect) {
                gapi.auth.authorize({ client_id: clientId, scope: scopes },             LoadEventListinAPI);
            }
        });
}

function LoadEventListinAPI() {

    gapi.client.load('calendar', 'v3', GetAllCalendar);
}

function GetAllCalendar() {
    gapi.client.load('calendar', 'v3', GetCalendarAndTheirEvents);
}

function GetCalendarAndTheirEvents() {

    objEventList = [];
    try {
        var objDate = GetMinAndMaxDate();
        var finalMinDate = (objDate.MinDate).toISOString();;
        var finalMaxDate = (objDate.MaxDate).toISOString();;

        var request = gapi.client.calendar.calendarList.list();
        var tempCount = 0;
        request.execute(function (resp) {

            var calLength = resp.items.length;
            $.each(resp.items, function (index, item) {
                if (item.accessRole == "owner") {
                    try {
                        calendarIdAtt = item.id;
                        var request = gapi.client.calendar.events.list({
                            'calendarId': item.id,
                            'showDeleted': false,
                            'singleEvents': true,
                            'orderBy': 'startTime',
                            'maxResults': 100,
                            'timeMin': finalMinDate,
                            'timeMax': finalMaxDate
                        });

                        request.execute(function (resp) {
                            tempCount = tempCount + 1;
                            var events = resp.items;
                            if (events.length > 0) {
                                objEventList.push(events);
                            }
                            if (tempCount == calLength) {
                                //Binding Kendo Scheduler with Google Calenda Events
                                var eventsList = BindEventToCalendar();
                                LoadEventsScheduler(eventsList);
                            }
                        });
                    }
                    catch (error) {
                        tempCount = tempCount + 1;
                        if (tempCount == calLength) {
                            BindEventToCalendar();
                        }
                    }
                }
                else {
                    tempCount = tempCount + 1;
                    if (tempCount == calLength) {
                        BindEventToCalendar();
                    }
                }
            });
        });
        return objEventList;
    }
    catch (exception) {
        BindEventToCalendar();
        return null;
    }
}

//Function will display google calendar events in the Kendo Scheduler
function LoadEventsScheduler(eventsList) {

    //This will retrun all the google calendar events to the server side for the scheduler
    var request = {
        EventsList: eventsList, CalendarAccount: calendarIdAtt
    };
    $.ajax({
        type: "POST",
        data: JSON.stringify(request),
        url: $_SetEventScheduler,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var data;
            if (msg.hasOwnProperty("d")) {
                data = msg.d;
            }
            else
                data = msg;
            if (data.success) {
                $("#scheduler").data("kendoScheduler").dataSource.read();
            }
            else {

            }
        }
    });
}

I noticed that API show me logged in but calendar is not stored in case of multiple accounts,so it asks me again to select the account.
Summary: I want to save the complete scenario (may be calendar_id or any unique identifier) which can tell API which account and which calendar should be picked up.
If you need more details, please let me know.
Answer: I simply used the auth2 implementation and it is working perfect.
Basically current session state function do not work properly in old API. That's why it was asking every time for selecting the account and calendar.

Handle multiple gmail accounts


How to create a card with image as background in CSS diagonally sliced

Question: I am trying to create a Card in HTML/CSS, that looks like:

BUT, what I want exactly is that the background, instead of being just grey like it is, is an image instead.
Here is what I've tried: JsFiddle
HTML:

John Doe

Architect & Engineer

CSS:
.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
}

.image {
  width:100%;
  clip-path: polygon(0 0, 100% 0, 100% 42%, 0 23%);
}

As you can see it works, but the problem is that there's space in between the image and the 'John Doe'.
I would like to know how to remove the space between the image and the John Doe.
Thanks
Comment: Check out: https://jsfiddle.net/sxbw8afq/ with your clip-path you cut off 58% of the image (100% from left and 42% from bottom) so start by changing that to 100% 100% and 0 23% to 0 70% or something. Then you can work with image `height`,  `object-fit` and negative `margin-top` on h3 to finetune it. Clip-Path only masks the element, but doesn't really modify it, so the other elements (h3 and text) will still behave as if `clip-path` is not there. So to debug you can remove your `clip-path` completely and you'll see why there is a space under the image.
Comment: Hi check this fiddle , i have created a `div` instead of `img` tag
Answer: Here is a simple solution with css transform.

.wrapper {
  position: relative;
  width: 280px;
  height: 350px;
  background: url('https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg') 0 0 no-repeat;
  background-size: cover;
  overflow: hidden;
}

.box {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 50%;
  background: #cdcdcd;
}

.content {
  position: absolute;
  z-index: 10;
  padding: 15px;
  box-sizing: border-box;
}

.folder {
  position: absolute;
  top: -20px;
  left: -10px;
  width: 120%;
  height: 60px;
  background: #cdcdcd;
  transform: rotate(8deg);
}

Here is my content.

Answer: You can add the following to your css:
.container {
  position: absolute;
  top: 150px;
}

You will see that your card's height is influenced. You can the just give your card a height that you desire, like this:
.card {
  height: 300px //this is your prefered height
}

Answer: .card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
  height:200px;
  position:relative;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
/*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  padding: 2px 14px;
  position: absolute;
  top: 45%;
}

.card p {
  margin: 14px 0;
}
.card img {
  position:absolute
  }

//that's all..
Comment: Code-only answers are discouraged. Please click on [edit] and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. [From Review](https://stackoverflow.com/review/low-quality-posts/22050730)
Answer: Rely on background and you will have better support and less code:

.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  padding:100px 10px 5px;
  width: 50%;
  background:
   linear-gradient(to bottom left,transparent 49.5%,#fff 50%) 0 50px/100% 100px,
   linear-gradient(#fff,#fff) bottom/100% calc(100% - 150px),
   url(https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg) top/100% auto no-repeat;
   background-repeat:no-repeat;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
}

John Doe

Architect & Engineer


Alternatives to Chapters 8-10 of Rudin's PMA

Question: S.E advisers,
I have been hearing that the chapters on multi-varaible analysis in Rudin's PMA are almost nothing like previous insightful chapters in the single-variable analysis, and I verified myself too (very difficult to read).  I would like to receive your suggestions on alternative books to learn the analysis in R^n, manifolds, and differential forms.  Do I need to read a book in differential geometry/topology?
Unfortunately, I forgot most of concepts from the multivariable calculus...
Comment: I do not like when people use this forum to scold others, because it usually stems from a motivation of self-assertion.  Rudin's writing is extremely Bourbakist and dry.  He omits the most important ingredient: guiding the student how to think so as to have discovered this math on their own.  Meanwhile, according to Sir Michael Atiyah (who, unlike Rudin, got the Fields Medal), "The mathematical problems that have been solved or techniques that have arisen out of physics in the past have been the lifeblood of mathematics."
Comment: I do not like when people complain about these particular chapters because it is "word on the street" that these are the bad chapters -- reading the book with this preconceived notion only worsens the situation. I will tell you this: chapters 8 and 9 are beautifully and efficiently written. The exercises in chapter 9 are on the computational side, aiding in intuition in higher-dimensional thinking. By nature of the subject, differential forms are tough to read (half the battle is notation). You may run into the same problem in other books, but check Spivak's Calc on Manifolds or doCarmo.
Comment: No, because criticizing someone's behavior is scolding.

Psychological bias is not an inevitability.  The Asker did try reading,  despite the hearsay.  And, at any rate, instead of "I don't like when people" (criticizing behavior), writing "Hearsay can create psychological bias, possibly leading to rejecting a book that's actually good" would have been factual, without getting personal.  Far too many people on this forum already try to self-assert by rather asocial means.
Comment: @avs right, because offering a second opinion is scolding. If you dive into a book or movie having heard that it is second-rate, you're going to come out thinking it's second-rate. That's called psychological bias. My point is that a re-read with the understanding that the math is beautifully written would help OP mentally. Anyhow, thanks for the condescending words.
Answer: Zorich, "Mathematical Analysis".  Intuitive explanations, physical connections; in short, a ``human touch'' of a caring teacher.
Comment: The books seem to be very good!  It is slightly heavy in physics, but vector calculus has a foundation in physics!


Find the maximum area of the rectangle confined between g(x) = $e^{\frac{1}{2}x}$, f(x) = $e^{-x}$, and $x$- axis. (photo and figure included)

Question: Find the maximum area of the rectangle confined between $g(x) = e^{\frac{1 }{2}x}, f(x) = e^{-x}$, and the $x-$ axis.
Here I attached a picture with the figure illustrated and how I attempted to solve the problem. First I assigned different x's to each function: $(x_2, e^{\frac{1}{2}x_2})$ and $(x_1, e^{-x_1})$. Then I formed an equation for the area of the rectangle: $(x_1 + x_2)(e^{\frac{1}{2}x})$. Next I tried solving for $e^{\frac{1}{2}x_2}$ = $e^{-x_1}$ to be able to represent one $x$ with another $x$ so I can substitute it in the equation. Next, I found the derivative of the area equation and equaled it to zero so I get the x-coordinate of the maximum point but I ended up getting the x-coordinate of where the two functions intersect. Please see image
to better understand the problem and see the full solving process.
Comment: Your derivation of the function $a(x)=-xe^{-x}$ is wrong. Use the product rule !
Comment: God, what a stupid mistake. It drove me crazy. Thanks!
Answer: Solution
Let $(x_1,e^{-x_1})(x_1>0)$ lie on $y=e^{-x}$,and $(x_2,e^{x_2/2})(x_2<0)$ lie on $y=e^{x/2}$.
Notice that we need a rectangle. Hence, $$ e^{-x_1}=e^{x_2/2}.$$ It's clear that $$-x_1=\frac{x_2}{2},$$namely, $$x_2=-2x_1.$$
Thus, for the area $A$, we have $$A=(x_1-x_2)e^{-x_1}=3x_1e^{-x_1},~~~x_1>0.$$
Denote $f(x)=3xe^{-x}(x>0).$ Then $f'(x)=\dfrac{3(1-x)}{e^x}$. We may know readily that $f(x)$ reaches its maximum value at $x=1$.  It follows that $$\max (A)=\max_{x>0}f(x)=f(1)=\frac{3}{e}.$$


How do I filter a view by the results of hook_node_access?

Question: I have been trying to wrap my head around a specific problem for a few days now and have been unable to find a solution. Here's my problem:
In my LMS I'm performing pretty complex access checks. (In particular, I need to check permissions over references: A lesson should be accessible, if it's part of some course that's marked accessible for that specific user.) I have already written a module implementing hook_node_access and, so far, everything is working fine. Here's part of the code:
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
  $type = $node->bundle();
  $user = $account->getAccount();
  $uid = $user->id();

  // only handle the lesson content type
  if ($type === 'lesson') {

    if ($account->id() !== 1) {

      // first, check the user's access to the lesson itself
      $lessonaccess = ...

      // then, check the user's access to the referring courses
      $courseaccess = FALSE;
      if ($node->hasField('reverse_entity_reference')) {
        $parentcourses = $node->get('reverse_entity_reference')->getValue();

        foreach ($parentcourses as $course) {
          $coursenode = \Drupal\node\Entity\Node::load($course['target_id']);
          // perform access checks for the referring course
          $courseaccess = $courseaccess || ...
        }
      }

      // combine the results; teasers should always be accessible
      if ($lessonisteaser || ($lessonaccess && $courseaccess)) {
        return AccessResult::allowed();
      } else {
        return AccessResult::forbidden();
      }
    }
  }

  else {
    return AccessResult::neutral();
  }
}

The problem is that I would now like to create a view listing all lessons that are accessible to the current user. So, simply filtering by node access -- as is straightforward to achieve in Views -- is not sufficient, as I need to filter by what is returned from the access checks in hook_node_access.
Can anybody think of a way to make that possible? Maybe storing the result somewhere?
Comment: Yes, you need to store the result somewhere. This is the node_access table of the node grants system (part of core), which you then can use to filter nodes in Views. See this great blog post https://www.droptica.com/blog/drupal-node-grants/
Comment: Thank you very much, that link is very helpful, indeed. Frankly, I have never used the grants system before, but can already imagine that it has the potential to be faster than my approach. However... I still fail to understand, how I am to proceed: Can I store the result of `hook_node_access` as a grant somehow? How do the realms come into play? I think, the concept is still a bit unclear to me...
Answer: The problem here is that hook_node_access is a PHP function that has nodes passed through it, but Views is doing a database query for the relevant nodes. These two are incompatible, as Views would have to fetch every node in the system from the DB, then pass them all through that function, which would add major overhead.
Drupal's solution to this is the node grants system, which writes a set of grants to the {node_access} table, which can then be used in querying nodes.
To implement a grants system, you'll need to implement hook_node_access_records(), which is called when each node is saved, and sets up a number of rules by which the node being save is allowed to be accessed. Then you implement hook_node_grants(), which generates a set of potential grants for the current user, and tries to match them with the grants created in hook_node_access_records(). When there is a match, the user is granted permission to access, and this will work with DB queries.
Comment: hook_node_access() is implemented when accessing a single node. Individual nodes are passed through this function. The grants system is used when requesting nodes from the DB. It's used in DB queries. You probably need/want to use a combination of both of them, but they work independently of each other (ie - you don't call node_access_records(), you rewrite the rules into the node grants system).
Comment: You'll need to read up on node grants and look at some existing examples to understand how the system is put together. Basically, you put together a template of grants in hook_node_access_records(), and you put together an array of grants in hook_node_grants(), and the system will overlay them to see if there is a match.
Comment: Thank you for the quick answer. That sounds like a viable route. But the grants system is still a bit unclear to me: At what point would the access checks that I defined in `hook_node_access` come into play? Do I rewrite these as rules in `hook_node_access_records`? Or do i call them from `hook_node_grants`?
Comment: So, to make sure, I understood this correctly... You are suggesting, I rewrite the access checks in my `hook_node_access` as grants in `hook_node_access_records` and then give the user the required grants in `hook_node_grants`, correct? If so, how can I make the grants that a user is given depend on the currently viewed node? I cannot access the node (and its referring nodes) in `hook_node_grants`, can I?
Comment: Thanks a lot for your help, I will read up a bit on the system and report back. Just one more quick question: In my case, a user's access to a specific node depends on that same user's access to another node (referring courses). I can't think of a way to check access in this case by just overlaying two separate arrays of grants... Any idea?
Comment: Play with it for a bit, then open a new issue with more specific questions. I believe the original question, "How do I filter a view by the results of hook_node_access?", has been answered here, and the format of this site is one question-one answer, rather than long discussions.
Comment: I do understand that and will, of course, play around with it myself. But let me add that the system, as I understood it so far, will **not** allow me to cover all I can do with `hook_node_access` (see my example). If I'm wrong, the answer could be improved by at least hinting to a possible solution...
Comment: "Was I understood it so far, will not allow me to cover all I can do with hook_node_access" - I don't see why not. I've never found a situation that couldn't be addressed through the node grants system, and reading yours, I don't see any red flags. But I'd have to write some code and debug it to provide an actual solution, and I've got my own code to write and debug today :)
Comment: Okay, thanks, that's all I needed to know. I'm prepared to write code, I just don't want to waste time trying to find a solution for a use case that the system wasn't intended for. (Admittedly, I'm still unsure, as to how to implement access checks, when none of these two hooks has access to both the user and the node at the same time, but maybe I'll find something...). Thanks again. Much appreciated.
Comment: For a pointer in the right direction: set a simple note grant in hook_node_access_records(). Put your logic into hook_node_grants(). See this thread where I gave a similar type example: https://www.drupal.org/forum/support/module-development-and-code-questions/2020-04-17/question-regarding-hook_node_grants
Comment: That'll help, thanks again. (Though, what's still unclear to me: My logic includes checking the referring nodes of the current node, but I don't have access to the current node in `hook_node_grants`... only to data about the user... but maybe I'm still misunderstanding something...)


Remover caracteres duplicados em string se não for dígrafo

Question: Como remover caracteres duplicados em uma string, caso não seja  um dígrafo (rr, ss) usando Regex? Ex:

Oiiiii => Oi
Aloooo => Alo
Passado => Passado
Carroooo => Carro

Se o rr ou ss aparecer no começo ou no final da palavra, pode ser removido, ex:

Carrosss => Carros
Comment: Existe a possibilidade de `r` ou `s` aparecer mais do que 2 vezes ? Se sim qual o procedimento nesse caso
Comment: Se isso acontecer, pode ser considerado só 2, e o resto removido. Ex: `carrrro = carro`
Comment: @ThiagoR. O que você ja tentou?
Answer: Começo por dizer que esta regex não cobre 100% dos seus casos, mas acerta em quase todos. E sinceramente não vejo muita forma de cobrir sem complicar drasticamente e talvez utilizar código à mão mesmo.
Mas começemos pela regex em si:
([^rs])(?=\1+)|(rr)(?=r+)|(ss)(?=s+)

Veja no regex101
Explicação:
([^rs])  - Qualquer letra que não r ou s
(?=\1+)  - Que se repita uma vez ou mais
|(rr)    - Ou dois r's
(?=r+)   - Que tenham mais r's à frente
|(ss)    - Ou dois s's
(?=s+)   - Que tenham mais s's à frente

E faz a substituição por nada, texto vazio, pois o que é capturado são as letras duplicadas que você quer remover.
Teste:
Entrada:
oiiiiiiii amiggggos passssado Carrrrrrrros

Saida:
oi amigos passado Carros

Pode sempre ajustar a regex a outras letras que quer deixar duplicar, mexendo em [^rs] e nos grupos (rr), adicionando outros que pretenda.
Repare que se você meter Carross a regex não consegue perceber que era suposto ser Carros, mais isso pode complicar e bem.
Comment: Muito bom! Já é o suficiente para mim. Muito obrigado pela ajuda!


How to check programatically whether a comment is new?

Question: I'd like to make some changes to a new comment programatically. I'm using the following code:
function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;
    // if ($comment->is_new) {
        $comment->field_image['und'][0]['fid'] = $user->field_image['und'][0]['fid'];
        }
    // }
}

I don't know how I can check whether the comment that's about to be saved is new or edited. $comment->is_new doesn't work.
How can I solve this?
Answer: Use hook_comment_insert() instead, that should work.
Comment: You'd have to let me know what your logic is inside the hooks, then :)
Comment: So, basically, you're trying to display the user avatars on the comments? Try looking into the file_load function. You can probably do this in the comment template file, rather than saving it to the comment entity, as well. In order to do something to new comments only, you'd use hook_comment_insert(), though!
Comment: Indeed, that's what I'm trying to do (see: http://drupal.stackexchange.com/questions/104123/how-to-add-custom-user-fields-to-their-comments and http://drupal.stackexchange.com/questions/104158/how-to-change-an-image-field-to-a-certain-fid-programatically). Maybe `file_load` can help me in solving the second question. In this case, however, `hook_comment_insert` really doesn't save any edits to the comment: the field may be an image field, integer field or whatever.
Comment: hook_comment_insert doesn't execute on updates, it is only executed when you insert a new comment. To print the avatar, see my comment on your other question :)


Thread Termination Condition

Question: I'm writing a producer-consumer thread program in C. Everything in my program is working perfectly with one major exception. When I have more than one consumer thread, which is pretty much always, only the first consumer thread will actually terminate. I've tried absolutely everything that I can think of, but the problem persists. Here's my code, with the guts of it stripped out, so that you can see just the part that is relevant.
I can see from my output that both of the termination condition variables become zero, which is of course why the first consumer thread terminates. But why don't the other consumer threads also terminate?
Thank you!
sem_t full, empty, mutex;
int threads;
int to_consume;
FILE* inputfp[5];
FILE* outputfp = NULL;
char in[BUF];

void* p(void* inpFile) {

    while (fscanf(inpFile, FMTSTRING, in) > 0) {
        sem_wait(&empty);
        sem_wait(&mutex);
        // production code here
        to_consume++;
        sem_post(&mutex);
        sem_post(&full);
     }

    fclose (inpFile);

    sem_wait(&mutex);
    threads--;
    sem_post(&mutex);

    return NULL;
}

void* c() {

    int continuing = 1;

    while (continuing) {

        sem_wait(&full);
        sem_wait(&mutex);
        //consumption code here
        to_consume--;
        fprintf("%d %d\n", threads, to_consume); //these both go to zero by the end

        if ( (threads <= 0) && (to_consume <= 0) ) {
            continuing = 0;
        }

        sem_post(&mutex);
        sem_post(&empty);
    }

    return NULL;
}

int main (int argc, char* argv[]) {

    int i;
    int con_threads;
    con_threads = 3;
    to_consume = 0;

    pthread_t *pr_thread[argc-2];
    pthread_t *con_thread[2];

    sem_init(&full, 0, 0);
    sem_init(&empty, 0, 50);
    sem_init(&mutex, 0, 1);

    for (i = 0; i < (argc-2); i++) {
        pr_thread[i] = (pthread_t *) malloc(sizeof(pthread_t));
        inputfp[i] = fopen(argv[i+1], "r");
        int rc = pthread_create (pr_thread[i], NULL, p, inputfp[i]);
        sem_wait(&mutex);
        threads++;
        sem_post(&mutex);
    }

    outputfp = fopen(argv[(argc-1)], "wb");

    for (i = 0; i con_threads 3; i++) {
        con_thread[i] = (pthread_t *) malloc(sizeof(pthread_t));
        int rc = pthread_create (con_thread[i], NULL, c, NULL);
    }

    for (i = 0; i < (argc - 2); i++) {
        pthread_join(*pr_thread[i], 0);
        free(pr_thread[i]);
    }

    for (i = 0; i con_threads 3; i++) {
        fprintf(stderr, "About to close consumer thread %d.\n", i);
        pthread_join(*res_thread[i], 0);
        fprintf(stderr, "Consumer thread %d closed successfully.\n", i);
        free(res_thread[i]);
    }

    printf ("About to close the output file.\n");
    /* Close the output file */
    fclose (outputfp);

    return EXIT_SUCCESS;
}

Comment: You might consider using more meaningful function names, such as `producer()` instead of `p()` and `consumer()` instead of `c()`.
Comment: Most semaphore implementations require a mutex that must be explicitly locked before the critical section.
Comment: `for (i = 0; i con_threads 3; i++)` ..?
Answer: I think your problem is that you don't post full again when the first consumer detects that there are no threads left, so the second consumer is waiting on full but the signal will never arrive.  You may need a count of the consumers, though for a first pass (proof of concept), you can leave full with a post that is never read.
Comment: Actually, this answer isn't quite right. What I think that I have is a classic case of deadlock. The consumer thread is waiting for sem_post(&full) to be called so that it has something to work with. However, the only threads that can call that are the producer threads, who have all finished up. I need to figure out what to do here, but at least I know what the issue is. Thanks for pointing out that the consumer was waiting for the post. Now I know what to think about!
Comment: I was thinking/assuming that in the `consumer()`, at the paragraph `if ((threads <= 0) && (to_consume <= 0)) { continuing = 0; }` you would add: `if ((threads <= 0) && (to_consume <= 0)) { continuing = 0; sem_post(&full); }`.  You'll only have the consumer post to `full` when there are no producers left to post to `full`, so it should be safe.
Comment: Yeah, I already figured it out. I created a test, along the lines of what you are suggesting, so that the first instance where all of the producer threads had exited and all of the produced items had been processed, that consumer thread would sem_post(full) for exactly the number of consumer threads (minus one). That would allow the other consumer threads to get past the sem_wait(full). Then I had a return statement immediately following so that those other threads would just terminate. Thanks for following up. I appreciate it.

Thread Termination Condition