IOS não aplica CSS

Question: Este meu formulário não está funcionado no IOS, porém no Android fica perfeito.
No IOS é como se não tivesse sido aplicado nenhum estilo.

form.frm-captura{
    width: 100%;
}
input.frmbtncapt{
    width: 100%;
    padding: 10px;
    font-size: 18px;
    box-sizing: border-box;
    margin: 2px;
    cursor: pointer;
    background-color: #FC613E;
    color: #fff;
    border-width: 6px;
    border-style: solid;
    border-color: #50636b;
}
input.frminput{
    width: 100%;
    padding: 10px;
    font-size: 18px;
    box-sizing: border-box;
    background-color: #FC613E;
    margin: 2px;
    border-width: 1px;
    border-style: solid;
    border-color: #ccc;
}

<form action="dados" method="post" class="frm-captura" name="frmcapt">
<input type="text" class="frminput" value="" name="emailcapt" placeholder="Insira seu email aqui!" required="required">
<input type="hidden" value="<?php echo $painel_noticias[0]; ?>" name="escondido">
<input type="submit" class="frmbtncapt" name="btnsub" value="BAIXAR O EBOOK AGORA!">
</form>

Comment: Nessa classe `input.frminput {` e nessa classe `input.frmbtncapt {` Coloca como primeiro atributo `all: unset;` tipo assim: `input.frmbtncapt { all: unset; ... resto das propriedade ... ` Testa colocando isso ai e me fala, se deu certo, depois vc pode testar tb colocando `!important`... mas primeiro testa com o `all: unset;` isso deve remover as classes padrão do `user-agent` do iOS, ("deve", pois não tenho um ambiente de teste aqui para confirmar isso)
Comment: Eu também tenho diversos problemas no IOS as vezes, eles parecem um IE da vida, um pouco melhorado.
Comment: @LucasCarvalho Verdade, alguns CSS funcionam perfeitamente, outros nada, como se não tivesse sido aplicado estilo algum.
Comment: Onde é `background-color` coloque apenas `background`, e na propriedade `box-sizing` tb coloque com prefixo `-webkit-box-sizing` e faz um teste ai pra ver se melhora. Se resolver me fala que dou uma resposta com mais detalhes
Comment: @hugocsl sim, ele colocou a borda e uma cor de fundo, distante a cor, mas foi. Só que a formatação está longe do código.
Comment: @hugocsl não entendo, só com o formulário que está acontecendo isso, todo o restante do site fora formulário funciona perfeitamente.
Comment: @hugocsl Desculpe a demora, funcionou perfeitamente! Muito Obrigado...
Comment: Gladison vc se incomoda se eu colocar o meu comentário como resposta? Assim vc pode marcar a resposta e fechar a pergunta já que ela está resolvida. Pode ser? Ai posso dar mais detalhes e explicações para quem cair na sua pergunta procurando uma resposta etc
Comment: @hugocsl Faça isso, será um prazer.
Comment: Valeu Gladison, transformei o comentário e resposta e dei mais uma série de detalhes caso vc interesse em se aprofundar um pouco nas coisas ;)
Answer: Como o assunto foi resolvido no comentário, vou postar aqui o registro como resposta.
O que provavelmente acontece é que o user-agent do iOS colocas alguns estilos por default no elementos. Então mesmo vc não declarando uma propriedade ou outra no elemento é possível que o próprio iOS esteja colocando esses estilos. Vc pode ler mais sobre user-agent nessa pergunta. O que é User Agent StyleSheets?
É por isso também que algumas pessoas gostam de usar um normalizer.css, ou reboot.css como o próprio Bootstrap faz para tentar remover os estilos do user-agent e deixar todos os navegadores com um CSS mais homogênico entre eles. Vc pode ler um pouco sobre isso nessa questão: CSS Reset ou Normalize?

Agora o workaroud que solucionou o problema da questão.
Primeiro colocar o que precisar com o prefixo -webkit- pois esse é o vendor prefix do iOS e Safari/Chrome
-webkit-box-sizing: border-box;
    box-sizing: border-box;

Segundo, evite propriedades long-hand, de preferencia por short-hand, pois alguma propriedade pode sobrescrever a outro, por exemplo, se vc tiver a estrutura como abaixo o estilo que fica valendo é o background-image: linear-gradient setado pelo user-agent e não a sua cor de background-color
background-image: linear-gradient(to bottom, #fff 0%, #000 100%); /* estilo user-agent */
background-color: #FC613E; /* seu estilo */

No entanto se vc colocar apenas background: vc vai indicar que todas as outras propriedades do background vão ficar como initial. Essa opção abaixo tem mais chance de prevalecer sobre o estilo do user-agent.
background: #FC613E; /* seu estilo */

Agora para tentar garantir que vc está removendo todas as propriedades do elemento e sobrescrever com a sua vc pode setar um all: unset; tipo assim: input.frmbtncapt { all: unset; ... resto das propriedade ... Dessa forma vc deve remover todos os estilos do user-agent. Vc pode ler mais sobre essa propriedade aqui: Propriedade all no CSS. Para que serve e como funciona?
Um exemplo de organização das propriedade para garantir que vão funcionar no iOS seria assim: (mas como disse vc ainda pode usar um normalizer.css ou reset.css)
input.frmbtncapt{

  all:unset; /* remove estilos setados pelo user-agent */

  width: 100%;
  padding: 10px;
  font-size: 18px;
  margin: 2px;
  cursor: pointer;
  color: #fff;
  border-width: 6px;
  border-style: solid;
  border-color: #50636b;

  -webkit-box-sizing: border-box; /* coloca o prefixo do browser do iOS */
        box-sizing: border-box;
  background: #FC613E; /* usa a propriedade em short hand */
}

IOS não aplica CSS


SpringBoot JPA in MySQL

Question: I defined this class:
<code>@Entity
@Table(name = "t_planets_tropical")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PlanetsTropical {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String desc;

}
</code>
but when I start the project I have this problem:
<code>Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255), primary key (id)) engine=InnoDB' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:763)
    at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94)
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java)
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:78)
    ... 132 common frames omitted
</code>
Answer: desc is a reserved SQL keyword and must not be used as a column name.
Either rename the attribute or us
<code>@Column(name = "desc_column")
private String desc;
</code>
or similar to give the column another name.

SpringBoot JPA in MySQL


Bourne Shell : How to insert some lines of text to a given line number of a file

Question: I'm writing a Bourne Shell script to automatically edit a source file.
I get the line number I need like this:
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]

Now I want to insert a few lines of text after this line number, how can I do this?
Answer: totallines=`cat test.h | wc -l`
head -n $line test.h >$$.h
echo "some text" >>$$.h
tail -n $((totallines-line)) test.h >>$$.h
mv $$.h head.h

?
(corrected)
Answer: If you have the simple unix editor ed installed, you can say something like this:
echo "$line i
$lines
.
w
q
" | ed filename.txt

This is vi without the "visual" mode. $line must be the line number and $lines the text to insert into the file.
Answer: It looks like you're working too hard.  Why not just insert the text instead of finding the line number?  eg:

$ sed '/#error/a\
> this text is inserted
> ' test.h

If the text you want to insert is in a file, it's even easier:

$ sed '/#error/r filename' test.h
Answer: you can just use awk
awk '/#error/{for(i=1;i<=NR-2;i++){print _[i]}print "new\n"_[NR-1];f=1 }!f{_[NR]=$0 }f' file > t && mv t file

Answer: line=$(sed -n '/#error/=' test.h)
line=$(($line - 2))
sed -i "$line s/$/\ntext-to-insert/" test.h

or
sed -i "$line r filename" test.h


Keystone js 6: How to add access control on id field of a list

Question: I have a problem with adding an access control on an id field of a list, since id field is added automatically when file schema.prisma is added. I want to make an id field with the following access:
access: { read: ()=> true, update: ()=> false }

I tried to find some explanation in keystone 6 docs, but it seems like there's none. Hope somebody could help me.
Answer: What you're describing is effectively the only behaviour ID fields support. Specifically:

You can't restrict read access for ID fields – if a user can read an item, they can always read its ID. The only way to hide the value of item IDs is to use filter-level access control to hide the entire item.
You can't (easily) update ID values – they're excluded from the GraphQL input types. I don't know if this is explicitly called out in the docs but you can see it in the examples in the GraphQL overview. This would also be true for the Query API, as it uses the same GraphQL schema under the hood, and I'm pretty sure it's also true for the DB API. (If you did ever want to modify the value of an ID field, you can possibly do it via the Prisma client on context – I'm not completely sure.)

For better or worse, these behaviours can't be overridden. ID fields are just special in this respect – they don't support standard field-level access control.


How to format output of antiword in php

Question: I'm using antiword to read doc files in php:
<?php
$filename = 'sample.doc';
$content = shell_exec('C:\\wamp\\www\\tester\\read_documents\\antiword\\antiword '.$filename);
echo $content;
?>

Is it possible to format the output?
Comment: ..what's the output? How do you want to format it?
Comment: You could also use the `-x db` flag to turn it into a docbook document, and then reformat that output.
Comment: You don't need to escape the \ in single quoted strings. Only if it comes before the closing '. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
Answer: manual page of antiword says:

-f  Output in formatted text form. That means that bold text is printed
  like *bold*, italics like /italics/
  and underlined text as _underlined_.
  -p papersize  Output in PostScript form. Printable on paper of the
  specified size: 10x14, a3, a4, a5, b4,
  b5, executive, folio, legal, letter,
  note, quarto, statement or tabloid.
  -t  Output in text form. (default)
  -x document type definition  Output in XML form. Currently the only document
  type definition is db (for DocBook).

So, you can choose various output formats; by default, antiword strips out all formatting. I'd guess you want the -f option, and possibly replace that simple formatting into HTML tags.
Comment: so how then do I format it if its already in *bold* /italics/ form?

How to format output of antiword in php


permutation and combination problem

Question: let us consider this problem:
Chelsea has a bookshelf consisting of ten classics: four Russian novels, three British novels, two French novels, and a German novel. If she wants to make sure that the novels are always grouped according to country, how many ways can she arrange the novels?
my attempt is following  because these novels  should be arranged according to country,it means that  i should multiply number of arrangement  of Russian novels together by number of British novels arrangement by French  and  one German Novels number of arrangement,which means that
$4!*3!*2!*1!=288$
but in answer there is $24*288=6912$  where  $24$ comes from?does it means that there is  $24$ ways  first book i could choose? $4*3*2*1=24$?
Answer: Consider the big group. So you have Russian, British, French, and German.
You can arrange them $4!$ ways.
For each type of book, you can arrange them $4!$, $3!$, $2!$, and $1!$ ways (which is what is in your attempt.)
So the final answer is $4!4!3!2!1!=6912$.
Comment: it means that  $4!$ is related to  number of country,not number of books right?
Comment: yes, $4!$ refers to the country, and the order matters.
Comment: and also  it means that order is important right?

permutation and combination problem


how can we determine our program well working?

Question: Can we determine if a program is well working by considering the following questions?

Memory is succesfully reclaimed by the Operating system
There is no Stack Overflow

after writing and running some code to determine whether there is any overflowing going on?
Our assistant give us feedback after running our program through some other program.
In the feedback, it shows whether if there was an overflow , whether we were using using free / delete in wrong way, and some other things.
I wonder How did she found out ?
Comment: Did you give that person the source code?
Comment: The two criteria listed are required, but not sufficient. A program can have other defects, e.g. produce wrong output, or be too slow for the intended purpose.
Comment: @MSalters, I write some program to determine its efficiency ( wrt time )
Comment: Hope my answer below explains clearly.
Answer: There could be a number of ways to deduce the above.

Use a tool such as valgrind : this
helps detect memory leaks and such
A simulator which would be creating
inputs to your programs for both
positive and negative testcases.

Cheers!
Answer: You say that person has the source code - that means he can analyze the program - either by reading and thinking or by using some clever program.
For example he could see the following:
void someCleverFunction()
{
   char* buffer = new char[100];
   if( someCondition ) {
       //do something with the buffer
       delete[] buffer;
       return;
   }
   Sleep( 1000 );
}

and then it's obvious to him that once someCondition isn't met delete[] is not called and that's a sure memory leak.
That's called static code analysis.
Answer: I would define the "well working" as the effectiveness of the program: does it do as was asked and does it do that in all situations?  This should be handled be 1) clearly describing what the program should do and 2) test all situations as thoroughly as possible.
However buffer overruns, memory leaks and stack overflows are part of "well behaving" which also means robustness of the program: there should be no cases in which the program crashes:  here thorough testing is also needed, but code reviewing and tools as static analysis (e.g. coverity) and dynamic analysis (e.g. valgrind) should be used too since issues with memory leaks can be unnoticed until much later when you actually run out of memory.  Which tools to use depend on your platform and on the scale of the program.
Answer: Do you use Visual C++?
If so, read this: http://msdn.microsoft.com/en-us/library/5at7yxcs(VS.71).aspx
On linux with gcc use Valgrind. It has a really good documentation.
Comment: That thing is great, but works only in debug version of CRT, also it is not very useful without the source code.


java.lang.UnsatisfiedLinkError while trying to load opencv

Question: I am trying to use opencv in a Scala application built using sbt and this is my build.sbt
name := "Marker"

version := "1.0"

scalaVersion := "2.11.8"

javaOptions in run += "-Djava.library.path=/home/priyatham/libs/opencv-3.1.0/build/lib"

And this the error I am getting when I sbt run
[error] (run-main-0) java.lang.UnsatisfiedLinkError: no opencv_java310 in java.library.path
java.lang.UnsatisfiedLinkError: no opencv_java310 in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at Main$.main(Main.scala:10)
    at Main.main(Main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
[trace] Stack trace suppressed: run last compile:run for the full output.
java.lang.RuntimeException: Nonzero exit code: 1
    at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) Nonzero exit code: 1
[error] Total time: 1 s, completed 13 Sep, 2016 8:40:09 PM

What's wrong with the way I am modifying java.library.path
EDIT: I did put the opencv-310.jar in Marker/lib folder
Compiling with java -Djava.library.path="/home/priyatham/libs/opencv-3.1.0/build/lib" works though, but not with sbt run
Comment: It seems library name issue, error saying opencv_java310 but you are saying opencv-310.jar, are sure this is how it should be/.
Comment: I don't think names are an issue
Comment: http://stackoverflow.com/questions/1403788/java-lang-unsatisfiedlinkerror-no-dll-in-java-library-path I am pretty sure you have either wrong path or missing jar.
Comment: This error typically happens when a native-language library is missing. Check the install instructions and look for some .so file that needs to be installed, or whether you need to compile binaries.
Comment: You provide differnt path. Look at first character (`/`)
Comment: I am sorry @talex that was typo here, but it's the same in my code.
Comment: add `fork in run := true`. I think now it tries to run your code in same JVM so `javaOptions` is not applied.
Comment: Thank you so much @talex, that fixed it.
Comment: I'll add it to my answer.
Answer: EDITED:
Add fork in run := true. I think now it tries to run your code in same JVM so javaOptions is not applied.
Comment: Does `/home/priyatham/libs/opencv-3.1.0/build/lib/libopencv_java310.so` file exists and contains what we expect? Is application have access to it (permissions)?


Component shows old state after action happened

Question: After action is happened component gets an old state anyway. I'm not mutating the state btw. The changes appears only after I refresh the page
My component TodoList.tsx
Here's I'm trying to get state via useEffect hook

export const TodoList: FC = () => {
    const {
        todoList, isLoading, isError, message
    } = useTypedSelector(
        (state) => state.todo
    )

    console.log(todoList)

    const { getTodo, reset } = useActions()

    useEffect(() => {
        getTodo()
        console.log("render")
        if (isError) {
            console.log(message)
        }
        return () => {
            reset()
        }
    }, [])

    const statusHandler = (event: React.ChangeEvent<HTMLParagraphElement>) => {
        const status = event.target.innerText
        if (status === "completed") {
            getTodo({ complete: true })
        } else if (status === "uncompleted") {
            getTodo({ complete: false })
        } else if (status === "all") {
            getTodo()
        }
    }

    return (
        <>
        ...
        </>
    )
}

my Reducer
I'm not mutating the state also.
const initialState: TodoState = {
  todoList: [],
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: ""
}

export const todoReducer = (state = initialState, { type, payload }: TodoAction): TodoState => {
  switch (type) {
    case "GET_TODOS":
      return { ...state, isLoading: true }
    case "GET_TODOS_SUCCESS":
      return { ...state, isLoading: false, isSuccess: true, todoList: payload }
    case "GET_TODOS_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "CREATE_TODO":
      return { ...state, isLoading: false }
    case "CREATE_TODO_SUCCESS":
      return { ...state, isLoading: false, isSuccess: true, todoList: [...state.todoList, payload]}
    case "CREATE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "TOGGLE_TODO":
      return { ...state, isLoading: true }
    case "TOGGLE_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.map((todo: ITodoItem) => {
          if (todo._id === payload.id) {
            console.log(payload)
            return {
              ...todo,
              complete: !todo.complete
            }
          }
          return todo
        })
      }
    case "TOGGLE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "DELETE_TODO":
      return { ...state, isLoading: true }
    case "DELETE_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.filter(
          (todo: ITodoItem) => todo._id !== payload.id
        )
      }
    case "DELETE_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "EDIT_TODO":
      return { ...state, isLoading: true }
    case "EDIT_TODO_SUCCESS":
      return {
        ...state, isLoading: false, isSuccess: true, todoList: state.todoList.map((todo: ITodoItem) => {
          if (todo._id === payload.id) {
            return {
              ...todo,
              text: payload.text
            }
          }
          return todo
        })
      }
    case "EDIT_TODO_ERROR":
      return { ...state, isLoading: false, isError: true, message: payload.error }
    case "RESET_TODOS":
      return { ...state, todoList: state.todoList }
    default:
      return state
  }
}

my action creator
Here I'm making a request from my own api.
...
export const getTodo = (data?: GetTodos) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            dispatch({ type: "GET_TODOS", payload: {} })
            let response
            if (data) {
                response = await todoService.getTodo((<any>data).complete)
            }
            response = await todoService.getTodo()
            console.log(response)
            dispatch({ type: "GET_TODOS_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "GET_TODOS_ERROR",
                payload: { error: "Cannot fetch the todos. Please try again later" }
            })
        }
    }
}

export const createTodo = (payload: CreateTodo) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            dispatch({ type: "CREATE_TODO", payload: payload })
            const response = await todoService.createTodo(payload)
            dispatch({ type: "CREATE_TODO_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "CREATE_TODO_ERROR",
                payload: { error: "Cannot create todo. Please try again later" }
            })
        }
    }
}

export const toggleTodo = (payload: ToggleTodo) => {
    return async (dispatch: Dispatch<TodoAction>): Promise<void> => {
        try {
            const response = await todoService.updateTodo(payload.id, { complete: payload.complete })
            dispatch({ type: "TOGGLE_TODO_SUCCESS", payload: response })
        } catch (err) {
            dispatch({
                type: "TOGGLE_TODO_ERROR",
                payload: { error: `${err}` }
            })
        }
    }
}
...
}

all code is here: https://github.com/maridoroshuk/todos-ts
the issue
Comment: Why are use calling an API in your action creator?
Comment: Where I have to do this? sorry, I'm currently learning...
Comment: Call your API in some other file (some sore of service file that calls the API in different functions) and simply pass the data to your action creator from the component you are calling the dispatch.
Comment: but I have a servies https://github.com/maridoroshuk/todos-ts/blob/main/frontend/src/store/servies/todo.ts
Answer: useEffect(callback, dependencies) triggers only when data in dependencies changes. In your code, you put useEffect( ... , []), meaning you don't have any dependencies, so the callback function only runs once when the component mounts.
If you want useEffect to run on every update, you need to not put any dependencies: useEffect(...).
Comment: yes, sorry I didn't mention that if I add any dependencies like getTodo()/reset() , It creates infinite loop. Any ideas how I can avoid it?
Comment: So if you are **not** adding any dependency, then `useEffect` runs every render. If that is causing an infinite loop, it means you are changing something in `useEffect` that triggers a re-render. If you are adding dependencies and it causes an infinite loop, it means stuff inside `useEffect` such as `getTodo` or `reset` is causing those dependencies to change, triggering another `useEffect`.


What is the most simple way to implement a newsletter?

Question: We have a quarterly newsletter, and a list of subscriptions in a csv file(this can change if necessary).
The previous method was to use a python script that generates the newsletter from a content source and sends the mail to the recipients one by one using smtplib.
Now we changed the way we write newsletters and we need some daemon to send and e-mail and will forward the email one by one for each recipient. What is the easiest way of doing this? Our manager uses MS Exchange to prepare the letter and we have a Linux server that we can configure however we want.
I heard EXIM can be configured in such a way.
Answer: Easiest way is probably to buy in a service like MailChimp.  There are a lot of advantages to this - particularly that those companies care to spend the time to get your newsletter through spam filters etc, saving you the hassle.
Next simplest is setting up a mailing list server such as Mailman.  This will get you double opt in, list management, and sends to recipients one by one, as you request.
If you don't already have EXIM or Postfix on your Linux server, you aren't going to find a super simple way of doing this, unless you already understand MTAs in general, and a specific one in detail.


Is there a way to stop execution of calling method to avoid DoubleRenderError in Rails?

Question: In my controller I have:
def update
  case params[:something]
  when 'x'
    if all_is_good
      good_stuff_happens
      flash[:notice] = "Good stuff happened"
    else
      access_denied
    end
  when 'y'
    other_good_stuff_happens
    flash[:notice] = "Other good stuff happened"
  when 'z'
    even_more_good_stuff_happens
    flash[:notice] = "Even more good stuff happened"
  end
  redirect_to good_place_path
end

And in my ApplicationController I have:
def access_denied
  redirect_to message_path, :alert => 'Access Denied'
end

For the most part, I always want to redirect_to the good_place_path after the case statement.
Occasionally, I want to deny access and leave it at that. Is there a way I can call
acccess_denied

from my controller and then not return to the calling controller (or else it attempts to do a second redirect and thus I get the DoubleRenderError). I understand I could just put
redirect_to good_place_path

in each when statement, but I'm wondering if there's a more elegant solution.
Thanks.
Sean
Answer: Add return after the redirect_to works so adding it after the access_denied should work as well. You basically don't want to fall through to the rendering, which is the default.
Comment: Thanks Steve.I tried putting return directly after the redirect_to in the access_denied method, but it still double-rendered because it's now back to the update method and still processing. I then tried your second suggestion and that worked fine. I actually ended up putting: access_denied && return
Comment: Yeah, the `rendering_method and return` is pretty idiomatic in Rails.


Calculating power of a Hypothesis Testing Problem based on Uniform distribution

Question: Consider the problem of testing $H_0:a=0$ against $H_1:a=1/2$ based on a single observation X from U(a,a+1). The power of the test "Reject $H_0$ if $X>2/3$" is
(A)1/6     (B)5/6   (C)1/3   (D)2/3
My Steps:
Power of Test=P(reject $H_0$|$H_1$ is true)
c.d.f. of continuous Uniform distribution is given be $\frac{x-a}{b-a}$, where a and b are parameters of the given Uniform distribution, $U(a,b)$.
$$\begin{align}
\text{Power of Test} & = P(\text{reject } H_0|H_1 \text{is true)} \\
 & = P(X>2/3|a=1/2) \\
 & = \frac{(2/3-1/2)}{1} \\
 & = 1/6
\end{align}$$
Did I solve this correctly ? Please help me confirm my solution.
Answer: No. It should be 5/6. Remember cdf of X is $P(X \leq x)$.
So your solution should be
$P(X > 2/3|a = 1/2)$
$= 1 - P(X \leq 2/3|a = 1/2)$
$= 1 - (2/3 - 1/2)/1$
$= 5/6$
Comment: Thanks for your time and effort .. I wish I could vote this up as well but I don't have enough reputation..
Comment: I got 15 rep ! so I can upvote now .... :)
Comment: @StuckinaJAM Welcome to Math SE :)
Comment: Good job and thanks too. I actually do need the rep for possible bounties.


How to edit a form using modelForm Based Using Django

Question: Currently this code below allows me to show a Form and save to the database if I want to. But as I've seen in many tutorials like this I seem to find only Add ModelForm Tutorials and not Edit. How can I modify this code to also allow editing? Passing a ID or a Slug to it is based on a get.objets.get() #suggestion ID in this case.
Thanks In advance.
Model.py
from django.db import models

class Suggestion(models.Model):
     title = models.CharField(max_length=100)
     email = models.EmailField(blank=True)
     link = models.URLField(verify_exists=True,blank=True)
     description = models.TextField(blank=True)
     time_sensitive = models.BooleanField()
     approved = models.BooleanField()

   def __unicode__(self):
        return self.title

Form.py
from django import forms
from django.forms import ModelForm
from contact.models import Suggestion

class SuggestionForm(ModelForm):

   class Meta:
         model = Suggestion
         exclude = ('approved',)

Views.py
from django.shortcuts import *
from django.template import RequestContext

from contact.forms import *

def suggestion(request):
    if request.method == "POST":

        form = SuggestionForm(request.POST)

        if(form.is_valid()):
            print(request.POST['title'])
            message = 'success'
        else:
            message = 'fail'

        return render_to_response('contact/suggestion.html',
              {'message': message},
              context_instance=RequestContext(request))
    else:
        return render_to_response('contact/suggestion.html',
                {'form': SuggestionForm()},
                context_instance=RequestContext(request))

Template
 {% extends "base.html" %}

 {% block content %}

Leave a Suggestion Here

 {% if message %}
 {{ message }}
 {% endif %}

     <form action="/suggestion/" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit Feedback" />
 </form>

 {% endblock %}

Comment: you could use updateview
Answer: Django comes with built in views that handle Creating, updating and deleteing objects using django's forms.
Using UpdateView should allow you to update an object using your ModelForm,
using updateview you have to specify the objects id in the url and tell the view which kwarg to look for the id in.  By default I think it uses pk
Comment: This exact answer helped me. @mkriheli got it right also but. this was more specific.
Answer: The best would be using django's generic class based views:
If you'd still won't to roll your own, you should use the instance keyword, e.g:
suggestion = Suggestion.objects.get(pk=pk)
form = SuggestionForm(instance=suggestion)

You should capture the pk in the url pattern, and make sure your function expects it:
def suggestion(request, pk=None):
    if request.method == "POST":
    ...

Still, the generic class based views do all the hard work for you, so not sure why you would do it manually (learning the mechanism could be one reason).


Is this a valid proof that A = B given A ∩ B = A ∪ B?

Question: Here is my proof. My instructor claims that it is invalid because I did not use a set membership table, and that the use of a predicate logic truth table is invalid.
That makes no sense to me. If I can do S := { x | P(x) }, then I should obviously be able to use predicate logic on the members of sets!
<code>Given 2 sets A and B such that A ∩ B = A ∪ B, what can be concluded about A and B?

A ∩ B = A ∪ B                                                           restatement

∀x(x ∈ A ∩ B ↔ x ∈ A ∪ B)                                               definition of set equality

∀x(x ∈ A ∧ x ∈ B ↔ x ∈ A ∨ x ∈ B)                                       set membership distributed over union and intersection

p(x) := x ∈ A

q(x) := x ∈ B

p    q    p ∧ q    p ∨ q    p ∧ q ↔ p ∨ q    p ↔ q

T    T      T        T            T            T

T    F      F        T            F            F

F    T      F        T            F            F

F    F      F        F            T            T

∀x(x ∈ A ↔ x ∈ B)                                                        logical equivalence (p ↔ q ≡ p ∧ q ↔ p ∨ q)

∀x(x ∈ A → x ∈ B ∧ x ∈ B → x ∈ A)                                        logical equivalence (p → q ∧ q → p ≡ p ↔ q)

∀x(x ∈ A → x ∈ B) ∧ ∀x(x ∈ B → x ∈ A)                                    universal quantifier distributed over conjunction

A ⊆ B ∧ B ⊆ A                                                            definition of subset

A = B                                                                     definition of set equality

We see that the sets A and B are equal. A and B may both be the empty set.
</code>
So, is my proof valid?
Edit: after further reflection, I think the point of contention may be the use of a truth table to demonstrate logical equivalence over an infinite domain. This proof may not be valid for infinite sets. I could instead demonstrate the logical equivalence p ↔ q ≡ p ∧ q ↔ p ∨ q another way.
Comment: @JohnColeman She claimed that the proof is not rigorous, in exact terms. In direct quote, "you adapted and tried to use a truth table for predicates which you can't do."
Comment: @Somos: If that is so, then that instructor is a stupid and lousy one.
Comment: Your conclusions are not mutually exclusive.
Comment: @SolomonUcko Thanks, I was just using the exact equivalences presented in my textbook (Rosen, 7th ed.). The section about demonstrating set equivalence explicitly asks to demonstrate mutual subsets. But I also used the definition you just mentioned as my first step, which was also in the book. Good point, the proof should be shorter. This is my first logic class, if it is not obvious :P
Comment: In any argument with an instructor, the instructor always wins.
Comment: @okovko: That's unfortunately true in some cases, but I will always stand against argument from mere authority, because it is one of the worst ways to teach. And please continue your critical thinking, because it is one of the best ways to learn.
Comment: Did your instructor claim that it is *invalid* (in the sense of being mathematically wrong) or did your instructor claim that your proof is *incorrect* in the sense of not using a technique whose use was either explicitly or implicitly (e.g. given the section of the textbook) required? There have been plenty of times that I have penalized students for doing something which is mathematically correct but didn't use the method that the problem description called for.
Comment: BTW, FWIW, IMO, it's easier to go directly from $∀x(x ∈ A ↔ x ∈ B)$ to $A = B$. This is exactly how Cantor defines set equivalence, in fact.
Answer: Your reasoning is perfectly valid. At the point where you use a truth table to show a propositional equivalence you're already looking at one particular $x$ (at a time), so the possibilities you need to consider are just the for rows of your table.
Formally, once you have established the propositional equivalence
$$ (p\land q)\leftrightarrow(p\lor q) \quad\equiv\quad p\leftrightarrow q $$
you're now allowed to substitute anything for $p$ and $q$, and it will be a valid equivalence -- even predicate-logic formulas.

(It is a bit the long way around, though. It's faster to see
$$ A \subseteq A \cup B = A \cap B \subseteq B $$
and vice versa, so $A\subseteq B$ and $B\subseteq A$, and therefore the sets are equal).
Comment: @okovko: In that question the asker seemed to be asking for a truth-table-like method to prove formulas whose validity depends on looking about the relation between the parts of the formula that is inside/outside of a _quantifier_. Such formulas can't be gotten by substituting into a propositional tautology. So the point there was not that it is _invalid_ to substitute predicate formulas for a psopositional tautology -- merely that it doesn't do the more complex job the asker there wanted _and can't realy be extended to do so_.
Comment: @okovko: Concerning your question about the linked post, in general truth-tables are insufficient to handle first-order logic (aka predicate logic). One needs inference rules or axioms to handle quantifiers. Indeed, if you look at the Fitch-style proof I gave you, we use one quantifier-rule (∀-intro) at the end, to get from the inner proof of "$x∈A ⇔ x∈B$" under the context of any given object $x$, to the outer conclusion of "$A = B$".
Comment: "At the point where you use a truth table to show a propositional equivalence you're already looking at one particular x (at a time), so the possibilities you need to consider are just the for rows of your table."
I thought so too. As long as the domain is countable, even if it infinite, then it should be valid to inspect every truth table over every x.
Comment: Oh, so if I demonstrate (p∧q)↔(p∨q)≡p↔q for propositional logic, then it is valid for use in any predicate logic substitution?
Comment: @okovko: Yes, exactly. (In the usual development of mathematical logic, this is the primary reason to care about propositional logic at all: We can use it to prove a certain kind of "easy" truths in predicate logic, which is what we're really after).
Comment: Just for the sake of my curiosity, can you tell me where [this](https://philosophy.stackexchange.com/questions/28467/does-predicate-logic-have-truth-tables) applies?
Answer: Your proof is fine. That you have shown $(x\in A\land x\in B)\iff(x\in A\lor x\in B)$ is equivalent to $(x\in A)\iff(x\in B)$ extends to all $x$ with no problem; if $\phi(x)$ is equivalent to $\psi(x)$, $\forall x(\phi(x))$ is equivalent to $\forall x(\psi(x))$.
Comment: @okovko No, your proof is perfectly OK whether the sets are finite or infinite. Your argument applies to every $x$, no matter how many $x$'s there might be.
Comment: What about [this](https://philosophy.stackexchange.com/questions/28467/does-predicate-logic-have-truth-tables)? It looks like my proof is only valid for finite sets.
Answer: Let me show you a Fitch-style proof corresponding to your (correct)reasoning, to make sure you understand why it is valid:

Given any sets $A,B$ such that $A∩B = A∪B$:
  Given any object $x$:
    $x∈A∩B ⇔ x∈A∪B$.
    Thus $x∈A ∧ x∈B ⇔ x∈A ∨ x∈B$.
    Let $P :≡ x∈A$.
    Let $Q :≡ x∈B$.
    Then $P∧Q ⇔ P∨Q$.
    Thus $P ⇔ Q$.   [by the truth-table you gave]
    Thus $x∈A ⇔ x∈B$.
  Therefore $A = B$.

Note that you perform the same reasoning for any given object $x$, so even though the $P,Q$ in the above proof may differ in truth-value for different $x$, it still holds in every case that $P ⇔ Q$, and hence you get the conclusion you seek. If your instructor cannot understand this, ask him/her to give you any sets $A,B$ such that $A∩B = A∪B$ and any object $x$ and explicitly follow the proof to show (by a single use of the truth-table) that $x∈A ⇔ x∈B$. If it is clear that he/she cannot prevent your conclusion no matter what $A,B,x$ he/she gives you, then you have won. (This is called game semantics, by the way, and I recommend you think of quantifiers this way to fully grasp the meaning of order of quantification.)
Comment: If you could share a source for Fitch-style proofs, that would probably help my case.
Comment: @okovko: I don't have a good online reference for it, and [the one I wrote](http://math.stackexchange.com/a/1684204/21820) is intentionally brief. The main point is that if you have a propositional logic proof from "$P∧Q ⇔ P∨Q$" to "$P ⇔ Q$", then you can insert that in-between those two steps in the above proof. And if anyone doesn't like the use of extra propositional variables $P,Q$, you can replace them everywhere by "$x∈A$" and "$x∈B$" respectively. Anyway I'm a logician; is that good enough for a reference? =)
Comment: Well, you have stoked my critical thinking fire and taught me, so I very much appreciate your time and energy. Unfortunately, there is probably no way to change my instructor's mind. In particular, understanding why my proof is correct has changed my perspective on logic in a fundamental and insightful way. Thank you!
Comment: @okovko: I'm very glad you fully understand the logical reasoning involved here, so you're welcome! If you have any future questions you can find me in [chat](https://chat.stackexchange.com/rooms/77161/basic-mathematics).


Como trabalhar com @media em css?

Question: Saudação para todos,
sou novo como programação em Frond-End, e estou começando a aprender a mexer com @media para aplicar chaveamento em uma pagina simples,mas o que seria cheveamento?
Criei um site responsivo quando a pagina tem mais de 991px de largura ele aparece o menu, porém quando ele tem menos de 991px aparece um ícone de três barrinhas, e se o usuário quer que apareça o menu estando a menos de 991px ele terá que clicar no ícone para aparecer o menu, como mostro na figura abaixo;
Menu acima de 991px;

Agora o menu a baixo de 991px sem clicar no ícone.

Agora o menu quando clicar no ícone.

O que preciso na verdade é mudar e tira o sublinhado quando passo o mouse, a parte do código responsável por isso seria esse;
@media(max-width: 991px){

    .menu{
        position: fixed;
        top: 0;
        left: 0;
        bottom: 0;
        width: 200px;
        display: none;
        background-color: #bfbfbf;

        border-right: 1px solid #eee;
    }

    .menu a{
        text-decoration: none;
    }

    .menu--exibindo{
        display: block;
    }

    .menu_item{
        display: block;
        line-height: 3;
    }
}

Mais especificamente essa parte do código referente ao que foi mostrado logo em cima;
.menu a{
        text-decoration: none;
    }

O problema é que esse código como mostra em cima não faz alteração no menu, era para fazer, eu não sei aonde estou errado.
Deixarei o meu código fonte completo que está no GitHub disponivel para melhores esclarecimentos.
BASTA CLICAR AQUI
Comment: Relacionada/duplicada: http://pt.stackoverflow.com/q/19342/129
Answer: Se você deseja retirar o sublinhado do menu lateral que aparece ao clicar no ícone do menu responsivo, simplesmente tem que usar o css: (baixei e funcionou em localhost)
@media (max-width: 991px){
.menu a {text-decoration: none;}
}

Caso queira tirar este sublinhado do menu em telas maiores, use o css:
.menu a {text-decoration: none;}

Answer: Na verdade o seu problema não está no media query. Para mudar a propriedade de sublinhado quando passa o mouse, você tem que selecionar o atributo hover do CSS (que é a estilização responsável para quando os elementos terão o mouse em cima deles)
O seu código dentro do media query tem que ficar assim então:
.menu a:hover{
    text-decoration: none;
}

Como trabalhar com @media em css?


Proving $\left(\mathbb{Z}/p^{d} \mathbb{Z}\right)^{\times}$ is cyclic for prime p

Question: My assignment asks me to prove $\left(\mathbb{Z}/p^{d} \mathbb{Z}\right)^{\times}$ is cyclic for prime $p>2$ and for any positive integer $d$.
They propose proving this by induction.
The base case:
I set $d=1$, then Fermat's Little Theorem states that:
$$\exists \hspace{3pt} x \in \left(\mathbb{Z}/p^{} \mathbb{Z}\right)^{\times} \hspace{7pt} s.t \hspace{6pt} x^{p-1} \equiv 1 \pmod p $$
Therefore, the statement is true for $d=1$. I am confused with how to move forward from here. I know that I need to show: assuming the statement is true for some $d$, this then implies that it is true for $d+1$.
I tried to prove directly: $\exists x$ such that
$$x^{p-1} \equiv 1 \pmod {p^d} $$
$$\Rightarrow x^{p-1} - kp^{d} = 1 \hspace{17pt} k \in \mathbb{Z}$$
Multiplying by $p$, I get:
$$\Rightarrow px^{p-1} - kp^{d+1} = p \hspace{17pt} k \in \mathbb{Z}$$
However, it seems that this strategy brings me nowhere. Does anyone know of any other approaches to this that are hopefully simpler?
I thought about using Chinese Remainder Theorem with the $p$ and $p^{d}$ case, which would imply the $p^{d+1}$ case, but this only works when $p$ and $p^d$ are coprime, right? (which is clearly never the case).
Any strategies, approaches, insight or advice would be greatly appreciated. Thanks!
Comment: Any $\mathbf Z/n\mathbf Z$ is cyclic, and you don't need to call lil' Fermat to see this.
Comment: The first step is to say for $p$ odd prime : $(1+p)^{p^k} = \sum_{j=0}^{p^k} {p^k \choose j} p^{p^k-j} \equiv 1+p^{k+1} \bmod p^{k+2}$, from which you find the subgroup of $\mathbb{Z}/p^d \mathbb{Z}^\times$ generated by $1+p$. Then look at the surjective morphism $\mathbb{Z}/p^d \mathbb{Z}^\times \to \mathbb{Z}/p \mathbb{Z}^\times$ (what is its kernel ?) to see $\mathbb{Z}/p^d \mathbb{Z}^\times $ has an element of order $p-1$.
Comment: Your proof for $d=1$ isn't correct: in $(\mathbb{Z/2Z})^2$, every $x$ satisfies $4x  = 0$ in particular there exists one that does; but it's not cyclic for that matter
Comment: $p$ is odd though
Comment: Your base case $d=1$ is *not* Fermat's little theorem! That theorem says $x^{p-1} \equiv 1 \bmod p$ for all nonzero $x \bmod p$. The formulation you give, that *there is* a nonzero $x \bmod p$ for which $x^{p-1} \equiv 1 \bmod p$, is  completely trivial: just take $x=1$. Even the correct Fermat's little theorem is not enough to give you the base case: for every modulus $m > 1$ we have $x^{\varphi(m)} \equiv 1 \bmod m$ whenever $\gcd(x,m) = 1$, but this does *not* mean the units mod $m$ have a generator (try $m = 15$). The base case $d=1$ requires more than just Fermat's little theorem.
Comment: The Chinese remainder theorem is about *relatively prime* moduli. Therefore it is not realistic to think it will help you combine an argument mod $p$ and $p^d$ in a direct way to say something about modulus $p^{d+1}$. (Of course $p-1$ and $p^{d-1}$ are relatively prime, so maybe CRT is useful when working with those moduli.)
Comment: Sorry, there was a typo in my title. Does it make more sense now?
Comment: Yes, that's entirely different.
Comment: Yes I stated that $p>2$ in the first line. Does that clear things up?
Answer: A sketch:
As mentioned in @reuns' comment, you first prove that
$$(1+p)^{p^k}\equiv 1+p^{k+1}\mod p^{k+2}$$
by induction on $k$ (you'll need the multinomial formula for that). this proves that in $(\mathbf Z/p^d\mathbf Z)^\times$, the class of $1+p$ has order $p^{d-1}$.
On the other hand, in the cyclic group $(\mathbf Z/p\mathbf Z)^\times$, there exists an integer $n\bmod p$ with order $p-1$ , hence the order of $n\bmod p^d\:$ is a multiple of $p-1$, so that some power  $n^r\bmod p^d$ has order exactly $p-1$. As $p-1$ and $p^{d-1}$ are coprime, $n^r(1+p)\bmod p^d$ has order $(p-1)p^{d-1}=\varphi(p^d)$.
Comment: Your notation is sloppy. Don't say "$n$ has order $p-1 \bmod p$" since it looks like you are writing about *the order reduced modulo* $p$. Instead say "$n \bmod p$ has order $p-1$." Fix the same kind of awkward writing when discussing orders of integers modulo $p^d$. Also, I feel the reasoning you give to get a unit mod $p^d$ with order $p-1$ needs more work: when $n \bmod p$ has order $p-1$, why should some power $n^r \bmod p^d$ have order $p-1$? Of course it might be okay to leave this for the OP to think about, but there is definitely something more needed there for a full argument.
Comment: I recall it's only a sketch, not a detailed solution. Roughly speaking, theorder $p-1$ is the generator of the subgroup of periods, so the order $\bmod p^d$ is a multiple of $p-1$, namely it is $r(p-1)$ for some $r$, in which case $n^r\bmod p^d$ has order $p-1$.
Comment: I agree. The edit looks good.
Comment: Wait, why does the fact that the ord$(n^r)$ $=p-1$ coprime to ord$(1+p) =p^{d-1}$ imply that the order of $n^r(1+p)$ is the product? Couldn't there be some $\ell$ of the form $\ell = (p-1)p^r; r
Comment: This results from the *Chinese remainder theorem* and the structure theorem for finite abelian groups* $1+p$ and $n^p$ are not in the same component of $\mathbf Z/p^d\mathbf Z$, hence the order of he product is the l.c.m. of the h, i.e. their product.


How to compute the progress of a download given the chunk number, its size and the total size of the download?

Question: Python's urllib.request.urlretrieve() accepts a function that will be called when each chunk is fetched from the network.
The function is called with three arguments: a progressive identifier of the chunk, its size and the total size of the download.
Given those three information can I compute the number of bytes already fetched? This will be used to compute the progress of the download.
I'm tempted to do chunk_number * chunk_size / download_size, but I'm not sure the chunk size is constant for all the chunks.
Comment: There's unfortunately no reason to assume chunks will all be the same size! If you want to give an accurate download percentage you may have to keep a running sum (e.g. `total_bytes += most_recent_chunk.size`)
Answer: You can keep a running total of all the sizes you've seen so far.
Try this:
import urllib.request

def my_downloader(url, filename = None):
    running_total = 0
    def my_reporthook(count, size, total):
        nonlocal running_total
        running_total += size
        print ("{}%".format(100*running_total//total))
    return urllib.request.urlretrieve(url, filename, my_reporthook)

print (my_downloader('https://www.gutenberg.org/files/55146/55146-h.zip'))


RAID1 vs RAID5: read performances of a 2-disks array

Question: I'm testing some RAID setups built with mdadm. This is about parallel reads on a 2-disks array.
RAID1 seems to balance the reads by process, some sort of coarse-grained balancing, so reading the whole raid array with a simple dd if=/dev/md0 of=/dev/null bs=1M, according to nmon, basically directs all the read to /dev/sda. When multiple dd commands run in parallel, some read from sda some from sdb.
Curiously, I tested with RAID5, same two disks, same redundancy and 50% disk utilization. One single low-level read with dd is spread across sda and sdb evenly, so every read operation seems to be better parallelized.
Effects on the CPU load seem to be negligible. I also haven't checked write operations.
Does using RAID5 for a 2-disks array make any sense?
By the way, going back and forth between 1 and 5 is as easy as mdadm --grow /dev/md0 --level 1 or 5, no data is moved, only the parallel read pattern changes.
Answer:
One single low-level read with dd is spread across sda and sdb evenly, so every read operation seems to be better parallelized.

You're misreading what's going on in RAID-5.  To read any data from a RAID-5 array, all disks have to be read from, and the actual data extracted from the "data + parity" that's stored on all the disks in the array.
In reality, you have to read twice as much data in the RAID-5 configuration to get your data, but with the added benefit of detecting data corruption. (To the extent RAID-5 protects against data corruption.  It's not complete.)
In a RAID-1 mirror, you'll only detect data corruption in a full scrub of the array.

Does using RAID5 for a 2-disks array make any sense?

If you want data corruption detection, yes.  But remember that comes at the cost of needing twice the read bandwidth and twice the number of read IO operations.
Answer:
Does using RAID5 for a 2-disks array make any sense?

No, it needs 3+ disks. You should specify RAID1 when you want a mirror. Do not rely on the implementation details like mdadm doing a sane thing and being effectively RAID1 for 2 disk array.
Also, don't use RAID5, a second failure on rebuild is likely. Two disks in RAID 1, or 4+ in RAID6 or RAID10.
Comment: RAID5 is making a comeback with the advent of commodity SSDs. Major vendors (HPE come to mind) are not exactly pushing RAID5 on SSD arrays but they're putting it on part with RAID6.
Comment: Just because you can configure single parity does not mean it is a good idea, those use cases are the exception. Dual- or triple-parity is the only option on several arrays, including the HPE-owned Nimble.
Comment: The rebuild time on a SSD is much faster than on spinning disk and the failure rate is much lower. Since rebuild time and failure rate are generally the reasons given for preferring RAID6 over RAID5, the argument really doesn't apply here. When Nimble was acquired by HPE, the majority of their portfolio was on spinning disk so they had to enforce RAID6 or erasure-encoding to ensure data protection. Another HPE acquisition, Simplivity, appears to use RAID5 by default on its installs, which is always on all-flash arrays.


Remote desktop sessions - Unwanted automatic log off after period of time

Question: I'm having an issue whenever I connect to any of our servers via RDP -
After a certain period of time, it seems to close these sessions, closing all the applications i had open etc...
This is particularly annoying if I am running a long process - for example, copying a file - it cuts it off...
I then re-connect via RDP, and it effectively loads a new session.
Is this set somewhere in Group Policy? Or somewhere else?
This is happening on Windows 2008 (it may also be on our 2003 servers, although I haven't noticed...)
Answer: The first thing to check would be the timeout settings in Terminal Services Configuration. It's in the Sessions tab in the TSC.
Comment: Exactly where it is - there is settings for log off when idle and another for logging off disconnected sessions.
Comment: In addition there are settings in the user settings in active directory that will control timeouts for terminal services.
Answer: There are group policy settings under Computer Configuration\Administrative Templates\Windows Components\Terminal Services\Sessions regarding how long you can stay connected.
Some details at http://www.windowsnetworking.com/articles_tutorials/Terminal-Services-Group-Policy.html
Bear in mind, these settings are at the computer level, not the user level so this will apply to anyone connecting to the servers you apply it to.
If you would rather keep others with the current behavior (and even yourself unless specifically needing to run longer operations) you can leave it as is but when you have the need to run something long term, connect to the console session of the server.
Depending on your version of the RDP client it is either /console or /admin when connecting, run mstsc /? to see which one for you.
For example: mstsc /v:192.168.1.1 /admin
That will connect you to the console session of the machine at 192.168.1.1.
The console session is the session that you would see when physically at the machine with keyboard, video and mouse. If you are disconnected from this session, your operations will continue to run and you can reconnect to it.
Comment: One caveat to running via /ADMIN - you'll lose access to things like local drives or clipboard.  So depending on the source and target of that big file being copied, this might not be optimal for other reasons!  My proposed solution would be to establish a network share that the server can see, then create a one-off scheduled task to copy the file "unsupervised" via Robocopy or FTP.
Comment: The question was regarding sessions ending prematurely not the transfer method so that is what I had addressed.  Using /admin you could transfer with ftp, scp, http or any others and the console session would maintain even if RDP disconnected as long as the users didn't logout.  If the server enforces an inactivity logout then yes using a scheduled task could be a method to circumvent that.
Answer: Open gpedit.msc
Browse to Computer Configuration --> Administrative Templates --> Windows Components --> Remote Desktop Services --> Remote Desktop Session Host --> Session Time Limits.
Enable the "Set time limit for disconnected sessions" and set it to Never
and change the Local Security Policy under Local Policies->Security Options-> Interactive logon: Do not require CTRL+ALT+Del" to Enabled, the problem dissapears.
Comment: Hi, The first part about Session Time Limits should be changed on local computer or the computer to which we remote desktop into?
Comment: Remote computer
Comment: https://imgur.com/a/kE7Tpfe   I've configured as your guide, but it still log me off.
Answer: delete the Default.rdp file under Documents folder. Thats all
if you want to delete specific settings:
1. Open the Run window (press Windows Key + R to bring up the Run Window, or right-click the Start menu and choose "Run")
2. Type regedit and press OK
3. In Registry Editor, expand: HKEY_CURRENT_USER > SOFTWARE > Microsoft > Terminal Server Client
4. Under the Terminal Server Client, there will be two keys: "Default" and "Servers". Delete both those keys if you want to delete all Remote Desktop Connection Data.
   • If you only want to delete a specific one, expand the "Default" key and delete the value type REG_SZ which should contain your Remote Desktop Server IP/HostName as Data.
   • Under the "Servers" key, there will be one key to delete for each Remote Desktop Server.


Laravel Pagination when database is empty

Question: I have a CRUD system where the administrator can manage users.
The users overview has a pagination function:
public function index()
{
    $users = User::first()->paginate(5);
    return view('users.index', compact('users'));
}

Which then goes through a foreach in my index.blade.php file. And this works perfectly.
Untill the Administrator decides to delete all database records. This gives me the following error:
Call to a member function paginate() on null
How should I fix this error?
I want it to show the page but just not execute the Foreach when there are no results.
Comment: Use `User::paginate(5);` instead, Not sure if you are fluent in english but its clear that you can not paginate anything if you have only **one** record `->first()` gets you the first record (only **one** can be first). For not-executing foreach, you need to have if statement, something like `@if($users->count() > 0) // do foreach // @endif`. Good Luck!
Comment: Of course. Now you say it it does make sence.
English is not my native language, but I do speak it fluently. I just didn't think of it this way. Thanks for pointing it out!
Comment: No problem, have fun!
Answer: remove first() from query
public function index()
{
    $users = User::paginate(5);
    return view('users.index', compact('users'));
}


Add a class to a image for a specific view

Question: I need add a class to a image for one specific views.
I tried:

theme_preprocess_field() but it doesn't work
theme_preprocess_image() but it's for all the images
I tried what suggested in Override image template for field image_formatter own, but it is too complex to simply add a CSS class
This answer is the more accepted but I like other ways

Is it possible to override a field/image template file for a specific view?
Answer: If your view is outputting fields (& not a teaser) you can easily do it in the views UI.

Edit your view
Click on the image field
STYLE SETTINGS > Customize field HTML > Create a CSS class
Save

Now your image field should have a class:
Comment: @100pic This option add the class to container of field not to the img tag.
Comment: Just posted the same answer at the same time! (removed my one, it's ok)
Comment: Great minds think alike, I guess, @DavidThomas


Is this correct use of linear mixed model?

Question: This is the current data I have

I want to know if fixed factor A has any effect on C.  That is, if A1 = A2 = ... = A5.
I think I am trying to find a group difference, correct me if I am wrong.
because I read a paper saying it is fine to treat Likert scale in parametric, I changed factor C into numeric., and I decided to use mixed-effects model through
library(lme4)
library(lmerTest)
model <- lmer(C ~ A + (1|B), data)
summary(model)
anova(model)

and reached the conclusion:  we cannot reject the idea that factor A is consistent in manner of variability in resultC.
Then I read about the controversies behind p-values in mixed model, then eventually question whether that p-value actually represents my question, or if it answers a completely different question.
If I want to answer my question of A1 = A2 = ... = A5, is my use of a mixed model correct?
Thank you for your guidance.
Answer: I think your approach for examining whether the levels of A have an equivalent or near-equivalent effect on C make sense. In addition to your ANOVA approach, you could run a second model that excludes A as a predictor and then use a likelihood ratio test to see if the model without A is a better fit to the data:
model <- lmer(C ~ A + (1|B), data)
model0 <- lmer(C ~ 1 + (1|B), data)
anova(model0, model)

A significant likelihood ratio test would be an indication that the model that has A as a predictor provides a better fit to your data whereas an insignificant likelihood ratio test would indicate that A is not needed to model the outcome C. You also get AIC and BIC fit statistics for the two models, and these are useful for model comparison. Information criteria measures such as these are useful only in comparing two models. Lower values indicate better fit. See this thread for more information.


Why is the Active Directory security setting for "Write Personal Information" automatically reset?

Question: In my Small Business Server 2003 environment, I would like to be able to have users manage their own delegate permissions for their Exchange mailboxes. By default, the Outlook delegate feature will not work unless I go to the user object in Active Directory and grant Allow on "Write Personal Information" to SELF. This will work temporarily, but something seems to reset this value shortly afterword. What would cause this automatic reset?
Answer: If the user in question is or was a member of an administrative group such as Domain Admins, Account Operators, Backup Operators, Print Operators, etc, the AdminSDHolder object protects members of these groups by resetting their permission to the default every 5 minutes and also breaking permission inheritance on them.
You can check this by seeing if the AdminCount attribute is set to anything other than 0. If it is set to anything other than 0, then check their group membership. If they are no longer a member of one of those protected groups, you can manually set AdminCount back to 0 and allow permissions to inherit to their object. If they are still members of this, there is nothing you can do short of modifying the AdminSDHolder object, which would be cause for opening another question.
Comment: Thanks for solving this mystery. I found a script attached to http://support.microsoft.com/kb/817433/ that I was able to use to clear the AdminCount, after removing the user from the "Domain Power Users" group.


Can't successfully Checkout using Braintree v.zero

Question: I'm integrating Braintree's v.zero drop-in ui as a payment method and on the checkout form.
I fill-up the credit card details and click "Continue to next step", the ajax submit and Braintree loads simultaneously. After a couple of seconds, Braintree finishes and returns the payment nonce. However, the form doesn't continue it's submission.

How can I process Braintree first before the form so that I can get the payment nonce value?
Module code

/**
 * Initializes the Braintree client library for use.
 *
 * @param $payment_method
 *   The payment method instance containing the Braintree credentials to use to
 *   submit API requests to Braintree.
 */
function commerce_braintree_vzero_initialize($payment_method) {
  require_once drupal_get_path('module', 'commerce_braintree_vzero') . '/braintree-php-2.37.0/lib/Braintree.php';

  Braintree_Configuration::merchantId($payment_method['settings']['merchant_id']);
  Braintree_Configuration::publicKey($payment_method['settings']['public_key']);
  Braintree_Configuration::privateKey($payment_method['settings']['private_key']);
  Braintree_Configuration::environment($payment_method['settings']['environment']);
}

/**
 * Implements hook_commerce_payment_method_info().
 */
function commerce_braintree_vzero_commerce_payment_method_info() {
  $payment_methods = array();

  $payment_methods['commerce_braintree_vzero'] = array(
    'title' => t('Braintree v.zero'),
    'description' => t('Payment method using Braintree v.zero.'),
    'active' => TRUE,
  );

  return $payment_methods;
}

/**
 * Returns the default settings for Braintree v.zero.
 */
function commerce_braintree_vzero_default_settings() {
  return array(
    'merchant_id' => '',
    'public_key' => '',
    'private_key' => '',
    'environment' => 'sandbox',
  );
}

/**
 * Payment method settings form.
 *
 * @param $settings
 *   Default settings provided from rules
 *
 * @return array
 *   Settings form array
 */
function commerce_braintree_vzero_settings_form($settings) {
  $form = array();

  // Merge default settings into the stored settings array.
  $settings = (array) $settings + commerce_braintree_vzero_default_settings();

  $form['merchant_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Merchant ID'),
    '#default_value' => $settings['merchant_id'],
    '#required' => TRUE,
  );
  $form['public_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Public key'),
    '#default_value' => $settings['public_key'],
    '#required' => TRUE,
  );
  $form['private_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Private key'),
    '#default_value' => $settings['private_key'],
    '#required' => TRUE,
  );
  $form['environment'] = array(
    '#type' => 'radios',
    '#title' => t('Braintree server'),
    '#options' => array(
      'sandbox' => ('Sandbox - use for testing, requires a Braintree Sandbox account'),
      'production' => ('Production - use for processing real transactions'),
    ),
    '#default_value' => $settings['environment'],
  );

  return $form;
}

/**
 * Payment method callback: checkout form.
 */
function commerce_braintree_vzero_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  // Load Braintree vzero php library
  commerce_braintree_vzero_initialize($payment_method);

  $clientToken = Braintree_ClientToken::generate();

  $form['test'] = array(
    '#markup' => '

' .
    '<input type="submit">',
  );

  $form['testt'] = array(
    '#type' => 'textfield',
    '#title' => t('Test'),
  );

  drupal_add_js(array('vzero' => array('clientToken' => $clientToken)), 'setting');

  // Load vzero.js.
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'commerce_braintree_vzero') . '/vzero.js',
  );

  return $form;
}

/**
 * Payment method callback: checkout form submission.
 */
function commerce_braintree_vzero_submit_form_submit($payment_method, $pane_form, $pane_values, $order, $charge) {
  commerce_braintree_vzero_transaction($payment_method, $order, $charge);
  drupal_set_message('success');
}

/**
 * Creates an example payment transaction for the specified charge amount.
 *
 * @param $payment_method
 *   The payment method instance object used to charge this payment.
 * @param $order
 *   The order object the payment applies to.
 * @param $charge
 *   An array indicating the amount and currency code to charge.
 */
function commerce_braintree_vzero_transaction($payment_method, $order, $charge) {
  $transaction = commerce_payment_transaction_new('commerce_braintree_vzero', $order->order_id);
  $transaction->instance_id = $payment_method['instance_id'];
  $transaction->amount = $charge['amount'];
  $transaction->currency_code = $charge['currency_code'];
  $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;

  $transaction->message = 'Test message';

  commerce_payment_transaction_save($transaction);
  return $transaction;
}

JS code
(function ($) {
  Drupal.behaviors.vzero = {
    attach: function (context, settings) {

      if ($('#edit-commerce-payment-payment-method-commerce-braintree-vzerocommerce-payment-commerce-braintree-vzero', context).is(':checked')) {
        console.log("LOADED " + $('#asd').length);
        braintree.setup(settings.vzero.clientToken, "dropin", {
          container: "asd",
          paymentMethodNonceReceived: function (event, nonce) {
            console.log('nonce received ' + nonce);
            $('.form-item-commerce-payment-payment-details-testt input').val(nonce);

            $('body').delegate('#edit-continue', 'click', function(event) {
              event.preventDefault();
              console.log('prevent submit');
              return false;
            });
          }
        });
      }
      else {
        console.log("NOT CHECKED");
      }
    }
  }
})(jQuery);

Note: This here is the complete module if you would like to test. https://github.com/leolandotan/commerce_braintree_vzero
Answer: this patch successfully adds support for Vzero https://www.drupal.org/node/2449881.


Links start with two slashes

Question: More and more, began to notice that the links in the source code on Web sites begin with two slashes. For example:
Image

Why do it?
Answer: It's a protocol-relative URL (typically HTTP or HTTPS). So if I'm on http://example.org and I link (or include an image, script, etc.) to //example.com/1.png, it goes to http://example.com/1.png. If I'm on https://example.org, it goes to https://example.com/1.png.
This lets you easily avoid mixed content security errors.

Links start with two slashes


An Abelian Type Theorem for Meromorphic Functions

Question: Suppose
$$f(z)=\sum_{n=0}^\infty a_nz^n$$
extends meromorphically to the whole complex plane. Show that if
$$\frac{r^n a_n}{n^k}\to c\neq 0\quad \mathrm{as}\quad n\to\infty\quad$$
for some integer $k\geq 0$ and some $r>0$, then $f(z)$ has a pole of order $k+1$ at $z=r$.
I tried finding $\lim_{z\to r}(z-r)f(z)$ but didn't succeed. I also tried to use the root test for $(z-r)f(z)$ but there isn't enough information. Now I don't know where I should start with. Any help is very much appreciated.
Answer: Cauchy's integral formula implies that the Taylor series of $f$ at $z=0$ converges for $|z|<r$ where $r$ is the modulus of the first pole. With $s_1,\ldots,s_K$ the finitely many poles on $|z|=r$ of order $e_1,\ldots,e_k$ we get that the Taylor series of $f-\sum_{k\le K}\sum_{j\le e_k} \frac{c_{k,j}}{(z-s_k)^j}$ converges for $|z|< r+\epsilon$. That is to say $$f(z)=\sum_{n\ge 0} a_n z^n, \qquad a_n = \sum_{k\le K} \sum_{j\le e_k} C_{k,j} n^{j-1} s_k^{-n} + O( (r+\epsilon)^{-n})$$
And $a_n\sim C_{e_1,1} s_1^{-n} n^{e_1-1}$ iff $e_1$ is larger than all the other $e_k$
Comment: As you see we do. The asymptotic is given by the first poles, not by the next ones.
Comment: How does this tell us that we have a pole at $z=r$?
Comment: The asymptotic is given by the first poles. From the asymptotic we know the first poles. From the first poles we know the asymptotic.
Comment: I think I roughly understand what you want to say. But anyways your answer was very helpful to me. Thank you so much!


Proof of a limit without geometry

Question: Can anbody write a proof that $$\lim_{x\to-\infty}-e^x = 0$$ without using a geometrical representation of the function? Is this something that I should know for Calculus I? (I am teaching myself).
Thanks!
Comment: How would you prove this WITH geometry? :) :) Teaching yourself? Go for it! This e-power stuff comes around a lot in Calc2 (and of course beyond)
Answer: This is equivalent to showing that $$\lim_{n\to-\infty} e^x = 0$$
What you must prove is that for every $\epsilon$, there exists some $M\in\mathbb R$ for which you can show that for every $x<m$, the value $$e^x<\epsilon.$$
This is the definition of a limit.
Answer: $$\lim_{x\to-\infty}-e^x = \lim_{x\to\infty}-e^{-x}=\lim_{x\to\infty}\frac{-1}{e^x} = 0$$
Comment: Thanks a lot! This is a great answer; very straightforward!

Proof of a limit without geometry


Any tools to manage and apply my configuration (installed packaged and so on) from machine-to-machine?

Question: You know, when you get brand new computer you have to install your toolchain, like vim/emacs, git/hg/..., ack, etc. Someday I've tired of doing this manually, and I've started to think how can I automate this process. Firstly there was a shell script, but bash is not as expressive as I want. Moreover, I want to keep my stuff cross-platform, independent of the things like yam/apt and so on. That's how I switched to puppet (and yes, I know about chef and fabric). But this tools are network oriented and I have a sense that my use is not idiomatic.
I have heard about FAI, but maybe there is much more pleasant tools, oriented for local use (on a par with puppet) that could help me to keep my config from machine-to-machine?
Answer: Nope, I'd say that Puppet (or it's equivalent, chef) is the tool you want.  While you can use those tools over a network, and that's the most common use case, they also can be used standalone, to apply a manifest (or cookbook) entirely locally, and I've used that mode to great effect for exactly the purpose you describe.
Comment: I know that I can apply puppet recipes localy (this is how I currently use it), but I thought that there could be a product that is not *client-server* oriented by nature.
Comment: Puppet is not client-server oriented by nature.


Why this error Exception print Connection refused on running

Question: look at this loop. I wanted to make a small port scanner example.
for (int port = 1; port <= 65300; port++) {
    try (Socket socket = new Socket("localhost", port)){
        socket.close();
        System.out.println("Port " + port + " Listen.");
    } catch (UnknownHostException uhe){
        System.out.println(uhe.toString());
        break;
    } catch (Exception e) {
        System.out.println("Something went wrong.");
    }
}

when I write System.out.println(e.toString()); code print:
java.net.ConnectException: Connection refused (Connection refused)
but when I delete it, code run well. tell me why it's happening if you know.
thanks
Comment: You should _expect_ to see "connection refused" exceptions, as it's very unlikely that _every_ port on your computer has a server listening for and accepting connections. See the [java.net.ConnectException: Connection refused](https://stackoverflow.com/q/6876266/6395627) Q&A for more information.
Comment: `System.out.println(e.toString());` prints the exception message when you delete the message that was not printed, but the exception still happens just you are not printing it. If you are confused about why "Something went wrong." was not printed you need to understand how exception catch works check https://stackoverflow.com/questions/34191745/exception-hierarchy-try-multi-catch
Comment: Thats because `new Socket("localhost", port)` throws two checked exception `UnknownHostException` and `IOException` you must explicitly handle these exception in you code . you are doing it for `UnknownHostException` but not for `IOException` since `Exception` is the super class for `IOException` when you add catch block with `Exception` which handles `IOException`
Comment: so what is my code's problem? when I remove that exception, I getting error on ```Socket socket = new Socket("localhost", port)```
Comment: You mean when you remove the catch block?
Comment: yes, when removing ```catch (Exception e) {
                System.out.println(e.toString());
                break;
            }```
Comment: For better understanding of how exception works in java check https://www.geeksforgeeks.org/exceptions-in-java/
Comment: Thanks a lot sir, but I getting error after new update. i'm not sure if you mean it or not. but again I get ``` java.net.ConnectException: Connection refused (Connection refused)``` error
Comment: and again when I delete IOException block, program working without any situations
Answer: I hate to tell you this but, the way you are trying to this will take what feels like forever to go through 65535 ports. Try setting a timeout on the Socket connection for any ports to at least speed up the process somewhat...something like perhaps 50 milliseconds. I suppose it depends upon the system you have. You can do this by using the Socket#connect() method. Now, an IOException like connect timed out, Permission denied: (or Connection refused) basically means the port is closed or simply not available (which to you, may as well be considered as closed). Ports that generate an exception message of Permission denied: or Connection refused would be used by either System Hardware or Software and protected for their specific use only.
In my opinion, the best thing to do is to run the scan thought several ExecutorService threads (like 3000 perhaps) to get the job done in maybe 30 to 40 seconds or so. Yes...your box will pump a little more blood for a bit, but, it beats waiting all day for the port scan to complete.
I would suggest that you don't display closed or unavailable ports during scanning...it's a waste of time. Sending output to a Console Window takes a lot of unnecessary processing time. Just store open ports in a Collection of some sort then display that collection of open ports to the Console (or whatever) when the port scanning is done. The runnable demo code below makes use of a LinkedHashMap so that the open port numbers inserted into the map remain in insertion order.
Unless you modify the code to run through several threads, I would suggest you set the portEnd int variable to 1000 (or 2000) to get a good idea how long a scan of 65000 ports will take. It should be enough to feed you something for results (I hope).
Here is the runnable demo code. Be sure to read the comments within:
final int timeout = 50;         // Socket Connection timeout in milliseconds
final int portStart = 1;        // 1 to 65535
final int portEnd = 65535;      // 1 to 65535
final String ip = "127.0.0.1";  // Local IP.
java.util.LinkedHashMap<Integer, String> openPorts = new java.util.LinkedHashMap<>();

System.out.println("Scanning Ports: " + portStart + " To " + portEnd + ". Please Wait!");
System.out.print("Finished Scanning Ports Up To: -> ");
for (int port = portStart; port <= portEnd; port++) {
    /* This increases the Scan time but at least
       it tells you that something is happenning:  */
    if (port % 100 == 0) {
        System.out.print(port + " ");
    }
    try (java.net.Socket socket = new java.net.Socket()) {
        // Open a connection to the current port Number:
        socket.connect(new java.net.InetSocketAddress(ip, port), timeout);
        // If successful, then the port is Open. If not, an Exception occurs.
        openPorts.put(port, "is Open!");
    }
    catch (java.io.IOException ex) {
        /* This takes time to process as well. It's only here
           if for some reason something critical happens:  */
        String errMsg = ex.getMessage().toLowerCase();
        if (!errMsg.contains("connect timed out") &&
                    !errMsg.contains("permission denied:") &&
                    !errMsg.contains("connection refused")) {
            System.out.println("Port: " + port + " -> *** "
                                 + ex.getMessage() + " ***");
        }
    }
}

// Display open ports in Console Window:
System.out.println(System.lineSeparator());
System.out.println("Port Scan Results - Open Ports:");
System.out.println("===============================");

// Read the LinkedHashMap:
for (java.util.Map.Entry<Integer, String> mapElement : openPorts.entrySet()) {
    Integer keyPort = mapElement.getKey();

    // Finding the value using getValue() method:
    String openClosed = mapElement.getValue();

    // Print the key-value pairs the way we want:
    System.out.println(String.format("Port #%-6d %-8s", keyPort, openClosed));
}

Comment: I copied and past your code, but again get ```Connection refused (Connection refused)``` error, so can this error happening because of some problem in system? and something else, it's just happening when I using loop, but in scanning one port, it's not problem.
Comment: @SaeedKiarsiZadeh Which port throws the "connection refused" exception? Why do you expect connecting to that particular port should succeed?
Comment: System hardware (or software) has most likely protected that port (and most likely other ports) for its own specific use. It would be the same as `Permission Denied`. Consider it a **Closed Port** to you and add the message to the `IOException` block, for example: `String errMsg = ex.getMessage().toLowerCase(); if (!errMsg.contains("connect timed out") && !errMsg.contains("permission denied:") && !errMsg.contains("connection refused")) { System.out.println("Port: " + port + " -> *** " + ex.getMessage() + " ***"); }`.


Replace a column data with data from another column in the same table mysql

Question: I have a table, TABLEA with columns, ID and CAT Name. I would like to run a query that outputs the column CAT with its values replaced in values in the ID column. could someone please help?
ID(0, 1, 2, 3, 4, 5)
CAT(leo, toby, oliver, blade, milo)
I want the output to be:
CAT(0, 1, 2, 3, 4, 5)
Comment: Can you provide some sample data and desired results?
Comment: updated my question, not sure how to input tables
Answer: <code>SELECT ID as CAT from yourtable
</code>


what security measures should be taken when creating/updating/retrieving entities with data from users' form submissions?

Question: We have webforms for authenticated users (anyone can create an account without admin approval) to fill out.  With their submission data I'm using the civicrm_api to create contacts and relationships.
For example:
// in hook_webform_submission_insert I do this:
$newcontact= civicrm_api3('Contact', 'create', array(
  'sequential' => 1,
  'contact_type' => 'Organization',
  'contact_sub_type' => 'Sub_Type',
  'organization_name' => $submission->data[20][0],
));

Is there any filtering I should be doing or are Drupal's security measures sufficient?
There are various hooks I could use.  Currently I'm using a combination of hook_form_alter with submit callbacks and hook_webform_submission_insert.  Would one of these or some other hook have significantly greater security measures?
Answer: Designers need to worry about two things, making sure that user-supplied data can go into the database successfully, and also that data pulled from the database can be written to the page successfully.
When adding data to the database, Drupal will use prepared statements to ensure the SQL injection does not occur. What this means is, Drupal will tell the database, "Expect to see an INSERT command that looks like {statement}." and then sends all the data. If the resulting statements does not match, there will be an error.
Drupal Fields are defined such that the system knows how the data in that field should be displayed. The database schema guarantees that only a certain data format is available. For example, if the field is a number, we know we won't get a string because the database is designed to only record numbers. Drupal can just worry about formatting it properly. Same if it's text, it will make sure that it is not displaying a URL by passing the text through check_plain() after retrieving the data from the database.
In your case, you are going to be inserting this user-supplied data into the database. The Drupal Field API should be ensuring that the data is of the correct type for the database, and that it is not too long, or improperly formatted before inserting the record. It will insert it using the prepared statement to prevent SQL injection. So, you should be fine.
Make sure you read the CiviCRM secure coding guide:
https://docs.civicrm.org/dev/en/latest/security/
Comment: I accidentally described this wrong... I'm not using Drupal "entities" but CiviCRM contacts ...so it's _not_ actually using the field_api.  But would the CiviCRM api likewise ensure the data is proper for saving to db?  In addition to the link you gave I'm also looking at https://docs.civicrm.org/dev/en/latest/security/inputs/ but still not sure of how my api calls fit into that...?  Maybe I should create a new question in the Civi forum.  Sorry for the confusion :/
Comment: I was assuming the API you are using was piggybacking on the Drupal API. If it doesn't, I have no idea what it does or does not do. Sorry.
Comment: Thanks for your help!  Now I can simply ask about civicrm_api3() in the Civi forum.
Comment: you said "Designers need to worry about two things" ...I assume you mean "developers"..?


Autofac Multi-Tenant ASP.NET Application return the tenant instead of the identifier

Question: I am using Autofac as a IoC container with Autofac.Multitenant package for multi-tenancy.
I have a container setup like this:
var builder = new ContainerBuilder();

// Register the controllers
builder.RegisterControllers(typeof(Deskful.Web.DeskfulApplication).Assembly);

// Tenant Identifier
var tenantIdentifier = new RequestSubdomainStrategy();

builder.RegisterInstance(tenantIdentifier).As<ITenantIdentificationStrategy>();

// Build container
var container = builder.Build();

// Tenant container
var mtc = new MultitenantContainer(tenantIdentifier, container);

// Set autofac as dependency resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

And my identification strategy:
public class RequestSubdomainStrategy : ITenantIdentificationStrategy
{
    public bool TryIdentifyTenant(out object tenantId)
    {
        tenantId = null;

        try
        {
            var context = HttpContext.Current;
            if (context != null && context.Request != null)
            {
                var site = context.Request.Url.Host;

                tenantId = 1;
            }
        }
        catch { }

        return tenantId != null;
    }
}

Then in my controller where I need the tenant I can do the following after injecting the ITenantIdentificationStrategy:
var tenantId = this.TenantIdStrategy.IdentifyTenant<int>();

My question is, how can I store the tenant object during my identification process so I can access all the properties of the tenant?
Because now it only returns the id.
Answer: Don't know if this is a correct solution, but I ended up by doing the following.
First I created a new interface to extend the current ITenantIdentificationStrategy:
public interface IDeskfulTenantIdentificationStrategy : ITenantIdentificationStrategy
{
    ITenant Tenant { get; }
}

I extended the interface with the Tenant property.
Then in my identifier class I set the Tenant property during identification:
public class RequestSubdomainStrategy : IDeskfulTenantIdentificationStrategy
{
    private ITenant _tenant;

    public ITenant Tenant
    {
        get
        {
            return _tenant;
        }
        private set
        {
            _tenant = value;
        }
    }

    public bool TryIdentifyTenant(out object tenantId)
    {
        tenantId = null;

        try
        {
            var context = HttpContext.Current;
            if (context != null && context.Request != null)
            {
                var site = context.Request.Url.Host;

                Tenant = new Tenant("tenant1.deskfull.be", "connString", "Tenant 1") { Id = 20 };

                tenantId = Tenant.Id;
            }
        }
        catch { }

        return tenantId != null;
    }
}

And finally I register the new inteface in my autofac container:
var tenantIdentifier = new RequestSubdomainStrategy();

builder.RegisterInstance(tenantIdentifier)
.As<IDeskfulTenantIdentificationStrategy>();

When I then use this inside my controller, I can do the following:
public string Index()
{
    int tenantId = TenantIdStrategy.IdentifyTenant<int>();

    return "Home - Index: " + TenantIdStrategy.Tenant.TenantName;
}


Creating a trigger when value is NULL use old value. Nested exception error

Question: Hello and thanks for viewing this, I have a table (with names changed from real names and some other info left out, please let me know if there is any more info on the table you'd like)
CREATE TABLE IF NOT EXISTS `example`.`coursetwo` (
  `candidate_no` INT(11) NOT NULL,
  `course_date` DATETIME NULL,
  `course_name` VARCHAR(45) NULL,
  PRIMARY KEY (`candidate_no`),
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

And I have an update query on a form which updates the table's course date and name for a candidate. Here is the query:
UPDATE coursetwo SET course_date=?, course_name=? WHERE candidate_no = ?;

When a user wants to go back and enter just one value, say the course_name and submit it, it sets the course date to null and not keeping the previous known input.
I am creating a trigger if a value is null then use the old value, however I am getting a nested exception error :

There was an unexpected error (type=Internal Server Error, status=500).
  PreparedStatementCallback; uncategorized SQLException for SQL [UPDATE coursetwo SET course_date=?, course_name=? WHERE candidate_no=?]; SQL state [HY000]; error code [1442]; Can't update table 'coursetwo' in stored function/trigger because it is already used by statement which invoked this stored function/trigger; nested...

Here is my trigger:
delimiter #
DROP TRIGGER IF EXISTS ifnull_keep_old_values#
create trigger ifnull_keep_old_values after update on coursetwo
for each row
begin
    IF NEW.course_date IS NULL THEN
    UPDATE example
    SET course_date = OLD.course_date WHERE candidate_no = OLD.candidate_no;
    END IF;
END#
DELIMITER ;

Does any one know what is wrong with this and if there is another work around? I have many tables and columns to change and I would have to do this trigger around 50 times for each (very bad!) . I am not so knowledgeable on triggers so any help would be great!
Thanks for taking the time to read and help me :)
Comment: Also, keep in mind if that UPDATE inside the query worked, you would have just updated the entire table for a single row change.
Answer: So you want to preserve the current value of course_date when an update happens that would have set it to NULL.
MySQL will not let you update the same table in the trigger that fires on the same table, hence the error you are getting.
However, in your use case, all you have to do is dynamically change the value that is about to be updated in a BEFORE trigger.
Like :
delimiter #
DROP TRIGGER IF EXISTS ifnull_keep_old_values#
CREATE TRIGGER ifnull_keep_old_values BEFORE UPDATE ON coursetwo
FOR EACH ROW
BEGIN
    IF NEW.course_date IS NULL THEN SET NEW.course_date = OLD.course_date;
    END IF;
END#
DELIMITER;

If you want to deal with more columns on the same table, then do it within the same trigger. You just have to add additional IF NEW.... IS NULL THEN NEW... = OLD... clauses. If you want to implement the same logic on other tables, then you have to create a new trigger for each table.
Here is an alternative body for the trigger that avoids the use a BEGIN/END block. The COALESCE function returns its first argument (here the new course date) unless it is NULL, in which case the second argument (old course date) is returned.
CREATE TRIGGER ifnull_keep_old_values BEFORE UPDATE ON coursetwo
FOR EACH ROW
    SET NEW.course_date = COALESCE(NEW.course_date, OLD.course_date)
;

Comment: I am pretty sure it needs to be a *before update* trigger as well.
Comment: Alternative trigger body: `... FOR EACH ROW SET NEW.course_date = COALESCE(NEW.course_date, OLD.course_date);` so you don't need a BEGIN/END block, and therefore don't need to change the `DELIMITER`.
Comment: @Uueerdo thanks for checking, updated my answer accordingly
Comment: thanks @BillKarwin, I added this alternative solution to my answer
Comment: Thank you very much everyone :) I was quite close I guess ha! That worked @GMB and thanks for saying to change to a before update too!

My problem is that I would have to do this for 4 more columns in this table and I have 6 more tables to do the same thing. Is there a more efficient way to do it than 1 column update in one trigger? Say if any values are null , do the same thing on each column? Thanks!
Comment: Thanks @GMB. Sorry I am new how do I accept an answer?


Not working example for Dialogflow V2 api

Question: Experienced problems with C# SDK documentation which can be found here:
http://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.Dialogflow.V2/api/Google.Cloud.Dialogflow.V2.SessionsClient.html#Google_Cloud_Dialogflow_V2_SessionsClient_Create_Google_Api_Gax_Grpc_ServiceEndpoint_Google_Cloud_Dialogflow_V2_SessionsSettings_
No reference for method ToChannelCredentials().
We cannot connect the SDK to dialogflow, even with blank project. Is this method still existing or deprecated?
<code>using Google.Cloud.Dialogflow.V2;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
...
GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
Channel channel = new Channel(
    SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
SessionsClient client = SessionsClient.Create(channel);
...
// Shutdown the channel when it is no longer required.
channel.ShutdownAsync().Wait();
</code>
Answer: Have you tried connecting using the service account private key ? (Json file)
Follow these steps (working example in C#)

After you create a Dialogflow agent go to the agent's settings --> General --> click on the Service Account link
You will be sent to to google cloud platform where you can create a service account
After you create a service account, there will be an option to create a KEY, create it and download the (JSON) format of it
This key will be used to connect from your C# project to the Dialogflow agent
Install Google.Cloud.Dialogflow.V2 package in your project
Create for example a Dialogflow manager class (check below for an example)
<code>    public class DialogflowManager {
    private string _userID;
    private string _webRootPath;
    private string _contentRootPath;
    private string _projectId;
    private SessionsClient _sessionsClient;
    private SessionName _sessionName;

    public DialogflowManager(string userID, string webRootPath, string contentRootPath, string projectId) {

        _userID = userID;
        _webRootPath = webRootPath;
        _contentRootPath = contentRootPath;
        _projectId = projectId;
        SetEnvironmentVariable();

    }

    private void SetEnvironmentVariable() {
        try {
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", _contentRootPath + "\\Keys\\{THE_DOWNLOADED_JSON_FILE_HERE}.json");
        } catch (ArgumentNullException) {
            throw;
        } catch (ArgumentException) {
            throw;
        } catch (SecurityException) {
            throw;
        }
    }

    private async Task CreateSession() {
        // Create client
        _sessionsClient = await SessionsClient.CreateAsync();
        // Initialize request argument(s)
        _sessionName = new SessionName(_projectId, _userID);

    }

    public async Task < QueryResult > CheckIntent(string userInput, string LanguageCode = "en") {
        await CreateSession();
        QueryInput queryInput = new QueryInput();
        var queryText = new TextInput();
        queryText.Text = userInput;
        queryText.LanguageCode = LanguageCode;
        queryInput.Text = queryText;

        // Make the request
        DetectIntentResponse response = await _sessionsClient.DetectIntentAsync(_sessionName, queryInput);
        return response.QueryResult;
    }
}
</code>
And then this can be called like this for example to get detect Intents
<code>     DialogflowManager dialogflow = new DialogflowManager("{INSERT_USER_ID}",
    _hostingEnvironment.WebRootPath,
    _hostingEnvironment.ContentRootPath,
    "{INSERT_AGENT_ID");

var dialogflowQueryResult = await dialogflow.CheckIntent("{INSERT_USER_INPUT}");
</code>
Comment: Those are being used to get the actual location of the json Key file, i just noticed that webRoothPath is not used in the manager so you can disregard it, but the _contentRootPath returns the absolute path to the directory that contains the application content files
Comment: In your example under #7: How / Where do I instantiate `_hostingEnvironment`?
Comment: @Shiasu-sama It is injected in the constructor (DI) where i am calling DialogflowManager
Comment: What should `_contentRootPath` be set to?


QML Camera não fica FULL SCREEN

Question: Estou desenvolvendo um aplicativo que necessita que a câmera frontal ocupe toda a tela de fundo, estilo o aplicativo snapchat, mas utilizando QML a câmera com espaçamento em cima e em baixo da câmera. QML Responsável pela câmera:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Layouts 1.1
import QtMultimedia 5.5
import QtQuick.Window 2.2

Item {
    id: item1
    width: 720
    height: 1080

    property alias camera: camera
    property alias video: video

    Camera {
        id: camera

        imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash

        flash.mode: Camera.FlashRedEyeReduction

    }

    VideoOutput {
        id : video
        anchors.fill: parent

        orientation: -90
        source: camera
        focus : visible // to receive focus and capture key events when visible
    }

}

Comment: Tente `fillMode: VideoOutput.PreserveAspectCrop` dentro do `VideoOutput`.
Comment: O `Item` onde você está colocando a câmera tem 720x1080px. É essa a proporção da imagem da câmera?
Comment: O Item tem sim, e a resolução da tela do aparelho celular é de 720x1080
Answer: Boas!
Sendo que o item pai tem  1080*720 se queres a camera esticada a esta resolução falta o fillMode: VideoOutput.Stretch
VideoOutput {
    id : video
    anchors.fill: parent
    //Adiciona isto...
    fillMode: VideoOutput.Stretch
    orientation: -90
    source: camera
    focus : visible // to receive focus and capture key events when visible
}

QML Camera não fica FULL SCREEN


println() in Spring Boot logs

Question: I use System.out.println() to debug my Spring Boot application. It is fine in my IDE. When run standalone, there is a strange situation when println from my @Controller prints to the console, but println from my @RestController doesn't (I see them both printing to the output in the IDE). I have this in application.properties:
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.directory=/dev
server.tomcat.accesslog.prefix=stdout
server.tomcat.accesslog.buffered=false
server.tomcat.accesslog.suffix=
server.tomcat.accesslog.file-date-format=

I am not sure what these constants mean. Is there a method of having all println from all threads print to the console? The @RestController executes, because Tomcat shows that it has been called, it returns 200 and the application works correctly.
Answer: Prefer using logs (slf4j, log4j) instead of System.out.println
With right configuration, it will write your logs in a file ".log", with date and time of traces (info, debug, warn, error levels)
It is more appropriate if you want to deploy your app on a remote server.

println() in Spring Boot logs