Seagull S6 acoustic guitar feels very hard to play

Question: I am beginner guitar player. I had a cheap $150 guitar for slightly more than 1 year. I started learning guitar with that. It's a 3/4 size guitar. I had no problem with it other than the sound bit low. It was easy to play for my fingers.
After lots of research in the internet i come down to 2 choices Seagull s6 vs Taylor big baby.  I bought Seagull S6 concert hall guitar for $400+ Coz, most forums suggest its a good guitar for a beginner and it's a full size too.
But, after playing couple of days, I feel it's very hard for me to play. My fingers hurt a lot. I can't do string bedding also.
I didn't change the strings, they are the original ones came with guitar(please see photos). Please advise me what can i do to make the guitar bit more playable for me?
Comment: That's "string bending", not "string bedding", right? Or is there a technique I don't know?
Answer: A 3/4 sized guitar has a shorter scale-length than a full-sized guitar, so there is less string tension for the same string gauges on the smaller guitar. This might be responsible for the difficulty you are encountering.
I would always recommend putting new strings on a newly acquired guitar, and you could try some lighter-gauge strings to reduce the tension (don't know what you have on now, maybe .012s or .013s, you could try some .011s). This might require a new setup. I would get the new strings and change them, and if you have any fret-buzz or other issues, take it to a guitar tech or luthier.
It is hard to tell from the photograph, but the string action looks like it might be a little bit high. Lighter strings might improve this a little, but it might be a good idea to take this to a good shop with a guitar tech (or the shop where you bought the guitar, if possible), and have them check it out. If you take your new strings with you (or buy them from the shop) they should be able to install the strings and make any needed adjustments for a small fee.
In any case, I think that it might take some time to get used to the transition from the 3/4 sized guitar to a full-sized one.
Answer: Along the same lines as what David Bowling said - a lot of cheap instruments (and some quite expensive instruments!) come from the shop not very well-set up. High action is a particular problem with acoustic guitars - it's easier to set the instrument up without fret buzz with a high action, but that makes it hard to play.
Your choice may well be to spend a bit of time learning how to set up the guitar, or a bit of money getting it set up professionally.


What is the smallest number n of positive distinct integers to guarantee that at least 15 of them are congruent mod 7?

Question: I need help figuring out how to do this question. I am not sure if set of given distinct integers is specifically the first n elements of the natural numbers set, but I assume that otherwise this question would have no solution.
Can someone help me with this question?
Comment: By some version of the pigeon-hole principle. it seems like it should be $7*14+1$ since then at least one equivalence class mod $7$ would have to have at least $15$ items.
Comment: https://en.wikipedia.org/wiki/Pigeonhole_principle
Answer: There are $7$ distinct congruence classes. Worst case scenario is that you get $14$ distinct elements for each congruence class, i.e. $14 \times 7=98$. Then the $99$-th element will make one of the classes with $15$ distinct elements, so the answer is $99$.
In general if you want to find the smallest number of distinct positive integer to guarantee that at least $k$ of them are congruent mod $m$ is $(k-1)\times m+1$.


C++, Pointer to an object resets values of string variables

Question: Here is a function getValue(string name) from the Map class that I am using in my program
The Map class stores strings as key and the ValueType as values.
template <typename ValueType>
  ValueType Map<ValueType>::getValue(string key)
    {
        if (containsKey(key))
            return (*this)[key];
        Error("Attempt to getValue for key which is not contained in map.");
        return ValueType(); // this code is never reached, but here to placate compiler
    }

In graph.h file I am using the Map to store nodes (node class implementation below) mapped by there names.
The graph.h file
#ifndef GRAPH_H
#define GRAPH_H

#include "node.h"
#include "map.h"

class Graph{
public :
    Graph();
    ~Graph();
    void addNode(string name, double x, double y);
    Node* getNode(string name);

private :
    Map<Node> nodes;

};

Graph::Graph(){}

Graph::~Graph(){}

void Graph::addNode(string name, double x, double y){
    if(!nodes.containsKey(name)){
        Node n(name, x, y);
        nodes.add(name, n);
    }
}

Node* Graph::getNode(string name){
    if(nodes.containsKey(name)){
        return (&nodes.getValue(name));
    }else{
        Error ("No node with that name exists");
    }
}

#endif

The Node Class
#ifndef NODE_H
#define NODE_H

class Node{

public:
    Node();
    ~Node();
    Node(string nodename, double nodeX, double nodeY);
    void toString();
private:
    string name;
    double x,y;

};

Node::Node(){}

Node::~Node(){}

Node::Node(string nodename, double nodeX, double nodeY){
    name = nodename;
    x = nodeX;
    y = nodeY;
}

void Node::toString(){
    cout<<"Name "<<name<<", Location "<<x<<", "<<y<<endl;
}

#endif

I am trying to create a pointer to the Node Object that is being retrieved from the Map
But the returning pointer sets the value of the string name
 varaible to blank.
In the main.cpp file
Graph g;
g.addNode("0COOL",42,42);
Node *n = g.getNode("0COOL");
n->toString();

The Output of the above code comes out to be

Name , Location 42, 42

Why is the name field being omitted?
Comment: temporary/local object getting destroyed after function scope...
Comment: is there a reason why you put your definitions into the headers?
Comment: An off-topic note: The name of the function `toString` is confusing. This name implies that a string representation *is returned*, not *printed*. I'm suggesting these names: `print`, `debug` or `dump`, and I'm also suggesting to put the output stream as an argument, defaulting to `std::cout` if you like, but giving the user the option to dump somewhere else. Or you write it as an `operator<<` to make it consistent with how you print stuff in the standard library: `cout << *n` instead of `n->print(cout)`.
Answer: The problem is that your Map<ValueType>::getValue(string key) returns the result by value. When you do this
return (&nodes.getValue(name));

you are returning a pointer to a temporary variable created by the compiler to store the result of getValue. Dereferencing this pointer later is undefined behavior, because the object pointed to by the temporary gets destroyed upon exiting the Graph::getNode(string name) function.
To fix this problem, return ValueType from Map<ValueType>::getValue(string key) by reference. This would limit the lifetime of the pointer to the lifetime of the corresponding element in the map. Of course you need to make sure that there is a valid reference to return in all cases - specifically, this would not be legal: return ValueType(). You would need to create a static variable to represent the missing value, and return a reference to it when the value is not found.


Implement Draft JS into Next JS, Text Editor Won't Show

Question: I am trying to implement draft js as text editor into my next.js project. I have implemented all code based on official guide but the text editor won't show. Here is my code
index.js
import React, { Component } from 'react'
import { useRouter, Router } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';
import MyEditor from '../../components/TextEditor';
import fetch from 'isomorphic-unfetch';
import {Editor, EditorState} from 'draft-js';

const Post = (props) => {
    const router = useRouter();
    const object = props.post.data[0];
  return (
    <Layout>

{object.title}

Oleh: {object.username}

      <MyEditor/>
    </Layout>
  );
}

Post.getInitialProps = async function(context) {
    const {id} = context.query;
    const FormData = new URLSearchParams();
    FormData.append('slug',`${id}`);
    const res = await fetch(Settings.api+'viewPost',{
        'method': 'POST',
        'body': FormData
    });
    const post = await res.json();
    console.log('aw');
    return {
        post
    };
};

export default Post;

TextEditor.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

export default function MyEditor() {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  return (
    <Editor
      editorState={editorState}
      onChange={setEditorState}
    />
  );
}

I really appreciate any answer. Thank you
Comment: please how did you resolve it ?
Answer: It looks like you're doing the right thing - Draft-js is very much a low-level editing tool that you can build rich text-editing on top of - I'm guessing that the editor is actually rendering on the page, but you haven't added any toolbars or complex initial state so you're just seeing a blank page.
I reproduced a super basic Next JS example here: https://codesandbox.io/s/naughty-swirles-7nmbf?file=/pages/index.js and you'll see that the editor itself is 'invisible' as there is no styling applied and no toolbar. If you look further into the Draft-js docs you'll see you can apply initial config objects that will give it a basic style (which you can further customize as you wish).
Comment: How do you apple basic style? The style and className properly do nothing.
Comment: Hey @Shamoon - in the time that I played around with Draft-js I also found styling unintuitive - you can actually apply changes a css (or sass / less) file e.g. style.css, targeting the Draft editor with the appropriate classes. For example - you can use the browser console or docs to find the relevant classes e.g. .DraftEditor-root and then apply styles as you would in any css stylesheet - there's a detailed example of styling Draft-js in this article: https://dev.to/tumee/how-to-style-draft-js-editor-3da2


Explain why there may not be $3$ people with same car.

Question: I don't really understand how to apply Ramsey Theory or the Pigeonhole Principal, so I can't see why this is true:
There are $100$ people at a party.
Assume each person has an even number of cars, possibly zero but no more than $98$ (super rich people).
Can anyone explain why there may not be three people with the same number of cars?
Comment: @fleablood : Most likely a translation problem.  How about "Can anyone explain how it could be that no three people have the same number of cars?"
Comment: You are leaving out details.  Suppose they all have no cars and there are no cars involved.  Or then all have 98 cars and there are 9,800 cars involved.  Those are both certainly possible.  I imagine there is some stipulation about how many total cars there are?
Comment: Or do you mean why it is not possible for there to be *exactly* one group of $3$ people with the same number of cars but no other group of three people can have the same number of cars?
Comment: @fleablood Exactly what I was thinking, but that is not the answer, So I am confused as well.
Comment: It is possible for $3$ people to have the same number of cars. Let people $1,2,3$ have $0$ cars, and people $4,5$ have $2$ and $6,7$ have $4$, ..... and people $2k, 2k+1$ have $2(k-1)$... so people $8,9$ have $6$ and people $10,11$ have $8$ and so on.. up to $98,99$ have $96$ and person $100$ has $98$.   And it is possible for there *not* to be $3$ people with the same number: person $1,2$ con have zero, and people $3,4$ have $2$ and people $2k+1, 2k+2$ have $2k$. up to $97$ and $98$ have $96$ and $99$ and $100$ have $98$.
Comment: What *exactly* is the question.  Word for word.  After thought as it is possible for $3$ people to have the same number.  And it possible for *exactly* one group of $3$ or multiple groups of $3$ and it is also possible for *no* groups of $3$.... I figure Eric Towers interpretation must be the correct one.
Answer: There are $50$ possible numbers of cars. If each number applies to $2$ people, that's $100$ people accounted for.


index out fo range error when trying to load a csv file to python

Question: The code worked when i initially put it in but then i added more late on and it started giving me this indexerror on index 0 when trying to load a cvs file. im trying to put the left most value in the first list and the right most value of each row in the csv file in the second list. it works when i manualy input the values but not when i input the values from a program
import csv

list1 = []
list2 = []

with open('file.csv') as f:
    f.readline()
    csvin = csv.reader(f)
    for row in csvin:
        list1.append(row[0])
        list2.append(row[1])

header1,header2
l1value,l2value
l1value,l2value

Error message:
list1.append(row[0])
IndexError: list index out of range

Comment: Hi, welcome. Please edit your post and include the code, not an image of it, and a sample of your CSV. Also please include the specific error message. Thanks, and good luck!
Comment: Hard to tell for sure what is going on exactly. However, one thing that does stick out, is `f.readline()`. You should not need that. Try removing or commenting that `f.readline()` out and try again.
Answer: Your code like it is posted works fine.
Using the readline() function to skip the header line is ok.
Your csv file appears to contain blank lines which cause the error message as csv.reader returns a blank line as en empty list.
with open(filename) as f:
     f.readline()
     csvin = csv.reader(f)
     for row in csvin:
         print(row)

# returns the following rows:
# ['1', '3']
# ['2', '4']
# []

To avoid this you can either check your csv file to not contain blank lines or add an if condition to check for an empty row by checking row:
l, r = [], []
with open(filename) as f:
     f.readline()
     csvin = csv.reader(f)
     for row in csvin:
         if row:
             l.append(row[0])
             r.append(row[1])


Sections which generate globally, generate global sections.

Question: I am not sure so I'll ask just in case. Let $X$ be a scheme and $\mathcal F$ a sheaf of modules on $X$ which is globally generated by $\{s_i\}$. Do these sections also generate $\Gamma(X,\mathcal F)$ as a module ?
Is it true if we suppose that there are finitely many generators, or more ?
In fact I tried to show that a morphism $\phi\colon\mathbb P^n_K\to \mathbb P^m_K$ with $n>m$ is constant. I argued by contradiction using that $\phi^*(x_1),\dots,\phi^*(x_m)$ were generators of $\phi^*\mathcal O_{\mathbb P^m_K}(1)$ (in fact they are global generators by Hartshorne II.7.1) and said that $\Gamma(\mathbb P^n_K,\mathcal O_{\mathbb P^n_K}(d))$ had a too big dimension for $\mathcal O_{\mathbb P^n_K}(d)$ to be isomorphic to $\phi^*\mathcal O_{\mathbb P^m_K}(1)$. But this argument might not work since it relies on saying that the dimension of $\Gamma(\mathbb P^n_K,\phi^*\mathcal O_{\mathbb P^m_K}(1))$ is at most $m$.
Comment: Let $V=\oplus_i {\cal O}_X$ and let $V\to M$ be the corresponding surjection (given by the $s_i$), where $M$ is your square (I don't know how to Tex a square). Let $K$ be the kernel of $V\to M$. Then the answer to your question is yes iff the induced map $H^1(X,K)\to H^1(X,V)$ is injective. This follows from the existence of the long exact sequence of cohomology groups associated with a short exact sequence.
Comment: In the answer below, $K={\cal O}(-2)$ and so $H^1(X,K)$ is one-dimensional. On the other hand, $H^1(X,V)=0$. So the induced map $H^1(X,K)\to H^1(X,V)$ is not injective.
Comment: For the question about the morphism between projective spaces, consider that $\phi$ must be given by some ${\cal O}(k)$, with $k\geq 0$ (because the Picard group of projective space is generated by ${\cal O}(1)$). Suppose first that $k>0$. Let $F$ be a fibre of $\phi$. Then ${\cal O}(k)|_F$ is trivial and ample, so $F$ must be finite (otherwise the trivial bundle is ample on a irreducible component of dimension $>0$ of $F$, which is impossible). Hence $\phi$ is finite. But this contradicts $n>m$. So $k=0$ and so $\phi$ is constant.
Comment: @DamianRössler And is it wrong to say that since the $x_i$ generate the global sections (not only globally this time) on $\mathbb P^m$, then their pullbacks $\phi^*(x_i)$ generate $\Gamma(X,\phi^*\mathcal O(1))$ ?
Answer: No. Take, for example, the sheaf $\mathcal O(2)$ on projective line with coordinates $(x_0:x_1)$. It is globally generated by sections $x_0^ 2$ and $x_1^2$, but they do not generate the space of global sections.
Comment: @raisinsec: For example, there may be no non-zero global sections.
Comment: Yes, of course, but this does not help to solve your question on maps of projective spaces. It is solved by noting that such a map should be finite, which is proven directly e.g. in Shafarevich's Basic Algebraic Geometry I, paragraph on finite maps.
Comment: But we can still form a basis of sections which globally generate our sheaf if the dimension of globals actions is finite right ?
Comment: I agree but in the finite dimensional case where we know there are nonzero global sections ?
Comment: I don't understand what do you mean by finite-dimensional case. For example, the sheaf $\mathcal O(-1)$ on projective space has no nonzero global sections.
Comment: I mean suppose $\Gamma(X,\mathcal L)\neq 0$ and is finite dimensional with sections which generate globally. This is the case of the question basically. Then we can just complete it (or extract from it) a basis, which will give a basis of sections which generate globally $\mathcal L$. It is nothing deep, just that in this case we can take sections which generate globally to be a basis of $\Gamma(X,\mathcal L)$.


$\alpha = \omega^\beta(\gamma+1)$

Question: This paper mentions that any ordinal $\alpha < \epsilon_0$ can be written uniquely as $\alpha = \omega^\beta(\gamma+1)$, where $\beta<\alpha$.
Does this presentation have a name? Also, how would one get $\omega^\beta(\gamma+1)$ for a given $\alpha$? I played with this for a while and got stuck when setting $\alpha$ to, say, $\omega^\omega+1$. (Or is this just Cantor normal form disguised?)
Comment: $\omega^{\omega}+1 = \omega^0(\omega^{\omega}+1)$
Comment: Well if $\alpha$ is a successor then you need $\beta=0$. If it's not a successor, factorise it's CNF.
Answer: This is very close to the Cantor Normal Form, and likely has no name of its own.
Note that given $\alpha < \varepsilon_0$ its Cantor Normal Form is $$\omega^{\beta_1} \cdot k_1 + \cdots + \omega^{\beta_n} \cdot k_n$$ where $\alpha > \beta_1 > \cdots > \beta_n$ and $0 < k_1 , \ldots , k_n < \omega$.  Now essentially factor out $\omega^{\beta_n}$ to the left to get the representation (as $0 < k_n < \omega$ whatever is left over after factoring out must be a successor ordinal).

$\alpha = \omega^\beta(\gamma+1)$


Show that the determinant $\mathcal{D}(\mathbf{x}, \mathbf{y})$ is the signed area of the parallelogram spanned by $\mathbf{x}$ and $\mathbf{y}$.

Question: Full question (which I couldn't put in the title due to text limits):

I've done 4a. and 4b. with manual calculation since they're just $2\times2$ matrices.

Here's my attempt on 4c.:
Four properties of the determinant $\mathcal{D}:
\mathbb{R}^2\times\mathbb{R}^2\rightarrow\mathbb{R}$:

$\mathcal{D}(\mathbf{x}, \mathbf{y}) = -\mathcal{D}(\mathbf{x}, \mathbf{y})$
$\mathcal{D}(c\mathbf{x}, \mathbf{y}) = c\mathcal{D}(\mathbf{x}, \mathbf{y}) = \mathcal{D}(\mathbf{x}, c\mathbf{y})$ for $c\in\mathbb{R}$
$\mathcal{D}(\mathbf{x} + \mathbf{y}, \mathbf{z}) = \mathcal{D}(\mathbf{x}, \mathbf{z}) + \mathcal{D}(\mathbf{y}, \mathbf{z})$ and $\mathcal{D}(\mathbf{x}, \mathbf{y}+\mathbf{z}) = \mathcal{D}(\mathbf{x}, \mathbf{y}) + \mathcal{D}(\mathbf{x}, \mathbf{z})$
For standard basis vectors $\mathbf{e}_1, \mathbf{e}_2$, $\mathcal{D}(\mathbf{e_1}, \mathbf{e_2}) = 1$

Using the properties of the determinants, I'll show that the properties of the determinant imply that $\mathcal{D}(\mathbf{x}, \mathbf{y})=x_1y_2 - x_2y_1$ for $\mathbf{x}, \mathbf{y}\in\mathbb{R}^2$:
$\begin{align*}
\mathcal{D}(\mathbf{x}, \mathbf{y})&=\mathcal{D}(x_1\mathbf{e}_1+x_2\mathbf{e}_2, y_1\mathbf{e}_1+y_2\mathbf{e}_2)\\
&=\underbrace{\mathcal{D}(x_1\mathbf{e}_1, y_1\mathbf{e}_1+y_2\mathbf{e}_2)}_a+\underbrace{\mathcal{D}(x_2\mathbf{e}_2, y_1\mathbf{e}_1+y_2\mathbf{e}_2)}_b \tag{by property 3} \\
\end{align*}$
Let's first evaluate $a$.
$\begin{align*}
\mathcal{D}(x_1\mathbf{e}_1, y_1\mathbf{e}_1+y_2\mathbf{e}_2)&=\mathcal{D}(x_1\mathbf{e}_1, y_1\mathbf{e}_1)+\mathcal{D}(x_1\mathbf{e}_1, y_2\mathbf{e}_2) \tag{by property 3}\\
&= x_1\mathcal{D}(\mathbf{e}_1, y_1\mathbf{e}_1)+\mathcal{D}(x_1\mathbf{e}_1, y_2\mathbf{e}_2)\tag{by property 2}\\
&= x_1y_1\mathcal{D}(\mathbf{e}_1, \mathbf{e}_1)+\mathcal{D}(x_1\mathbf{e}_1, y_2\mathbf{e}_2)\tag{by property 2}\\
\end{align*}$
By property 1, $\mathcal{D}(\mathbf{e}_1, \mathbf{e}_1) =-\mathcal{D}(\mathbf{e}_1, \mathbf{e}_1)$ implies that $\mathcal{D}(\mathbf{e}_1, \mathbf{e}_1) = 0$. So,
$\begin{align*}
x_1y_1\mathcal{D}(\mathbf{e}_1, \mathbf{e}_1)+\mathcal{D}(x_1\mathbf{e}_1, y_2\mathbf{e}_2)&=\mathcal{D}(x_1\mathbf{e}_1, y_2\mathbf{e}_2)\\
&=x_1\mathcal{D}(\mathbf{e}_1, y_2\mathbf{e}_2)\tag{by property 2}\\
&=x_1y_2\mathcal{D}(\mathbf{e}_1, \mathbf{e}_2)\tag{by property 2}\\
&=x_1y_2\tag{by property 4}
\end{align*}$
Similarly for $b$,
$\begin{align*}
\mathcal{D}(x_2\mathbf{e}_2,y_1\mathbf{e}_1+y_2\mathbf{e}_2)&=\mathcal{D}(x_2\mathbf{e}_2,y_1\mathbf{e}_1)+\mathcal{D}(x_2\mathbf{e}_2, y_2\mathbf{e}_2)\tag{by property 3}\\
&=\mathcal{D}(x_2\mathbf{e}_2, y_1\mathbf{e}_1)+0 \tag{shown with a}\\
&=x_2y_1\mathcal{D}(\mathbf{e}_2, \mathbf{e}_1) \tag{by property 2}\\
&=-x_2y_1\mathcal{D}(\mathbf{e}_1, \mathbf{e}_2) \tag{by property 1}\\
&=-x_2y_1 \tag{by property 4}
\end{align*}$
And so,
$$\mathcal{D}(\mathbf{x}, \mathbf{y}) = a + b = x_1y_2 + (-x_2y_1)$$
Boom! Now we got proof that the properties of the determinants mean that in $\mathbb{R}^2$, $\mathcal{D}(\mathbf{x}, \mathbf{y})=x_1y_2 - x_2y_1$.
Because in the earlier parts of the text I was shown how to get from the area of a parallelogram to the determinant, I can in fact just "work backwards" to get the area of the parallelogram back:
$\begin{align*}
\mathcal{D}(\mathbf{x}, \mathbf{y})&=x_1y_2 - x_2y_1\\
&= \rho(\mathbf{x})\cdot\mathbf{y}\\
&=||x||\hspace{1mm}||y||\cos(\frac{\pi}{2}-\theta) \tag{by definition of dot product}\\
&=||x||\hspace{1mm}||y||\sin(\theta)
\end{align*}$
Here $\theta$ is the angle between the "un-rotated" vector $\mathbf{x}$ and $\mathbf{y}$ and $\frac{\pi}{2}-\theta$ is the angle the rotated vector $\rho(\mathbf{x})$ and $\mathbf{y}$.
Questions:

Is my proof correct? I think it must be wrong somewhere because I didn't use 4b. ($\text{det}(A_\theta B) = \det(B)$) here.
How would I use 4b. ($\text{det}(A_\theta B) = \det(B)$) in my proof?
Answer: Hmm, this looks mighty familiar to me. This is certainly not the approach the author intended. You're just deriving the formula for the determinant in the $2\times 2$ case from the defining properties, but that wasn't the point.
Here's how you should start. Choose $\theta$ so that $A_\theta\mathbf x$ lies on the positive $x$-axis. We know from part b. that $\mathcal D(\mathbf x,\mathbf y) = \mathcal D(A_\theta\mathbf x,A_\theta\mathbf y)$. But how do we see from the latter that we have the usual "base times height" for the area of a parallelogram?
Comment: Yes, sometimes it really is a hint (and not a rude remark) when a teacher tells you that you're making a problem too complicated/hard. :)
Comment: Hi @Ted Shifrin, I've been thinking about this for some time now and I can't seem to move past what you gave me. I just can't see how I can get $||\mathbf{x}||\hspace{0.5mm}||\mathbf{y}||\sin\theta$ from the 4 properties of the determinant and $\mathcal{D}(A_\theta \mathbf{x}, A_\theta \mathbf{y})$. Can you give me another hint?
Comment: What are the coordinates of those two vectors, and what is the determinant?
Comment: Thanks for that hint! I'm still in the progress of doing the math but I've got a question. When you say (in the text) "Use ... the properties of the determinant ...", did you mean that I would use the properties of the determinant to get an expression for the determinant, and then using that expression along with 4b. I would then give an alternate proof?
Comment: This is really meant to be easy, so don't make a huge deal out of it. The point is that when we rotate we can make $\mathbf x = (a,0)$ and then what becomes of the determinant?
Comment: sorry I still seem to be stuck. I tried to evaluate $\mathcal{D}(A_\theta \mathbf{x}, A_\theta\mathbf{y})$ and ended up with $(\cos\theta\cdot x_1-\sin\theta\cdot x_2)(\sin\theta\cdot y_1+\cos\theta\cdot y_2) = \cos\theta\sin\theta(x_1y_1-x_2y_2)+\cos^2\theta\cdot x_1y_2 - \sin^2\theta\cdot x_2y_1$. I don't know how to get from here to $x_1y_2-x_2y_1$.
Comment: You're ignoring my repeated comments. You don't want to do anything with $\theta$. It's theoretical in nature. You pick $\theta$ so that $A_\theta\mathbf x = \begin{bmatrix}a\\0\end{bmatrix}$ and $A_\theta\mathbf y =  \begin{bmatrix}b\\c\end{bmatrix}$. What is $\mathcal D\left(\begin{bmatrix}a\\0\end{bmatrix},\begin{bmatrix}b\\c\end{bmatrix}\right)$? Effectively, you've replaced the original two vectors with two other vectors, but you haven't changed either signed area or determinant.
Comment: thanks so much for your patience! I see that I've been looking in the wrong direction now!


Preview is not showing after upload

Question: When i am trying to upload image as a Authenticate user, After upload i am not able to see preview. fields got disappear fully.
If i try to do as a admin, i am able to see that.
Any suggestions?
Comment: please copy-paste your permissions (fields, node & files) as an image
Comment: its 775.  all permissions are fine
Comment: you are providing very little info, have you field permission module? do you have some custom module affecting permissions? as admin you have all rigths to see/update everything, to me it looks that you have a permissions issue.
Comment: I am facing issue if i am editing other fields with image. or alone image. Other fields are working fine, if i dont touch image
Answer: Could be that you have private file setting turned on and have not given permission to authenticated users to see an uploaded field.
But the commenters above are correct, there are literally a dozen or more ways a field may not display an image. A few that come to mind:

Images styles aren't writeable
A preprocess function has a weird permission it's checking
.htaccess or server settings is screwing up the image headers
the path is getting rewritten because of a path alias
Some access module is being wonky
The access permissions are out of date and need to be flushed
You have a field-level access module preventing authenticated users from seeing the image field
You are using some display module that is tweaking your template or display mode based on permissions
The views module is tweaking your field availability
etc

Preview is not showing after upload


Derivatives of a parametric equation

Question: Suppose a curve $S$ in 2-D is parameterized by
$$S=\{(u(s),v(s)): s\in\mathbb{R}\},$$
where $u$ and $v$ are $C^{1,\alpha}$ for $\alpha \in (0,1)$ with
$$u(s+2\pi)=u(s)+2\pi \qquad \text{and} \qquad v(s+2\pi)=v(s) \qquad \text{for all } s \in \mathbb{R}.$$
They claim that
$$u'(s)^2 + v'(s)^2 \ne 0 \qquad \text{for all } s \in \mathbb{R}.$$
I think there must be a simple reason for it, but I don't see it.  Can someone please help me on this?
I don't think the periodicity has anything with the claim.
Answer: Here is what I am thinking:
If $u(s+2\pi) = u(s) + 2\pi$, then we know that $u(s)$ is not a constant function. Thus, the derivative of $u$ with respect to $s$ cannot be $0$ for all $s$.
We also do not know for certain what $v(s)$ is. From what we are given, it could be constant, or it could be periodic.
Notice that for $u'(s)^2 + v'(s)^2=0$ to be true, both $u'(s)$ and $v'(s)$ would need to be $0$. But we've already shown above that $u'(s) \ne 0$

Derivatives of a parametric equation


Free groups and isomorphism

Question: Is it true that if $F_a(X)$ is the free group with free basis $X$, and the same for $F_a(Y)$, and $X,Y$ have the same cardinality, then there is an isomorphism between $F_a(X)$ and $F_a(Y)$?
Answer: Yes, this follows immediately from the universal property of a free group. If $\phi: X \to Y$ is a bijection, then composing it with inclusion $Y \subset F(Y)$ we get function $X \to F(Y)$ which uniquely determines a homomorphism $F(X) \to F(Y)$ that maps bijectively $X \subset F(X)$ to $Y \subset F(Y)$. Similarly, considering $\phi^{-1}: Y \to X$, we get a unique homomorphism $F(Y) \to F(X)$ that maps $Y \subset F(Y)$ to $X \subset F(X)$. Now the composition of these two is identity.
Comment: But why the composition of $\phi$ with inclusion determines a homomorphism instead of an ordinary map?
Comment: If we denote the inclusion by $i: Y \hookrightarrow F(Y)$, then indeed, $i \circ \phi: X \to F(Y)$ is only an ordinary map. However, the universal property of the free group $F(X)$ says precisely that any ordinary function $X \to G$, where $G$ is some group, gives rise to a unique homomorphism $F(X) \to G$, and that's how we get a homomorphism $F(X) \to F(Y)$ from an ordinary map $X \to F(Y)$.
Comment: Yes, man. I have just started studying it and I had misunderstood the definition of the universal property. Shame on me. I am sorry.
Answer: Hint: You know that there is a bijection $X \to Y$; how might you extend this to a group isomorphism?

Free groups and isomorphism


Criando strings com caracteres especiais

Question: Eu estou fazendo um programa simulador de relógio. Porém, ao imprimir o resultado, estou tendo erros.
Segue exemplo de como faço:
float abc = 1:00 + 2:00 ;

printf("horario: %f",abc);

Como faço então para fazer e imprimir uma string com caracteres especiais?
Answer: Vejamos...
Existem vários tipos de abstração de dados. Em C, por exemplo, temos dois tipos que se encaixam na dúvida: float e char (em cadeia ou array).
O tipo float armazena números em ponto flutuante. Trocando em miúdos, números com casas decimais (alguma coisa vírgula outra coisa). Portanto, ele não armazena caracteres diferentes de algarismos - e, de certa forma, o "ponto" que acaba por indicar as casas decimais (aqui usamos a vírgula mas, ao programar, adotamos o padrão inglês).
O tipo char armazena 1 caractere qualquer dados os limites de ambos compilador e sistema operacional. Todavia, pode criar uma cadeia (array) de char que simula o conceito de string.
Vale lembrar que os tipos não conseguem fazer as operações um do outro usando os mesmos símbolos. Ou seja: você consegue "somar" dois caracteres numéricos mas isso não significa adicionar dois números. Significa concatenar (ou juntar). Exemplos:

'a' + 'b' resulta em "ab"
'1' + '1' não resulta em 2 e sim em "11".

Problema
Considerando seu código
float abc = 1:00 + 2:00 ;

printf("horario: %f",abc);

Você está justamente tentando somar algo que não faz parte do que o tipo float entende: os dois pontos :. Você deve primeiro somar as horas e só então transformar em string da forma apropriada - considerando C, C++ e Rust.
Solução:
Por exemplo, em C, poderia-se considerar:
int hora_1 = 1;
int hora_2 = 20;

int soma_hora = hora_1 + hora_2;

printf("Horário: %d:00", %soma_hora);

Neste exemplo, fiz a soma das horas. Note que os dois pontos ficou a cargo do printf já que não há necessidade de lidar com ele para cálculos de horas.
Foi utilizado int pois o float é desnecessário neste exemplo - e talvez seja mais interessante dividir os minutos e as horas para tornar o trabalho menos complexo. Não foi levando em conta os minutos pois é interessante que pense em como ligar com casos em que a soma fique, por exemplo, igual a 61 - mesmo que não seja necessário, é interessante do ponto de vista técnico para quem está aprendendo.
Seu exemplo ficaria assim:
float abc = 1 + 2 ;

printf("horario: %f:00", abc);

Notas finais
Se realmente for tratar as horas com "dois pontos" - ou seja, com strings - vou sugerir que leia sobre as funções que lidam com isso na linguagem de sua preferência. Em C/C++, pode olhar neste site para possíveis utilitários. E a teoria fica aqui e aqui. E claro, vale a pena sempre procurar no Google outras formas que possam surtir mais efeito em seu entendimento.
Comment: vlw amigo ^^" resolvido
Comment: @GustavoAlves sem problemas! Se a resposta foi adequada e solucionou, pode marcar ela com o sinal de "certo" bem rente ao topo da resposta para que ela não fique em aberto.


Derivative of $\ln|x|$ is the principal value of $1/x.$ Distribution Theory.

Question: I have been looking at the proof for $\frac{d}{dx}\ln|x|=\operatorname{p.v.}\left(\frac{1}{x}\right)$ in the context of distributions and I am having trouble understanding why in the second term after integration by parts the limits we are subbing for $x$ are $\epsilon$ and $-\epsilon$ (the bit is highlighted in blue). The reason for my confusion is that $[a,-a]\backslash[-\epsilon,\epsilon]$ means $[-a,-\epsilon]\cup[\epsilon,a]$ so I am not sure why we are not using this for limits in the integral instead.
Please note that $\operatorname{p.v.}\left(\frac{1}{x}\right)$ is Cauchy principal value of $\frac{1}{x}$ defined as:
$$\left\langle \operatorname{p.v.}\left(\frac{1}{x}\right), \phi\right\rangle = \lim_{\epsilon\to0} \int_{|x|>\epsilon} \frac{1}{x}\phi(x)\,dx$$
Here is the proof I have been referring to:
For any $\phi\in\mathcal D(\mathbb R)$ (i.e. it is a test function) with $\operatorname{supp}\phi = [a,-a]$ we have:
\begin{align*}
\left\langle\frac{d}{dx}\ln|x|, \phi\right\rangle
&=-\langle \ln|x|, \phi'\rangle\\
&= - \lim_{\epsilon\to0} \int_{\mathbb R\backslash[-\epsilon,\epsilon]} \ln|x|\phi'(x) dx\\
&=- \lim_{\epsilon\to0}\left[\int_{[a,-a]\backslash[-\epsilon,\epsilon]} \frac{1}{x}\phi(x) dx + \color{blue}{(\ln|\epsilon|)(\phi(\epsilon)-\phi(-\epsilon))}\right]\\
&= - \lim_{\epsilon\to0} \int_{[a,-a]\backslash[-\epsilon,\epsilon]} \frac{1}{x}\phi(x) dx\\
&=\left\langle\operatorname{p.v.}\left(\frac{1}{x}\right), \phi\right\rangle
\end{align*}
Comment: You are forgetting that $f(a)=f(-a)=0$, by definition of "support".
Comment: Integrate by parts $\int_{\epsilon}^a \ln |x| \phi'(x)dx$ then do the same with $\int_{-a}^{-\epsilon} \ln |x| \phi'(x)dx$, both have a divergent term which cancel out in the sum (since $\phi'(x) = \phi'(0)+O(x)$)
Comment: Thank you for your comment. When integrating by parts I get to what is stated in the proof an additional term $ln|a|(\phi(a)-\phi(-a))$ but don't quite see what you mean by the divergent term there. Also I am not sure how in the Taylor expansion of $\phi'(x)$ we can just omit terms of order x or higher since for example $a$ is not necessarily $<<1$?
Comment: The factor $\ln |\epsilon|$ is divergent, but the term $(\ln |\epsilon|) ( \phi(\epsilon) - \phi(-\epsilon) )$ is not. That tends to zero:
$$(\ln |\epsilon|) ( \phi(\epsilon) - \phi(-\epsilon) )
= 2 (\epsilon \ln |\epsilon|) \frac{\phi(\epsilon) - \phi(-\epsilon)}{2\epsilon}
\to 2 \cdot 0 \cdot \phi'(0) = 0.$$
Comment: @md2perpe Yes, I agree that the expression in blue tends to zero. However, what I do not understand is where does the additional term $ln|a|(\phi(a)−\phi(−a))$ disappear to from integration by parts, since the limits of the integral are $[-a,-\epsilon]\cup[\epsilon,a]$?
Answer: We can split the integral into two parts, one on $[\epsilon, \infty)$ and one on $(-\infty, -\epsilon]$.
We rewrite both parts using integration by parts:
$$
\int_\epsilon^\infty \ln |x| \, \phi'(x) \, dx
= \left[ \ln |x| \, \phi(x) \right]_\epsilon^\infty
- \int_\epsilon^\infty \frac{1}{x} \, \phi(x) \, dx
= -\ln \epsilon \, \phi(\epsilon) - \int_\epsilon^\infty \frac{1}{x} \, \phi(x) \, dx
$$
and
$$
\int_{-\infty}^{-\epsilon} \ln |x| \, \phi'(x) \, dx
= \left[ \ln |x| \, \phi(x) \right]_{-\infty}^{-\epsilon}
- \int_{-\infty}^{-\epsilon} \frac{1}{x} \, \phi(x) \, dx
= \ln \epsilon \, \phi(-\epsilon) - \int_{-\infty}^{-\epsilon} \frac{1}{x} \, \phi(x) \, dx
$$
Thus,
$$
\int_{|x|>\epsilon} \ln |x| \, \phi'(x) \, dx
= \left( \ln \epsilon \, \phi(-\epsilon) - \ln \epsilon \, \phi(\epsilon) \right)
- \int_{|x|>\epsilon} \frac{1}{x} \, \phi(x) \, dx \\
= ( \ln \epsilon ) \left( \phi(-\epsilon) - \phi(\epsilon) \right)
- \int_{|x|>\epsilon} \frac{1}{x} \, \phi(x) \, dx.
$$
Comment: Thank you! This makes sense now, keeping $\infty$ on the limits instead of $a$ seems to make it easier to see the vanishing terms.


Problemas com a AsyncTask travar o aplicativo

Question: Eu estou desenvolvendo um chat online que deveria atualizar sozinho o tempo todo, o problema é que cada consulta trava o aplicativo por uns meio segundos. Eu já havia feito uma pergunta parecida em: Como fazer conexões a um php funcionar em background no Android mas não era exatamente o que eu queria.
Eu preciso que as páginas não travassem o app em cada consulta. Já ouvi falar sobre backgroundWoker e Service mas sinceramente não tenho a menor ideia do que eu posso estar fazendo de errado.
Estou utilizando MySQL+PHP+JSON.
Esse é meu código:
package com.Dannark.livechat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

class Connect extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("-- MYSQL --",result);
        //Do anything with response..
    }
}

EDIT: E estou interagindo a clase connect Com a classe Conectar dessa maneira:
package com.Dannark.livechat;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

public class Conectar {

    String response;
    int status;

    public Conectar(String website){
        //First - send request to server
        AsyncTask<String,String,String> task;
        String uri = website;       //  www.meusite.com/get_chat/?room=10

        try {
            task = new Connect().execute(uri);
            response = task.get();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

E finalmente a classe conectar desta maneira:
Conectar Conn = new Conectar("http://animesslife.engine001.com/chat/login.php?login=" + campoLogin.getText() + "&senha=" + campoSenha.getText() );
Log.i("-RESPOSTA-",Conn.response); //Conn.response seria a resposta no decodificada em JSON

Deveria eu usar outro método ao invés deste?
Comment: como é que você está interagindo com a classe "Connect"? Aparentemente não estou vendo nada de errado com a AsyncTask, exceto o de não está fechando os recursos apropriadamente em um bloco "finally".
Comment: Adicionei algumas informações...
Comment: Adicionei a resposta. Estou respondendo do meu smartphone, daí não dá pra colocar o código exemplo, mas espero que pegue a idéia.
Answer: A AsyncTask foi feita para você executar o código "pesado" no método doInBackground() e o código de UI (atualizar a tela) no método onPostExecute() o que você tá fazendo ao executar esse método get() é executar uma operação pesada de forma síncrona na MainThread, o que faz 'travar' pois a Main Thread fica ocupada com a operação.
O que você deve fazer é apenas chamar o método execute(), e dentro do onPostExecute() vc receberá o resultado da operação pesada como parâmetro (o retorno do método doInBackground() e poderá atualizar a tela dentro. Ou seja, no onPostExecute() vc irá fazer algo do tipo: textView.setText(dataResult)
Tem exemplo de uso aqui: http://developer.android.com/reference/android/os/AsyncTask.html
Comment: Ahh eu entendi cara, poxa foi bem legal sua explicação... Teria so como vc me mostrar um exemplo (quando vc tiver no seu pc) baseado no meu código para que eu possa ter certeza do que estou fazendo? :) Pra mim definir logo a resposta como aceita?
Comment: http://developer.android.com/reference/android/os/AsyncTask.html olha o código que tem nessa página.
Comment: Ei valeu mesmo cara... :)
Comment: E se fosse o caso de eu retornar um valor da onPostExecute(), nao gostaria de digitar o camando textView.setText(result) la dentro...
Comment: não dá pra fazer isso, pois o comportamento da AsyncTask, como o próprio nome diz é assincrono e o método onPostExecute() é o callback final...o que você pode fazer é repassar a chamada para um outro metodo...mas se você usar a AsyncTask não dá pra evitar o onPostExecute().


About digits sum and divisibility

Question: Let $D$ be the function define as $D(b,n)$ be the sum of the base-$b$ digits of $n$.
Example: $D(2,7)=3$ means $7=(111)_2\implies D(2,7)=1+1+1=3$
Define $S(a,m)=1^m+2^m+3^m+...+a^m$ where $a,m\in\mathbb{Z}_+$

Edit:-Update claim

For $m$ is every positive integer. How do you show that
If $a\nmid S(a-1,m)$
Then $D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m))=(a-1)(m+1)$?
And
If $a\mid S(a-1,m)$
Then $D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m))\ne(a-1)(m+1)$?

Source code
<code>n1= 2
o = 1
while n1 < 100:
    m = 2
    print("\n n1=",n1)
    #print("m=",m)

    num=n1
    sum_num = 0

    for i in range(1, num):
        sum_num += i**(m)
    n2 = (sum_num)

    if(n2%num == 0):
        print("div & sum=",n2)
    else:
        print("not div & sum=",n2)

    rem_array = []
    while n2 != 0:
        mod = n2%n1
        if mod != 0:
          rem = mod
          n2 = n2 - rem
          rem_array.append(round(rem))
          n2 = n2/n1
        else:
            n2 = n2/n1
            rem_array.append(0)

    print(rem_array[::-1],sum(rem_array))
#    print(sum(rem_array))

    n2=(sum_num)+n1**m
    rem1_array = []
    while n2 != 1:
        mod = n2%n1
        if mod != 0:
          rem1 = n1-mod
          n2 = n2 + rem1
          rem1_array.append(round(rem1))
          n2 = n2/n1
        else:
            n2 = n2/n1
            rem1_array.append(0)
#   print(rem_array)
    print(rem1_array[::-1],sum(rem1_array))
    if((n1-1)*(m+1) == sum(rem_array)+sum(rem1_array)):
        print("oooooooooook")
    print("(a-1)(m+1)=",(n1-1)*(m+1))

    n1 += o
</code>

Update claim helps to show below claim

For $m$ is even positive integer. How do you show that
If $(a-1)\mid S(a-1,m)$
Then $D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m))=(a-1)(m+1)$?

We can easily prove for every prime$-p>m+1$ is $p\mid S(p,m)$
Formula
$$ S(a,n)= \sum_{i=1}^{a} i^{n}=\sum_{b=1}^{n+1} \binom{a}b\sum_{j=0}^{b-1} (-1)^{j}(b-j)^{n}\binom{b-1}j$$
for formula
Proof
Let $a=p(prime)>n+1$
We can see, $a$ can be common out from $\sum_{b=1}^{n+1}\binom{a}b\sum_{j=0}^{b-1} ...$
$\implies a|S(a,n)$
Comment: Can you provide the definition of $D$?
Comment: See also: https://math.stackexchange.com/questions/328562/divisibility-criteria-for-7-11-13-17-19
Answer: Your equation $D(a,a^{m+1} - S(a,m)) + D(a,S(a-1,m)) = (a-1)(m+1)$ is not always true when $(a-1) \mid S(a-1,m)$.
For example, take $a=4$, $m=3$.  $S(3,3) = 1^3 + 2^3 + 3^3$ is divisible by $3$, but
$D(4,4^4 - S(4,3)) + D(4,S(3,3)) = 6+3=9$ while $(4-1)(3+1) = 12$.
Comment: I don't mean that, but I found no counterexamples where $m$ is even.
Comment: Thanks professor, Actually I am trying to understand the answer in this post, can you please comment whether this answer is right or wrong, https://mathoverflow.net/a/347766/149083
Comment: That MathOverflow post requires $a-1 \mid S(a-1,2m)$, not $S(a-1,m)$.
Comment: You mean, in the case of '$2m$', this is true. How can we prove it?
Comment: Professor, because my real problem is related to $m$ is even, so I am unable to accept your answer. And i fixed the given problem statement. Thanks again for your precious time to go through.
Answer: Proof for update claim:
Clearly for $a\gt1$, $a^m\lt (S(a,m))\lt a^{m+1}$ so $(S(a,m))_a$ have  $m+1$ digits in base-$a$
Thus, in base $a$,
$$S(a,m) = \sum_{i=0}^{m}b_i a^i, \; 0 \le b_i \le a - 1 \text{ for } 0 \le i \le m - 1, \text{ and } 1 \le b_m \le a - 1 \tag{1}\label{eq1A}$$
$$\begin{equation}\begin{aligned}
S(a,m) &=(b_m b_{m-1} ... b_1 b_0)_a \\
a^{m+1}-S(a, m) & = a^{m+1}-\sum_{i=0}^{m}b_ia^{i} \\
& = (10...00)_a-(b_m b_{m-1} ... b_1 b_0)_a \\
& = (b'_{m} b'_{m-1} ... b'_1 b'_0)_a
\end{aligned}\end{equation}$$
note-
•$D(a,S(a,m)) = 1 + D(a,S(a-1,m)) \tag{2}\label{eq2A}$
So $S(a-1,m)= (b^*_{m} b_{m-1} ... b_1 b_0)_a$ where digit $b^*_m=b_m-1$
proof for (2)
•if $a\mid S(a,m)$ then $b_0=b'_0=0$.$\tag{3}$
By $(1),(2)$ and $(3)$ follows
If $a\nmid S(a-1,m)$ then
$$\begin{equation}\begin{aligned}
& D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m)) \\
&=(b'_m+b'_{m-1}+...+b'_0)+(b^*_m+b_{m-1}+...+b_0) \\ &=(b'_m+b^*_m)+(b'_{m-1}+b_{m-1})+...+(b'_0+b_0) \\ &=(a-2)+(a-1)+(a-1)+...+(a-1)+(a) \\ &=(a-1)(m+1)
\end{aligned}\end{equation}$$
And if $a\mid S(a-1,m)$ then $b_0=b'_0=0$ implies $D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m))\ne (a-1)(m+1)$

Proof for second claim:
Because we now know, if $a\nmid S(a,m)$ then $D(a,a^{m+1}-S(a,m))+D(a,S(a-1,m))= (a-1)(m+1)$ so we only need to prove,"For m is even, if $a-1\mid S(a-1,m)$ then $a\nmid S(a,m)$" was I already asked here

About digits sum and divisibility


HostingEnvironment.ApplicationID equivalent for .NET 6

Question: I'm building a webservice using .NET 6 and I need an (almost) constant ID identifying my application.
I was thinking about using  HostingEnvironment.ApplicationID but it seems to not be available for .NET 6.
What is the equivalent of this property for .NET 6 ?
Comment: How constant? A single value that never changes? A value that can be configured per-installation...?
Comment: @JeremyLakeman : Either options. I need a value to identify this application. It must be constant between two execution in case of reboot, for example.
Comment: DataProtectionUtilityExtensions.GetApplicationUniqueIdentifier(IServiceProvider) is supposed to work, but when I tried it the full path to the web root was returned.
Answer: In .NET 6, the HostingEnvironment class has been replaced with the IHostEnvironment interface, and the ApplicationID property is no longer available. Instead, you can use the ApplicationName property of the IHostEnvironment interface to get an identifier for your application.
Here's an example of how you can retrieve the application name in a .NET 6 web service:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
// Inside your service or controller class

private readonly IWebHostEnvironment _hostEnvironment;

public YourServiceOrController(IWebHostEnvironment hostEnvironment)
{
    _hostEnvironment = hostEnvironment;
}

public void YourMethod()
{
    string applicationName = _hostEnvironment.ApplicationName;
    // Use the applicationName as needed
}

By using the ApplicationName property, you can retrieve an identifier that represents your application in a .NET 6 web service.


Hyper-V on Windows 7?

Question: I'm running the new Windows 7 RC x64.  I would like to set up a couple of virtual servers running on the same box as my desktop OS.  I know that I can do this with some of the other virtualization pacakges (Windows Virtual PC, VirtualBox, etc.) but there a couple features of Hyper-V that I would like to take advantage of.
Is it possible to install Hyper-V on Windows 7 x64?  If so, how?
Answer: I would say it isn't possible to use Hyper-V on Windows 7. You could put Server 2008 with Hyper-V as the host and use Windows 7 as a guest machine. Your best bet is to either use the new Windows Virtual PC or VirtualBox and the like.
Comment: @Wayne not correct - all currently supported Microsoft OS's are offically supported on Virtual PC, but other things like Linux are working too.

Virtual XP is a preconfigured XP VM, also runs a new version of terminal services (to allow application sharing) and has some special hooks into the Win7 OS to make it easier to start/stop them.

You are correct on specific processors - they need the virtualisation support. That is the same as Hyper-V currently.
Comment: Oh, c'mon, saying that approach uses Hyper-V on Windows 7 is like saying you can use VMware ESX on Windows 7 if you install 7 as a guest on ESX.  The *on* word is important.  The question asked if the user could install Hyper-V on Windows 7 x64, and that answer is no.
Comment: Correct, even the new Windows Virtual PC only supports 32-bit guests. I would recommend VirtualBox over VMWare but that's just personal opinion at that point. Good luck!
Comment: +1 as win7 has NO support for hyper-v. Only Virtual XP on specific processors.
Comment: Thanks for the answers.  There isn't Windows Virtual PC doesn't support 64 bit guests, right?  If not, looks like I'll have to go with VirtualBox or VMWare
Comment: On Windows 8 will be possible to run Hyper-V on the client OS
Answer: Windows 7 is a client OS and thus does not support the bare metal (level 1) Hyper Visor technology that Win2k8 server does.
However Windows 7 does have a new Virtual PC client - which is NOT the same as the old one (which used emulation), this basically uses a level 2 hyper visor. Mark Wilson covers it in detail in his blog post
So it is much faster than the old one, but not as fast as native Hyper-V. The trade off is that with this you get more hardware support (USB devices are fully supported) and some of nicer features like drag/drop support.
Finally an important note (since you already have VM) is that Hyper-V machines do not natively run on the new virtual PC due to HAL issues (I have yet to try uninstalling the Hyper-V components first, but I suspect it won't work because the HAL is a driver update). Old Virtual PC to new Virtual PC is fine.
Comment: @user65549 I dunno, Windows 8 has full Hyper-V support (provided you have a CPU with SLAT) and it is a client OS. I think it was purely a feature that didn't make the cut, because it wasn't important enough - not deliberately removed as a business move.
Comment: Hmm, ok, you may be right.
Comment: This is true, but it's worth pointing out that it's a result of Microsoft's business model to force people to use server products, not a technical restriction.
Answer: Hyper-V only available on Windows Server 2008 with Hyper-V or the freely available Hyper-V Server
You could install one of these as the base OS and then install Win7 into a Hyper-V VM
Answer: In fact, yes, it is somehow possible.
Windows 7 includes a "boot to VHD" feature. So, it is possible to install Windows Server 2008 R2 (64bits) inside a VHD that resides on the Windows 7 file system. This system will be available as dual-boot on system startup.
When booted on Windows Server 2008 R2, it is possible to enable the Hyper-V Server Role and everything works perfectly.
In order to set this up on your Windows 7 workstation:
a) Boot on the Windows Server 2008 R2 Installation Media
b) When the language selection dialog appears, hit Shift+F10
c) In the command prompt, run a series of command to create a virtual hard disk.
Something like:
http://technet.microsoft.com/en-us/library/dd744338(WS.10).aspx
diskpart
create vdisk file=c:\windows7.vhd maximum=25600 type=fixed
select vdisk file=c:\windows7.vhd
attach vdisk
Then, you can proceed with the installation.
Comment: This isn't running Hyper-V from Windows 7, you are still booting directly to Server 2008, Windows 7 would never be loaded.  My question is specific to running Hyper-V from within Windows 7.
Answer: Windows 7 has a new version of Virtual PC available currently in Beta. This is available here. There is also the new Virtual Windows XP Mode for Windows 7 available.
Answer: Has nobody considered creating a Virtual Windows Server 2008 R2 instance on a 2k8 box, and booting to that Hyper-V virtual hard drive using Windows 7 multi-boot?  Win2k8R2 and Win7 can both boot to a Hyper-V OR Virtual PC virtual hard drive so that the virtual host becomes the physical host.
As an added benefit, the virtual OS running as a physical OS (multi-booted to Win2k8 R2 virtual hard drive) should be able to utilize the virtualization hardware to run Hyper-V.  With the assistance of a 2k8 Hyper-V box, you won't even need a separate partition to do this.
I recommend researching "boot to a VHD with Windows 7."  As stated above, this solution would require another Windows Server 2008 box, or a Server 2008 multi-boot partition to create the VHD (I have a spare / clean external hard-drive for such drop-of-the-hat configurations).  This VHD, once created, should be movable to a Hyper-V server, and if multi-booted in Win7 should be able to utilize the virtualization hardware once the HAL is detected.
Someone smarter than me should chime in to validate this.
Answer: You'd need to run the server version of Windows 7, AKA Server 2008 R2 or whatever it ends up being called.
Answer: Might want to look at remote server administration tools for Windows 7 (KB958830)
Microsoft KB958830
Comment: Looks to be more geared at managing Hyper-V enabled Windows 2008 servers.  I'm looking to install Hyper-V on a Windows 7 system.

Hyper-V on Windows 7?


Creating a recommender system for shoe sizing

Question: (Sorry if I have mis-categorized or titled this question.)
Suppose you have shoe size data for a bunch of people across a variety of shoe brands. So, one person might have Nike = 11, Reebok = 10.5, Adidas = 11, Converse = 11.5, and so on. You might define a matrix $M_{ij}$ where $i$ represents the $i$-th individual and $j$ their size in the $j$-th brand.
Then suppose you have a person who knows their Nike size is, say, 9, and wants to know their most likely Adidas size (or maybe they know their size in multiple brands, but not Adidas). What is the best way to predict their Adidas size?
A simple method might be to look at the size difference of each person between Nike and Adidas ($M_{i,j=Nike} - M_{i,j=Adidas}$ for each $i$), and then to take the most common difference and add it to the person's Nike size to get their Adidas size. For example, if most people size up one half size when going from Nike to Adidas, the most likely Adidas size for this person would be 9.5.
But is there a more sophisticated method? For example, maybe there are people who are outliers and have really weird feet, and the relationship of their sizes among all brands does not fit well with most other people. Is there some natural way to weight the data of these people less than that of others, and would you want to do this?
I have a feeling that this is a common problem, for example anything online these days that makes a recommendation based on consumer data.
Comment: It might be a multi-pronged approach depending on the sparsity of the data. If you have "enough" specific matches of people who wear Nike size 9 and Adidas size x, then you might use the average of the specific matches. Then, if there aren't enough, you use a general sizing rule like +0.5.
Answer: Depends what assumptions you're willing to make about the sizing of shoes. For instance, I think it's safe to assume the difference between a size 9 to 10 Redwings Iron Ranger is similar to the difference between a 10 and 11 Adidas Samba. If a 9 IR wears a 10 Samba, then we'd know a 10IR would wear an 11 Samba.
It also depends on whether you have information on multiple shoes within individuals in which case you'd get more information with your repeated measures. Assuming you didn't, you can simple take the grand average of sizes within each shoe group and compare the average difference between groups under the assumption people don't own shoes that don't fit.
If you did have multiple measurements, you can get a more precise recommendation by fitting a mixed effects model which will average over the individual effects and estimate a categorical individual difference between sizes in each shoe.
$$ \mathbb{E}[ \mbox{Size} | \mbox{Brand}, \mbox{Individual}] = \beta_{0, i} + \beta_{1, b} * \mbox{Brand} $$
SPSS, R, SAS and statistical software can fit these, but not your plain vanilla Excel.
It's worth noting that shoes in general run both wide and long, so you might consider asking a more refined question about how to recommend someone buy a pair of shoes based on fits which are purported to run long/wide.


Is it safe to use $vars['name_raw'] instead of $vars['name']?

Question: I ran into an issue with usernames being trimmed in articles. I found a thread here with a fix suggesting to use $vars['name_raw']: https://www.drupal.org/node/854762#comment-7614255. It works.
But I'm wondering if $vars['name_raw'] should be sanitized with check_plain or not before being displayed to the screen. I'm not sure what the difference is between $vars['name'] and $vars['name_raw'] ? I searched and found no clear answer.
Answer: For this particular instance you should be fine because usernames already are filtered to a limited set of characters.
Like you assumed *_raw is unfiltered input. So in almost any other circumstance, it should be sanitized in some way before use.


Getting the multiplicative inverse of a polynomial

Question: I have a polynomial $m(x)=  x^2 + x + 2$ that's irreducible over $F=\mathbb{Z}/3\mathbb{Z}$. I need to calculate the multiplicative inverse of the polynomial $2x+1$ in $F/(m(x))$.
I'd normally use division with two polynomials like this, but it doesn't work here. So how can I get the inverse?
Comment: $\mathbb{Z}/3\mathbb{Z}$ is a finite field, so just use Euclid's algorithm to find polynomials $a(x), b(x)$ with $a(x)m(x) + b(x)(2x+1) \equiv 1\ldots$
Answer: Working in $(\mathbb{Z}/3\mathbb{Z})[[x]]/\langle x^2 + x + 1 \rangle$,
one (awful) way to do it is to notice that $2x + 1 = 1 - x$, so
$$(2x+1)^{-1} = \frac{1}{1-x} = 1 + x + x^2 + x^3 + \dotsb. $$
But $1 + x + x^2 = -1 = 2$
and, since $x^2 = -x - 2 = 1-x$,
$$x^3 + \dotsb = \frac{x^3}{1-x} = \frac{x^3}{x^2} = x,$$
giving $(2x+1)^{-1} = 2 + x$.
Answer: You can just let the unknown inverse be $ax+b$ and then multiply $(ax+b)(2x+1)=2ax^2+(a+2b)x+b.$ Equate this to $1$ in $Z_3[x]/(m)$ which means using $x^2=-x-2$ that the term $2ax^2$ becomes $2a(-x-2)=-2ax-4,$ which is then added to $(a+2b)x+b.$ Try from there.
I'm pretty sure this method should work, though in a comment, the user Unit already gave the result.
Comment: The inverse is actually $x+2$.


Boolean algorithm producing true output when output should be false

Question: Basically i am trying to create an algorithm that will test whether a given string is a cover string for a list of strings. A string is a cover string if it contains the characters for every string in the list in a way that maintains the left to right order of the listed strings. For example, for the two strings "cat" and "dog", "cadhpotg" would be a cover string, but "ctadhpog" would not be one.
I have created an algorithm however it is producing the output true when the output should be false, as the given string is a cover String for Strings list1 and list2, but not for list3.
Any help into why this algorithm is producing the wrong output would be highly appreciated.
public class StringProcessing2 {

//ArrayList created and 3 fields added.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "phillip";
public static String list2 = "micky";
public static String list3 = "fad";

//Algorithm to check whether given String is a cover string.
public static boolean isCover(String coverString){
    int matchedWords = 0;
    stringList.add(list1);
    stringList.add(list2);
    stringList.add(list3);

    //for-loops to iterate through each character of every word in stringList to test whether they appear in
    //coverString in left to right order.
    for(int i = 0; i < stringList.size(); i++){
    int countLetters = 1;
        for(int n = 0; n < (stringList.get(i).length())-1; n++){
            if(coverString.indexOf(stringList.get(i).charAt(n)) <= (coverString.indexOf((stringList.get(i).charAt(n+1)),
                    coverString.indexOf((stringList.get(i).charAt(n)))))){
                countLetters++;
                if(countLetters == stringList.get(i).length()){
                matchedWords++;
                }
            }
        }
    }
if(matchedWords == stringList.size()){
    return true;
}
else
    return false;
}

public static void main(String[] args) {
System.out.println(isCover("phillmickyp"));

}

}

Comment: You should debug it using IDE. It'll help you learn. I would also start with an easier example to understand what is wrong.
Comment: Think about the example `phillip`. This contains an `i` immediately before an `l` **and** an `l` immediately before an `i`. Think about why that makes things more tricky.
Comment: Might want to [test drive](https://en.wikipedia.org/wiki/Test-driven_development) this. Lot of scope for regression errors here.
Comment: If your code was indented properly it would more clearly show that it does not make any sense as written. It would not even compile.
Comment: @BobTheBuilder Thank you for the suggestion. I am fairly new to coding, and when i attempt to debug my project by selecting "debug project" under the debug tab on netbeans, it simply outputs true with no errors, am i correctly debugging my project to test for errors?
Comment: @Mickd94 You can add a breakpoint at a line (usually click next to the line number) and see when you stop there what is the value of all variables and see step-by-step what happens and why.
Answer: Probably the easiest way to go about this is to break down the problem into parts.  Have every function do the least possible work while still getting something done towards the overall goal.
To accomplish this, I'd recommend creating a helper method that takes two Strings and returns a boolean, checking if one String is the cover of another.
boolean isCover(String s, String cover)
{
  int i = 0;
  for(char c : s.toCharArray())
    if((i = cover.indexOf(c, i)) == -1)
      return false;
  return true;
}

Then once you have something that can correctly tell you if it's a valid cover String or not, it becomes much simpler to check if one String is a valid cover for multiple Strings
boolean isCover(List<String> strings, String cover)
{
  for(String s : strings)
    if(!isCover(s, cover))
      return false;
  return true;
}

Comment: Thank you very much for the response, i have never before seen the method of creating an advanced for loop or considered the concept of converting the string into a char array, which are both incredibly helpful tips.
Comment: I have never before seen an advanced for-loop, could you please explain to me the logic behind the first boolean, and how it ensures that the left to right order of the characters are maintained in the cover? It would be very helpful.
Comment: @Mickd94 The [for-each loop](https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html) iterates over collections, in this case an array.  The for-each loop shows each value in the array one by one, starting at 0, in this case each char in the String.  The int is to save the last position of a found letter, as each new letter must be beyond the last, otherwise the cover string would be out of order.


CopSSH SFTP -- limit users access to their home directory only

Question: Let me preface this by saying I've read and followed these instructions at the FAQ many times: http://www.itefix.no/i2/node/37
It does not do what the title claims...  It allows every user access to every other user's home directory, as well as access to all subfolders below the copssh installation path.
I'm only using this for SFTP access and I need my users to be sandboxed into only their home directory.
If you know a fool-proof way to lock users down so they can see only their home directory and its subfolders, stop reading now and reply with the solution.
The details:
Here is exactly what i tried as I followed the FAQ. My copSSH installation directory is: C:\Program Files\CopSSH
net localgroup sftp_users /ADD      **Create a user group to hold all my SFTP users

cacls c:\ /c /e /t /d sftp_users    **For that group, deny access at the top level and all levels below

cacls "C:\Program Files\CopSSH" /c /e /t /r sftp_users    **Allow my user group access to the copSSH installation directory and its subdirectories

For each sftp user, I create a new windows user account, then I:
net localgroup sftp_users sftp_user_1 /add    **Add my user to the group I've created

Open the activate user wizard for CopSSH, choosing the user, "/bin/sftponly" and

Remove copssh home directory if it exists   **Remains checked
Create keys for public key authentication     **Remains checked
Create link to user's real home directory   **Remains checked

This works, however, every user has access to every other user's home directory as well as the CopSSH root directory....
So I tried denying access for all users to the user home directory:
cacls "C:\Program Files\CopSSH\home" /c /e /t /d sftp_users    **Deny access for users to the user home directory
Then I tried adding permissions on a user-by-user basis for each users home\username folder.  However,these permission were not allowed by windows because of the above deny rule i created at the home directory was being inherited and over-riding my allow rule.
The next step for me would be to remove the deny rule at the home directory and for each user folder, add a deny rule for every user it doesn't belong to, and add an allow rule for the one user it does belong to.
However, as my user list gets long, this will become very cumbersome.
Thanks for the help!
Answer:
create group 'SSH Users' in computer management
Add group to gpedit -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignment -> Allow log on locally
(see Can't login to Cygwin sshd server with a non-administrator user account)
run gpupdate
Add ftpuser to group SSH Users
Append details in /etc/sshd_config:
Subsystem sftp internal-sftp

Match User ftpuser
    ChrootDirectory /home/ftpuser
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

(the keywords on the lines following the Match directive apply only to the user ftpuserand  override those set in the global section of the config file, until either another Match line or the end of the file.)
Activate ftpuser user through copSSH wizard
Delete all .ssh .bashprofile files/folders under ftpuser folder
Set SvcCOPSSH user to root id 0
SvcCOPSSH:unused_by_nt/2000/xp:**0**:545:U...

(see http://www.itefix.no/i2/node/11956)
Might need to do the following as well in copSSH 'UNIX BASH Shell'
cd /
chown SvcCOPSSH /
chmod 0755 /

restart openssh service


Grant Sharepoint Access to all employees

Question: What's the easiest way to grant access to all the employees of our company to sharepoint portal. There are some general sites which all employees have read access. So Do I have to create an AD group for all employees and add to the site or is there some better way to manage this?
Comment: as an update, you can now share with "Everyone except external users"
Answer: Permissions are set on the site level, so I don't think there is a good way to do this.  However, by default new sites created with unique permissions will use the " Visitors" group as the default read-only group on on the new site.
Assuming that the Vistors group does have read-only permissions on each site, then you can edit that group from the root portal site (Site Actions > Site Settings > People and Groups) and add "Domain Users" do the " Visitors" group.
If, for some reason, all domain members are not part of the "Domain Users" group, then you can add "authenticated users" instead.  I don't like using "authenticated users" because they could be authenticated to any trusted domain or a local authority.
Comment: I don't like using "Domain Users" because there are some Domain Users who shouldn't get access to the Sharepoint site.
Comment: I agree with that too, but if your requirement is "all employees" and only employees have domain accounts.  I guess in an ideal world, you would create a new group in AD called "SharePoint Users". :)


Jquery Drop Down Box issue

Question: I'm currently having an issue implementing a dropdown menu using Jquery using the .hover option.
The issue is that it sometimes disappears even when you are hovering over the element.
The JSFiddle is http://jsfiddle.net/liamsorsby/dN3Tr/
but if you wish to see the code here it is below:
html

OCCASION

test

test

test

JQuery
$(".occ").hover(
    function(){
        $(".occasions").css("display","inline");
    },
    function(){
        $(".occasions").css("display","none");
    });

CSS
.header_links{
float:left;
margin-left:12px;
}
.header_links ul{
padding:0px;
margin:0px;
}
.header_links li{
border:1px solid #C09356;
float:left;
list-style-type:none;
width:125px;
font-family:Arial;
position:relative;
color:#000000;
height:35px;
background-color:none;
}
.occasions{
display:none;
position:absolute;
margin-top:23px;
margin-left:-96px;
z-index:3000;
}
.occasions li{
border:1px solid #C09356;
height:25px;
width:110px;
background-color:#000000;
text-align:center;
}
.occasions p{
margin:3px 0 0 0;
padding:0px;
}

I have as an alternative tried using mouseover and the mouseleave but had the same issue. Can anyone suggest how to improve this code? Thank you in advance
Comment: It's probably because you're using `$(".occ").hover()` and there are multiple elements in there with the same class. Use `occasion_title` for hover instead which is unique.
Comment: @Krishna i have used the class multiple times to try and get the hover to stay active in IE8 which it currently is not the occasion_title hover does work but not very well on ie8
Comment: check if you have `` on top of you page..
Comment: i've got
Answer: you need to target occasion_title instead of occ to achieve your requirement.
just change this line:
$(".occ").hover

to this one:
$(".occasion_title").hover

a working Fiddle link:http://jsfiddle.net/dN3Tr/2/
Comment: works like a treat on firefox but not on IE8 any suggestions?
Comment: No, don't know why.
please consider to "mark as answer" if it really helped you solving your question. many thanks :)
Comment: i've marked the answer up but it's not completely resolved the issue
Comment: with all my respect, my answer has addressed your question perfectly, the issue of not working on IE8 is another thing, not that your question was asking how to get it to work probably, not asking about an error on IE :)
anyway, it's your decision, and I respect it.
Comment: the dropdown was to far down so it hid itself
Answer: If you're okay with ditching the jQuery, you could use just CSS to do this:
.occasion_title:hover .occasions {
    display: inline;
}

Comment: this also works fine other then with IE 8 any ideas as to why?
Comment: It seems to be working for me in IE8: [link](http://jsbin.com/EvakIdE/1/edit)  I copy/pasted your code into jsbin, since fiddle doesn't get along well with IE8.

Jquery Drop Down Box issue


Número de processadores no Hyper-V

Question: Tenho um servidor Windows Server 2003 virtualizado com Hyper-V.
Configurei a opção "números de processadores lógicos" para 4.
No Windows, ele aparece na lista de gerenciamento de dispositivos 4 CPUs. Porém no gerenciador de tarefas do Windows, no histórico de uso de CPU só aparece 1 gráfico.
As dúvidas são:

Está rodando com os 4 CPUs ou está rodando somente com 1 CPU?
Se estiver rodando somente com 1, como faço para rodar com os 4?

Observações:

Tenho outra máquina igual, e virtualizei com VMware e aparecem os 4 CPUs no gráfico.
Fisicamente, o hardware possui somente 1 socket, 1 processador com 4 núcleos e 4 threads.
Comment: Esta pergunta está a ser discutida no meta http://meta.pt.stackoverflow.com/questions/2640/perguntas-referente-a-programa%C3%A7%C3%A3o-de-servidores
Comment: @MaisonSakamoto no `Task Manager`, botão direito sobre o gráfico do *CPU*, escolha Alterar gráfico para e depois escolha Processadores Lógicos. Por defeito, o *WinSrv* apresenta o gráfico de utilização geral do *CPU* invés de apresentar um gráfico por *thread*.
Comment: li na central de ajuda http://pt.stackoverflow.com/help/on-topic que o foco é "programação" acho que a minha dúvida é sim enquadrada como "programação de servidores" o SO inglês abrange configurações de servidores tipo http://stackoverflow.com/questions/24862967/zabbix-jmx-tomcat-monitoring seria bom se tivéssemos um conteúdo desses em portugues, porque a area onde atua um profissional de programação geralmente atua um profissional  que gerencia os servidores dos programadores, e acredite, este profissional também tem dúvidas e também precisa de ajuda.
Comment: @Omni é S.O. Windows Server 2003, não achei essa opção de alterar o gráfico, clico com o botão direito e não me aparece nada.
Answer: Este caso resolvi reiniciando o servidor hyper-v, já tinha reiniciado a maquina virtual e não tinha resolvido, mas após reiniciar o servidor hyper-v apareceu certinho os 4 cpu

Número de processadores no Hyper-V


Análise Combinatória - Gerar n! arranjos

Question: Preciso de um algoritmo que gere todos os arranjos possíveis para n elementos em n posições, ou seja, n! é a quantidade de arranjos possíveis, como no exemplo abaixo:
n = 3
3! = 6 arranjos

123
132
213
231
312
321

Estou tentando criá-lo em JavaScript, mas não está dando certo.
function partida(){
    var nc = 4;
    var nl = fatorial(nc);

    var jogada = new Array(nl);
    for (i = 0; i < nl; i++){
        jogada[i] = new Array(nc);
    }

    for (c = 0; c < nc; c++){
        var q = fatorial(nc - c)/(nc - c);
        for (l = 0; l < nl; l++){
            jogada[l][c] = Math.trunc(l/q) + c;
        }
    }

    textarea = document.getElementById('arranjos');
    for (l = 0; l < nl; l++){
        textarea.innerHTML += (jogada[l].toString()).replace(/,/g, "");
        textarea.innerHTML += '\n';
    }
}

Answer: Minha resposta foi inspirada nesse post, caso quera maiores explicações.
Usei três funções para chegar na resposta.
function buld_char(valor){
    for (var i = 0; i < valor; i++) {
        lista.push(i+1);
    }
    permutacao_recursiva(lista,0);
}

Essa funão vai receber um valor, que no seu caso é n e vai montar um array com todos os valores de 1 até n. Ao final ele vai chamar a função permutacao_recursiva();
function permutacao_recursiva(str,k){
    var i, len;
    len = str.length;

    if (k == len)
        console.log(str);
    else {
        for (i = k; i < len; i++) {
            str = troca_char(str, k, i);
            permutacao_recursiva(str, k + 1);
            str = troca_char(str, i, k);
        }
    }
}

Sempre que necessário esse função chamará uma terceira, que vai trocar os caracteres do array
function troca_char(str, p1, p2) {
    aux = str[p1];
    str[p1] = str[p2]
    str[p2] = aux;
    return str;
}

Tendo essas três funções basta declarar uma variável global
var lista = [];

e chamar a função buld_char(3); passando o valor de n
Comment: Não creio que a global seja necessária. Pelo que percebi, ela poderia muito bem ser local de `build_char`


Implementation layout of object model

Question: Does the standard standardize the implementation detail of object? what i have heard that it is different on some compilers. Even if it is, Is it worth it to get 'inside the c++ object model' by lippman and how?
Answer: I cannot talk about the book, because I have not read it personally, but it is a common recommendation, so it will not hurt.
As of the standard, it does not mandate a particular object layout, but only places constraints on the behavior of the program, but understanding even one implementation will help you understanding what goes on under the covers. For most things different compilers take similar approaches.
As an example, the dynamic function dispatch mechanism is not defined by the standard, only the behavior, but all compilers implement it based on virtual function tables. The layout of the table (i.e. how the methods are organized there, what extra data might be before/after the table) might differ but the problem of dynamic dispatch is the same and the solutions are similar enough that understanding one will usually help you understand the overall problem.

Implementation layout of object model


Is there any way to get feeds from public facebook pages using spring social, restfb, etc

Question: I am trying to get feeds of public facebook pages in my java application. I am using graph api.
I keep getting an error. Error listed below.
I have generated the access token several times.
<code>FacebookClient facebookClient = new DefaultFacebookClient("my access token goes here", Version.VERSION_4_0);

User user = facebookClient.fetchObject("me", User.class);
Page page = facebookClient.fetchObject("cocacola", Page.class,
        Parameter.with("fields", "fan_count"));

out.println("User name: " + user.getName());
out.println("Page likes: " + page.getFanCount());
</code>

Exception in thread "main" com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#10) To use 'Page Public Content Access', your use of this endpoint must be reviewed and approved by Facebook
Answer: Like the error response says to read public page data your app needs to reviewed and approved for Page Public Content Access, you cannot access/read public page data w/o it. See https://developers.facebook.com/docs/apps/review/feature/#reference-PAGES_ACCESS


Using the Fourier series to calculate $\sum_{n\geq1}\frac{\text{sin}^{2}(2\pi an)}{n^2}$

Question: Let $-1/2<a<1/2$ I am asked to use the fourier series of the function $$f(x)=\begin{cases}1,\text{ if  } |x|\leq a \\
0,\text{ if  }a<|x|<1/2\end{cases}$$
to calculate $$\sum_{n\geq1}\frac{\text{sin}^{2}(2\pi an)}{n^2}$$
I have noticed that the function $f(x)$ is even. The fourier series of $f(x)$ is $$2a +2\sum_{n\geq 1}\frac{\text{sin}(2\pi an)}{\pi n}\text{cos}(2\pi nx)$$
Since $$\int_{-1/2}^{1/2}f(x)dx=2a,\text{ }\int_{-1/2}^{1/2}f(x)\text{cos}(2\pi nx)dx=\frac{\text{sin}(2\pi an)}{\pi n}$$
And I am stuck here, the fourier series does not seem to help since $f(x)$ is even, what am I doing wrong?
Comment: Maybe Parseval's theorem?
Answer: On the one hand $sin^2(2\pi na)=\frac{1-cos(4\pi na)}{2}$.
On the other hand $sin(2\pi na).cos(2\pi nx)=\frac{1}{2}(cos(2\pi n(a-x))-cos(2\pi n(a+x)))$ so taking $x=a$ yields $sin(2\pi na).cos(2\pi na)=\frac{1}{2}(1-cos(4\pi na))=sin^2(2\pi na)$.
These both come from trigonometric formulae. Once you are here only need to make a substitution in your series which is convergent to $f$ and use Dini since $f$ is not continuous at $x=a$ (you will state the series is equal to $\frac{1}{2}$ in stead of $1$) and a couple more calculations will land you on the desired result.
Comment: Looking further at your problem I can see that the denominator is $n^2$. This means that once you have calculated the series coming from $f$ it will be necessary to apply comparison by taking limits. You will be able to prove that your series is convergent but it won't be possible to find the value of convergence. At least not with this idea stated up here.... maybe you can try changing $n$ for $x$, show uniform convergence and then integrate on $f$ and inside the sum... an idea to get you going... hope this helps!


Setting up Multisite on windows server with IIS7

Question: First off I'm not a server person. New windows box spun up, IIS7 was used to install one instance of Drupal 7. Great :)
However I need to have multiple sites running. I've read several tutorials on getting this to work, tried several solutions, and continue to gets errors (from page not found to "this drupal site is already set up"). Does anyone know if there are step by step instructions somewhere on exactly how to set up multisite on a windows box with IIS7?
The "base" drupal install is /inetpub/wwwroot/Drupal/DrupalTest/
Having very little knowledge of Windows servers is probably part of the issue. I really need basic step by step instructions and I have yet to locate any that assume you know essentially zero about windows. I've been taking notes so I can write some out if I eventually figure it out :)
One example I've followed: http://drupal.org/node/554336 : Yielded the "site already setup" when I tried to access the install.php from the second site.

I'm at the point where multisite would be nice, but if I need to use multiple instances of Drupal that's fine, I just need to be able to move forward with the content and be finished messing with the dang server, but I have no idea how to accomplish that as well.
Answer: After much digging, found out the combo of msSQL and PHP 5.3 caused the site to break. Reinstalled with PHP 5.4 and mySQL and it's running swimmingly!
Answer: If any one still using IIS server to configure the multisite on drupal its pretty simple.
First thing is make sure of two important files that need to be modified.
sites.php
settings.php
you don't need the local files (settings.local.php and sites.local.php) for multi site setup.
Configuring the above two files would be enough to setup the multi site on IIS.
https://www.drupal.org/docs/7/multisite-drupal/multi-site-on-windows-using-iis
Answer: Hi you can read more on how to install multisite in drupal 7 with below links.
http://mydons.com/drupal-7-multisite-install-steps-in-windows/
Comment: Welcome to Drupal Answers! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: Plus this is with Apache


Simultaneous verbal arithmetic

Question:
A B C D + A E F = E F G H and
I C J * E = A B C D

Each letter represents a unique digit from 0 to 9 and both equations must hold true.
Having some trouble solving this, here is what I have so far:
B + A = 10 or B + A > 10 since something must be carried over to the thousands column (A) in equation 1
I also know that A + 1 = E since the 1 is carried over
17 >= B + A >= 10
A cannot equal 0,9
Any idea how to solve this?
Any contributions are greatly appreciated.
Comment: You also know that $E = A + 1$, because the carried digit must have been a $1$.
Comment: @Omnomnomnom Yeah sorry, forgot to add that to my question. Thanks
Answer: A quick computer search finds the unique answer:
$A, B, \dots, J = 6, 5, 3, 8, 7, 2, 1, 0, 9, 4$.
Hence there is not much to explain. Without any context, I cannot tell whether it is intended to solve it by computer or without computer.
Comment: without a computer preferably
Comment: No idea for the moment. Sometimes these puzzles are even generated with the help of computers in the first place, so I'm not really willing to spend time thinking about a no-computer solution...
Comment: I wrote a program to go through all possibilities of $I, C, J, E$. This then determines $A, B, C, D$. I then go through remaining possibilities of $F$, which determines $G$ and $H$.
Comment: It was in C, and I already deleted it... It's not that tricky and you may write it yourself, with Python or any of your preferred programming languages.
Answer: Well, it's doable by hand. At least, I did it (with a couple of sheets of paper...)
We know that A + 1 = E. Look now at xCJ * E = xxCD and search for all the possible combinations for (A) CJED: they are
A C J E D
1 9 7 2 4
1 9 8 2 6
2 4 7 3 1
2 4 9 3 7
2 9 7 3 1
2 9 8 3 4
3 6 7 4 8
3 9 8 4 2
5 3 9 6 4
5 7 9 6 4
6 3 4 7 8
6 8 3 7 1

Moreover, from the multiplication we have a range of the possible values of I:
A E  I
1 2 5-9
2 3 6-9
3 4 7-9
5 6 8-9
6 7 8-9

Putting all together and completing the multiplication, we have
A C J E D I B
1 9 7 2 4 6 3
1 9 8 2 6 7 5
2 4 7 3 1 8 5
2 4 7 3 1 9 8
2 4 9 3 7 8 5
2 9 7 3 1 6 0
2 9 7 3 1 8 6
2 9 8 3 4 6 0
3 9 8 4 2 7 1
5 3 9 6 4 8 0
5 7 9 6 4 8 2
6 3 4 7 8 9 5

From here, considering D + F = (1)H we remain with
A B C D E F G H I J
1 5 9 6 2 4   0 7 8
2 0 9 1 3 4   5 6 7
2 6 9 1 3 4   5 8 7
2 0 9 4 3 1   5 6 8
6 5 3 8 7 2   0 9 4

and only the last line (with G = 1) satisfies the sum.
Answer: Putting this up. If anyone has partial insights, feel free to add to this post instead of commenting (since writing as is text is difficult in the comments).
So far, we have
  A    B  C    D
+      A (A+1) F
--------------
 (A+1) F  G    H

   I  C  J
x       (A+1)
-----------
A  B  C  D

Simultaneous verbal arithmetic


Fractions and invitations

Question: Diane sent out 25 invitations to her birthday party.  If 1/6 of the invitations were for her family, about how many invitations were for her family?  Please show your work and explain.
Answer: Translate to math.
The key to answering "word problems" of this sort is being able to translate the given information into mathematical operations involving the data provided. Key words here are "of" and "about".
"About one-sixth of the (25) invitations sent were for her family."
$\iff \text{About}\;\dfrac 16 \underbrace{\times}_{\text{OF}} 25\,$ of the invitations were for her family.
$\iff \dfrac 16\times 25\, =\, 4.1\overline{66} \underbrace{\approx}_{\text{about}} 4$ invitations were for her family.
Answer: Your data says that $25 \cdot \frac 16 = 4\frac 16$ were for her family.  What it means to get $\frac 16$ invitation, I don't know.
Comment: These answers didn't deserve downvotes, certainly not downvotes with no explanation. Anyway, here's my two-cent's worth: +1
Comment: Notice the "about" in the phrasing of the question.  It's really poorly stated, and I fear that it's coming verbatim from an actual textbook .. sad.
Comment: @Doc:  the about should be on the $\frac 16$, rather than on the $4$.  Clearly we were expected to round it off, but I agree it is badly written.

Fractions and invitations


Understanding empty set, set with empty set and set with set of empty set.

Question: I am having trouble understanding the difference between these sets.
$\emptyset,\{\emptyset\},\{\{\emptyset\}\},...$
I think they're supposed to be different to eachother, but I read that the empty set is a subset of every set including itself.
So every set in $\emptyset$ is in $\{\emptyset\}$ and every set in $\{\emptyset\}$ is in $\emptyset$. So they're subsets of each other and therefore the same set.
So $\emptyset,\{\emptyset\},\{\{\emptyset\}\},...$ are all the same. Is this right?
Comment: No. $\emptyset$ has no element, while $\{\emptyset\}$ has one element.
Comment: Sometimes it helps to think of the empty set as $\{\}$, so $\{\} \in \{\{\}\}$.
Comment: "So every set in ∅ is in {∅} and every set in {∅} is in ∅." NO; there are **no** sets in $\emptyset$ while there is exactly **one** set in $\{ \emptyset \}$. Thus, the two are **not** the same.
Answer: It might also help to think of the sets as being boxes, which might contain any number of objects (including infinite).  For instance, the set $S = \{\text{apple}, \text{ball}, \text{corkscrew}\}$ might be represented by an actual box containing an apple, a ball, and a corkscrew.
In this analogy, the empty set $A = \varnothing$ is just an empty box.  Being the empty set, it is a subset of any other set.  That would mean that every item in the empty box is also in every other box.  That is manifestly true: There are no items in the empty box that aren't also in every other box.
Note that the empty set is not an element of every other set.  For example, the box representing the set $S$ contains three ordinary objects, but does not contain an empty box.
However, something that would contain an empty box would be $B = \{\varnothing\}$, which would be represented by a box that contains only an empty box (which would represent $A$).  And $C = \{\{\varnothing\}\}$ would be—you guessed it—a box, which contains only a box, which in turn contains only an empty box.
Observe that these various boxes are evidently not the same: Something that contains only an empty box is not the same thing as an empty box.
(Please don't ask me about $\{\text{box}\}$.)
Answer: It is true that every element of the empty set $\varnothing$ is an element of $\{\varnothing\}$ (since the empty set $\varnothing $ has no elements) but it is not true that every element of $\{\varnothing\}$ is an element of $\varnothing$. Indeed, $\varnothing\in \{\varnothing\}$ but $\varnothing\notin \varnothing$. So $\varnothing \subset \{\varnothing\}$ but $\{\varnothing\}$ is not a subset of $\varnothing$.
Answer: $\phi$ simply means the set is empty, i.e has no elements. Eg. A= $\phi$ implies A is an empty set.
On the other hand, {$\phi$} means a set S= {$\phi$} has the element $\phi$ $\Rightarrow$ $\phi \in$ {$\phi$}
Similarly, $\phi \in$ {$\phi$} $\in$ {{$\phi$}}


How do I increase the character limit for the default "Fixed value" of a contextual filter?

Question: I'm trying to make a view of my new products using the Content: Nid contextual filter.
In this filter I opted to provide a default value, with a type of "Fixed value". On the "Fixed value" field, only 27 values are added, after which no more are accepted.
Apart from the character limit for the text field, is there another reason  I can't add more values here? If not, how do I increase the character limit so I can add all the values I wish to?
Comment: Hi alok, I rewrote the question in an attempt to make it a bit clearer and hopefully more useful to future visitors. In that spirit I've taken a bit of a leap, and assumed that you realise that the physical reason you can't add any more values is because of a character limit set on the HTML input element. I've also assumed that what you're really interested in is removing that limit if it's safe to do so. I hope that still captures the original intent of your question, but please let me know if it doesn't and we'll sort it out. Thanks
Answer: Why don't you write a small code snippet and pass contextual filters using hook_views_pre_view(), that allows altering a view at the very beginning of processing a preview.
<code>function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'YOUR_VIEW_MACHINE_NAME' && $display_id == 'page_1') {
    $nids= get_nids(); //write a custom function to get nids.
    $args[] = implode('+', $nids);
  }
}
</code>


Filter Segments Only From HL7 Messages Using HL7APY

Question: I want to grab the OBX segments, and then field # 3, the observation identifier.
My code currently iterates everything, trying to find a solution to output just OBX.field3, for a dataset with multiple hl7 messages.
hl7 = open(r"file.txt", "r").read()

try:
msg = parser.parse_message(hl7.replace('\n', '\r'), find_groups=True, validation_level=2)
except UnsupportedVersion:
msg = parser.parse_message(hl7.replace('\n', '\r'), find_groups=True, validation_level=2)

indent = "    "
indent_seg = "    "
indent_fld = "        "

def subgroup (group, indent):
indent = indent + "    "
print (indent , group)
for group_segment in group.children:
if isinstance(group_segment, Group):
subgroup (group_segment)
else:
print(indent_seg, indent ,group_segment)
for attribute in group_segment.children:
print(indent_fld, indent ,attribute, attribute.value)

def showmsg (msg):
print(msg.children[1])
for segment in msg.children:
if isinstance(segment, Segment):
print (indent ,segment)
for attribute in segment.children:
print(indent_fld, indent, attribute, attribute.value)
if isinstance(segment, Group):
for group in segment.children:
print (indent,group)
for group_segment in group.children:
if isinstance (group_segment, Group):
subgroup (group_segment, indent)
else:
print(indent_seg, indent ,group_segment)
for attribute in group_segment.children:
print(indent_fld, indent, attribute, attribute.value)

showmsg (msg)`enter code here

Answer: If you change find_groups=True to find_groups=False in parser.parse_messsage(.. you need only this showmsg
def showmsg (msg):
    for segment in msg.children:
        if segment.name == 'OBX':
            print (indent ,segment)
            for attribute in segment.children:
                if attribute.name == 'OBX_3':
                    print(indent_fld, indent, attribute, attribute.value)


Find all k-tuples of (strictly) monotonically increasing numbers

Question: Topic might be missleading so here's what I want to achieve in Oactave/Matlab (result preferably row-wise in a matrix):
Let $\lambda=(\lambda_1,\ldots,\lambda_k)\in\mathbb{N}^k_{\geq0}$. So I want all the tuples fullfilling: $0\leq\lambda_1\leq\lambda_2\leq\ldots\leq\lambda_k\leq n$ for a given $n\in\mathbb{N}$. I also would like to able to teawk the alogrithm to exchange the $\leq$ for a $<$.
So for $k=2$, $n=3$ it should give something like that:
0 0
0 1
0 2
0 3
1 1
1 2
1 3
2 2
2 3
3 3

Comment: Are the $k$-tuples meant to be ordered so that $\lambda_1 \leq \lambda_2 \leq \cdots \leq \lambda_k$? You mention this in your title but not in your problem description.
Comment: @K.Miller Yes! Now corrected.
Comment: And you show 3 tuples for k = 2
Comment: @Pieter21 Right! Corrected.
Answer: The following Octave code should work in the $\leq$ case. It can be modified to work in the $<$ case as well. The amount of work to compute all tuples in the $\leq$ case is proportional to $k {n + k\choose k}$.
n = 3;
k = 5;
curr = zeros(k, 1);
A = zeros(nchoosek(n + k, k), k);
for r = 1:size(A, 1)
    A(r,:) = curr;
    ++curr(k);
    j = k;
    while (j > 1 && curr(j) > n)
        curr(j) = 0;
        ++curr(--j);
    end
    for i = 2:k
        if (curr(i - 1) > curr(i))
            curr(i) = curr(i - 1);
        end
    end
end

Comment: I just realized that you can do the strict case in Octave using the built-in command: nchoosek(0:n, k). Moreover, using this function will be much much faster then the code I gave you.


Swift type casting and parenthesis

Question: Both of this type casting works
Edit
(as written by Nate Cook this is not a real Type Casting, in Swift type casting is done with the as keyword. With the following call I'm initializing an Int64 with a Float parameter.)
anInt = Int64(aFloat)

anInt = (Int64)(aFloat)

First
    var anInt : Int64 = 0
    var aFloat : Float = 11.5

    anInt = Int64(aFloat)
    println(anInt) // this prints 11

Second
    var anInt : Int64 = 0
    var aFloat : Float = 11.5

    anInt = (Int64)(aFloat)
    println(anInt) // this prints 11

In the second example the main difference is that there are parenthesis around the type Int64, but I don't find any information about this syntax in the docs.
The statement Int64(aFloat) is a typical initializer call that creates an Int64 passing a Float as the initialization parameters. Is this correct?
What is the meaning of the parenthesis in (Int64)(aFloat)? Is for better readability or there is another meaning?
Thanks
Comment: Not that you aren't *casting* `aFloat`, you're calling the initializer for `Int64` with a float value. Casting in Swift is done using the `as` keyword, and would fail in this case. (Your "The statement..." summary is correct, but the title and other details point in the wrong direction.)
Comment: Yes @NateCook , you are correct, it is not a type casting, as I wrote "The statement Int64(aFloat) is a typical initializer call that creates an Int64 passing a Float as the initialization parameters. Is this correct?". My first statement (at the beginning of the question) is incorrect. I'll correct it. Thanks
Comment: possible duplicate of [Swift Types inside Parentheses](http://stackoverflow.com/questions/24422108/swift-types-inside-parentheses)
Comment: I've read, but this seems a more specific case. The answer and example of Thomas Kilian seems a good explanation
Answer: It looks like you can add an arbitrary number of parentheses (e.g. (((Int64)))). The main reason for the parentheses is to make a cast like (object as SomeClass).method()
Answer: See the duplicate question, but the short answer is that (Int) declares a tuple containing a single Int, which is semantically identical, per language specification, to a single Int Int.

Swift type casting and parenthesis