c++ #define a macro with brackets?

Question: Instead of doing the following everytime
start();

// some code here

stop();

I would like to define some sort of macro which makes it possible to write like:
startstop()
{

//code here

}

Is it possible in C++?
Answer: You can do something very close using a small C++ helper class.
class StartStopper {
public:
    StartStopper() { start(); }
    ~StartStopper() { stop(); }
};

Then in your code:
{
    StartStopper ss;
    // code here
}

When execution enters the block and constructs the ss variable, the start() function will be called. When execution leaves the block, the StartStopper destructor will be automatically called and will then call stop().
Comment: +1. This approach is rock-solid. Even if an exception is thrown, stop() will still be called, because C++ guarantees that destructors are always called on scope exit.
Comment: Also it avoids sort of hard-to-debug problems that can occur with macros.
Comment: Btw - with MSVC++ compiler I've seen it calling a destructor before the scope was complete. It somehow detected that the variable will not be used anymore and called the destructor immediately, although there were still more things left in the scope.
Comment: +1.  The conversation in dirkgently's response is intriguing, but this is the best solution because it does not create a "secret macro language."
Comment: @Vilx: Interesting. I checked the standard and that is definitely non-conforming behaviour if the destructor has side effects (side-effect-free destruction is allowed earlier than scope exit by 126.96.36.199).
Comment: j_random_hacker: does side effects mean what I think it means here? like printing to cout, or assigning to a global? is this actually defined anywhere?
Comment: @Iraimbilanja: Yes, it means what you think it means. 1.9 para 6 says that reading/writing a volatile object or calling a library I/O function is "observable behaviour" (as is anything additionally specified by the implementation), and the compiler is obliged to perform these in the correct sequence (note that there are cases where more than 1 sequence is permitted).
Comment: @Iraimbilanja: Also para 7 says any modification of an object, reading of a volatile object, or call of an I/O function is a "side effect" and the compiler must produce observable behaviour "as if" (para 2) all side effects were completed by the next sequence point (meaning it technically could execute them in some other order, but not in such a way that anyone could ever tell).
Answer: The idiomatic way of doing this in C++ is called Resource Acquisition Is Initialization, or shortly RAII. In addition to providing what you want, it also has the added benefit of being exception safe: the stop function will be called even if your code throws an exception.
Define a guard struct:
struct startstop_guard
{
    startstop_guard()
    {
        start();
    }
    ~startstop_guard()
    {
        stop();
    }
};

and then rewrite your code this way:
{
    startstop_guard g;
    // your code
}

The guard's destructor (and thus the stop function) will be called automatically at the end of the enclosing block.
Answer: Other answers have addressed the RAII side of the question well, so I'm going to address the syntax side of it.
#define startstop for(Starter s; s.loop; s.loop = false)
struct Starter {
    bool loop;
    Starter() { start(); loop = true; }
    ~Starter() { stop(); }
};

Used like:
startstop {
    // some code
}

Should be self-explanatory enough.
Comment: indeed, i wanted to write exactly that thing too. you could also do #define startstop() if(...) ... , which would have the benefit of not touching things like  int startstop = 1; and so on. i.e a function-like macro would need parens to do substitution, which would be safer (and would also directly correspond to his wishes, and would additionally allow pushing arguments to Starter's ctor). but you still get +1 of course :)
Comment: one other thing: as of c++03, the compiler is allowed to take a copy of Starter() and bind the reference to that copy. that means, you would create two objects (one explicitly, and one created by the compiler for binding the reference to it). you would, similar to alexandrescu's scope_guard's implementation, need to introduce a mutable boolean variable which you set to false (rhs.bool_var) by a cctor and true in the default ctor, and this->bool_var by the cctor. only if it is true call end())
Comment: so something like (inverted the _guard meaning, because i think it makes more sense :)) struct Starter { mutable bool trash; Starter() : trash() { start(); } Starter(Starter const& rhs):trash(rhs.trash) { rhs.trash = true; } ~Starter() { if(!trash) end(); } operator bool() const { return false; } }. now, end is called only once, for the one that was not copied (the one that was bound to the reference).
Comment: whoa does C++ allows a copy here? weird, why would it :) Thanks for the improvement. Now the code is sufficiently complicated that I'm compelled to write an "explanation" section :)
Comment: for details, consult this one: http://www.comeaucomputing.com/iso/cwg_defects.html#391 :) that is weird. i'm glad it will change with c++1x :)
Answer: #define startstop(x, y, ...) for( /* use macro args */ )

Comment: The question specifies the signatures of start() and stop(), and requests a macro that makes the "startstop { ... }" syntax call start() at the opening brace and stop() at the closing brace. Your answer does not provide a working implementation of that. It is unclear what the /*use macro args*/ comment should be replaced with, and it's unclear how the macro arguments x and y are related to the question. FWIW it _is_ possible to make a working implementation with 'for' but you haven't done it.
Comment: +1, even if not that many people will understand the dependency injection there...
Comment: @Iraimbilanja: What is unclear and what is incomplete? The question does not specify anything about start() or stop().
Comment: you should mention that "..." syntax is c99 and not yet part of C++ (will be with c++1x)
Comment: @litb: I did not intend varargs.
@Iraimbilanja: I don't think it is possible without getting to know what start() and stop() really is.
Comment: Well, I think it's safe to assume that both start() and stop() are functions taking no arguments and returning a discardable value (or none)... and that they are scoped such that you can call them unqualified, with syntax such as "start();" -- what more do you need?
Comment: @Iraimbilanja: What tells you it's a safe assumption? IMO, macros beget macros. So, if either of start() or stop() is a macro, the for loop will not exactly be sugar.
Comment: Well there is an implementation using `for` that works for macros too. I'll spare you the details but here's the general form: #define startstop for(pair p(true, RaiiStarter()); p.first; p.first = false)
Comment: similar to this for-each loop: http://stackoverflow.com/questions/400951/c-foreach-or-similar/400970#400970
Comment: the for-version could work without that mutable thingy. like for(RaiiStarter r; r; ) then you can do  struct RaiiStarter { bool e; operator bool() const { return e=!e; } RaiiStarter():e(){ start(); } ~RaiiStarter() { stop(); } }; :)
Comment: yeah cool idea :) this is shaping up to be the nicest solution. maybe dirkgently could put it in his answer so it can get accepted.
Comment: When I saw the OP's code, my first impression was -- he wants some profiling done. Which is why I discounted any RAII stuff. But looks like you guys are having fun! Cheers.
Answer: Generic solution with RAII and boost::function ( std::function ).
class starter
{
    typedef boost::function< void () > action;
    action end_;
public:
    starter(action start, action end):
        end_(end)
    {
        log("starter start");
        start();
    }
    ~starter()
    {
        log("starter end");
        end_() ;
    }
};
int main()
{
    {
        starter s(start, stop);
        middle();
    }

    return 0;
}

or to test and check the idea
    void print(const std::string& message)
    {
        std::cout << message << std::endl;
    }
    int main()
    {
        starter s(boost::bind(print, "globalstart"),
                  boost::bind(print, "globalend"));

        {
            starter s(boost::bind(print, "start"),
                      boost::bind(print, "end"));
            std::cout << "middle" << std::endl;
        }
        return 0;
    }

Comment: +1 Nice implementation of scoped guards using boost::function, can be combined with dependency injection into a macro for a more natural usage.
Answer: What are you trying to do? I'd recommend checking out RAII as a much more C++ oriented way of doing things than macro hacking, with all its unforeseen consequences.
Answer: Don't use macros. You can use inline functions instead as it provides type checking and other features. You can take a look here: inline functions
Answer: credit to dirkgently for the idea.. I thought I'd fill the rest in
#define startstop() for(start();isStarted();stop())
Answer: In c#, you could use the IDisposable pattern, and implement your Stop() functionality in the Dispose() method, but that would would work if you were using a .net variant of c++.
Comment: eh, aside from being off-topic, C++/CLI doesn't even have the using() construct of C#.

c++ #define a macro with brackets?


How can I find $n$ such that $\sum_{k=1}^n f(k) \leq c$ without computing many partial sums?

Question: Say I have a series $\sum_{k=1}^n f(k)$ for some function $f$. I want to find the biggest $n \in \mathbb{N}$ such that $\sum_{k=1}^n f(k) \leq c$ for some $c \in \mathbb{R}$ without actually computing the partial sums. Is there a method for finding such $n$ for general $f$?
For example take
$$\sum_{k=1}^n \binom{12}{k} \frac{1}{k} \leq 400.$$
If I am not mistaken, this should hold for $n \leq 4$. How would I find this without computing the partial sums? Thanks in advance for any help.
Answer: A technique that can help to solve many complicated sums is called calculus of finite differences. If the tools of calculus are defined over infinitesimal intervals, expressed in various ways, the calculus of finite differences defines similar tools to deal with differences over discrete intervals.
Using calculus of finite differences, you can reduce complex sigma expressions into integrals, or directly reduce them using the similar tools you'd use to find an anti-derivative.
There is actually not as much information about the calculus of finite differences as I'd hoped. However, after searching a bit, I found the wonderful article that introduced me to the subject, and a few more. Its name will no doubt sound rather appealing.
A Tutorial for Solving Nasty Sums - A wonderful article that provides a detailed, but not too technical look at calculus of finite differences as used to solve various sigma expressions.
Introduction to Difference Equations - A more comprehensive book about the topic. Not everything here is directly relevant.
Concrete Mathematics - Another rich book on the topic. Also contains identities specifically regarding binomials and binomial sums. Alas, nothing to compute the example problem.
Additional information and methods of finite calculus:
Indefinite Sum, Wikipedia - Wikipedia article. Has a good overview of indefinite sums and several useful identities and rules.
Euler-Maclaurin Formula, Wikipedia - Which defines a relation between the integral of a function and the indefinite sum of a function. Highly powerful for evaluating indefinite sums.
The problem posed in the question is an example that probably can't be solved using finite calculus, because the sum $\sum_{k}^{m} \binom{n}{k}$ doesn't have a closed form representation.
as far as I know, this specific sum cannot be computed without also computing all the partial sums.
Still, I hope this information helps you out.
Comment: Can you show how to apply this method to this particular problem?
Comment: I've edited my answer to provide additional information, and also pointed out (and realized, actually) that there is no way to solve the example sum using this method.


Asp.net MVC + NoSQL Database

Question: Is there any good/simple asp.net MVC application that uses NoSQL database(cassandra). Any suggestion.
Answer: I could not find a specific example, but perhaps using a linq provider like Cassandraemon  will help align the many existing ASP.NET MVC examples with using a Cassandra database.
Answer: This is a late answer, but I came across it and thought it would be useful.
Chirper

Asp.net MVC + NoSQL Database


jQuery ajax post data with javascript submit form

Question: This is my code:

<?php
include('header.php');
?>

 <form name="search" id="searchForm" method="post">
 ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:

 <input type="text" name="my_site"/></form>

PAGE RANK

The problem is the ajax post works perfect if I use a submit button in the form.It doesn't work if I use a sub_form() method to submit the form after on click event.My doubt is will the java script sub_form() method trigger the jquery ajax function or not?
Note:
The data returned by the post url is
echo ""
Comment: The name and id of the form should be the same, unless you know 110% what you're doing.
Comment: @Jonast92 This is first time I am hearing something like that....r u serious?
Comment: @Jonast92 what are you talking about?
Comment: @Jonast92 has html changed itself?
Comment: I think you might find your answer here http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form
Comment: @NaeemShaikh27 Nope my question is different my ajax works if I use the default form submit button I want to know how to make it work if I use a js submit function.
Comment: Check your browser's console for errors...
Answer: document.forms[].property

This returns an array of all the forms in the current document.
Since it is a array, you should pass the index value as integer.
document.forms[0].submit();
this will submit the form, if you have this form as your first form in the html page from top.
Comment: Nope document.forms["name_of_form"].submit() is a perfectly valid method to submit the form and what you have mentioned is  no way relevant to what I asked.


Categories like $\mathsf{FinSet}$, but with elements of $\mathbb{Z}$ or $\mathbb{Q}$ as objects?

Question: Suppose, we do universal algebra in a "non-evil" fashion, such that every algebra carries around an equivalence relation $\cong$ that poses as equality and such that size issues don't matter (we may have proper classes as underlying "sets").
If we consider the category of finite sets with binary products $\times$, binary coproducts $+$, the empty set $0 := \emptyset$ and some one-element set $1$ together with isomorphy (is that a word?) of objects $\cong$, we get the rig (or semiring if you will) of natural numbers.
Are there "nice" and "interesting" categories equipped with finite products and coproducts that in the same fashion yield the ring of integers or the field of rationals?
I'm afraid, that this question may have a really easy answer, however...
Comment: "isomorphism" is the word
Comment: @Berci I thought "Isomorphism" refers to a morphism and not to an equivalence relation between objects.
Answer:
I'm afraid, that this question may have a really easy answer,
  however...

Unfortunately it does. Assume $A×B ≅ 1$ (the terminal object). Then for every $C$ we have $$1 ≅ \mathrm{Hom}(C, 1) ≅ \mathrm{Hom}(C, A × B) ≅ \mathrm{Hom}(C, A) × \mathrm{Hom}(C, B),$$
so $\mathrm{Hom}(C, A)$ and $\mathrm{Hom}(C, B)$ are both one-element sets, and $A$ and $B$ both terminal (you can easily show this directly). Dually, $A + B = 0$ implies $A$, $B$ initial. You will find some ideas on categories that represent $ℤ$ and $ℚ$ by googling categorification of integers/rationals. They will necessarily be more complicated than this however.


How to add js in view created by interface

Question: I want to create a new button control in my ip_geoloc leaflet map. So, i created a view by using the drupal interface -> /admin/structure/views/view/markers_admin/edit
And now i want to set a custom JS wich execute only in this view. I've create a module to create custom form. And my goals are when the user click on the button control in the map, a modal pop with a form with lat/lng field to add dynamically the marker on the map.
I searched everything (how to create a modal -> colorbox, how to create a custom button, how to add the marker...) but i don't know how to attach the javascript to this page.
I've tried to implements these hooks (4th comments) in my custom module but this not work : https://www.drupal.org/node/1993228
Can you help me ?
Answer: If you are following that 4th comment exactly the problem is probably that it is a hook for viewing a node, not for a 'view'. Ambiguous to be sure.
The accepted answer here should be helpful: How do I add JavaScript specific for a view?.
EDIT
Okay, this may be more helpful. The trick here is finding a place to hook in to check to the page before it is rendered to add the javascript to the render array. The assumption this code makes (which may not be accurate) is that you are looking at a views page. If the view is nested in a block or a panels pane this may not work as well.  Here goes:
<code>/**
 * Implements hook_page_alter().
 */
function food_truck_form_page_alter(&$page) {
  $views_page = views_get_page_view();

  if ($views_page->name == 'marqueurs_admin') {
    $path = drupal_get_path('module', 'food_truck_form' );
    $page['#attached']['js'][] = array(
      'type'=>'file',
      'data' => $path . 'js/food_truck_form.js'
    );
  }
}
</code>
This also assumes that you are implementing it in a module called food_truck_form and your view is named 'marqueurs_admin'.
Also, as a side-note, it often works better formatting-wise to edit your post to add the additional info there rather than in the comments.
Comment: i've code this `function food_truck_form_views_pre_render(&$view) {
  // check to make sure the view has a classname
  if ($view->display_handler && ! empty ( $view->display_handler->options ['css_class'] )) {
    $cln = $view->display_handler->options ['css_class'];
    $cls = 'view-marqueurs-admin';
    // test that the classname contains our class
    if (preg_match ( '/(^|\s+)' . preg_quote ( $cls ) . '(\s+|$)/i', $cln )) {
      drupal_add_js ( drupal_get_path ( 'modules', 'food_truck_form' ) . 'js/food_truck_form.js' );
    }
  }
}` but this isn't work :/ ps sorry for the lack of indent
Comment: and i try this : `function food_truck_form_views_pre_render(&$view) {
  if ($view->name == 'marqueurs_admin') {
    drupal_add_js(drupal_get_path('modules', 'food_truck_form') . 'js/food_truck_form.js');
  }
}` and this : `function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  if ($view->name == 'marqueurs_admin') {
    drupal_add_js(drupal_get_path('modules', 'food_truck_form') . 'js/food_truck_form.js');
  }
}`
Comment: I have updated my suggestion. If the assumptions made are wrong - chiefly where this view is being used - let me know and we'll find a different place to hook in.
Comment: IDK why but this not work :/ it's strange... i access to this url http://localhost/drupal/marqueurs-admin wich is the 'marqueurs_admin' view (it's the right name, i do a var_dump(views_get_page_view()->name) in my view and it show the right machine_name. In all hooks if i do var_dump(views_get_page_view()->name) it show nothing :/ it's a bit strange...
Comment: Maybe i solve the problem... https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_page_alter/7.x first comment : Refresh cache... thanks, every solutions works correctly when i refresh the cache ;)
Comment: Glad to hear it!


Add custom font to mpdf while using PDF using mPDF module

Question: I made a custom module to create a PDF from a views page. This module depends on PDF using mPDF. I'm now trying to add a custom Google font. This should be the default font when generating a pdf. But I can't find out what I should do to have a custom font used in the PDF.
The mPDF documentation gives me an example of what I should do to load the custom font. I tried adding this in a custom function called right before generating the pdf but it doesn't work.
I both tried adding the font as default font to the setting (as shown in the example) or/and via css just using font-family: aller, none of it worked till now.
So my question is, am I using the code snippet in the right way? Or what can I do to get this to work?
My code:
GenerateViewsPdf.php -> Controller
<?php

namespace Drupal\views_pdf\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\pdf_using_mpdf\Conversion\ConvertToPdf;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GenerateViewsPdf extends ControllerBase
{
  /**
   * @var ConvertToPdf
   */
  protected $convertToPdf;

  /**
   * Inject ConvertToPdf service
   *
   * GeneratePdf constructor.
   * @param ConvertToPdf $convert
   */
  public function __construct(ConvertToPdf $convert)
  {
    $this->convertToPdf = $convert;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('pdf_using_mpdf.conversion')
    );
  }

  public function generateviews($arg = NULL, $views_name = NULL, $display_id = NULL)
  {
    addFont();
    $settings = $this->convertToPdf->getConfig();
    $settings["pdf_font_size"] = '10mm';
    $settings["default_font"] = 'aller';
    $settings["orientation"] = 'landscape';
    $settings["pdf_css_file"] = __DIR__ . "/../../css/style.css";

    $rendered_view = \Drupal::service('renderer')->render(views_embed_view($views_name, $display_id, $arg));
    $this->convertToPdf->convert($rendered_view, $settings);
    return true;
  }
}

function addFont(){
  $defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
  $fontDirs = $defaultConfig['fontDir'];

  $defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
  $fontData = $defaultFontConfig['fontdata'];
  $mpdf = new \Mpdf\Mpdf(
    [
      'tempDir' => __DIR__ . '/../../upload',
      'fontDir' => array_merge($fontDirs, [
        __DIR__ . '/../../fonts'
      ]),
      'fontdata' => $fontData + [
          'aller' => [
            'R' => 'aller_rg-webfont.ttf',
            'I' => 'aller_it-webfont.ttf',
          ],
        ],
      'default_font' => 'aller'
    ]
  );
}

——UPDATE——
I just tried adding the fontdata directly to the mpdf code in the vendor folder and this works perfectly so the font files work fine. And the idea of adding the fontdata is fine. But I don't know where to inject this code to make it work.
Answer: Using the method I tried didn't work because I added the font to the other mPDF object than used when generating the pdf. The trick is to add the fontdata and fontDir to the setting when the new Mpdf() is created in the ConvertToPdf.php file in the PDF using mPDF module. This can simply be done by adding the fontdata and fontDir to the $settings before calling $this->convertToPdf->convert($rendered_view, $settings);
So the final solution looks like this:
<?php

namespace Drupal\views_pdf\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\pdf_using_mpdf\Conversion\ConvertToPdf;
use Symfony\Component\DependencyInjection\ContainerInterface;

class GenerateViewsPdf extends ControllerBase
{
  /**
   * @var ConvertToPdf
   */
  protected $convertToPdf;

  /**
   * Inject ConvertToPdf service
   *
   * GeneratePdf constructor.
   * @param ConvertToPdf $convert
   */
  public function __construct(ConvertToPdf $convert)
  {
    $this->convertToPdf = $convert;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container)
  {
    return new static(
      $container->get('pdf_using_mpdf.conversion')
    );
  }

  public function generateviews($arg = NULL, $views_name = NULL, $display_id = NULL)
  {
    $settings = $this->convertToPdf->getConfig();
    $settings["pdf_font_size"] = '10mm';
    $settings["default_font"] = 'aller';
    $settings["orientation"] = 'landscape';
    $settings["pdf_css_file"] = __DIR__ . "/../../css/style.css";

    //start adding custom font
    $settings["fontDir"] = __DIR__ . '/../../../../custom/views_pdf/fonts';
    $settings["fontdata"] = ['aller' => [
        'R' => 'aller_rg-webfont.ttf',
        'I' => 'aller_it-webfont.ttf',
    ]];
    //stop adding custom font

    $rendered_view = \Drupal::service('renderer')->render(views_embed_view($views_name, $display_id, $arg));
    $this->convertToPdf->convert($rendered_view, $settings);
    return true;
  }
}


What values of $n$ is $A=\frac{a_1}{a_2}+\frac{a_2}{a_3}+\cdots +\frac{a_{n-1}}{a_n}+\frac{a_n}{a_1}$ an integer?

Question:
Suppose $a_i\in \mathbb{N} $ such that $a_i\ne a_j$ and $\displaystyle\frac{a_i}{a_{i+1}}\ne \frac{a_j}{a_{j+1}}~$ for $i \ne j$ $($take $a_{n+1}=a_1)$ and $\displaystyle A=\frac{a_1}{a_2}+\frac{a_2}{a_3}+\cdots +\frac{a_{n-1}}{a_n}+\frac{a_n}{a_1}$.
Then for what values of $n\ge  2$ can $A$ be an integer?

I  found that if $a_i=(n-1)^i$ then $A$ is a integer but I realised that this  violates the condition $\displaystyle\frac{a_i}{a_{i+1}}\ne \frac{a_j}{a_{j+1}}~$. It was easy to prove that $A$ is not an integer  for $n=2$, but I was stuck for the cases where for $n>2$. I then I plugged in some values for $a_i$ but for $n>2$ but I found no solution.
Intuitively I think there is no solution but I am unable to prove it. Any help would be appreciated.
Edit-1: As pointed out by @WillJagy it is possible for $n=3,4,5$. So can we actually prove it is true for $n>6$ or are there some $n>6$ for which it isn't true?
Edit-2: I was able to find a solution for $n=5$ from a solution for $n=4$.
$$~~~~~~~~~~\frac{6}{4} + \frac{4}{3} + \frac{3}{1} + \frac{1}{6}  = 6$$
$$\implies \frac{2}{4} + \frac{4}{3} + \frac{3}{1} + \frac{1}{6}  = 5$$
$$\implies \frac{6}{2} +\frac{2}{4} + \frac{4}{3} + \frac{3}{1} + \frac{1}{6}  = 8$$
But I could not find a solution for $n=6$ from a solution for $n=5$  because when I rewrite  $\frac{4}{3} =1+\frac{1}{3}$, the $1$ in the numerator of $\frac{1}{3}$ is used by another $a_i$. I don't know whether we can prove by induction. Any suggestions is welcome.
Comment: https://artofproblemsolving.com/community/c6h114708p651437
Comment: @FearfulSymmetry This question has an additional constraint of $\displaystyle\frac{a_i}{a_{i+1}}\ne \frac{a_j}{a_{j+1}}~$
Comment: Sure; try and start there and see if you can eliminate some of the general solutions.
Answer: $$ \frac{81}{2} + \frac{36}{81} + \frac{2}{36}  = 41  $$
$$ \frac{98}{12} + \frac{63}{98} + \frac{12}{63}  = 9  $$
$$ \frac{6}{4} + \frac{4}{3} + \frac{3}{1} + \frac{1}{6}  = 6  $$
$$ \frac{6}{5} + \frac{5}{3} + \frac{3}{10} + \frac{10}{12}  + \frac{12}{6} = 6  $$
$$ \frac{3}{12} + \frac{12}{9} + \frac{9}{10} + \frac{10}{8}  + \frac{8}{5} + \frac{5}{3} = 7  $$
$$ \frac{2}{8} + \frac{8}{10} + \frac{10}{6} + \frac{6}{5}  + \frac{5}{4} + \frac{4}{3} + \frac{3}{2}= 8  $$
Comment: @Asher2211 I just wrote a program. It's worth checking something before trying to prove it; with integers, pretty firm indications can come from a computer. There is probably some sort of order to these, the only integers I've gotten ( with 3 variables) are  9, 41, 66
Comment: @Asher2211 alright. I forgot that condition. I suspect it will force the $a_i$ to be a bit larger, but the job seems to be getting easier with more variables. As far as your wish for a proof,  it is a bit early to be asking about that, given that you began in the opposite direction. If it is important, you will write your own programs and look for patterns.
Comment: What was your approach for finding these numbers?
Comment: Have you assumed $a_i$ to be ordered in the program? I got $6$ with $a = (2, 12, 9)$ and it seems to follow the restrictions.
Comment: @AnilCh good point, I did have them ordered, apparently that was not a valid restriction.
Comment: @WillJagy  Can we prove that it is possible for every $n>2$  or is it just too hard to prove it.
Comment: @WillJagy $\frac{10}{5} + \frac{5}{6} + \frac{6}{5} + \frac{5}{3} + \frac{3}{10}  = 6$ here $a_2=a_4$
Answer: I guess you do not want any ratio $a_i/a_{i+1}$ to be an integer, otherwise trivial solutions can be produced.
For $n=3$, a solution can be produced as already seen in the answers.
We will use Egyptian fractions to prove that there always exists a sequence of such $a_i$'s for $n\gt 3$
$$1=\frac 12+\frac 13+\frac 16$$
We can break the last unit fraction $\dfrac 16$ using the fact that $\dfrac 1m=\dfrac 1{m+1}+\dfrac 1{m(m+1)}$
In this way, you can create an Egyptian fraction representation (with distinct unit fractions) for $1$ of arbitrary length, ie, for any $n\gt 3$, there exist a sequence of distinct $p_i (\neq 1)$'s ($i=1...(n-1)$) such that $1=\displaystyle\sum_1^{n-1}\frac 1{p_i}$
All that is left is to define our $a_i$'s in a suitable way. We define $a_1=1$ and $a_{i+1}=a_ip_i$ for all $i=1...(n-1)$ so that all the $a_i$'s are distinct and $\dfrac{a_i}{a_{i+1}}=\dfrac 1{p_i}$ are distinct for all $i=1...(n-1)$ and sum up to $1$ and $\dfrac{a_n}{a_1}=a_n$ is an integer, so the resulting sum $A=a_n+1$
Examples:
$$\frac 12+\frac 26+\frac 6{36}+\frac{36}1=37\\ \frac 12+\frac 26+\frac 6{42}+\frac{42}{1764}+\frac{1764}1=1765$$
Here's a Tio.run link if you want to generate a sequence of $a_i$'s for any $n$, but beware that the $a_i$'s grow larger quite quickly due to the construction.

Hmm, then again, perhaps this answer also generates trivial solutions because $a_n/a_1$ is an integer. I'm unsure if I can fix that. I'll update if I can.
Answer: $$\frac{3}{2}+\frac{4}{3}+\frac{5}{4}+\frac{6}{5}+\frac{15}{6}+\frac{24}{15}+\frac{10}{24}+\frac{2}{10}=10$$
$$\frac{3}{2}+\frac{4}{3}+\frac{5}{4}+\frac{6}{5}+\frac{7}{6}+\frac{30}{7}+\frac{14}{30}+\frac{24}{14}+\frac{2}{24}=13$$
$$\frac{3}{2}+\frac{4}{3}+\frac{5}{4}+\frac{6}{5}+\frac{7}{6}+\frac{9}{7}+\frac{36}{9}+\frac{15}{36}+\frac{42}{15}+\frac{2}{42}=15$$
$$\frac{3}{2}+\frac{4}{3}+\frac{5}{4}+\frac{6}{5}+\frac{7}{6}+\frac{9}{7}+\frac{10}{ 9}+\frac {28}{ 10}+\frac {27}{ 28}+\frac {36}{ 27}+\frac {2}{ 36}=14$$


ASP.NET Core Identity - Confirm email return url

Question: I've managed to set up SignUp and LogIn for my project with ASP.NET Core Identity. Everything works fine but there is a small thing really bugging me.
Since it is a simple project I don't want to configure account confirmation by really sending email to the user so I'm using the default templates, the user is redirected to the Account.RegisterConfirmation where they can select a link to have the account confirmed which redirects the user to the /Identity/Account/ConfirmEmail which is a blank page with the title only. I don't like it. After selecting a link to confirm the account I'd like to redirect the user to the /Account/Login. But where do I set that up?
This is what I've tried so far: Add>New Scaffolded Item>Identity>Account/ConfirmEmail(file to override) and I now I have ConfirmEmail.cshtml.cs:
[AllowAnonymous]
    public class ConfirmEmailModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;

        public ConfirmEmailModel(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }

        [TempData]
        public string StatusMessage { get; set; }

        public async Task<IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return RedirectToPage("/Index");
            }

            var user = await _userManager.FindByIdAsync(userId);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{userId}'.");
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);
            StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
            return Page();
        }
    }

Changing return Page(); to return RedirectToPage("/Account/Login"); results in InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Project.Areas.Identity.Pages.Account.ConfirmEmailModel'.
Where do I set up the return url to /Account/Login after the email is confirmed?
I also tried without Scaffolding and overriding Account/ConfirmEmail, in Register.cshtml.cs there is
 var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

and I tried changing  returnUrl = returnUrl to returnUrl = "~/Account/Login" , it didn't work.
**** UPDATE ***
Since I don't need email confirmation for such a simple project I just added this
options.SignIn.RequireConfirmedAccount = false

to the Startup class so account confirmation nor email confirmation is needed.
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
                    .AddEntityFrameworkStores<ProjectContext>();

services.Configure<IdentityOptions>(options =>
{
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedAccount = false;
});

Comment: @RohitKumar I just noticed that it does not work for return Page() also, actually after  Add>New Scaffolded Item>Identity>Account/ConfirmEmail(file to override) I get  InvalidOperationException even if I do not make any changes to the ConfirmEmail.cshtml.cs
Comment: does it works fine for return Page();  I am seeing the error message is for the DI....
Comment: try adding a tilde '~' to the url like return RedirectToPage("~/Account/Login")
Comment: @JonathanAlfaro it also doesn't work with ~
Comment: the error is with DI .....does the execution even reaches till **var result = await _userManager.ConfirmEmailAsync(user, code);**
Answer:
I'm using the default templates, the user is redirected to the Account.RegisterConfirmation

In default code of configuring Identity service, we would find that RequireConfirmedAccount option is set to true, like below.
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

And we can find that user will be redirected to RegisterConfirmation page after user account is create in RegisterModel class page handler.
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
    return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{

it is a simple project I don't want to configure account confirmation

If you do not need account confirmation, you could not set
RequireConfirmedAccount property (defaults to false) of SignInOptions while you configure Identity service.
services.AddDefaultIdentity<ApplicationUser>()
        .AddEntityFrameworkStores<ProjectContext>();

Or as you did, set SignIn settings explicitly.
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<ProjectContext>();

Besides, we can find that you call services.AddDefaultIdentity<ApplicationUser>(...) to configure Identity service with your custom ApplicationUser class in Startup ConfigureServices method, but you inject an instance of UserManager within ConfirmEmailModel class using UserManager<IdentityUser> (should use UserManager<ApplicationUser>), which cause the exception.


How to create custom field in ubercart 3.x checkout page?

Question: I want to customize checkout page and remove/add some fields from client information.
How can I do it?
Answer: I found the Extra Fields Checkout Pane module.

This module allows an administrator to define additional (billing and shipping) address fields as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.
  This module has been developed and tested with Ubercart 2.6.


Derived tensor product , independence of resolution

Question: Right after Lemma 20.26.13
We have the following paragraph of how to derive the tensor product.

It  claims that the end result is independent of choice of K-flat resolution
Suppose we take $L^\bullet \rightarrow F^\bullet$, then we have to show a quasi iso.  $$Tot(G^* \otimes K^*) \simeq Tot(G^* \otimes L^*)$$
This would follow if we can exhibit a map $K^* \rightarrow L^*$ (or vice versa) and apply 20.26.13, but this is unclear to me.

What am I missing?
Some explaination would be appreciated.
Answer: Suppose $\alpha_K:K^*\to F^*$ and $\alpha_L:L^*\to F^*$ are two $K$-flat resolutions of $F^*$.
As one typically proves when constructing the derived category (see Prop. 10.4.1 of Weibel's Introduction to Homological Algebra, for example) there is a complex $G^*$ with quasi-isomorphisms $\beta_K:G^*\to K^*$ and $\beta_L:G^*\to L^*$ such that $\alpha_K\beta_K$ and $\alpha_L\beta_L$ are chain homotopic.
Let $\gamma:M^*\to G^*$ be a $K$-flat resolution of $G^*$. Then $\beta_K\gamma:M^*\to K^*$ and $\beta_L\gamma:M^*\to L^*$ are quasi-isomorphisms of $K$-flat complexes, so you can now apply Lemma 20.26.13 of the Stacks Project.


Tooltips stop working after an ajax call

Question: I'm using this jQuery snippet to create tooltips on some JSF primefaces elements in an html table.
$(document).ready(function() {

    $('.ui-icon-pencil, .ui-icon-check, .ui-icon-close, .ui-icon-trash').hover(function(e) {    // this is the hover in function

        // Since the elements have multiple classes, this function gets the one that starts with ui-icon-<something>
        var icon = $(this).attr('class').match(/ui-icon-(?:pencil|check|close|trash)/)[0];
        var title = null;

        if(icon == 'ui-icon-pencil') {
            title = 'Edit';
        } else if(icon == 'ui-icon-check') {
            title = 'Save';
        } else if(icon == 'ui-icon-close') {
            title = 'Cancel';
        } else if(icon == 'ui-icon-trash') {
            title = 'Delete';
        }

        $('body').append('
'+title+'
');
        $('.tooltip').css('top', (e.pageY-50) + 'px').css('left', (e.pageX-10) + 'px').fadeIn('fast');
    }, function() { // this is the hover out function
        $('.tooltip').remove();
    });

    // this handles the tooltip moving when the mouse moves
    $('.ui-icon-pencil').mousemove(function(e) {
        $('.tooltip').css('top', (e.pageY-50) + 'px').css('left', (e.pageX-10) + 'px');
    });
});

This works great except that if you either modify/add/delete a row in the table via jsf ajax magic, the tooltips stop working.
How can i keep the tooltips working after modifying/adding/deleting a row in the table?
I'm think i should be using jquery's live function to keep the tooltips working, but i'm not sure how i would use them in this circumstance.
Answer: Most likely the handlers are lost when you modify the table row (via jsf ajax magic). Try using .on like below and let us know the results,
Note: Below is for jQuery version 1.7. Use .live or .delegate if you using older version of jQuery.
$(document).ready(function() {

    $(document).on('mouseenter', '.ui-icon-pencil, .ui-icon-check, .ui-icon-close, .ui-icon-trash', function(e) {    // this is the hover in function

        // Since the elements have multiple classes, this function gets the one that starts with ui-icon-<something>
        var icon = $(this).attr('class').match(/ui-icon-(?:pencil|check|close|trash)/)[0];
        var title = null;

        if(icon == 'ui-icon-pencil') {
            title = 'Edit';
        } else if(icon == 'ui-icon-check') {
            title = 'Save';
        } else if(icon == 'ui-icon-close') {
            title = 'Cancel';
        } else if(icon == 'ui-icon-trash') {
            title = 'Delete';
        }

        $('body').append('
'+title+'
');
        $('.tooltip').css('top', (e.pageY-50) + 'px').css('left', (e.pageX-10) + 'px').fadeIn('fast');
    });

    $(document).on('mouseleave', '.ui-icon-pencil, .ui-icon-check, .ui-icon-close, .ui-icon-trash', function() { // this is the hover out function
        $('.tooltip').remove();
    });

    // this handles the tooltip moving when the mouse moves
    $(document).on('mousemove', '.ui-icon-pencil', function(e) {
        $('.tooltip').css('top', (e.pageY-50) + 'px').css('left', (e.pageX-10) + 'px');
    });
});

Comment: Assuming he is using 1.7+, this would be my guess.
Comment: @MatthewBlancarte True, Added Note mentioning that it is for jQuery 1.7. Thanks!
Comment: jQuery 1.7.x is included since PrimeFaces 3.2. So if OP is using 3.2 or newer, s/he should be all set.
Comment: I'm using primefaces 3.0.1 so i must not be using 1.7. Your code seems to work for the most part (using delegate instead of on). The only issue now is that I'm seeing multiple tooltips.
Comment: @Catfish mm interesting, are u seeing different tooltips when you hover on 1 of those item?
Comment: I changed it from hover to mouseover/mouseout. Works like a charm.
Comment: @Catfish I forgot to convert the mouseleave function where you were removing the tooltip. Try to use .delegate on mouseleave like above and it should work well.
Answer: Are you adding/removing elements with one of the classes that should show a tooltip on hover after you've done the ajax-call (changing the DOM)?
Eventlisteners are by default bound to the elements that are in the DOM at that moment. You indeed shoud use live, or even better: delegate.
I will post an answer that bounds the eventlistener to the body, but if you have, for instance a deeper nested wrapper-element that will contain al the child-elements that should have the tooltip, then you should bind the eventlistener to that.
$("body").delegate('.ui-icon-pencil, .ui-icon-check, .ui-icon-close, .ui-icon-trash', 'click', function(event){
// Just do the things you would do in a normal .hover-event that is binded to these classes
});

Answer: Warning: I don't know JSF
You would need to rebind the mousemove event to the loaded content.
JSF will probably offer a callback to achieve this. This link looks promising: http://javaserverfaces.java.net/nonav/docs/2.0/jsdocs/symbols/jsf.ajax.html#.addOnEvent
Apparently Primefaces has an oncomplete attribute for this purpose:

Maybe that will help you?
Answer: The hover events aren't bound to the new elements added by an ajax call.
You will have to manually add the hover function to those newly added elements.
I don't really advocate it, but it will probably work when you run the code you posted above after every ajax call. Just be aware that you will probably have bound the event twice on some elements, which will sometimes produce some strange bugs.


What are JCL Alternitives for Embeded Applications?

Question: What are modern alternatives for IBM's old JCL (Job Control Language) scripting language?
For the past several years a client is working on a rewrite/overhaul of their old Mainframe system porting over to the cloud. The rewrite is largely in C# .NET Framework, with a smattering of C++ creating a VM simulating the old mainframe on Azure servers. Right now they are running their old JCL to handle large parts of their database in the new rewrite.
For those that aren't as familiar with JCL in a legacy environment, the client is using it to point to parts of the database, call applications/processes with parameters, and pipe file-I/O to/from the relative applications. It pretty much reads like the old punch-cards, and doesn't have any personal processing power (basic arithmetic/logic key words, memory handling, or use of any kind of module/library expansions).
Right now their looking at Lua or TCL as potential replacements to embed in their new system.
What are alternative languages you have used for process control scripting? Pros? Cons?
Comment: Any scripting language would solve a scripting task :-)  Lua is the most easy to embed in a C host application, but has very few ready-to-use libraries.
Comment: First, JCL does have some of those capabilities, and second, JCL isn't a scripting language.  REXX is a scripting language.  JCL is much more analogous to a CLI for z/OS, where you're specifying a program to run, various arguments to the program, and information about what data to run the program against.  There's some amount of macro/symbol capability.
Answer: You might also look at Python or (given that you're also using C# and so probably considering running on Windows) Powershell. In a Unix environment, bash would be the first option (even if it was one you then reject).
This isn't something that has a definite answer though, at least with the small amount of information you have provided; there are lots of options. As long as you have language or basic library support for the operations you need, you should be able to make that work.
Comment: What job control advantage does Python have over some of the other embedded scripting languages mentioned above?
Comment: I had proposed Powershell to them a while back, but they felt that it was to complex to hand to their product servicing team. Thus the interest in Lua for it's simpler syntax, and ease to learn.


compilation error "diamond operator is not supported in -source 1.5" when mvn install

Question: I am developing a java project and every thing working fine, then once I needed to change the version of a library I use. When I run mvn install a compilation error appeared:

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Users/marwa/eclipse-workspace-photon/OntologyReuseProject/src/main/java/OntologyMatchingPackage/AMLMappings.java:[94,61] diamond operator is not supported in -source 1.5
(use -source 7 or higher to enable diamond operator)
[ERROR] /C:/Users/marwa/eclipse-workspace-photon/OntologyReuseProject/src/main/java/OntologyMatchingPackage/OntologyMatchingAlgorithm.java:[42,60] diamond operator is not supported in -source 1.5
(use -source 7 or higher to enable diamond operator)
[INFO] 2 errors

I am using Java 1.7 and also after this error I try to use 1.8 but the error still appear although the project is running correctly . How to solve this compilation error?
Comment: Add the relevant pom please.
Comment: Does this answer your question? [Specifying java version in maven - differences between properties and compiler plugin](https://stackoverflow.com/questions/38882080/specifying-java-version-in-maven-differences-between-properties-and-compiler-p)
Answer: This error is most likely caused by a wrong or missing source version in the maven-compiler-plugin configuration in your project's pom.xml file. You should set the source property to at least 1.7, as the diamond operator was introduced in Java 7.
Example configuration:
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <showDeprecation>true</showDeprecation>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

Comment: But still give me errors although the project runs normaly from eclipse
The errors are:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project OntologyReuseProject: Compilation failure: Compilation failure:
[ERROR] /C:/eclipse-workspace-photon/OntologyReuseProject/src/main/java/OntologyMatchingPackage/AMLMappings.java:[8,11] package aml does not exist
[ERROR] /C:/eclipse-workspace-photon/OntologyReuseProject/src/main/java/AgentClasses/ConceptUtilityClass.java:[8,38] package org.coode.owlapi.rdfxml.parser does not exist
Comment: seems as it can not see some packages although they exist and nothing changed!
Comment: Solved. I had a java version mismatch ,so I have corrected it and i am able to build successfully.


I/O Fail of unsigned char typed variable

Question: I have a file named input.in. I need to read the number and store it in an unsigned char typed variable. I read in the number and print the content of the variable on the screen and I can see it's true(prints 1). However, the if statement fails. It prints False to the stdout. Why does this happen? How can I store this number into an unsigned char variable?
The input.in file:
asus@ubuntu:~/Desktop$ cat input.in
1

I work on Ubuntu. sizeof(unsigned char)=1
#include <fstream>
#include <iostream>

using namespace std;

int main(){

    unsigned char ucbuffer;

    fstream in;

    in.open("input.in",ios::binary | ios::in);

    in.read((char*)&ucbuffer,1);

    cout << ucbuffer << endl;
    if (ucbuffer==1) cout << "True" << endl;
    else cout << "False" << endl;

        return 0;
}

Answer: if (ucbuffer==1) is false. The value is '1', not 1. The numerical value of '1' is 49.
Comment: But with the statement in.read((char*)&ucbuffer,1); why is it treating it as a character? Also I opened the file in binary mode.
Comment: It doesn't matter in what mode you opened the file, what matters is what's inside, and inside you have the character '1'. That's what you're reading, and that's what you're getting. If you want it to be converted to a value 1 you need to perform formatted read.


Elemento fora do dialog

Question:
Como faço para exibir uma ul/div que esta dentro do dialog?
Observe no canto inferior direito do dialog

    <button id="status-candidato">Run last action</button>  <button id="select">Select an action</button>

Open...

Save

Delete

Answer: Acredito que da pra consertar isso com o z-index:
#dialog {
    display: block;
    z-index: 9999;
}

Comment: não da já tentei diversas formas com css (word-wrap,display, z-index, overflow), parece que o dialog delimita a div
Answer: CONSEGUI!!
#dialog {  overflow: visible; }
.ui-dialog { overflow: visible; }

tem que forçar a class do dialog a exibir

Elemento fora do dialog


Getting two sender values instead of one for particular case?

Question: I am having a IBAction for 4 buttons which represent 4 available answers and each time I press a button I read the sender ID, then it figures out if answer is correct and so on.
Now I have a special case, when another button (nothing in common with those 4 buttons) is pressed, it waits for two of these answers, checks if one of them is correct( i know how to do that) and then the program continues running.
So for now, I have :
- (IBAction)answerButtonPressed:(id)sender {
    NSString* answer= [[sender titleLabel] text];

   //checks if answer key is equal to a1 ( which is always the correct answer )
    if([[currentQuestionUsefulVariable valueForKey:@"a1"] isEqualToString:answer] ){

        correctQuestionsCount1 ++;
    }
    //answer is wrong
    else{
        wrongQuestionsCount1 ++;
    }
}

As you see I store the answer string in a variable called answer
And again - All I need is to store two answers and check the two of them when this special button is pressed. I will of course put a boolean variable to indicate when it is pressed and it will do the work.
EDIT:
The two answer thing is when I press a specific joker button and it gives the advantage to the user to chose two of four available answers. This is why I need to do that. For any other cases I need only one answer at a time.
Any ideas ?
Answer: Well you're going to need an instance variable, the value of which persists throughout the lifetime of the object, and perhaps using a mutable array of the answers is the way forward:
@interface MyViewController ()
{
    NSMutableArray *_correctAnswers;
}

It must be initialised in viewDidLoad (other options are available):
-(void)viewDidLoad {
    [super viewDidLoad];
    _correctAnswers = [NSMutableArray new];
}

and then start collecting correct answers into this array:
- (IBAction)answerButtonPressed:(id)sender {
    NSString* answer= [[sender titleLabel] text];

   //checks if answer key is equal to a1 ( which is always the correct answer )
    if([[currentQuestionUsefulVariable valueForKey:@"a1"] isEqualToString:answer] ){
        [_correctAnswers addObject:answer];
    }
    //answer is wrong
    else{
        wrongQuestionsCount1 ++;
    }

    if ([_correctAnswers count] == 2) {
        // Do something?  It's not exactly clear what you want to do
        // when 2 correct answers have been given.
    }
}

Note: you can dump correctQuestionsCount1 as that will be [_correctAnswers count] now.  Also you will need to reset the array at some point.
Note 2: You could also start collecting incorrect answers as well, for some analysis or perhaps to disable that button so the user cannot repeatedly answer the question wrong.
Comment: I am trying it right now and I will update it in few minutes.
To make things clear - I have a running program that gets one answer at a time and everything's good. The two answer thing is when I press a specific joker button and it gives the advantage to the user to chose two of four available answers. This is why I need to do that. For any other cases I need only one answer at a time.
As I see , you add the answer to the array, after the ( if answer is correct check is done) . I need to fill the array with two answers, THEN -> check if one of these two is okay.
Thanks for the fast response!
Comment: Hmm, I think I've got it wrong in my answer then.  Sounds to me like all you want to do is enable/disable certain buttons to make the answer easier to guess?
Comment: I updated my comment above.
The only thing left is to

first :  (if joker button pressed) -> fill the array with two answers, THEN -> check if one of these two is okay. That's simply everything i need. But I need the program to freeze while two answer button are being pressed. I don't want to jump to another question when only one is pressed. That's the catch.
Comment: But if you have a UI with 4 buttons containing different answers and the user presses the "easy mode" button, then isn't it enough to disable two of the wrong answer buttons so the user can ignore them (and cannot even select them)?  It doesn't sound like you need to make any changes anywhere else?
Comment: You just got in the "50/50" joker case, which is already done. And yes, i just remove two wrong answers.
In my case you can mark two wrong answers and still don't get a point for a correct question. That's the game :)
The case i am working now is called Double Dip.
You press the joker , and now you can mark two answers and see if you get one of them correct.
Comment: Ah OK.  My answer goes some way towards that then.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/64880/discussion-between-xdevx-and-trojanfoe).


How custom a form with twig

Question: I make a form programmatically, and I am looking how a web designer can change render.
 public function buildForm(array $form, FormStateInterface $form_state)
{

    $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
    );

    $form['position'] = array(
        '#type' => 'search',
        '#title' => $this->t('Où'),
        '#placeholder'=>'Où',
        '#attributes' => array('title' => $this->t('Où')),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Search'),
    );

    return $form;

}

If the path of my form is /test the suggestion template form--test.html.twig doens't work.
I would like give access to a template for webdesigner can custom the render.
I can do something like that :
  $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
        '#prefix'=>'
',
        '#suffix'=>'
'
    );

But it's hard coded.
So I am looking for a way to return a brut table and let the web designer make his template.
The best way for the designer ll be :
form--test.html.twig

{{ form.metier }}

{{ form.position }}

{{ form.submit }}

I don't know if I am right, I have try to return my variable $form to a template like that :
return array(
    '#theme' => 'form_test',
    '#form' => $form,
  );

All work I can access to my fields with

{{ form.metier }}
  {{ form.position }}
  {{ form.submit }}

But the submit button doesn't work because the hidden fields are not display like the form_token and he is not in my variable $form.
Answer: You need to implement hook_theme() in your .module file to define a new theme implementation, set the #theme key in your form to the name of your implementation and create a twig template with this same name, but replacing hyphens with underscores:
example.module
function example_theme() {
  return [
    'my_awesome_form' => [
      'render element' => 'form',
    ],
  ];

Form/MyAwesomeForm.php
class MyAwesomeForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    $form['#theme'] = 'my_awesome_form';
    [...]

templates/my-awesome-form.html.twig
<form{{ attributes }}>
  {{ form.form_build_id }}
  {{ form.form_token }}
  {{ form.form_id }}

      {{ form.name }}

      {{ form.type }}

  [...]

In this example form.name and form.type are your form fields, the array keys that you used to create the form, and I used bootstrap markup to show them in two columns.
Hope this helps.
Regards.
PS: This is a copy of my post at https://www.drupal.org/node/2788835#comment-11785706. I cloned it here because I'm not allowed to post comments.
Comment: This is exactly how it should be done
Answer: you can access your filed with this code this is perfectly works
{{ form.metier }} {{ form.position }} {{ form.submit }}
{# Renders the rest of the form #}
{{ form|without('metier','position','submit') }}

Comment: i ll try that and let you know thx
Comment: ok welcome..but tell me must.how many face this problem.
Comment: Its my problem too . {{ form|without('metier','position','submit') }} worked but when we have a lot fields how to use this ? This code was very big and not good . {{ form.actions.submit }} was show element but I want after submit form , page redirect . How to use this ?
Comment: it is not possible to display without twig filter.you can get more information from here **https://www.drupal.org/node/2212845**  and if you will find a solution tell me thanks in advance
Answer: You need to add:
{{ form.form_build_id }}
{{ form.form_id }}

These are the fields that make the submit work.
Comment: nop that don't work, {{ form.form_build_id }} and {{ form.form_id }} doesn't exist in the form variable
Comment: I found those fields by debugging with `{{ dump() }}`. The one thing i did different is not to add the #form in the array but made the theme like this; `$themes['form_test'] = [
      'render element' => 'form',
    ];`
Comment: i don't have this field in {{ dump() }} how do you pass your form to your theme ?
Comment: `dump()` is only available when you change the twig.config debug setting in the /sites/default/services.yml file
Comment: yes i got it, but i see just field in my '#form' variable, i see nothing like build_id or form_build_id
Comment: What is in your theme?
Comment: for the moment that : `
{{ dump() }}

{{ form.metier}}

{{ form.position}}

{{ form.submit}}
` but this is how i call my theme from my form : `return array(
          '#theme' => 'recherche_form',
          '#form' => $form,
        );`

How custom a form with twig


Standardized median estimation

Question: Is there a 'standard' way to calculate an estimated median value for a given data-set that either never references a data point in the set, or is unlikely to?  I'm familiar with the median of medians approach, but I'm not sure what it's limitations are.
Example:
Assume each element in the data-set is associated with a unique individual (e.g it can be mapped back 1-1)
Data = {1, 2, 3, 4, 5, 6}

Note than when the number of elements in the dataset is even, the median is defined as (3+4)/2=3.5, which does not correlate with a value in the data-set, and hence does not map back to an individual.
The same cannot be said when the number of elements is odd.
Data = {1, 2, 3, 4, 5}

Here, the median is 3, which can be mapped back to an individual.  So perhaps there's an interpolation technique that can be applied when the number of elements is odd?
Hopefully this clears things up.
Comment: The sample median is defined differently between odd and even sample sizes.  In odd samples it is the middle value as you say.  For even sample sizes it has to be between the two observations closest to the middle.  Taking the average between those two observations is the most common way.  But any value between the two could be considered a median.
Comment: I am no more enlightened. What do you mean by "percentiles that are not exact"? In what sense does inexactness apply?  What do you mean by "preserve the shape of the distribution but do not give the exact distribution"? I also don't see how that second part relates to "either never references a data point in the set, or is unlikely to". I really have no clear concept what you're asking for. If it's not clear to either whuber or myself what you're asking, I expect it will be unclear to most people here. Please consider explaining in plain and simple terms what underlying problem you have
Comment: It sounds like your question is, "is there a definition of the median that is the same for even- and odd-sized samples?". Is that an accurate characterization?
Comment: I really don't see what you mean by your first sentence. Please explain what you're talking about.
Comment: Basically, is there a standard algorithm that computes percentiles that are not exact.  Preserve the shape of the distribution but do not give the exact distribution.
Comment: I'll take another stab at it - appreciate your patience.
Comment: Yes that is a simpler way to articulate the question - will update the title
Answer: The simple answer to your question is that your suggested calculation of the median in a sample having even $n$ is a good one, but certainly not the only one nor is it universally agreed upon as the best one.
If you think of the sample median as the empirical quantile function evaluated at 0.5, you will always select the $ceiling(n/2)$ order statistic as the median. This has the property that the median is always a member of the sample. We choose the lower value in even $n$ samples because the empirical distribution function and empirical quantile function are left continuous.
Suppose in R we take a sample of normal variates:
set.seed(123)
x <- rnorm(6)
m <- median(x)
plot(ecdf(x))
segments(min(x), 0.5, m, 0.5, col='red')
segments(m, 0.5, m, 0, col='red')
text(m, .25, 'Sample median', cex=0.5, srt=90, pos=2)

Gives us:

Changing 6 to 7

A radical idea is that instead of the median being a single number, it could be whole range of values which interpolates the $n/2$ and $n/2+1$ domain when n is even, making a kind of functional inverse.

Standardized median estimation


Saving an array containing some empty elements using saveAll

Question: I have an array containing many arrays with data which I want to save using saveAll or saveMany. However, due to factors I can not change, not all arrays are actually containing any data. In the dump you can see below, only the first two arrays are filled.
When saving this array with saveAll or saveMany, I receive the following error:Integrity constraint violation: 1048 Column 'productinfo_id' cannot be null.
How can I avoid this error when saving the arrays using saveAll or saveMany?
array(
    (int) 1 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '68',
        'quantity' => '30',
        'productName' => 'ciplorex syp 125',
        'pack' => '60ml',
        'purchasePrice' => '49.30',
        'grossAmount' => '1479.00',
        'discountPercent' => '20.00',
        'discountAmount' => '295.80',
        'netAmount' => '1183.20'
    ),
    (int) 2 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '69',
        'quantity' => '27',
        'productName' => 'ciplorex syp 250',
        'pack' => '60ml',
        'purchasePrice' => '85.00',
        'grossAmount' => '2295.00',
        'discountPercent' => '20.00',
        'discountAmount' => '459.00',
        'netAmount' => '1836.00'
    ),
    (int) 3 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 4 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 5 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 6 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 7 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 8 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 9 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 10 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 11 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 12 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 13 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 14 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 15 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 16 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 17 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 18 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 19 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 20 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 21 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 22 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 23 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 24 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 25 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 26 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 27 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 28 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 29 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    ),
    (int) 30 => array(
        'purchaseinfo_id' => '7',
        'productinfo_id' => '',
        'quantity' => '',
        'productName' => '',
        'pack' => '',
        'purchasePrice' => '',
        'grossAmount' => '',
        'discountPercent' => '',
        'discountAmount' => '',
        'netAmount' => ''
    )
)

Comment: Welcome to StackOverflow, thank you for your question. I have quickly applied some modifications to your question to make it more understandable. I hope you don't mind. If you do, please feel free to revert back to a previous revision. If you have any questions, take a look at the [help center](http://stackoverflow.com/help). Have fun!
Comment: What do you want do with the empty product?
Answer:
Integrity constraint violation: 1048 Column 'productinfo_id' cannot be null

I assume you understand what this means? You're required to pass a value into this field, you can't save a table row with an empty productinfo_id. Also I think this should be called product_info_id.
So instead of filtering empty arrays, like suggested by Lars, I would first ask the question: Why are they present at all? I would avoid that.
The proper solution to avoid the hard error you'll get when the SQL error happens would be to use validation in the model to make sure the record can't be saved at all and fails validation on an empty product_info_id. This will ensure a graceful and meaningful way to handle this.
Additionally to this you can filter out "empty" associated records in the beforeSave() callback. But this is not the primary fix for this, the validation is.
Answer: Before saving the array, I would suggest looping over it and filtering the empty arrays. Example:
$originalArray = #Your Data;

$saveArray = array();

foreach($originalArray as $item) {
    if(!empty($item['productinfo_id'])) {
        $saveArray[] = $item;
    }
}

Then you can feed the new array to the saveAll method.


Learning about the sustain pedal modification

Question: Can a keyboard be damaged later on when you use a homemade sustain pedal on it? Is it necessary to put a resistor in a sustain pedal?
Comment: What make, what model?
Answer: I have used various switching pedals as sustain on various keyboards. There has never seemed to be a problem with using something as simple as a bell-push to activate sustain on any. Best to check what the original pedal actually does. It could be a momentary make/break, like a bell-push, or a switching mode, working like a light switch. More likely the former, with nothing needed more than a bit of wire shorting another.
Comment: Some keyboards don't even care which way round the switch works, they analyse at boot. If it detects a closed contact, it assumes open to activate & vice versa.


Extend the Fourier transform over $L^2(\mathbb R^n)$

Question: Using Plancherel theorem, we have that the Fourier transform is an isometry over $L^2(\mathbb R^n)$. But anyway. In my course it's written that Plancherel theorem is extremely important since it allow us to prolonge the fourier transform from $S(\mathbb R^n)$ (i.e. the schwarz space) to $L^2(\mathbb R^n)$. Indeed, $$\int_{\mathbb R^n}f(x)e^{2\pi i x\cdot \xi}dx$$
doesn't converge in the absolute sense if $f\in L^2(\mathbb R^n)$. However, given such $f$, we simply pick a sequence $\{f_n\}\subset S(\mathbb R^n)$ (that exist by density of $S(\mathbb R^n)$ in $L^p(\mathbb R^n)$) with $$f_n\underset{n\to \infty }{\longrightarrow } f$$ in the $L^2$ sense. Then, using Plancherel's theorem, $\{\hat f_n\}_{n\in \mathbb N}$ is a cauchy sequence in $L^2(\mathbb R^n)$, and hence we can defined $$\hat f=\lim_{n\to\infty }\hat f_n$$
using the fact that $L^2(\mathbb R^n)$ is complete.
My questions are the following:
1) Finally, when $f\in L^2(\mathbb R^n)$ does $\int_{\mathbb R^n}f(x)e^{2\pi ix\cdot \xi}dx$  exist or not ?
2) And does $\hat f$ that is the limit of the $\{\hat f_n\}$ is given by $$\hat f(\xi)=\int_{\mathbb R^n}f(x)e^{2\pi ix\cdot \xi}dx.$$
I'm a little bit lost in all that.
Comment: Formula 1) only works for a dense subset, while the Plancherel transform is defined (by extension) for the entire space. However, it is customary to write the formula on the right hand side of 1) rather than using another symbol to represent the Plancherel transform. Formula 2) is only strictly valid if the left hand side is in the aforementioned dense subset.
Answer:
In the sense of Lebesgue integration, the integral defining the Fourier transform of $f$ makes sense if and only if $f \in L^1$. That's easy to see: the integral has to converge absolutely, and the modulus of the integrand is just $|f|$. Since $L^2(\mathbb{R}^n) \setminus L^1(\mathbb{R}^n)$ is nonempty, there are $L^2$ functions for which the integral does not converge. One example would be $x^{-2/3} 1_{[1,\infty)}(x)$ on $\mathbb{R}$.
I don't really understand what you mean here. If you mean "if I Schwarz-approximate the FT of an $L^1$ function, do I get the FT in the sense of Lebesgue integration?", the answer is yes. (If it weren't, this Schwarz trick would be awful.) If you mean "is the Schwarz limit of the FT of an $L^2$ function the FT of it in the sense of distribution theory?", the answer is again yes. (This means that $\langle \hat{f},\hat{g} \rangle = C \langle f,g \rangle$ for any Schwarz function $g$, where $C$ is a constant depending only on the FT normalization you are using.) It is in this sense that we identify this Schwarz-approximation limit as "the FT" of a function for which the FT integral doesn't converge. I think in pretty much any other sense the answer to this question is no.
Comment: My question for 2) would be does $\int _{-\infty }^\infty f(x)e^{2\pi inx\cdot \xi}dx$ will converge to $\hat f(\xi)$ in the $L^2$ sense ?
Comment: @MathBeginner If $f \not \in L^1 \cap L^2$, no. It has to be in $L^1$ for the integral to converge at all, and it has to be in $L^2$ for it to be able to converge in $L^2$ (since $L^2$ is complete). If $f \in L^1 \cap L^2$, I think it works (intuitively it must because the FT is unique in the sense of distribution theory).
Comment: @Ian: I think what Mathbeginner want's to says is that if $f\in L^2(\mathbb R^2)$, then $\int_{|x|\leq N}f(x)e^{2\pi in x\cdot \xi}dx$ will converge in the $L^2$ sense, and that we can define it's limit as the FT of $f$. And I think that this is true. But the fact that the $\lim_{n\to \infty }\int_{|x|\leq N}f(x)e^{2\pi in x\cdot \xi}dx=\int_{\mathbb R^n}f(x)e^{2\pi in x\cdot \xi}dx$ required indeed $f\in L^1(\mathbb R^n)$ (I think)
Comment: @MSE The actual integral definition of the FT makes sense iff $f$ is in $L^1$. I didn't see anything about cutting off to $[-N,N]$ here, all I saw was using Schwarz approximations.
Comment: To all: I answered to try to clarify the situation for MSE and MathBeginner, I hope it will be fine, and let me know if it doesn't.
Comment: @Surb: Could you answer to my question here: http://math.stackexchange.com/questions/1846755/is-fourier-series-l2
Comment: @MathBeginner: please, don't do that in the futur, it's not a good attitude.
Answer: To clarify the situation
Using your definition, the Fourier transform is defined as following
\begin{align*}
\mathfrak F: \mathcal S(\mathbb R^n)&\longrightarrow \mathscr F(\mathbb R^n):=\{f:\mathbb R^n\longrightarrow \mathbb R\mid f\text{ is a function}\}\\
f&\longmapsto \hat f
\end{align*}
where \begin{eqnarray}\mathfrak F(f)(\xi)=\hat f(\xi)=\int_{-\infty }^\infty f(x)e^{2\pi ix\cdot \xi}\mathrm d x.\tag{1}\end{eqnarray}
You can also define
 \begin{align*}
\mathcal  F: L^1(\mathbb R^n)&\longrightarrow  \mathscr F(\mathbb R^n)\\
f&\longmapsto \hat f
\end{align*}
 but this definition is less interesting than the previous one since $\mathcal F$ will not be extendable to $L^2$ as easily (the only way to extend it to $L^2$ is to consider the restriction to function with compact support, but I'm not even sure if it's really enough). Anyway. Now, what you said (and your arguments are true) is that you can prolonge $\mathfrak F$ on $L^2(\mathbb R^n)$ using density of $\mathcal S(\mathbb R^n)$ in $L^2(\mathbb R^n)$ and completness of $L^2(\mathbb R^n)$.
This doesn't mean that for $f\in L^2$ unspecified it's Fourier transform is going to be given by $(1)$. It just mean that you can defined \begin{align*}
\tilde{\mathfrak F}:L^2(\mathbb R^n)&\longrightarrow \mathscr F(\mathbb R^n)\\
f&\longmapsto \tilde{\mathfrak F}(f):=\lim_{n\to \infty }\mathfrak F(f_n),\quad f_n\in\mathcal S(\mathbb R^n)
\end{align*}
such that $\left.\tilde{\mathfrak F}\right|_{\mathcal S(\mathbb R^n)}=\mathfrak F$. Notice that $$f=\lim_{n\to \infty }f_n,$$ in the $L^2-$sense. Then $\tilde{\mathfrak F}$ is called the prolongement of $\mathfrak F$ and is well defined by the argument you said.
Therefore, for $f\in L^2$ unspecified, if $f$ is in $\mathcal S(\mathbb R^n)$, then $\tilde{\mathfrak F}(f):=\hat f$ in the sense of $(1)$, and if $f\in L^2(\mathbb R^n)\backslash \mathcal S(\mathbb R^n)$, then $$\tilde{\mathfrak F}(f):=\lim_{n\to \infty }\hat f_n,$$
where $$\hat f_n(\xi)=\int_{|x|\leq n}f(x)e^{2\pi i x\cdot \xi}\mathrm d x$$ and the limit is of course taken in the $L^2-$sense.
Maybe you can notice that it's the same as $g:]0,1]\longrightarrow \mathbb R$ defined by $g(x)=\frac{\sin(x)}{x}$. You can prolonge $g$ on $0$ mean that there is $\hat g:[0,1]\longrightarrow \mathbb R$ s.t. $\hat g|_{]0,1]}=g$ and $\hat g(0)=\lim_{n\to \infty }g(x)$, but it doesn't mean that $g(0)=0$ (since $g$ is not defined at $0$).
Comment: Ok, I see much better. But for this prolongement $\tilde F$ could I says that $\tilde F(f)=0$ when $f\in L^2(\mathbb R^n)\backslash  \mathcal S(\mathbb R^n)$ ? we also would have that $\tilde F|_{\mathbb S(\mathbb R^n)}=F$, no ?
Comment: This is not a prolongement ! By "prolongement" we mean in the sense that $$\tilde {\mathfrak F}(f)=\tilde {\mathfrak F}(\lim_{n\to \infty }f_n)=\lim_{n\to \infty }\tilde {\mathfrak F}(f_n)=\lim_{n\to \infty }\mathfrak F(f_n).$$ Or if you prefer, "prolongement by continuity" since in a metric space, the continuity and sequential continuity are equivalent.
Comment: I think this is a bit muddled, though it is encapsulating some important points. I think the biggest problem is that @MathBeginner appears to believe that the integral definition of the FT is *the* definition of the FT. It's not. We first define the FT that way for $f \in \mathcal{S}$ (note that $\mathcal{S} \subset L^1$). Then we *extend* it by duality to $\mathcal{S}'$, using the identity $\langle \hat{d},\hat{f} \rangle = C \langle d,f \rangle$.
Comment: (Cont.) Here $\langle \cdot,\cdot \rangle$ is the dual pairing between tempered distributions and Schwarz functions, $d$ is a tempered distribution, $f$ is a Schwarz function, and $C$ is a normalization constant. This mapping on $\mathcal{S}'$ is "the FT". The topology here is that of pointwise convergence of tempered distributions. If we want a different topology, we restrict the domain and proceed accordingly.
Comment: @Ian: I think it's a good answer :) It's not confusing and clear (+1)
Comment: @user330587 I think it would be better to take the initial definition to just map into $\mathcal{S}$ rather than into $\mathscr{F}$ (which incidentally is not standard notation). Then extending the domain extends the codomain (which should be no surprise).
Comment: @Ian: I totally agree with you on this point. I first wanted to map $\mathfrak F$ into $\mathcal S$, but then, to justify that the prolongement map to $L^2$ was a little bit complicate, that's why I prefer to map into $\mathscr F(\mathbb R^n)$. In fact it's a consequence of plancherel, but I prefer to be prudent an take things more "simple". For the notation $\mathbb R^{\mathbb R^n}$, it has to many exposant, that's why I prefer using $\mathscr F(\mathbb R^n,\mathbb R)=:\mathscr F(\mathbb R^n)$. But I don't think that it's an unusual notation.


Dictionary order topology based query

Question: I am not sure i fully understand dictionary order topology...first picture still confusing me, why there is line in upward of a*b , why its jot downward.
and what will be diagram for (2*2,4*5).
Comment: Essentially: to your last question: to be *greater* than $a \times b$ and also have $x=a$ we need $y > b$ by definition of the lexicographic order.
Comment: thanks sir, i understood.
Answer: Just apply the definition of the lexicographic order: the interval is all $x \times y$ with $a \times b < x \times y < c \times d$ (notation following Munkres, under protest..). To be bigger than $a \times b$ is to have $x$-coordinate $>a$ or $=a$ but then $y > b$. But we must also be smaller than $c \times d$ so $x < c$ or $x=c$ and $y < d$. So the vertical lines in between are all point where $a < x < c$.
The points above $a \times b$ are the points with $x=a$ and $y > b$.
The ones on the right are those with $x=c$ and $y < d$.
You can draw the similar picture for $2 \times 2$ and $4 \times 5$ yourself: vertical lines with $2<x<4$, some up-reaching part above $2 \times 2$ and so down-reaching part below $4 \times 5$.  (the left point shifts downwards and the right one upwards; it's really the same).
Comment: hii,thanks a lot, i give myself more than 1 hour for this topic but fail,you clear my doubt thoroughly.

Dictionary order topology based query


How to fix the warning: "RPMDB altered outside of yum"?

Question: I have a RHEL 6 system, that I primarily manage through RHN Satellite.  Recently I scheduled some updates through Satellite and received a response that the updates had failed.  I ssh'd into the system to investigate, and saw this warning when running yum:
Warning: RPMDB altered outside of yum.

How do I fix this warning?
Comment: Stop installing and removing packages with the rpm command and stick to yum.
Comment: yum clean all , then next time you use yum warning should not appear or you can try " yum history sync"
Comment: See https://superuser.com/questions/558200/is-it-possible-to-use-yum-to-install-a-rpm-file-in-red-hat-linux about installing RPMs with yum
Answer: As noted by arana and supported by RHEL documentation, another command (that worked in my situation) is:
yum history sync

It will iterate through the installed RPMs and synchronize the rpm & yumdb databases.
Answer: As mentioned in the comments, this is a harmless warning that informs you that a package has been installed or removed directly using the rpm command instead of yum. The difference is that yum is smarter in automatically resolving dependencies, and it is the default way of keeping the package-management DB on your system up-to-date (hence the warning).
See Execution of yum leads to "Warning: RPMDB altered outside of yum." for an official explanation of the message on the Red Hat Customer Portal.
To get rid of the warning, run:
# yum history new

See also yum or rpm, which contains further explanations and links to Red Hat documentation about both Yum and RPM.
Comment: that DID solve the problem, but it also deletes the history.
Comment: Thanks @chris-adams. I updated the answer to be more specific.
Comment: This part is confusing as written because RPM also does both of those things: "The difference is that yum automatically resolves dependencies for you and keeps the package-management DB on your system up-to-date."

The difference is that YUM has a more advanced resolution system which can avoid edge cases such as when a dependency isn't in the same repository.


Drupal forum post not showing on forum index

Question: I posted a new topic in the Drupal "Post installation" forum. When I clicked "Save", I got a new page with my post at the URL
https://www.drupal.org/node/2465665
The post is in a red box on that page. When I go back to the forum index, the post is not listed there. It's also not listed when I go to my profile and click on "Your posts".
I don't see any message that the post is awaiting approval nor anything in my dashboard saying that my account needs anything.
What's going on? I'm not likely to get a response if people can't see my post!
Thanks for your help.
Answer: The red box means the post has been unpublished.  You are still able to see the post, but everyone who is not a webmaster gets a 403.
Drupal.org uses a number of automated tools to detect and unpublish unwanted posts (e.g. suspected spam).  The most likely explanation is that your post tripped up one of these automated tools.
If you believe your post was unpublished in error, request it to be republished in the Drupal.org webmasters issue queue.


omega where to make changes?

Question: I've installed Omega 7.x-4.2 and created my subtheme and I just want to start practising making changes with page.tpl.php and css but there are just so many files and so far nothing has affected change.
I copied over page.tpl.php found in omega/system folder and placed it in my subtheme/templates then placed styles in my subtheme/css/subtheme.hacks.css but see no changes at all.
Also have noticed in sites/all/themes the path structure is different for omega that is all/themes/omega/(ohm)omega/templates and in other
all/themes/subtheme/templates. I set this up a while ago following documentation and can't remember why it has ended up this way and whether or not that would cause problems. There are no errors just no changes taking effect.
Just all seems so unnecessarily complicated!
Comment: Which parts of the documentation do you not understand? Please be specific, or this is likely to be closed as too broad.
Comment: Omega 4 is working with SASS so it will be wrong to modify the CSS files manually
Comment: I'd really suggest going through the tutorials on level up tuts http://leveluptuts.com/tutorials/drupal-tutorials/the-complete-guide-to-omega
Comment: cea, documentation says not to do it, and use SASS. There literally **is no main CSS file you should change**. And if you insist, @Kevin linked a tutorial. Have you seen it? #7?
Comment: its prob beyond me at this point- too complicated
Comment: @Clive I don't understand which is the MAIN css file that will affect change and which template just to get started. I see no changes take effect.
Comment: @Molot yes that's how i created subtheme with levelup but i really am better just diving in after the fact so was hoping for a heads up
Comment: Plus level up suggests using drush however i use recommended release and not alpha 7 so am doing manually - anyway
Answer: A couple of things you can check...

In your subtheme, have you declared omega as your base theme in the .info file?

<code>name = omega sub theme
description = my sub theme
base theme = omega
</code>

Have you enabled your subtheme as the default theme in admin/appearance?
Have you flushed the cache after making changes? ( configuration > development > performance > clear cache )
In dev tools, or whatever you use to inspect an element, when you have the source open, what is the path? Is it definitely coming from your sub theme folder?
Comment: Yes, all of the above.
Answer: Omega 4 is essentially built around using SASS for styling.  It's not a requirement, but the starterkit almost assumes it.
Assuming you have created a proper subtheme from the starterkit, you should have a directory called "sass".  These are the files you would change.  Peruse the README.md that is in there.  A basic SASS file structure for partials is set up, and I find that it maps fairly well to Drupal.  Each subdirectory also has a README.md.  Nothing forces you to use this structure for your partials, but I like it.
After this, you need a working SASS environment.  Everything should be there to get bundler going to install the gems you need.  Personally, I move all of the SASS and other build files out of the theme, and to my project root folder.  Then I have a single Gruntfile for making and deploying my project.
Comment: @cea As much as it is a pain to set up, more and more F/OSS projects are using SASS.  It has more or less become a defacto standard now.  After working with SASS for a while now, I really hate going back to work plain CSS projects.  Omega includes also work nicely into this scheme.  Every template file I add to my custom theme gets a custom preprocess include, and also gets its own SASS partial.  It make is very easy to find things, which is especially nice with complicated themes.
Comment: I think you've answered my question as not happy I am about it. Just because I think this whole SYSTEM is screwed.
Comment: fair enough- I will do the homework. thank you for your time and input.
Answer: A SASS environment is not a strict requirement for writing CSS in Omega. It has provision for directly editing CSS. SASS makes things a lot easier.
Have you added your CSS file in the theme's info file? Did you clear the cache after that?
Don't follow Ohm(the sample theme which ships with Omega 4) as a standard. It is bleeding edge and not recommended for production use.
If you create the subtheme using the drush subtheme wizard command(drush owiz), it will create a subtheme with sensible defaults which is easier to get started with.
Comment: I did it manually but you know what I give you points for understanding it all because honestly it is a mess for me right now.

omega where to make changes?


Help with showing $\int_{\mathbb{C}P^1} \omega_{FS} = \pi$

Question: Suppose $\mathbb{C}P^1$ is covered by two open sets $U_1, U_2$.
On
$U_1 = \{[Z_1,Z_2]\in \mathbb{C}P^1 : Z_1 \neq 0\},$
we have the coordinate map $z:\mathbb{C}P^1 \rightarrow \mathbb{C}$ with
$$[Z_1, Z_2]\mapsto Z_2/Z_1.$$
To compute $\int_{{U_1}} \omega_{FS} $, I know the Fubini-Study metric on $U_1$ is
$$\omega_{FS}=\frac{i}{2}\frac{1}{(1+|z|^2)^2} dz\wedge d\bar z$$
the next step is really confusing for me, people directly said
$$\int_{U_1} \omega_{FS} = \int_\mathbb{C} \frac{i}{2}\frac{1}{(1+|z|^2)^2} dz\wedge d\bar z.$$
But by definition
$$\int_{U_1} \omega_{FS} = \int_{z(U_1)} \delta z(\omega_{FS})$$
where $\delta z$ is the adjoint of $dz$, so why is
$$ \delta z(\omega_{FS}) = \frac{i}{2}\frac{1}{(1+|z|^2)^2} dz\wedge d\bar z ?$$
And from
$$\int_\mathbb{C} \frac{i}{2}\frac{1}{(1+|z|^2)^2} dz\wedge d\bar z =
-2i  \int_{\mathbb{R}^2} \frac{i}{2}\frac{1}{(1+x^2+y^2)^2}dxdy = \pi,$$ so does this mean $\int_{U_1^c} \omega_{FS} = 0?$
Answer: Let $\varphi : U_1 \to \mathbb C$ mapping $p \mapsto z(p)$ be the first coordinate chart.
$\omega_{FS}$ is a differential form on $\mathbb CP^1$; it can't be written in terms of $z$'s and $\bar z$'s.
However, $(\varphi^{-1})^\star \omega_{FS}$ is a differential form on $\mathbb C$. $z$ and $\bar z$ are coordinates on this $\mathbb C$. We can write
$$
(\varphi^{-1})^\star \omega_{FS} = \frac i 2 \frac 1 {(1 + |z|^2)^2} dz \wedge d\bar z
$$
So
$$
\int_U \omega_{FS} = \int_{\varphi(U)} (\varphi^{-1})^\star \omega_{FS} = \int_{\mathbb C} \frac i 2 \frac 1 {(1 + |z|^2)^2} dz \wedge d\bar z
$$
To address the question about $U_2$, note that $U_1 \cap U_2 $ is non-empty. So
$$
\int_{\mathbb {CP}^1} \omega_{FS} \neq \int_{\mathbb U_1} \omega_{FS} +\int_{\mathbb U_2} \omega_{FS}
$$
because the expression on the RHS double-counts on the overlap!
To evaulate the integral correctly, you can use a partition of unity subordinate to the cover $U_1, U_2$. Or even better, notice that $U_2 \backslash U_1$ is a single point - the south pole - which has measure zero. so really, $\int_{\mathbb {CP}^1} \omega_{FS} =\int_{\mathbb U_1} \omega_{FS} = \pi $.
Comment: $\phi$ goes from $U$ to $\mathbb C$. So $\phi^{-1}$ goes from $\mathbb C $ to $U$. So $(\phi^{-1})^\star$ takes pulls $\omega$ from $U$ back to $\mathbb C$.
Comment: Thank you very much for the helpful reply! And do you know why people often write $\omega_{FS}=\frac{i}{2}\frac{1}{(1+|z|^2)^2} dz\wedge d\bar z$, or like this for $\mathbb{C}P^n$ with $\omega_{FS} = \sum \cdots dz_j \wedge d\bar z_k$, is this like a standard notation? So I thought $z$ here is a coordinate map from $U_1$ to $\mathbb{C}$.
Comment: It's just shorthand for $(\varphi^{-1})^\star \omega_{FS} = ...dz \wedge d\bar z$.
Comment: And you wrote $(\phi^{-1})^* \omega_{FS}$ is a differential from on $\mathbb{C}$, should it be $(\phi)^* \omega_{FS}$?
Comment: No, I think my way is right. The notation $\phi^\star$ means pullback.
Comment: I see, but later in the integral, how do we see the term $\phi^* \omega_{FS}$?
Comment: Sorry, that was a typo!