Hook menu item not Showing

Question: I have two hook menu items:
function myid_print_menu()
{
    $items = array();
    $items['user/%user/myid_print_settings'] = array(
        'title' => 'ID Print Settings',
        'description' => 'Configuration options for the myid_print module',
        'page callback' => 'myid_print_admin_settings',
        'page arguments' => array(1),
        'access callback ' => 'myid_print_user_access',
        'type' => MENU_LOCAL_TASK,
        'weight' => -9,
    );

    $items['user/%user/myid_print'] = array(
        'title' => 'Print an ID',
        'page callback' => 'myid_print_user_page',
        'page arguments' => array(1),
        'access callback' => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_LOCAL_TASK,
        'weight' => -10,
    );
    return $items;
}

function myid_print_admin_settings()
{
     return drupal_get_form('myid_print_settings_form');
}

function myid_print_settings_form()
{
     $form = array();
     $form['summary'] = array(
         '#type' => 'fieldset',
         '#title' => t('ID Summary'),
         '#description' => t('Summary of ID printed, submitted and reset on a specific range of time')
     );
     return $form;
}

The 'ID Print Settings' was not showing, but Print an ID was showing. I tried clearing my cache, it was still not visible. Why?
Comment: Make sure that Drupal is able to flush the cache without any problem by checking if there is any errors at admin/reports/dblog
Comment: include the code for `myid_print_admin_settings($arg)`?
Answer: I have a feeling with the access callback. Either your function is wrong (which you haven't posted) or something is up with your permission setting for this module.
Try temporarily updating your access callback to true to verify that it is causing the issue:
'access callback' => TRUE,

and clear your cache.
I think you may be better off creating a permission using hook_permission and using access arguments instead of access callback.
/**
 * Implement hook_permission()
 */
function myid_print_permission(){
  return array(
    'administer myid_print' => array(
      'title' => 'Administer myid_print'
    ),
  );
}

/**
 * Implements hook_menu().
 */
function myid_print_menu() {
  $items = array();
  $items['user/%user/myid_print_settings'] = array(
      'title' => 'ID Print Settings',
      'description' => 'Configuration options for the myid_print module',
      'page callback' => 'myid_print_admin_settings',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -9,
  );

  $items['user/%user/myid_print'] = array(
      'title' => 'Print an ID',
      'page callback' => 'myid_print_user_page',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'file' => 'myid_print.pages.inc',
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
  );
  return $items;
}

Answer: Try putting the call to drupal_get_form directly in your menu hook like this:
$items['user/%user/myid_print_settings'] = array(
    'title' => 'ID Print Settings',
    'description' => 'Configuration options for the myid_print module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myid_print_settings_form', args[1]),
    'access callback ' => 'myid_print_user_access',
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
);

Note the args[1] in the arguments which will pass the %user argument from the path to the form.

Hook menu item not Showing


Convenção para atributos que preservam tipos

Question: Uma tabela armazena dados de professores. Cada professor possui uma titulação: especialista, mestre, doutor, pós-doutor e outros.
Outra tabela presente na base é a de publicações. Cada publicação pode (ou não) possuir um determinado tipo: livro, periódico, evento, tcc e outros.
É certo que em cada tabela haverá uma coluna (atributo) para manter o tipo do determinado registro.
Abaixo, duas sugestões para o valor desses atributos:

abreviações (strings)
professor.tipo = 'mes' || professor.tipo = 'dr' || professor.tipo = 'esp'
publicacao.tipo = 'liv' || publicacao.tipo = 'tcc' || publicacao.tipo = 'evt'
inteiros
professor.tipo = 1 || professor.tipo = 2 || professor.tipo = 3
publicacao.tipo = 1 || publicacao.tipo = 2 || publicacao.tipo = 3

Minha questão é: existe alguma convenção para esses atributos ou a decisão é de responsabilidade do(s) desenvolvedor(es) do projeto?
Answer:
Existe as regras normais para normalização de banco de dados:

Primeira Forma Normal (ou 1FN) requer que todos os valores de colunas em uma tabela sejam atômicos (exemplo: um número é um átomo, enquanto uma lista ou um conjunto não o são). A normalização para a primeira forma normal elimina grupos repetidos, pondo-os cada um em uma tabela separada, conectando-os com uma chave primária ou estrangeira;
Segunda Forma Normal (ou 2FN) requer que não haja dependência funcional não-trivial de um atributo que não seja a chave, em parte da chave candidata;
Terceira Forma Normal (ou 3FN) requer não haver dependências funcionais não-triviais de atributos que não sejam chave, em qualquer coisa exceto um superconjunto de uma chave candidata;
Forma Normal de Boyce-Codd (ou BCNF) requer que não exista nenhuma dependência funcional não-trivial de atributos em algo mais do que um superconjunto de uma chave candidata. Neste estágio, todos os atributos são dependentes de uma chave, de uma chave inteira e de nada mais que uma chave (excluindo dependências triviais, como A → A);
Quarta Forma Normal (ou 4FN) requer que não exista nenhuma dependência multi-valorada não-trivial de conjuntos de atributo em algo mais de que um superconjunto de uma chave candidata;
Quinta Forma Normal (ou 5FN ou PJ/NF) requer que não exista dependências de joins (associações) não triviais que não venham de restrições chave;
Domain-Key Normal Form (ou DK/NF) requer que todas as restrições sigam os domínios e restrições chave.

Respondendo ao seu problema especifico:

<code>CREATE TABLE titulo (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(255) NOT NULL
);

CREATE TABLE professor (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(255) NOT NULL,
    titulo_id INT,
    FOREIGN KEY titulo_key (titulo_id) REFERENCES titulo(id)
);
</code>
Fonte para regras normais: Link


Find the general solution of the PDE $ 2u_x-3u_y = x$

Question: Find the general solution of the PDE
$2u_x-3u_y=x$ , where $u=u(x,y)$ .
We have to use the method of characteristics. I know that the slope is $-\dfrac{3}{2}$ and the characteristic lines are $-3x-2y=\text{constant}$ .
After doing a change of variables $w=-3x-2y$ and $z=y$ , the PDE becomes $-3V_z=\dfrac{w+2z}{-3}$ .
I am not sure on how to go on after this
Answer: Assume that $u(x,y)=\frac14x^2+g(3x+2y,2x-3y)$ for some function $g:(s,t)\mapsto g(s,t)$, then $u_x=\frac12x+3g_s+2g_t$ and $u_y=2g_s-3g_t$ hence $u:(x,y)\mapsto u(x,y)$ solves the PDE iff $2(\frac12x+3g_s+2g_t)-3(2g_s-3g_t)=x$, that is, $g_t=0$.
Thus, the function $u:(x,y)\mapsto u(x,y)$ solves the PDE iff $u(x,y)=\frac14x^2+g(3x+2y)$ for some function $g$.
Answer: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=2$ , letting $x(0)=0$ , we have $x=2t$
$\dfrac{dy}{dt}=-3$ , letting $y(0)=y_0$ , we have $y=-3t+y_0=-\dfrac{3x}{2}+y_0$
$\dfrac{du}{dt}=x=2t$ , letting $u(0)=f(y_0)$ , we have $u(x,y)=t^2+f(y_0)=\dfrac{x^2}{4}+f\left(\dfrac{3x}{2}+y\right)$


Locked myself out of root access

Question: I'm very new to owning a dedicated server. I'm learning and was configuring one I bought with OVH. I was configuring what I thought was other SHH users.
It was a sshd_config. I appended this to the very bottom of the file:
<code>Port 24
PermitRootLogin no
AllowUsers zax
</code>
After that I logged off putty and WinSCP and attempted to log back into the servver. It was giving me denied access.
I know OVH is a budget provider, and I attempted to ask them support and they replied as the only option is to  re-install the OS.
I'm totally fine with, because I didn't do much with the OS but I'd rather still want to make sure if theres any other option to get back into the OS. So my question is: Is there any other way to get back into the OS?
If it is the only option, what do I input into the following options to re-install an OS?
https://i.stack.imgur.com/tgOlw.png
It's a 64-bit Ubuntu Server.
Comment: Did you restart sshd? If not, ssh is going to accept connections on your previous port.
Comment: If you restarted `sshd`, did you tell WinSCP/Putty to use port 24 in the first place?
Comment: Is port 24 blocked in a firewall?
Comment: Yes, I restarted sshd. And I tried port 22-24
Answer: OVH offers a Serial-over-LAN option you can use to login to your dedicated server as if you had a keyboard and monitor directly connected to it. Since this login does not go through SSH, you won't be constrained by the options you set.
OVH Serial-over-LAN Product Description

Locked myself out of root access


Syntax highlighting code with Javascript

Question: What Javascript libraries can you recommend for syntax highlighting  blocks in HTML?
(One suggestion per answer please).
Comment: http://shjs.sourceforge.net/
Answer: StackOverflow uses the Prettify library.
Comment: You can give the language to Prettify if you know it, it will improve the performance. This is just not used in StackOverflow due to the large language audience.
Comment: I second this. Google Code uses it for their own repo highlighting (since they wrote it) and automatically detects the language.
Comment: Surely using one which "automatically" detects the language simply puts more weight on the client's machine/browser...
Comment: Just added this to my web site, and it's great and so simple to use!
Comment: @Vincent: it improves more than just performance ;-)
Comment: @SamB: feel free to edit the answer to add more information. If you don't have enough reputation, you can add a comment and someone will add it to the answer
Comment: by any chance this works on Drupal 7 ? i will try this later tonight and let you all know, but prior to that if anyone knows any potholes do let me know
Comment: For me works just fine. Really easy to implement into the HTML and the result is astonishing. Thanks for the suggestion :)
Comment: Is it possible to comment code like Git-hub does?
Comment: This is now archived.
Answer: I recently developed one called rainbow.
The main design goal was to make the core library really small and make it really easy for developers to extend.
See http://rainbowco.de.
Comment: This needs to go up to the top, Craig. I tried all of the other solutions and only Rainbow handled Python correctly and had *readable* theme stylesheets. Amazing plugin!
Comment: I just ran across Rainbow today — it looks to me like it can discriminate more finely than Prettify (like for instance, being able to tell when `rdf:type` is used as an element and when it's an attribute).
Answer: SyntaxHighlighter is available as a GitHub project.
Answer: What about Prism by Lea Verou.
From her blog post announcement in June (2012):

It's tiny. The core is only 1.5KB minified & gzipped.
It's incredibly extensible. Not only it's easy to add new languages (that's a given with every syntax highlighter these days), but also to
  extend existing ones.
It supports parallelism through Web Workers, for better performance in certain cases.
It doesn't force you to use any Prism-specific markup, not even a Prism-specific class name, only standard markup you should be using
  anyway. So, you can just try it for a while, remove it if you don't
  like it and leave no traces behind.
Comment: This ended up being the best option of all the answers for me because of the ease of adding new language definitions.
Answer: jQuery Syntax Highlighter is a new one based on Google's Prettify - a really really really popular plain javascript syntax highlighter.
It supports such things as code and pre blocks, able to use classnames like language-javascript to indicate we want it to highlight, as well as wordwrap. You can copy and paste code by selecting it normally instead of having to open a raw view like many others. It can be further customised by using the HTML5 data attribute data-sh or via specifying options at initialisation. A great stable choice which is updated regularly.
Comment: The author actually says it's based on Google's Prettify, not SyntaxHighlighter. Looks just like SyntaxHighlighter 3, though, but seems to require a lot less work to set up. Thanks for the link!
Answer: How about:
syntaxhighlighter
highlight.js
JSHighlighter
Comment: A simply Google search would also give me that list--but which one you prefer and why?
Answer: If you're using jQuery there's Chilli:
http://code.google.com/p/jquery-chili-js/
All you have to do is include the jquery-chili.js and recipes.js, and do the highlight with
$("code").chili();

It should figure out the language by itself.
Comment: The links to examples on that page all lead to an expired domain full of ads so it's a little bit difficult to get an idea of what this highlighter looks like.
Answer: I'm very happy with SHJS. It supports a bevy of languages and seems pretty fast and accurate.
Here's an example where I use it on my blog. I'm using my own custom CSS file that simulates Coda's syntax highlighting. Email me if you'd like to use it.
Answer: jQuery.Syntax is an extremely fast and lightweight syntax highlighter. It has dynamic loading of syntax source files and integrates cleanly using CSS or modelines.
It was developed specifically to fill a gap - that is: a fast, clean, client-side syntax parser.
Comment: unfortunately it thought a standard FpML message to be SPAM :)
Comment: @ehosca, are you able to give me some clarification on problem you are having?
Comment: when i paste the xml in http://goo.gl/PPcDx to http://goo.gl/qSqm9 it says Invalid content, appears to be spam. hope this helps.
Comment: You need to include some line breaks in the text, otherwise it looks like link spam. I can't remember the exact formulae I used, but I think if you have more than one URL per line the text is considered spam - this is because heaps of bots were spamming the system (http://www.syntax-highlighing.com).
Answer: I'm not being argumentative but just thought it worth mentioning that if you're using a CMS or blog platform then using a backend highlighter is better for obvious reasons — Have a look at Geshi(http://qbnz.com/highlighter/) if you're interested. Actually you could set up your server to parse HTML content through a backend technology — so there is no need for the JS highlighters at all. (The only functionality they add is the ability to print/copy[using swf].)
Comment: It's not obvious to me. Why is using a backend highlighter better?
Comment: Yeah, I, too, would *really* love to know what is "obvious" about preferring to send a larger response to the client...
Comment: I prefer the syntax highlighting to still be present on devices that don't have JS enabled. Additionally, client-side highlighters have runtime costs that can be quite hefty if you've got lots of code to highlight. That said, it depends on your specific use-case :)
Comment: What devices don't have JS enabled?
Answer: If you are looking for syntax highlighting in an in-browser editor, try CodeMirror.
Answer: SyntaxHighlighter
Answer: This article at the Web Resources Depot lists a bunch of options for highlighting code, some of which use Javascript. It was published on 4th May 2009.


Calling a web service from javascript and .net 2.0

Question:
Thanks all for the help, rod.

Hi All,
Is it possible to call a web service (on my localhost) from jquery in a plain html page inside an asp.net 2.0 webform application using visual studio 2005?

I'm getting a 500 error? Not sure if it's even possible to do this way?
thanks,
rod
Answer: By default, ASP.Net doesn't enable web methods for GET requests (which is what a data-less .load() does).  Scott Guthrie has a nice blog post on how to enable GET on Web Methods.
However, keep in mind that they're disabled for a reason (security mainly), you may want to just use a $.post() instead, like this:
$('#button1').click(function(){
  $.post('http://localhost/testservice/Service1.asmx/HelloWorld',
    function(data) { $('#targetDiv').html(data); }
  );
});

Or make .load() trigger POST with a dummy data object, like this:
$('#button1').click(function(){
  $('#targetDiv')
    .load('http://localhost/testservice/Service1.asmx/HelloWorld', {});
});

The {} is the key, passing an object makes .load() do a POST instead of a GET.
Answer: Are you sure this line is correct?
http://localhost/testservice/Service1.asmx/HelloWorld
Have you tried calling the webservice directly through the browser?
Comment: If I goto this link without the '/HelloWorld' I can see the service in my browser...but then how do i call my method called 'HelloWorld()'
Answer: Enable web method in the web service so that it can be called with ajax.
Answer: Use Jquery + Ajax Instead:
http://api.jquery.com/jQuery.ajax/
Answer: A 500 error means your web service threw an exception. Look in the event log to find out what the problem is, or debug the web service to find out.


Updating custom field with module upgrade gives a "Page not found"

Question: I have been working for quite some time on a custom module. So far I have always been able to reinstall everything from scratch, but now I need an update to a custom field. Following the indications in Manually Downloading Module or Theme Files and in Updating a Module I created a mymodule.install file with a content like this:
use Drupal\Core\Database\Database ;

function mymodule_update_8101(&$sandbox) {
    $spec = [
      'type' => 'varchar',
      'length' => 32,
    ) ;

    $schema = Database::getConnection()->schema();
    $schema->addField('node__field_newfield', 'column_name', $spec);
}

Then I put the site in maintenance mode, replaced my module directory with the new one, and then went to http://myserver:myport/update.php, which showed me the small update file as a message. I clicked on Continue, and I got a Page not found.
I am sure I am missing something trivial, but I can't understand what :(
Answer: There's not a lot of information, but you do have an error in your code,
use Drupal\Core\Database\Database ;

function mymodule_update_8101(&$sandbox) {
    $spec = [
      'type' => 'varchar',
      'length' => 32,
    ];
//    ) ;

    $schema = Database::getConnection()->schema();
    $schema->addField('node__field_newfield', 'column_name', $spec);
}

Comment: Oh--now I feel rather stupid :(

Unfortunately, there was a problem _before_ the one in the code, I had put Drupal in a subdirectory and, while index.php worked well, update.php loaded correctly when called without parameters, but returned a 404 when a parameter (specifically, `/selection`) was passed. I solved the first problem by moving back Drupal to root, then of course I corrected the error you pointed up, now my updates are not found, but that's a different problem...


How do I translate an expression tree of one type to a different expression type?

Question: If I have two nearly identical classes Animal and AnimalViewModel and an expression tree related to the viewmodel, how can I translate it to Animal?
public class Animal
{
   public string Species { get; set; }
   public string Name { get; set; }
   public string Sound { get; set; }
}
public class AnimalViewModel : ViewModelBase
{
   public string Species { get; set; }
   public string Name { get; set; }
   public string Sound { get; set; }
}

How can I translate an Expression<Func<AnimalViewModel,bool>> to Expression<Func<Animal,bool>>?
public static Expression<Func<Animal,bool>> Translate (Expression<Func<AnimalViewModel,bool>> expression)
{
  // What goes here?  I assume I have to traverse the tree somehow.
}

Answer: Here's a visitor that does the job.

it makes a copy of the parameter (since we'll need to create a new parameter and substitute all references of the old parameter for the new one)
it walks the .Body of the tree, substituting the parameter, and switching any member-access against the old type to a like-named member on the new type
it re-assembles a lambda using the parameter we invented earler

Code:
class TypeChangeVisitor : ExpressionVisitor
{
    private readonly Type from, to;
    private readonly Dictionary<Expression, Expression> substitutions;
    public TypeChangeVisitor(Type from, Type to, Dictionary<Expression, Expression> substitutions)
    {
        this.from = from;
        this.to = to;
        this.substitutions = substitutions;
    }
    public override Expression  Visit(Expression node)
    { // general substitutions (for example, parameter swaps)
        Expression found;
        if(substitutions != null && substitutions.TryGetValue(node, out found))
        {
            return found;
        }
        return base.Visit(node);
    }
    protected override Expression VisitMember(MemberExpression node)
    { // if we see x.Name on the old type, substitute for new type
        if (node.Member.DeclaringType == from)
        {
            return Expression.MakeMemberAccess(Visit(node.Expression),
                to.GetMember(node.Member.Name, node.Member.MemberType,
                BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Single());
        }
        return base.VisitMember(node);
    }
}
public class Program
{
    public static void Main()
    {
        Expression<Func<AnimalViewModel, bool>> predicate = x => x.Name == "abc";
        var switched = Translate<AnimalViewModel, Animal>(predicate);
    }
    public static Expression<Func<TTo, bool>> Translate<TFrom, TTo>(Expression<Func<TFrom, bool>> expression)
    {
        var param = Expression.Parameter(typeof(TTo), expression.Parameters[0].Name);
        var subst = new Dictionary<Expression, Expression> { { expression.Parameters[0], param } };
        var visitor = new TypeChangeVisitor(typeof(TFrom), typeof(TTo), subst);
        return Expression.Lambda<Func<TTo, bool>>(visitor.Visit(expression.Body), param);
    }
}

Note that if you have x.Something.Name you might need to be a bit more careful, but this should get you a reasonable way.
Comment: Why it doesn't work if you derive AnimalViewModel from an abstract class that has a public property? Although if you put the very same property to the AnimalViewModel and not into the abstract class, it will work
Comment: @Agzam replace DeclaringType with ReflectedType in that case
Comment: check for yourself - if you have Int Id in Animal and also AnimalViewModel derived from BaseViewModel which holds Id. And if you try to use Id in predicate wouldn't work. Don't know why
Answer: Have you tried Automapper for something like this?


How can I use stemmer with Search API Solr but show non-stemmed results in the autocomplete form?

Question: I'm trying to use the Greek stemmer with Apache Solr. If I edit the schema.xml and add the lines:
<code>    <filter class="solr.GreekLowerCaseFilterFactory"/>
    <filter class="solr.GreekStemFilterFactory"/>
</code>
in both analyzers (index and query) of the text fieldType, the stemming works without problems and proper results are being returned. However, the suggestions that are created both in the facets and in the autocomplete form, include the stemmed version of the various keywords. I suppose that this makes sense from a developer's point of view, but the stems that are produced have no actual meaning in Greek.
I did a lot of research (I'm not a Solr expert but I'm starting to learn the basic stuff due to this issue) and I'm hitting a wall. I tried to use many variations of the solution that is described in the question: "How to index fulltext fields with and without stemming" but I can't get solr to copy the fields that I'm interested in, into the dynamic fields that I create (I can see the dynamic fields in the solr interface but no content is copied to them). I even tried to use the filter only in the query analyzer and only in the index analyzer (you can guess how that went).
Any ideas on how I can get this to work properly?
Answer: This is not a "best practice" answer but it might help you get an acceptable result (at least till you figure out how to solve this):

Enable just the GreekLowerCaseFilterFactory in your schema.xml (not the stemmer).
Use the NGramFilterFactory to get partial results in your keywords. You can find information on how to do this here.


what is the meaning of $\mathbb{R}\oplus\mathbb{R}$?

Question: what is the  meaning $\mathbb{R}\oplus\mathbb{R}$?
My  confusion is that
Is  $\mathbb{R}\oplus\mathbb{R}\cong 2\mathbb{R}$  or $\mathbb{R}\oplus\mathbb{R} \cong \mathbb{R}^2$?
Comment: That would just be $\mathbb{R},$ since $\mathbb{R}$ is a field.
Comment: Where did you find this expression? Can you quote it in context?
Comment: By $2\mathbb{R},$ do you mean $\{2x|x\in \mathbb{R}\}$?
Comment: yes @WoolierThanThou
Comment: @TheoBendit actually  this  question  https://math.stackexchange.com/questions/3349338/yes-no-mathbbr-is-isomorphic-to-mathbbr-oplus-mathbbr-as-vector-sp
Comment: @jasmine Where did you get the question? Assignment? Exam? Textbook exercise? Were there any other questions that used the $\oplus$ symbol nearby?
Answer: In general, for abelian groups (or, here, vector spaces, I guess) $X$ and $Y$, we can form a new abelian group/vector space, the direct sum $X\oplus Y$, by formally adding elements of $X$ with elements of $Y$.
So the symbol $x\oplus y$ with $x\in X$ and $y\in Y$ cannot be reduced further. It's a formal symbol. We then define $x\oplus y+x'\oplus y'=(x+x')\oplus (y+y'),$ because all of these additions are assumed to already make sense (since $X$ and $Y$ have the prerequisite algebraic structure). In the vector space case, for a scalar, $\lambda,$ we define $\lambda(x\oplus y)=(\lambda x)\oplus (\lambda y),$ since this is the rule we would get if we really could add these things.
Now, you run into confusion because, in your case, $X=Y,$ so you could already add $x$ and $y$ (just use the structure in $X$), but in the direct sum, we forget this.
So, for $x,y\in \mathbb{R}\oplus \mathbb{R},$ $x\oplus y\neq x+y$. However, as a vector space, it is clearly spanned by $1\oplus 0$ and $0\oplus 1$, and hence, $\mathbb{R}\oplus \mathbb{R}$ is isomorphic to $\mathbb{R}^2$.
Answer: If you have a vector space $V$ and two subspaces $W_1,W_2\subseteq V$, then one defines
$$W_1+W_2=\{w_1+w_2\mid w_1\in W_1,w_2\in W_2\}.$$
In this context, $W_1\oplus W_2$ means the exact same thing as $W_1+W_2$, but should emphasize that the chosen subspaces $W_1$ and $W_2$ have trivial intersection, that means, $W_1\cap W_2=\{0\}$. This has all kinds of nice consequences, e.g. that for every $w\in W_1\oplus W_2$ there is exactly one way to write $w=w_1+w_2$ with $w_1\in W_1$ and $w_2\in W_2$.
Now, if your vector spaces $W_1$ and $W_2$ are not given as subspaces of a common space $V$, then $\oplus$ is defined to resemble the behavior that I explained above, but in an abstract way.
In your specific example, this means the following. In $\Bbb R\oplus \Bbb R$ you will enforce that these two $\Bbb R$'s (despite they look the same) are considered as distinct subspace of a bigger (but not further specified) vector space with trivial intersection. E.g., we can imagine that both of them are subspaces of $\Bbb R^2$, the first one as $\Bbb R\times\{0\}\subseteq\Bbb R^2$, and the second one as $\{0\}\times\Bbb R\subseteq\Bbb R^2$. You then can apply above definition of $\oplus$ for subspaces, that is
$$\Bbb R\oplus\Bbb R\cong \{(x_1,0)+(0,x_2)\mid x_1\in\Bbb R,x_2\in\Bbb R\}=\{(x_1,x_2)\mid x_1\in\Bbb R,x_2\in\Bbb R\}=\Bbb R^2.$$
Comment: thanks  a lots @ M .Winter


Probability - Calculate chance total score will be over or under a score line

Question: I am working on a model which predicts the total final score (sum of the scores of both teams) of certain sports matches. I have checked the predictions of the model against the actual scores of matches for the last several years. The error in the predicted total score to the actual toal score is approximately normally distributed with mean $=-0.3$ and standard deviation $= 13$.
Say I have a predicted total score $x$, how can I determine the probability that the actual score will above or below a given score line $y$.
For example, say my model predicts that the total score will be $8$ and the score line is $5.5$, what is the probability that the actual score will be $\le 5$ and  what is the probability that the actual score will be $>5$ (given that the errors in my prediction can be assumed to be normally distributed)?
Cheers,
Pete
Comment: One warning:  Just because you can follow the calculation of a standard deviation doesn't mean the distribution is Gaussian.  Most real world distributions have larger tails than the Gaussian would predict, so the likelihood of a value farther from the mean than 3 sigma (for example) is much larger than 1 in 370.  Closer to the mean things aren't so bad.  One of my favorite remarks goes something like "Physicists think the Gaussian distribution is a mathematical theorem, mathematicians think it is an experimental fact."
Comment: http://en.wikipedia.org/wiki/Confidence_set
Comment: Thank you, that has given me an insight but I am still struggling to understand how to calculate the probabilities I'm after. Would a worked example be possible?
Answer: OK, sorry for misunderstanding your point. So, your model predicts $PV=8$ with errors $\epsilon \sim N(-0.3,13)$. Or, this is equivalent to saying that you expect the actual value to be $AV \sim N(8.3,13)$. ($PV=AV+\epsilon$)
Now, to compute the probability that $X\leq 5.5$ (or $x>5.5$) under the hypothesis that your model is correct. This is
$$\mathbb{P}(X\leq 5.5|X \sim N(8.3,13)) \; .$$
I don't know what programming language or other computer program you use, but most math or statistics interpretative languages (Matlab, R, etc...) have the necessary commands inbuilt. So in R, you would use the command
pnorm(5.5,8.3,13)

which computes the cumulative normal distribution in point $5.5$ for mean and variance as given. For the probability bigger than $5.5$, you take
1-pnorm(5.5,8.3,13)

If you want the explicit formula for the computation, I can provide that too, but unless you want to make a lot of extra work implenting the functions yourself, I don't think that is really useful.
Comment: Just to make sure I understand fully, does \mu_0 = 8 (i.e. what my model predicts) and \sigma_0 = 5.5 (i.e. the score line) or are \mu_0 and \sigma_0 supposed to be -0.3 and 13 respectively (i.e. the mean and stdv of the prediction errors)
Comment: Well, I took the values of your final example. Why do you change example by the way? I have the impression you are confused about something, but I can't tell what. If you know that your model is a normal distribution, you should already know what to do. Yet, you seem lost? Strange.
Comment: I don't believe I changed the example...? I am a bit confused, I'm happy to admit.
Comment: What are your model values? Is it -0.3 and 13 or is it 8 and 5.5?
Comment: OK, I apologize, I seem to have been reading your post incorrectly. So, your model values are $\mu_0=-0.3$ and $\sigma_0=13$.
Comment: My model will predict that the total score of the game will be some value `x`. The errors in the prediction against the actual total score of the game  are normally distributed with \mu = -0.3 and \signma = 13.
Comment: OK, I see, it's the errors that are normally distributed. I'll adapt my answer.
Comment: Say the model is predicting the outcome of a soccer match between team A and team B. The model gives a prediction of the sum of the scores of A and B. I have tested the model against past games and the mean error in the prediction against the actual score of games is -0.3, with standard deviation 13.
Comment: I adapted the answer, again, sorry for misreading your post. It was actually clearer than I thought. I was the confused one.
Comment: Just one last thing to be certain, is the relationship between Predicted Value (PV), Actual Value (AV) and error ($\epsilon$) as follows: $PV=AV+\epsilon$ or is it $AV=PV+\epsilon$ ? This is also important. Because in the first case, the mean should be $8-(-0.3)$ in the second it should be $8+(-0.3)$.


Evaluate $\lim_{x \to 1} \frac {2x+5}{x^{2}-4x+3}$

Question: $$\lim_{x \to 1} \frac {2x+5}{x^{2}-4x+3}$$
We have $0$ in denominator i don't know how to use l'Hoptial rule and i think we can't use the rule of polynomial functions
Comment: No you can use whenever you have the forms $\frac{0}{0}, \frac{\infty}{\infty}$. However this limit is of the form $\frac{7}{0}$ which does not exist as left-approach is not equal to the right-approach.
Comment: if the numerator was also zero, then you could use l'Hopital rule. Here the function diverges in the vicinity of 1.
Comment: @Math-fun so it's $\infty$
Comment: for $x \to 1^+$ you get $-\infty$ and for $\infty$ for the left limit.
Comment: @user315918 don't forget to accept one of the answers clicking the 'V' in the left side of the answer, and also to vote
Answer: This limit does not exist. left hand limit is - infinity. Right hand limit is +infinity
Answer: The limit does not exist:

$$\lim_{x \to 1^{+}} \frac {2x+5}{x^{2}-4x+3}$$

$$\lim_{x \to 1^{+}} (2x+5) \lim_{x \to 1^{+}}\frac {1}{x^{2}-4x+3}$$
$$=7\cdot\lim_{x \to 1^{+}}\frac {1}{\underbrace{x^{2}-4x+3}_{\to 0^-}}=-\infty$$

$$\lim_{x \to 1^{-}} \frac {2x+5}{x^{2}-4x+3}$$

$$\lim_{x \to 1^{-}} (2x+5) \lim_{x \to 1^{+}}\frac {1}{x^{2}-4x+3}$$
$$=7\cdot\lim_{x \to 1^{-}}\frac {1}{\underbrace{x^{2}-4x+3}_{\to 0^+}}=+\infty$$
Comment: $\lim_{x \to a} \frac{f(x)}{g(x)} \ne \lim_{x \to a} f(x) \lim_{x \to a} \frac{1}{g(x)}$ if $\lim_{x \to a} g(x) = 0$
Comment: Basic Limit Laws - Division Law : http://math.oregonstate.edu/home/programs/undergrad/CalculusQuestStudyGuides/SandS/lHopital/limit_laws.html
Comment: In fact the same constraint is still valid for the product rule. $\lim_{x \to a} \frac{1}{g(x)}$ should be finite. Try to use the rule for  $\lim_{x \to 0} x.\frac{2}{x}$


Como fazer update de um select com sub consultas que contem Group by e order by

Question: Tabela Fisica
Registro IDBanco DataMovimento Credito Debito SaldoAtual Ordenado
    1      26     2020-07-05   500,00   0,00    0,00        5
    2      26     2020-07-03    0,00    10,00   0,00        3
    3      26     2020-07-06    0,00    20,00   0,00        6
    4      26     2020-07-01    0,00    30,00   0,00        1
    5      26     2020-07-06    0,00    40,00   0,00        7
    6      26     2020-07-01    0,00    50,00   0,00        2
    7      26     2020-07-08    0,00    60,00   0,00        8
    8      26     2020-07-04    0,00    70,00   0,00        4
    9      26     2020-07-11    0,00    80,00   0,00        9
   10      26     2020-07-15    0,00    80,00   0,00       11
   11      26     2020-07-11    0,00   100,00   0,00       10

Quando executo este select obtenho o resultado da consulta na tabela abaixo na coluna "Soma".
SELECT t1.Ordenado, SUM(t2.SaldoInicial + T2.Credito - T2.Debito) as Soma
FROM tbl_SaldoAtual AS t1
INNER JOIN tbl_SaldoAtual AS t2 on t1.Ordenado >= t2.Ordenado
GROUP BY  t1.Ordenado
ORDER BY t1.Ordenado  ASC

Ordenado  Soma
    1   -30.00
    2   -80.00
    3   -90.00
    4  -160.00
    5   340.00
    6   320.00
    7   280.00
    8   220.00
    9   140.00
   10    40.00
   11   -40.00

Não estou conseguindo encontrar um caminho para fazer update da coluna "Soma" da consulta para a tabela física na coluna "SaldoAtual", onde a coluna "Ordenado" será a coluna do Group by e Order by conforme o select acima.
Já tentei com CTE, Tabela temporária, Update com sub consultas, mas sem exito.
Se alguém puder dar uma luz agradeço.
Answer: Solução encontrada para o problema acima.
UPDATE tbl_SaldoAtual
SET SaldoAtual = Soma
FROM
(SELECT TOP(15) WITH TIES t1.Ordenado, SUM(t2.SaldoInicial + T2.Credito - T2.Debito) as Soma
FROM tbl_SaldoAtual AS t1
INNER JOIN tbl_SaldoAtual AS t2 on t1.Ordenado >= t2.Ordenado
GROUP BY  t1.Ordenado
ORDER BY t1.Ordenado  ASC) TS
WHERE tbl_SaldoAtual.Ordenado = TS.Ordenado


Azure AD SAML2 SSO wrong NameID format

Question: I am trying to integrate a SaaS application with an autonomous (not federated with anything) Azure Active Directory for SSO purposes. The SaaS application (the Service Provider) is SAML2 compliant (SP-initiated), so this should work. However, inside the SAMLRequest, the SP specifies
<samlp:NameIDPolicy AllowCreate="true" Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" />
And when AAD answers, the NameID is formatted with urn:oasis:names:tc:SAML:2.0:nameid-format:persistent.
It is weird: the documentation at MSDN, paragraph "NameIDPolicy Element in AuthnRequest" lists 'unspecified' as a possible request format...
As the SaaS application expects 'unspecified' instead of 'persistent', it fails.
Would anyone know of a method to get 'unspecified' format instead with Azure AD?
Answer: In this doc they have a warning:

Azure AD currently supports the following NameID Format URI for SAML 2.0:urn:oasis:names:tc:SAML:2.0:nameid-format:persistent.

This is vague but I assume it means that is ALL that they support.
Comment: Marking this as the answer, even if not a definitive answer. We were eventually able to change this at the SP level.
Answer: We just did some investigations and learned that if you do some string manipulation on the NameID then AAD changes the format to 'unspecified'.

Azure AD SAML2 SSO wrong NameID format


Renaming a windows 2003 domain?

Question: we currently have an office server running on Windows 2003. The server hosts e-mail (exchange) and active directory. Also we have two client pc's which get their internet connection and their profiles through the server.
The server is currently running at a specific domain. xxx.companyname.nl. Our companyname has changed and we would like to change the domain to xxx.newcompanyname.nl. Is this a complex procedure (are we better off re-installing?), or can this be done easily?
Comment: I've always heard advice for NOT doing this, so I'm curious to read some detailed explanations for why not.  *Grabs popcorn
Comment: Here's a great discussion about it: http://techrepublic.com.com/5208-6230-0.html?forumID=102&threadID=229757&start=0  It's perfectly feasible to rename a domain and / or DCs. It's not complex at all.
Comment: You're not looking to a Domain Controller rename here (that's a lot easier), but a full domain rename operation; it's a whole different thing, you should re-phrase your question accordingly.
Comment: BTW, are you talking about your Active Directory domain name or your company's e-mail domain? If by chance you only want to change your e-mail domain in Exchange, that's definitely simpler.
Answer: Seriously don't do it!  Renaming your domain will take you far longer than migrating/creating to a new domain name.
Or easier still just ignore your domain name, end users never need interact with it.  Aside form the "member of domain" section in Windows it is irrelevant what your Domain is called - simply creating a new DNS zone and adding the new domain name to Exchange will do the trick.
Comment: Risk vs. reward.  If you're not gaining substantial reward from the rename, file it down there with the other 'aesthetics' projects, in favor of projects providing real value.
Comment: I wouldn't call the 19 page guide to do it a piece of cake
Comment: I'd agree that there's probably no good reason to do it other than aesthetic reasons, but it is pretty easy to do. This guy's got a single DC and a single Exchange Server computer. Renaming it would be a piece of cake.
Comment: Bah! Page counts are meaningless. The vast majority of the text in the "Step-by-Step Guide to Implementing Domain Rename" doesn't apply to this single DC scenario the poster describes. He doesn't have to worry about multiple DCs, the forest and domain functional levels, trusts, domain DFS, and Exchange (if he does a PST migration like I suggest). Likely he doesn't have to worry about a CA, either, which is a large part of the guide as well. It would be an afternoon's job, at most to plan and execute.
Answer: Exchange being on a DC makes a normal "Domain rename" a bit complicated. If you've only got a few mailboxes I'd consider doing a full PST export of the mailboxes with EXMERGE (and any Public Folders, using Outlook), uninstalling and retiring the Exchange organization, then performing a normal domain rename (see http://technet.microsoft.com/en-us/library/cc786120(WS.10).aspx), and re-installing Exchange and importing the email.
Be aware that after such a "PST migration" you'll need to edit the X500 address proxies on recipients so that replies to old intra-organization emails work properly (see http://blogs.technet.com/sbs/archive/2009/05/21/cannot-reply-to-old-emails-or-modify-old-calendar-items-after-pst-mail-migration.aspx for details about what I'm talking about).
This shouldn't be too hard of a road, really. Since you can gather all the pertinent details re: Exchange prior to the export / uninstall / reinstall / import, it should go fine.
Answer: Renaming domains has been possible since Windows Server 2003 was introduced (as opposed to Windows 2000, which explicitly stated domain names were not changeable). The procedure is a bit complex and involves using command-line tools (rendom.exe) and editing XML configuration files, but it can be done and works quite well.
Now, renaming a domain with Exchange is a bit more tricky. You can find a good guide to this here:
http://www.msexchange.org/tutorials/Domain-Rename.html
Answer: just adding a related caution on ghost and DCs but can't comment in line with the ghosting discussion due to rep:
Having recovered a DC from a Ghost image, it's possible but there can be wrinkles if replication has continued with "current" version of the DC that you wish to restore.
As replication continues, the USN continues to be incremented and restoring the ghost image results in the DC reporting lower USN and it will be out of sync with the up-to-date DCs.
There are ways around this but adding Exchange into the mix likely adds even more wrinkles.
For ref. there's a discussion of this issue and possible ways to correct it:
http://utools.com/help/UsnRollback.asp
Answer: I have done this several times at customers, and although the walkthrough documentation is a bit on the heavy side, the procedure itself actually isn't that complicated. For a one-server job with two pc's I'd say this is done in 3-4 hours if you know what you're doing.
IF you are running Exchange 2007 the procedure is unsupported though, so don't go there.
Answer: We can rename both domain/domain controller by using netdom tool
look at this article http://www.morgantechspace.com/2013/08/how-to-rename-domain-controller-name.html

To use Netdom, you must run the netdom command from an elevated command prompt. To open an elevated command prompt, click Start, right-click Command Prompt, and then click Run as administrator.
At the command prompt, type the following command to add the new domain controller name, and then press ENTER key:
<code>   netdom computername <CurrentDCName> /add:<NewDCName>
</code>

Type the following command to designate the new name as the primary computer name, and then press ENTER key:
<code>netdom computername <CurrentDCName> /makeprimary:<NewDCName>
</code>
3.Restart the computer.
4.After the computer restarts, open a Command Prompt. At the command prompt, type the following command to remove the old domain
    controller name, and then press ENTER:
<code>    netdom computername <NewDCName> /remove:<OldDCName>
</code>
Comment: Hi Kombaiah, your answers seem useful to me but the constant links to your own blog could be considered spam if you don't disclose your affiliation.  Have a read of [these guidelines for self promotion]( http://meta.stackexchange.com/questions/57497/limits-for-self-promotion-in-answers).  Make sure you disclose any affiliations you have with links you post in questions and answers.  Hope you stick around and provide more good answers.
Answer: Renaming a Domain Controller's ComputerName
Petri has some advice for renaming your domain controller, and it's possible. There are lots of hooks throughout the DC into the domain's name. This article is simply for renaming your DC's computer name, as indicated in the title of this question: "Renaming windows 2003 domain controller?"
Really the best advice is to ensure that you have a second DC, and rebuild this machine once that second DC is able to take control. Certainly just power off your machine, ensure everything works on your domain using the second DC. That'll give you confidence that it's OK to go ahead and rebuild your first DC.
Heck, take a Ghost image of the machine that you want to rename in case things go sideways. If the re-naming project over the weekend doesn't give you good results, then you could reimage the machine and the users wouldn't be any wiser when they walk into work on Monday morning.
Renaming a Domain
You will encounter too many hidden hooks in Windows, Active Directory, and Exchange. You'll be paying the price in time wasted downstream, that I'd not even consider this option.
Comment: You can't just go "ghosting" around a distributed multi-master replicated database.  *sigh*  You're going to end up breaking something. Disk imaging PCs is one thing-- servers are a different animal.
Comment: I read that page already. But I am not sure if this procedure classifies as 'renaming your entire domain'...?
Comment: I don't think this answer is valid. Having a second DC isn't going to help matters w/ Exchange very much at all. This can be done on the single box w/ a PST-style migration. Technically, you could do it w/ promoting a second DC, demoting the first DC, doing a run-of-the-mill domain rename and running the Exchange-related fixups, then re-promoting the original box and retiring the temporary secondary DC, but the way I outlined is, I think, easier. Thing is, you don't even mention that. You talk about, like, taking "Ghost" images of DC's. Not a good idea at all.
Comment: Hi everybody; the title of the question is "renaming the DC". Turns out the question and the title + tags are mismatched. The Ghost suggestion is all about fail-over strategies, which is valuable when performing surgery like this.
Answer: I would say its not worth it.
Here is the link to the technical guide for renaming a domain, its 19 pages log.  Honestly if its that important, I'd EXMerge the mailboxs out then rebuilt the DC/Exchange server from new.
I'd personally not worry about it if its not really required. Unless like the boss to do it.

Renaming a windows 2003 domain?


model relations and bulk deletes

Question: I have a model relation of dependant=>destroy that has to do 50K+ deletes when the destroy is triggered. Looking at the console, rails is trying to do an explicit delete with ID for every single row, which is taking a while. Is there a way for me to force rails to do a bulk delete? Or, I can remove the model dependency, is there a way to do this kind of bulk delete from the code?
Thanks
Answer: You should be able to set dependent: delete_all
If you can't get that to work, you might want to use delete_all in your own callback.
To be clear, delete_all should generate a single statement to delete all child objects

model relations and bulk deletes


Breakpoints are ignored when debugging in Visual Studio 2008 on 64-bit system

Question: I'm trying to debug an ASP.NET web application in this environment:

Windows Server Standard 2008 SP2 x64
Single-core CPU
4GB RAM
Visual Studio 2008 with Remote Debugger SP1
.NET 3.5 Web Application running in IIS in 64-bit mode

The code I am trying to debug is a simple event handler with some basic sequential code.
What I observe is that breakpoints get randomly ignored and VS often exits debug mode when I try to step through the code.
The code is compiled in debug mode.
EventViewer shows no warning or error messages that would relate to this. I am certain that this is not caused by IIS app pool recycle/reset.
I've tried all the usual steps: iisreset, reboot VM, rebuild solution, reinstall Visual Studio.
Any ideas?
Answer: I had the same problem with a Windows Form application, and I applied the same hotfix as Julien did. (http://code.msdn.microsoft.com/KB957912). I haven't had the problem since.
Answer: Maybe your IIS App Pool is recycling for some reason once in a while. This kills the IIS worker process and therefore unhooks the debugger.
You can check if this happening in the Eventlog. Also check you application pool settings in IIS Manager.
Comment: EventViewer shows no warning or error messages that would relate to this. I am certain that this is not caused by IIS app pool recycle/reset.
Answer: Got the same problem with randomly missed breakpoints and debug mode resuming/stopping when stepping through, on a WPF application though. This fix solved it:
http://code.msdn.microsoft.com/KB957912
Answer: Could not find a solution.
Worked around this behaviour by using a combination of Debug.Print() and Sysnternals DebugView
Hope this helps.


Increasing Exam Expected Mark

Question: You are in an exam, and are presented with the following question:

Write down what mark do you expect to
  take in this exam... If you get it
  right in range of +/-10 % then you
  will take 10% bonus... if wrong (or
  not answered) you will lose 5%

Assume that you have no idea of how you are going to perform in this exam. How would you choose a mark that maximizes your expected return mark?
In other words, I need to help deriving an equation for the expected mark given a decided mark, if that is possible...
Comment: I interpreted "10% bonus" as an additional 10% towards your return mark. For example, 30% goes to 40% with this bonus. However, it could be that your return mark is increased by 10% (30% goes to 33%). Would you clarify?
Comment: 30% goes to 40%....
Answer: First a couple of assumptions:
1. All marks are equally likely.
1. If you guess your mark to be 95 and you get 95, your return mark is 100 not
   105.
1. Similarly, if your exam mark is 1 and you guess 50 (say), then your return
   mark is 0 not -4.
1. I'm only considering discrete marks, that is, values 0, ..., 100.
Suppose your guessed mark is $g=50$. Then your expected return mark is:
$$
\frac{\sum_{i=0}^{34} + \sum_{i=50}^{70} + \sum_{i=56}^{95}}{101} = 49.15482
$$
This is for a particularly $g$. We need to repeat this for all $g$. Using the R
code at the end, we get the following plot:

Since all marks are equally likely you get a plateau with edge effects. If you  really have absolutely no idea of what mark you will get, then a sensible strategy would be to maximise the chance of passing the exam. If the pass mark is 40%, then set your guess mark at 35%. This now means that to pass the exam, you only need to get above 35% but more importantly your strategy for sitting the exam is to answer every question to the best of your ability.
If your guess mark was 30%, and towards the end of the exam you thought that you would score 42%, you are now in the strange position of deciding whether to intentionally make an error (as 42% results in a return mark of 37%).
Note: I think in most real life situations you would have some idea of how you would get on. For example, do you really think that you have equal probability of getting between 0-10%, 11-20%, ..., 90-100% in your exam.
R code
<code>f =function(s) {
  mark = 0
  for(i in 0:100){
    if(i < (s-10) | i > (s + 10))
      mark = mark +  max(0, i-5)
    else
      mark = mark + min(i+10, 100)
  }
  return(mark/101)
}
s = 0:100
y = sapply(s, f)
plot(s, y)
</code>
Comment: With a uniform prior distribution wouldn't guessing 30 be equivalent to guessing 35, since both will have 65 actual test grades that will result in a passing grade?
Comment: @Andy-w Good point, I should have explained my reasoning. I've now updated my answer.
Answer: I'm not sure if this would be a funny game or your professor is mildly sadistic. It would be torturous for students who are right on the edge of passing (which we may expect them to be the worst guessers!) Sorry not an answer but I couldn't help myself.
Answer: Use the bootstrap! Take lots of practice exams and estimate what your score will be on the real exam. If it does not improve your estimate, it will probably be good preparation!
Comment: +1, I think this is a better strategy if your goal is to maximize the grade and you have prior distribution of test grades. It seems a bit overkill if your only goal is pass the exam though.

Increasing Exam Expected Mark


Display an image for the first item in a Views news list

Question: I want to create a view to display news like in this image:

The list shows an image only for the first news, the other news only display the title.
Answer: Views nodes split does exactly this:

This module allows site administrators or builders to have a different
  view mode for the first nodes of a view result.

Source: Lullabot - Module Monday: Views Nodes Split
Answer: Quick and dirty, if you don't mind having all the images loaded in your page, you can use CSS to display the first one and not all the rest, eg:
<code>.views-row img {
   display: none;
}

.views-row-first img {
   display: block;
}
</code>
I would just theme it a bit more specifically on your site, eg, with the views css names and views field names and so forth, the point is that views themes each row specifically, just take a look at the html output.
Comment: and this way, if you want to get fancy, you can use jQuery and pop open these hidden images when you hover over the other titles :)
Comment: Nice trick Jimajamma


I have found a system of 3 variables that lead to a quadratic equation, so how do I find the answer?/

Question: $$p^2 + q^2 = 81$$
$$p^2 + (q-x)^2 = 225$$
$$(p-x)^2 + q^2 = 144$$
So these are the 3 equations.
Comment: What have you tried?
Comment: Interestingly, $$144+81=?$$
Comment: If you expand the squares in the last two, the first can simplify both of them.  It doesn't get you there, but it is a start.  Subtracting the last two eliminates the squares of all three.
Answer: Let $(p,q)=9(\cos t,\sin  t)$, then
\begin{align}
  81+x^2-18x\sin t &= 225 \\
  81+x^2-18x\cos t &= 144 \\
  (18x)^2 &= (x^2-144)^2+(x^2-63)^2 \\
  0 &= 2x^4-738x^2+24705 \\
  x &= \pm 3\sqrt{\frac{41 \pm 3\sqrt{119}}{2}} \\
  p &= 9\cos t \\
  &= \frac{x^2-63}{2x} \\
  q &= 9\sin t \\
  &= \frac{x^2-144}{2x}
\end{align}
Answer: \begin{align}
p^2+q^2 &= 81
\tag{1}\label{1}
,\\
p^2+q^2-2qx+x^2 &= 225
\tag{2}\label{2}
,\\
p^2-2px+x^2+q^2 &= 144
\tag{3}\label{3}
.
\end{align}
Subtract \eqref{1} from \eqref{2} and \eqref{3}
to get $p$ and $q$ in terms of $x$,
\begin{align}
p &= \tfrac12\,\frac{x^2-63}x
\tag{4}\label{4}
,\\
q &= \tfrac12\,\frac{x^2-144}x
\tag{5}\label{5}
,
\end{align}
then substitute \eqref{4} \eqref{5} into \eqref{1}
to get biquadratic equation in $x$
\begin{align}
2\,(x^2)^2-738\,x^2+24705
&=0
,
\end{align}
which gives
\begin{align}
x^2&=\tfrac{369}2\pm\tfrac{27}2\,\sqrt{119}
\end{align}
and hence, four solutions for $x$:
\begin{align}
x_1&=\tfrac32\,\sqrt{82+6\sqrt{119}}
,\\
x_2&=-\tfrac32\,\sqrt{82+6\sqrt{119}}
,\\
x_3&=\tfrac32\,\sqrt{82-6\sqrt{119}}
,\\
x_4&=-\tfrac32\,\sqrt{82-6\sqrt{119}}
.
\end{align}


Adding Pagination to to custom form block results

Question: I have created a custom block that has a form which has a list of result and I wanted to know how to add pagination to the results
Thanks for any help on this
Colin
Answer:     /**
 * Implements hook_block_info().
 */
function custommodule_block_info() {
    $blocks = array();
    $blocks['latest_news'] = array(
        'info' => t('Latest News'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

    /**
 * Implements hook_block_view().
 */
function custommodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {

        case 'latest_news':
            $block['subject'] = t('');
            $block['content'] = latest_news();
            break;
    }
    return $block;
}

/*
 * Implementation of hook_theme
 * */

function custommodule_theme() {
    return array(

        'latest_news' => array('variables' => array('data' => array()),
        'template' => 'latest_news'),

    );
}

    function latest_news() {
     $query = db_select('node', 'node');
    $query = $query->fields('node', array('nid'))
            ->condition('node.status', 1) //Published.
            ->condition('node.type', 'auction_news');
    $query = $query->extend('PagerDefault');
    $result = $query->limit(20)->orderBy('node.created', 'DESC')->execute()->fetchAll(PDO::FETCH_ASSOC);
    $paging = theme('pager');

    return theme('latest_news',array('data' => $result,'paging'=>$paging));
}

In a tpl file latest_news.tpl.php

    <?php
    foreach($data as $lat_news)
    {

       echo '
'.$lat_news->nid.'
';
    }
    ?>

<?php echo $paging;?>


Active Directory Child Domain Replication Problems

Question: I've recently inherited an Active Directory (all DCs Windows 2003) which has been configured with several child domains that are used as test environments for out CRM software. Two of these child domains have been used for testing using dates in the future (2015), throwing them well outside of the Kerberos tolerance for time, and they're flooding my event logs with replication errors such as the following:
<code>Description:
The attempt to establish a replication link for the following writable directory partition failed.

Directory partition:
CN=Schema,CN=Configuration,DC=ad,DC=xxxxxxx,DC=com
Source domain controller:
CN=NTDS Settings,CN=TESTDC001,CN=Servers,CN=SiteName,CN=Sites,CN=Configuration,DC=ad,DC=xxxxxxx,DC=com
Source domain controller address:
38e95b2a-35af-4174-84ba-9ab039528cce._msdcs.ad.xxxxxxx.com
Intersite transport (if any):

This domain controller will be unable to replicate with the source domain controller until this problem is corrected.

User Action
Verify if the source domain controller is accessible or network connectivity is available.

Additional Data
Error value:
5 Access is denied.
</code>
I'd also like to upgrade to Windows 2008 at some point, but wouldn't want to attempt any schema updates while I'm not 100% confident on the replication. I'm guessing my only real solution will be to get rid of these child domains.
The child domains are operating as stand alone domains, the DC is up and running and authenticating test users fine. I'm guessing the best solution to this would be to delete the domains (although I'd be happily told otherwise). The clock forwarding appears to have been happening for several years, so I'm assuming I can't just put the clock right (I'm guessing scope for this would be 180days, the same as the tombstone lifetime)
With the replication errors would I be able to dcpromo the child domains DC, select it as the last domain controller in the domain and the child domain would be deleted? Or would I be better off treating the domain as an orphaned domain and use Microsoft's instructions to clear up as such.
Any advice would be much appreciated.
Answer: Because you are seeing replication errors there is the possibility that doing a dcpromo would not cleanly remove the child domains.
Doing the metadata cleanup as described in the KB article will remove all traces of the child domain from your parent domain.  I would make sure the domain controllers for the child domains are powered down or rebuilt without the active directory role before doing the metadata cleanup.
This all assumes there is nothing in the child domains that needs to be retained.


Laravel direcionando método HTTP para função errada no Controller

Question: Tenho um projeto em Laravel e Vue.js onde tenho uma função no Vue.js que manda um post com os dados de um formulário, até aí tudo bem, só que quando a função this.$http.post() faz a requisição para o back-end, o laravel direciona para o método errado, ele deveria mandar para o método store(que trata das requisições post), porém envia para o método index(responsável pelas requisições GET), um detalhe é que estou usando RestFull Controllers, então todos os métodos estão sendo acessados com base na requisição que está sendo feita(ou pelo menos deveria ser assim).
Um detalhe é que localmente na máquina que utilizo para desenvolver funciona perfeitamente, e numa outra máquina servidora local, também funciona perfeitamente, agora colocar esse projeto no servidor de produção da Amazon acontece o que relatei acima.
As configurações são as seguintes:

Máquina local
PHP 5.6.28

Servidor Local
PHP 7.0

Servidor do Amazon(EC2)
PHP 5.6.30

O que pode estar acontecendo? Realmente já pensei em várias possibilidades e não tenho ideia do que pode ser.
Comment: Edita a pergunta e adiciona os códigos referentes ao problema, tais como o código JS que faz a requisição e o código do controlador do Laravel que possui os métodos `index` e `store`.
Answer: Acontece que quando se trabalhar com o VueResource, em alguns projetos você precisa dizer a ele para emular uma requisição normal como HTTP.
Para realizar esta configuração, adicione o parâmetro de Configs ao VueResource, ficaria da seguinte forma:
var config = {
    emulateJSON: true,
    emulateHTTP: true
};

// Adicionado o CONFIG para emular
this.$http.post(url, data, config).then((val) => {
    console.log(val);
});

Comment: Nos métodos http já inclui as configurações acima, porém sem o emulateHTTP, tentei com e não adiantou também.
Answer: Achei a solução, na verdade encontrei a resposta no fórum estrangeiro, o que estava acontecendo era que a url nos métodos $http estavam com uma "/"(barra) no final, por exemplo:
"test.com/api/v1/resource/"
foi só tirar ficando assim:
"test.com/api/v1/resource"
fazendo isso deu certo.


Classical Guitar Piece Notation

Question: What does the + and .. sign mean on top of the notes?
Answer: This is probably an obsolete notation for right-hand fingering, instead of the modern p,i,m,a,e notation.
I guess that + means pluck with the thumb, and 1-4 dots mean use the corresponding finger.
A similar (but not identical) notation was used by Mertz in a 19th-century guitar tutor, see https://imslp.org/wiki/Special:ImagefromIndex/442101/torat page 10.
Comment: Yes, this is right. I have quite a few German editions of classical guitar music using this notation.
Comment: Takes me back a long time, it's correct.
Answer: It's right-hand fingering shorthand, used more often in the 1800s and early 1900s.
. - I, .. - M, :. - A, + - P
P = Pulgar/Thumb
I = Indice/Index
M = Medio/Middle
A = Anular/Ring
E = Mignolo/4th (pinky)
Comment: You appear to have mixed up the Spanish and Italian names for the fingers: `Spanish:` Pulgar, indice, medio, anular, menique. `Italian:` Pollice, indice, medio, anulare, mignolo. `Letters:` p, i, m, a, [c/e/x](http://rec.music.makers.guitar.jazz.narkive.com/nI1nx3h8/finger-naming-standard-p-i-m-a-c)

Classical Guitar Piece Notation


How does achieve a "distant" effect on piano?

Question: I'm trying to teach myself some piano pieces by Joaquín Turina and he marks certain passages as "lointains" (French for "distant"). It occurred to me that I have no idea what this means in terms of performance. Is it a mood to be impart somehow? (How?) A specific dynamic effect (like "cantabile")? Something stylistic?
More generally, are there any good books or other reference material that explain how to interpret terms like this? I found a nice dictionary of terms here, but nothing about translating them into performance.
I remember learning a lot of basic musical terms from John Thompson's "Keyboard Attacks" and other of his elementary books; it not only explained what the terms meant, but also how to execute them through various playing techniques. Something like that (but more comprehensive) would be very nice, particularly if it was oriented to the self-learner.
Answer: I've never played a piece with a lointains marking, nor have I learnt about it.  But this is how I would interpret "distant".
It's definitely a mood, which of course encompasses dynamics.  I would slow down a bit, and quiet down dramatically.  I would want the audience to strain to hear, as if listening for something in the distance.  I would expect this passage to have a lot of rests or at least longer notes, rather than fast ones; that would allow for pausing and delays.  I would use them to further augment the straining of the audience.  "Has he stopped playing?  Ah, there it is."  That sort of idea.  You don't want to stray too far from the tempo and beat, of course; an audience becomes frustrated when their expectations are entirely violated.  You just want to make them question whether that expectation will be met.  You could play in time, but a little off-beat; insert a sixteenth rest before a half note and shorten the note by a sixteenth, for example.
Mich makes a good point below that using the soft pedal would help create a muted sound, which would fit perfectly with this idea.
Sorry for the vagueness, but I think that's unavoidable when talking about mood (even if I had studied it).  If I could play it for you, I would!
Comment: Sounds good. I'd elaborate that the performer may want to consider specifically using the soft pedal, as that would also create a veiled, distant tone.
Comment: This is great. I can see how to apply these techniques to get a "distant" effect. Thanks to both of you! By the way, the piece I'm learning is Turina's Op. 20 No. 1. The mark _lointain_ comes after 16 opening bars marked _pp mystérieux_, and is actually a little syncopated and faster. So is this something a performer is supposed to invent based on a general meaning of the mark?
Comment: I had already read that post of yours (also very nice). :) By the way, the title of the piece is "Before the tower of Clavero (ancient fortress of Salamanca)". Turina's own commentary on the piece is, "The poet dreams of ancient archer's rounds, and suddenly the silhouette of a woman appears."
Comment: @Mich Ah, I thought about that and forgot it by the time I wrote my answer.  It would definitely be a good way to create not just a quieter sound, but a more muffled one.  Fits perfectly with "distant".  Thanks!
Comment: @Ted Some mood/tempo markings are supposed to be "understood" (see the quoted part in my answer [here](http://music.stackexchange.com/questions/3294/what-tempo-is-agitato/3296#3296) for a little detail) but in this case I don't think *lointain* is commonly used, and interpretation is more than acceptable.


C# WPF - Acessar elemento de outra XAML por codigo

Question: Olá, tenho  duas telas uma Window e uma Page carregada dentro da tela
Class Window1{
   //to do ..
 __mainFrame; // acessa normal
}

Class page1{
 //to do
__mainFrame; // sem  acesso ao frame
}

Dentro da classe window tenho um  <Frame x:Name="__mainFrame"></frame> a onde carrego as paginas e queria quando clicasse em  um botão que esteja dentro de page1 fosse carregado nesse iframe como  os dois estão em classes diferentes não estou  conseguindo carregar, teria alguma forma de fazer esse acesso ?
Obs, utilizar o extend de uma classe dentro da outra não funciona
Como  no exemplo abaixo
Class window1 : page1{

}

Answer: A forma como você fez resolve o problema, mas em um ambiente com várias classes e múltiplos níveis de objetos você terá problemas de referência. Fora o acoplamento entre as classes que vai só crescer, se você precisar mudar o nome __mainFrame em algum momento, terá que sair mudando em vários arquivos. Enfim, a manutenção vai ficar extremamente complexa.
Uma solução melhor (existe outras, com certeza), é você criar uma propriedade do tipo Action na sua page1, atribuir uma função à ela na sua Windows1 e depois executar na page1 quando precisar.
Exemplo:
Class Window1{

    construtor(){
        // crie uma instancia de page1 ou acesse uma já existente, como exemplo, vou criar
        var page1 = new page1();
        page1.FazerAlgumaCoisa = () => {
            __mainFrame; // aqui você tem acesso ao objeto __mainFrame para fazer o que quiser
        }
    }
    __mainFrame; // acessa normal
}

Class page1{
    public Action FazerAlgumaCoisa { get; set;}

    public void ExecutarAcaoNoMainFrame(){

        this.FazerAlgumaCoisa?.Invoke();

    }
}

Você também pode passar parâmetros se necessário, basta alterar a sua propriedade Action, como no exemplo abaixo onde passo uma string.
Class Window1{

    construtor(){
        // crie uma instancia de page1 ou acesse uma já existente, como exemplo, vou criar
        var page1 = new page1();
        page1.FazerAlgumaCoisa = (parametro1) => {
            __mainFrame; // aqui você tem acesso ao objeto __mainFrame para fazer o que quiser
//parametro1 pode ser usada aqui
        }
    }
    __mainFrame; // acessa normal
}

Class page1{
    public Action<string> FazerAlgumaCoisa {get;set;}

    public void ExecutarAcaoNoMainFrame(){

        this.FazerAlgumaCoisa?.Invoke("qualquer valor");

    }
}

Comment: obrigado pela resposta, agora eu estou  fazendo de uma forma  um pouco diferente utilizando uma classe controladora de instancia assim evetia que haja eventuais crashing por arquivos não intanciado então fica public static TipoPage NomeAcess; ai faço a verificação se o arquivo está instanciado e chamo por ele
Answer: Bom consegui  aqui  a forma para fazer isso
Class page1{

((Window1)System.Windows.Application.Current.MainWindow).__mainFrame;

}

A onde Window é o nome da classe da minha Window1 que referencia o xmal que quero acessar  e MainWindow é o  x:Name do elemento window
desta forma  pode-se acessar qualquer elemento externo a sua classe


Infix vs prefix syntax: name lookup differences

Question: Operators in C++ are usually considered to be an alternative syntax for functions/methods, especially in the context of overloading. If so, the two expressions below should be synonymous:
std::cout << 42;
operator<<(std::cout, 42);

In practise, the second statement leads to the following error:
call of overloaded 'operator<<(std::ostream&, int)' is ambiguous

As usual, such error message is accompanied with a list of possible candidates, these are:
operator<<(basic_ostream<_CharT, _Traits>& __out, char __c)
operator<<(basic_ostream<char, _Traits>& __out, char __c)
operator<<(basic_ostream<char, _Traits>& __out, signed char __c)
operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c)

Such error raises at least two questions:

In what way are the two statements different (in terms of name lookup)?
Why operator<<(basic_ostream<char, _Traits>& __out,int__c) is missing?

It seems, that infix and prefix notations are not fully interchangeable -- different syntax entails different name resolution tactics. What are the differences and where did they come from?
Comment: There's another interesting difference between `x << y` and `operator<<(x, y)`: name lookup in for operators in expressions (the first one) *always* performs ADL, whereas lookup for ordinary (free) function calls (the second one) not always performs ADL. [Live example](http://coliru.stacked-crooked.com/a/975907df23216a48)
Comment: "Prefix operator invocation" uses the *usual* unqualified name lookup rules. Those will search the scopes beginning with the nearest enclosing scope, until the name is found in one scope, then it stops (any enclosing scopes then are ignored). If no name has been found, or if the found name is *not* a member function, (pure) ADL is invoked additionally. I think the reason is that member functions are special, and inside the class itself shall take precedence over any free function. But for operators, ADL is essential, and it just wouldn't work well inside classes with overloaded operators.
Comment: @dyp Great example! It seems that prefix operator invocation within method implies "class-major" name lookup (like plain method invocation «checked»), while infix notation uses "standard" name lookup (including ADL). But why is it so?
Comment: @dyp Further explanation of your example:  `operator<<(*this, 2.5);` is inside a member function of `X` , so unqualified lookup finds `X::operator<<`; and the rule [basic.lookup.argdep/3] says that if the unqualified lookup set finds a class member function then ADL is not performed
Answer: No, the two expressions should not be synonymous. std::cout << 42 is looked up as both operator<<(std::cout, 42) and std::cout.operator<<(42). Both lookups produce viable candidates, but the second one is a better match.
Comment: @40two: the original question is why `std::cout << 42` works while `operator<<(std::cout, 42);` doesn't; why the two aren't the same. The answer is that `std::cout << 42` may be interpreted both as `operator<<(std::cout, 42)` and also as `std::cout.operator<<(42)`. The compiler performs two name lookups, for both forms, then performs overload resolution on all candidates found by both lookups. This is why the difference in name lookup is most significant for the problem at hand, while the failure of overload resolution in  one of the two cases is secondary.
Comment: `operator<<()` is an operator function found in namespace `std` through ADL. The overloads that take integers are not found there, but only as member functions. That's why the compiler listed those as ambiguous overloads and said `operator<<(ostream&, int)` couldn't be found.
Comment: @40two `operator<<(std::cout, 42);` doesn't find, via name lookup it performs, as many candidates as `std::cout << 42` does.
Comment: What name lookup has to do with it? The error is an ambiguous overload, that is the compiler can't decide which overload to choose.
Comment: @IgorTandetnik I can't understand your last comment.
Comment: OK cleared out, thanks. The reason Ι was persistent is that the OP is trying to print 42 :)
Answer: These are the operator lookup rules from C++17 [over.match.oper/3] where I have edited for brevity by removing text that does not pertain to overloading operator<< with the left operand being a class type; and bolded a section which I will explain later on:

For a binary operator @ with a left operand of a type whose cv-unqualified version is T1 and a right operand of a type whose cv-unqualified version is T2 , three sets of candidate functions, designated member candidates, non-member
  candidates and built-in candidates, are constructed as follows:

If T1 is a complete class type or a class currently being defined, the set of member candidates is the result of the qualified lookup of T1::operator@ (184.108.40.206.1); otherwise, the set of member candidates is empty.
The set of non-member candidates is the result of the unqualified lookup of operator@ in the context of the expression according to the usual rules for name lookup in unqualified function calls except that all member functions are ignored.

The built-in candidates are empty here, that refers to searching functions that would implicitly convert both operands to integer types and apply the bit-shift operator; but there is no implicit conversion from iostreams to integer type.

The set of candidate functions for overload resolution is the union of the member candidates, the non-member candidates, and the built-in candidates.

What is the rationale is for having operator lookup differ from other function lookup and what does this all mean?  I think this is best answered through a couple of examples. Firstly:
struct X{ operator int(); };

void f(X);

struct A
{
    void f(int);

    void g() { X x; f(x); }    // Calls A::f
};

In this example there is a principle: if you try to call a member function of the class from another member function of the class; it should definitely find that member function, and not have the search polluted by outside functions (even including ADL).
So, part of the unqualified lookup rules is that if the non-ADL part of lookup finds a class member function, then ADL is not performed.
Without that rule, f(x) would find both A::f and ::f and then overload resolution would select ::f as better match, which we don't want.
Onto the second example:
struct X{};
std::ostream& operator<<(std::ostream&, X);

struct S
{
    std::ostream& operator<<(int);

    void f()
    {
         X x;
         std::cout << x;   // OK
         // operator<<(std::cout, x);  // FAIL
         // std::cout.operator<<(x);   // FAIL
    }
};

As per the principle of the previous example -- if the rules were just that std::cout << 42; is transformed to operator<<(std::cout, 24); then name lookup would find S::operator<< and stop. Whoops!
So I think it is not quite correct to say that the behaviour of the OK line above comes from doing both of the lines marked FAIL, as other answers/comments have suggested.

SUMMARY:
Now we can understand the actual wording of the standard quote at the top of my answer.
The code std::cout << x; will:

Look up as std::cout.operator<<(x); AND
Look up as operator<<(std::cout, x) EXCEPT THAT member functions are ignored (and therefore, there is no ADL-suppression due to member function being found).

Then overload resolution is performed on the union of those two sets.


For $p$ prime, is the polynomial $x^p-x+1$ irreducible in $\mathbb{Z}_p$?

Question: It is possible, for $p\in\mathbb{N}$ prime, that the polynomial
$x^p-x+1$ is irreducible in $\mathbb{Z}_p$?
By the identity
$a^p\equiv a$  mod $p$ for any $a\in \mathbb{Z}_p$ surely there is not a root for this polinomial.
Comment: This is an Artin-Schreier polynomial. Google this. If it had a root then it completely splits ("one out, all out").
Comment: Several approaches to proving this are given [here](https://math.stackexchange.com/q/81583/11619). But, barto's method is nice (+1) even though variants of it are also in that "mother" thread.
Comment: Is $\mathbb Z_p = \mathbb Z/p$ or the $p$-adic integers?
Comment: Sorry, $Z_p=Z/pZ$
Comment: Presumably the intended question was is this polynomial irreducible for all primes $p$?
Comment: Yes I want to prove what you said
Answer: It is always irreducible: by Little Fermat, if $f(x)$ is a monic irreducible factor, then so is $f(x+n)$ for all $n$. Let $k>0$ be minimal for which $f(x) = f(x+k)$. Then $k \mid p$, hence $k=1$ or $k=p$.
If $k=p$, we conclude that all $f(x+n)$ are distinct mod $p$ for $n=0,1,\ldots, p-1$. Hence $f$ has degree $1$. But $x^p-x+1$ has no roots, contradiction.
If $k=1$, $f(x)=f(x+1)$ hence $f(x)-f(0)$ has $p$ roots, so $f$ has degree $p$, and $x^p-x+1$ is irreducible.

By the exact same argument, we see that $x^p-x-\alpha$ is irreducible for $\alpha \neq 0$.


How do I crop each page in pdf using PDFBOX in Java?

Question: I want to remove the bottom part of each page in the PDF, but not change page size, what is the recommended way to do this in java in PDFBOX? How to remove the footer from each page in PDF?
Is there possibly a way to use PDRectangle to just delete all text/images within it?
snippet of what I tried, using rectangle with setCropBox seems to lose page size, maybe cropBox is not intended for this?
<code>            PDRectangle rectangle = new PDRectangle();
            rectangle.setUpperRightY(mypage.findCropBox().getUpperRightY());
            rectangle.setLowerLeftY(50);
            rectangle.setUpperRightX(mypage.findCropBox().getUpperRightX());
            rectangle.setLowerLeftX(mypage.findCropBox().getLowerLeftX());
            mypage.setCropBox(rectangle);
            croppedDoc.addPage(mypage);
            croppedDoc.save(filename);
            croppedDoc.close();
</code>
Closest example in pdfbox cookbook examples I could find is on how to remove entire page, however this is not what I'm looking for, I'd like to just delete few elements from the page:
http://pdfbox.apache.org/userguide/cookbook.html
Comment: Why -1? I don't see any comments, at least explain why this is not a valid question or point to other questions or sources?
Comment: I think it would be helpful, if you edit the question itself and all these information as part of your question itself.
Comment: I agree that the person who downvoted this could've left a comment. However, one possible reason might have to do with your question itself - what you wrote does not show any research of your own. Perhaps you want to try something out or *if you already have*, let us know your roadblocks, and then perhaps people over here can help you out. It always helps to show [what have you tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/)
Comment: OK, here's a bit more background. I basically looked through the API looking for function,something like "clip", which I had used in the past(in pdflib), also looked through the cookbook examples and did not find an example that covers cropping a page. I can see there is something called cropbox, but was not sure how this is supposed be used exactly and my attempt at using it caused the page size to change. Since both pdflib and iText had clear "clipping/cropping" examples, I thought maybe somebody would have a similar example for pdfbox.
Comment: http://stackoverflow.com/questions/6831194/how-can-i-remove-all-images-drawings-from-a-pdf-file-and-leave-text-only-in-java
Comment: :    cropbox,trimbox,ref:http://www.prepressure.com/pdf/basics/page_boxes. Try
Comment: thanks, i looked at that question, for some reason removing imamges code in that example would not work with the logos in my pdf's footer, anyways, I'm now thinking of using PDFStreamParser and removing tokens that match particular rules
Answer: I'm also a newbie, but take a look at this page, in particular, the description of TrimBox.  If there's no TrimBox on the page, it defaults to CropBox, which would cause what you're seeing.
In general, don't expect the PDFBox docs to tell you much of anything about PDF itself - to use PDFBox well I think you need to go elsewhere - AFAIK, mostly just to the PDF specification.  I haven't even skimmed it yet, though!
Comment: Thanks for the tip on trimBox, I tried setting it, no luck yet, still getting the sama result, ie. after I set rectangle, set both trimBox and cropBox, save, document has cut the footer, but is now no longer letter size. If I then restore the size to letter(mypage.setTrimBox(PDPage.PAGE_SIZE_LETTER)), footer comes back. It seems like there should be a function to make new size permanenent, or the ability to remove things that are not inside cropBox/trimBox. Anyways, I'll keep playing with these boxes more, thanks
Comment: @VilleM - Is MediaBox set?  I'm wondering if, in the first save, it's defaulting to CropBox.  Also, see section 14.11.2 (page 627) of [the spec](http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf) to brainstorm more ideas.
Comment: see my comment on debugging output below, in the next response, seems like all those other dimensions are ignored even though I'm setting them, only cropBox seems to matter
Answer: The CropBox is the way to go if you want to remove a portion of a page while keeping a rectangular region visible. If you want the page size to remain the same, you need the MediaBox to remain the same.
From the PDF Spec:

CropBox - rectangle (Optional; inheritable) A rectangle, expressed in default user space units, defining the visible region of default
  user space. When the page is displayed or printed, its contents are to
  be clipped (cropped) to this rectangle and then imposed on the output
  medium in some implementation-defined manner (see Section 10.10.1,
  "Page Boundaries"). Default value: the value of MediaBox.
MediaBox - rectangle (Required; inheritable) A rectangle (see Section 3.8.4, "Rectangles"), expressed in default user space units,
  defining the boundaries of the physical medium on which the page is
  intended to be displayed or printed (see Section 10.10.1, "Page
  Boundaries").

A have seen (faulty) applications and libraries that force the CropBox and the MediaBox to be the same, double check that this is not what is happening on your case.
Also take into account that the coordinates origin (0,0) in PDF is the bottom-left corner, some libraries do the translation to top-left for you, some others not, you may also want to double check this on the library you are using.
Comment: OK, thanks, I think you could be right, maybe PDFbox is not operating to the spec you describe above, I set cropbox to my cropped rectangle, I set mediabox to LETTER size, and yet, resulting PDF is cropped, but size is 11x7.64, ie, page size changed.           mypage.setCropBox(rectangle);
          mypage.setMediaBox(PDPage.PAGE_SIZE_LETTER);I will next try to debug in more detail.
Comment: Here's some debuggin output, I would think Adobe acrobat should show this in the LETTER size, but it does not, it almost looks like all the other dimensions are ignored except cropbox:
old cropBox:612.0
old mediabox:612.0
old trimBox:612.0
old bleedBox:612.0
new cropBox:550.0
new mediabox:612.0
new trimBox:612.0
new bleedBox:612.0
Comment: Can you post a link to the old file and the new file? I do not have a Java development environment ready but I could get some ideas by looking at those files.
Comment: thanks for the offer but sorry, can't share them due to the data in them, anyways, I'm now thinking of using PDFStreamParser and removing tokens that match particular rules instead of using cropBox since i can't get it to do what I'd like.
Comment: @Ville M You do not need to send me your production files, any PDF file processed by your application that shows the problem will do.


sharepoint list permissions

Question: please help with following task:
i have sharepoint list, all participants see only own records (they are can create, modify and read only own records),
i need to give permissions for two users for editing each other records only, and not allow to see other users records.
is ir possible to do with Sharepoint?
Answer: Yes, it is possible.  The best solution is to create a seperate list and only give these two people access to this list.  This creates a clean seperation between the "special" users and everyone else.
If you really want to keep everything in one list then you will need to write some custom code to reset the permissions after items are created by these two users.  You will need to break the permission inheritance for these items and remove everyone else permissions.  A little clunky but possible.
Answer: This SharePoint tool Called SharePoint Column & View Permission is a good way to cope your issue.

sharepoint list permissions


Hide block if content is empty not working

Question: I want to hide an entiere block is it has not result.
I went into my view, then I add "Contextual filter", "Empty", "Hide view".
But my view is always hidden if I do this, and I don't understand why... (I have content in this view, but it could be empty).
Do display my view, I'm using this : https://drupal-bootstrap.org/api/bootstrap/templates%21system%21region.html.twig/8
See my config :
Comment: Can you add screenshot plz ?
Comment: Looks like this is a known bug: https://www.drupal.org/node/2443457
Comment: It looks like it, but how do I fixe that ?
Answer: Up solution :
In views, go to "advanced". At the very bottom, see "hide block if view is empty". Change it to yes and it will work.
Comment: I have checked it and it is not working in my case.


How to understand (void*)0

Question: Recently in my exercise I have found a question (void*)0 answered NULL pointer how to understand this actually.
How can this be understood?
Is this is what the definition of macro NULL?
Comment: Please provide us a code snippet. I'm not really an expert, but I even don't understand what language you are using oO
Answer: Yes, actually ((void *)0) is a correct definition of the NULL pointer.

How to understand (void*)0


Using CRT to find arbitrarily long gaps between primes

Question: It is straight forward to find a gap between primes that consists of at least $2n$ using only the Chinese Remainder Theorem.
Let $p_n$ be the $n$th prime.
Find $x$ such that:
$$x \equiv -1 \pmod 2$$
$$x \equiv -2 \pmod 3$$
$$x \equiv -4 \pmod 5$$
$$x \equiv -6 \pmod 7$$
$$x \equiv -8 \pmod {p_5}$$
$$\dots$$
$$x \equiv -{2n} \pmod {p_{n+1}}$$
Clearly, not every condition is needed for the gap.  For example, $x\equiv -8 \pmod {3}$ so we could find a gap of at least $2n$ using CRT with less than $n+2$ distinct primes.
Limiting a set of equations such that every condition is needed for the gap size, it occurs to me that finding a prime gap of at least $2*p_{n}$ using CRT only need involve $n+2$ conditions each with distinct primes.
For example, a prime gap of at least $2*p_{5}=22$ can be found using the following $7$ conditions:
$$x \equiv -1 \pmod 2$$
$$x \equiv -2 \pmod 3$$
$$x \equiv -4 \pmod 7$$
$$x \equiv -6 \pmod 5$$
$$x \equiv -10 \pmod {11}$$
$$x \equiv -12 \pmod {13}$$
Using CRT, I find that $x = 9439$ which is prime and has a gap of $9461-9439 = 22$
To show how I came up with these set of conditions, let me use the following notation:
$$\#-\#-\#-\dots$$
to characterize the least prime factor of each odd integer in the gap which is not a prime.
In the above example, the gap of size $22$ consists of $10$ odd integers in the following order:
$$3-7-5-3-11-13-3-5-7-3$$
Finding a gap of $p_n$ consists of finding a set of $n+2$ CRT conditions that characterize this sequence.  For example, I can find a gap of at least $26$ using $8$ distinct conditions based on these $12$ odd integers:
$$11-3-7-5-3-13-17-3-5-7-3-11$$
It occurs to me that this approach will work for any $p_n$ using $n+2$ distinct primes as long as $2$ of the primes are greater or equal to $p_n$ and the order of the all but these two primes are the least prime factors in reverse natural order.  Natural order of the odd integers for the above would be:  $3,5,7,9,11$ with the least prime factors being $3,5,7,3,11$.  Reverse natural order of the least prime factors is therefore:  $11,3,7,5,3$.
Here's my question:
Does it follow that this method delivers the minimum number of distinct prime factors involved with a gap size of $2p_n$ or larger?
It seems to me that the answer is yes.
Let $f(m,p_n)$ be the number of distinct primes $p$ where $p < p_n$ and there exists $x$ such that $m < x \le (m+2*p_n)$ and $p$ is the least prime factor of $x$.
Does it follow that $f(m,p_n) \ge n+2$?  Is there a counter example where $f(m,p_n) < n+2$?

Edit 1:
I found a counter example for my second question.  In the case of $p_n=23$, $2*f_7(0,22) = 2$ but $f_7(76,122)=3$
Based on this, I am updating my question to just ask if there is an example of a prime gap that involve $n+1$ or less distinct least prime factors in the sequence of non-primes but is still $2p_n$ or larger.
Comment: Note with your example of $2*p_{5}=22$, you state there are $7$ conditions, but you only list $6$. I assume the $7$ was meant to be $6$ instead. Also, in your "Edit 1" section, your counter example applies *only* to your original second question. In the current version, $f$ functions with a subscript, e.g., $f_7()$, are not even defined.
Comment: We can even easier show that there are arbitary large prime gaps : The numbers $n!+2,\cdots ,n!+n$ must be composite for $n>1$ since they are all divisible by the second summand. Therefore, the gap is at least $n$. Whether every even prime gap occurs is unknown, but it is conjectured that every even prime gap occurs infinite many often.
Answer: Your idea of using the least prime factors in "reverse natural order" is a good one which always works. To see this, let $x$ be the end point of this reverse order. What you've basically done is have, for each $1 \le i \le n$, the least prime $p_i$ be specified at $x - p_i$, which gives $x - p_i \equiv 0 \pmod{p_i} \implies x \equiv 0 \pmod{p_i}$. Combining these gives $x \equiv 0 \pmod{p_n\#}$. This covers not only the primes in reverse order back to $x - p_n$, but also the ones in forward order up to $x + p_n$. As such, each integer in $[x - p_n, x + p_n]$ has at least one prime factor associated with it except for $x - 1$ and $x + 1$, which you can use with any other $2$ primes, e.g., $p_{n+1}$ and $p_{n+2}$, giving a total of $n + 2$ primes being used.
You can extend this to $[x - (p_{n+1} - 1), x + (p_{n+1} - 1)]$, for a total prime gap size of $2p_{n+1}$ using $n + 2$ integers, which reducing $n$ by $1$ gives a gap size of $2p_{n}$ using $n + 1$ integers. This answers your basic question. You show this yourself with your example of a gap of $26 = 2 \times 13$, with $13 = p_6$ so $n = 6$. Among the $12$ odd integers, you only use primes up to $p_7 = 17$, so $7 = n + 1$ primes are needed. Thus, I assume your intent is to ask about having a gap size of at least $2p_n + 2$ using just $n + 1$ primes.
Note your strategy works well basically because you're trying to optimize the average number of integers each prime covers. Since there will be overlaps where an integer is covered by more than one prime, to get the most integers covered overall involves keeping the number of integers with prime overlaps to a minimum. One way to accomplish this quite well is to have one integer with almost all the primes overlapping, e.g., $x$ with your method.
However, this strategy is not always optimal. Using your notation, consider
$$\begin{equation}\begin{aligned}
3 - 5 - 11 - 3 - 13 - 17 - 3 - 7 - 19 \; - \\
3 - 23 - 5 - 3 - 11 - 7 - 3 - 5 - 13 - 3
\end{aligned}\end{equation}$$
Here $n = 8$ since there are $p_8 = 19$ odd integers covered, giving a guaranteed prime gap size of $2 \times 19 + 2 = 40$, but it only uses the $9 = n + 1$ primes up to $p_9 = 23$.
With your $f(m, p_n)$ function, you wrote it's

... the number of distinct primes $p$ where $p < p_n$ ...

However, this would mean $f(m, p_n) \lt n$, so your question asking if $f(m, p_n) \ge n + 2$ is always true doesn't make sense. Removing the restriction $p \lt p_n$, a counter-example to your question then is $f(0, 5) = 4$ since $5 = p_3$ giving $n = 3$, and the $0 \lt x \le 10$ range has just the $4 = n + 1$ least prime factors of $2$, $3$, $5$ and $7$.


IDL READFITS() syntax error

Question: I'm trying to use the READFITS() function on IDL 8.3 on Mac 10.9.3
My input on the IDL promt:
readfits('image.fits',h, /EXTEN, /SILENT)

Result:
readfits('image.fits',h, /EXTEN, /SILENT)
                          ^
% Syntax error.

*note: the '^' is below '/EXTEN'
Maybe it will help, so here is a link to the IDL help page on using READFITS() --> http://www.exelisvis.com/docs/readfits.html
I tried using the brackets like they show on that help page, but it still didn't work, so I'm stuck now. Didn't know if anyone here has experience reading .fits files in IDL.
Answer: ok, so it turns out the readfits procedure isn't included in IDL's original library, so I just had to download AstroLib (contains lots of useful astronomy procedures - including Readfits). The original syntax then worked.
Answer: I'm using IDL 8.2.2 on OS X 10.9.4.
Try keeping it simple first. Do these work?
readfits('image.fits')
readfits('image.fits', header)

Next try this:
readfits('image.fits', header, EXTEN_NO=0)

I suspect you really want extension number 0, not 1. See (e.g.) http://www.stsci.edu/documents/dhb/web/c02_datafiles.fm2.html.
Comment: well, only including the image name and ',header' worked. But putting in any extension number caused the syntax error. I tried not putting in any extension, but keeping '/SILENT', and the syntax error just pointed to '/SILENT' then.
Comment: Ah yes, I was assuming you had AstroLib installed.

IDL READFITS() syntax error