Upper bound on trace of solution to discrete lyapunov or discrete matrix ricatti equation

Question: Take a discrete Lyapunov equation
$$
P = R + \beta A' P A
$$
for $\beta \in (0,1)$, $R$ and $A$ symmetric.
Quetsion: Can I put an upper bound on $tr(P)$ given properties of the primitives?  In particular, I have the $tr(R)$ and bounds on the maximum eigenvalue of $A$.
I can probably deal with something that doesn't generate the tightest bound exploiting the $A$ as long as the $tr(R)$ is involved.
Alternatively:  I am happy to use similar results for the solution to the Discrete matrix ricatti equation that comes out of optimal LQ control if that is available.
Answer: By using a cyclic permutation it can be shown that the matrix part of the trace of the second term of the right hand side can also be written as
$$
\text{tr}(A'\,P\,A) = \text{tr}(A\,A'\,P). \tag{1}
$$
When assuming that $\sqrt{\beta} A$ is Hurwitz (this would be the case for all $\beta$ if $A$ is Hurwitz) and $R$ positive definite, then the solution for $P$ should also be positive definite. In that case one can use the Cauchy-Schwarz inequality, such that $(1)$ satisfies
$$
\text{tr}(A'\,P\,A) \leq \text{tr}(A\,A')\,\text{tr}(P). \tag{2}
$$
The trace of a matrix is equal to the sum of its eigenvalues, thus an upper bound for $\text{tr}(A\,A')$ would be $n$ times the maximum eigenvalue of $A\,A'$. If $A$ is symmetric then the maximum eigenvalue of $A\,A'$ would simply be the square of the the maximum eigenvalue of $A$, so
$$
\text{tr}(A\,A') \leq n\,\lambda_\text{max}\!(A)^2, \tag{3}
$$
with $A\in\mathbb{R}^{n\times n}$.
Taking the trace of the Riccati equation and substituting in $(2)$ and $(3)$ yields
$$
\text{tr}(P) \leq \text{tr}(R) + \beta\,n\,\lambda_\text{max}\!(A)^2\,\text{tr}(P). \tag{4}
$$
Solving $(4)$ for $\text{tr}(P)$ thus yields
$$
\text{tr}(P) \leq \frac{\text{tr}(R)}{1 - \beta\,n\,\lambda_\text{max}\!(A)^2}, \tag{5}
$$
assuming that $\beta\,n\,\lambda_\text{max}\!(A)^2 < 1$.
Or a less tight bound could be obtained by only substituting in $(2)$ which yields
$$
\text{tr}(P) \leq \frac{\text{tr}(R)}{1 - \beta\,\text{tr}(A\,A')}. \tag{6}
$$


installed memcache, no noticeable improvements

Question: I just installed varnish and memcache on my server. Varnish works great but I don't really know how memcache should perform. I can't see any improvements for authenticated users.
I turned on memcache statistics and saw that it is working but I can't see a noticeable improvements in the page loading time.
Any ideas on how I can improve performance for authenticated users for an existing website?
Thanks, M.
Comment: Improving performance for authenticated users is a non-trivial topic, and you're unlikely to get "a good answer" without breaking the question down significantly. The solution will vary from site to site.
Comment: did you try cloudflare.com? the basic account is free and has some very good caching. how much is the cache filled of memcache?
Comment: Hmm..I noticed something similar or to say memcache hurting page load times - http://serverfault.com/questions/445223/is-memcache-impacting-my-performence-negatively
Answer: I recommend you to try/use Authcache module
http://drupal.org/project/authcache
Make sure to configure it with memcache by adding the following line in your settings file
<code>$conf['cache_inc'] = './modules/authcache/api/authcache.inc';
</code>


Can file extensions be associated with TS2008 Remote Applications

Question: Just wondering if there's any way to associate a local file extension with a remote app running via a Windows 2008 Terminal Services session?
If, for example, I've published Acrobat as a Remote App, is there any way of making it launch when I double-click a .PDF file? I'm guessing that this isn't possible, given that the server would need access to the file in question, but just wanted to check.
Answer: You need to use the .MSI creator in Remote App Manager on the server. There is an option to create a file association for the Remote App,


Injective functions and Open mapping theorem.

Question: Is there any theorem that says continuous injective function is an open map. I tried to scan few analysis books but could not find it. Can anyone suggest a reference for it?
Comment: Without more detail about the domain and range, this is impossible to answer.  For example, the map $f:\mathbb{R}\rightarrow\mathbb{R}^2$ given by $f(x) = (x,0)$ is about as a nice as possible (in particular, it's continuous and injective), but no where near open.  It's image doesn't even contain an open set!
Comment: The closest thing I can think of now is the theorem *invariance of domain*. I don't know how to put a link here but you can just Wiki it. It says a continuous injective map is open if both the domain and codomain are Euclidean spaces of the same dimension.
Comment: Here is a claim from one book that i found without any proof:
Comment: Here is a claim from one book that i found without any proof:If $\Phi :D \rightarrow \Re^n $ is continuous and injective in the open subset of D of $\Re^n$, then $\Phi(D)$ is open.
Comment: http://math.stackexchange.com/questions/176526/open-mapping-of-the-unit-ball-into-itself/176527#176527
Answer: Without more assumptions about the domain and codomain of the function, this is not necessarily true. As a particular example, the function $$f : \mathbb{R} \to \mathbb{R}^2, f(x) = (x, 0)$$ is a continuous function which is clearly injective. However, $f$ is not an open map: Any open subset of $\mathbb{R}^2$ cannot be contained within $\mathbb{R} \times \{0\}$.
Answer: HuiYu: Just paste the link in the comment: http://en.wikipedia.org/wiki/Invariance_of_domain
user42574: The relevant theorem is the invariance of domain; see the link. You won't see this proved in most analysis books, since this is a statement of topology and typically is proved using the Brouwer fixed-point theorem. You may find the invariance of domain proved in Topology by J. Munkres, a fairly standard reference on topology.


How can I programmatically change the view mode?

Question: In Drupal 7 I did something like:
  function mymodule_views_pre_render(&$view) {
    //dpm($view);
    if ($view->name == 'services') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('services_teaser');
    }
    else if ($view->name == 'portfolio') {
      $view->style_plugin->row_plugin->options['view_mode'] = variable_get('portfolio_teaser');
    }
  }

I don't know how to set the view mode on the fly, in Drupal 8. The idea is to be able to select the view mode for the view from a configuration form, instead of doing it from the view form.
How do I achieve this?
Answer: You can select VIew Mode as:
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'taxonomy_term' && $entity->bundle() == 'tag' && $view_mode == 'full') {
    $view_mode = 'CUSTOM VIEW MODE';
  }
}

Comment: I did not know this existed and I am now very pumped about having it in my toolkit.
Comment: Not sure why this is the accepted answer when the question is about changing the view mode used in a view output. The answer by Stephan below is the correct one.
Comment: Definitely @liquidcms this isn't an answer to a question. It refers to something completly different.
Answer: Since the example code seems to be for a view, with hook_views_pre_build() you can programmatically set the view mode in a Drupal 9 view.
/**
 * Put the following lines on the top of the module file,
 * after the PHP opening tag and the documentation comment containing the
 * @file tag.
 */
use Drupal\views\Plugin\views\row\EntityRow;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_build().
 */
function YOUR_MODULE_views_pre_build(ViewExecutable $view) {
  if ($view->rowPlugin instanceof EntityRow && $view->rowPlugin->getEntityTypeId() === 'node' && $view->rowPlugin->options['view_mode'] === 'teaser') {
    $view->rowPlugin->options['view_mode'] = 'other_teaser';
  }
}

Maybe this is useful for others who need to migrate their Drupal 7 custom code to Drupal 9 or higher.
Comment: @vrijdenker: Yes and no. The title of his question belongs to how to change the view mode programmatically, which could be done with hook_entity_view_mode_alter(). But his D7 code select a view mode for different views in a programmatically way. Maybe he want something, that website visitors of the view output could switch the view mode of displayed entities via some selectable field or for some amount of entities of the view result?
Comment: This question isn't about Views, but about a content view-mode
Comment: I'm sorry, you are absolutely right. I myself didn't read the question correctly.
For some reason StackExchange won't let me undo my vote untill you edit the post. Maybe adding a space or a dot is enouch so that I can undo my vote.
Comment: Our application was solved with @SteffenSchlaer's answer but we needed to select Views format view mode based on number of results. Using this code: $view->execute(); $count = count($view->result); solves this except sets up unwanted recursion. Using a drupal_static variable to break out of the 2nd call to this makes it all work.
Comment: I was using your code, but not all views have a rowplugin. That depends on the styleplugin...
Answer: Extending @tim's answer, I found that I had to change the cache key as well.
function HOOK_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
      if ($entity->getType() === 'my_content_type') {
        // Get the value of the "setting" field.
        switch ($entity->field_list_style->value) {
          case 'custom':
            // Set the view mode.
            $count = $build['field_my_entity_reference']['#items']->count();
            for ($i = 0; $i < $count; $i++) {
              $build['field_my_entity_reference'][$i]['#view_mode'] = 'custom_view_mode';

              $cache_key = array_search('default_view_mode', $build['field_my_entity_reference'][$key]['#cache']['keys']);
              $build['field_my_entity_reference'][$key]['#cache']['keys'][$cache_key] = 'custom_view_mode';
            }
            break;
        }
      }
    }

Answer: In a preprocess function, it can be done depending of a value of one field like this:
function hook_preprocess_paragraph(array &$variables) {
  $paragraph = $variables['paragraph'];
  if ($paragraph->field_paragraph_image_clickable->value === "0") {
    $variables['content']['field_paragraph_image_ref']['0']['#view_mode'] = 'image_without_link';
    unset($variables['content']['field_paragraph_image_ref']['0']['#cache']['keys']);
  }

Answer: If you have an entity reference field attached to a node, and want to offer the editor a choice of view modes through another field, you can change the view mode in the render array.
In this example my_content_type has a field field_my_entity_reference that is set up to be rendered using default_view_mode. The field_list_style field offers a list of display options that are used to override the default view mode.
function HOOK_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($entity->getType() === 'my_content_type') {
    // Get the value of the "setting" field.
    switch ($entity->field_list_style->value) {
      case 'custom':
        // Set the view mode.
        $count = $build['field_my_entity_reference']['#items']->count();
        for ($i = 0; $i < $count; $i++) {
          $build['field_my_entity_reference'][$i]['#view_mode'] = 'custom_view_mode';
        }
        break;
    }
  }
}


relationship between ARMA and AR

Question: I once heard some statements regarding the relationship between ARMA and AR process, such as
An average of severl lags of an autoregression forms an ARMA process

or
A weighted mixture of lags of an AR(P) model is ARMA

I am not very clear about these two statements, whether they are right? If they are right, how to get them? Thanks.
Answer: As I'm sure you are aware, ARMA is an acronym for AutoRegressive Moving Average (Stochastic Process).  More fully, we use ARMA(p, q) where p is the order of the autoregressive portion and q the order of the moving average portion.
Both of the statements are saying the same thing: if you form a linear combination of AR processes an ARMA process of some order results.  This is a consequence of an inversion theorem in Time Series analysis which states that all stationary ARMA processes have a representation as a (possibly infinite) stationary AR process.
The ARMA model expresses $X_t$ as the sum of polynomials in the lagged values of X_t and the lagged values of $\epsilon_t$ (the i.i.d. noise terms).  So an AR(1) model looks like
$X_t = \theta X_{t-1} + \epsilon_t$.
The single lagged value of the series is
$X_{t-1} = \theta X_{t-2} + \epsilon_{t-1}$.
Now, let $0 < \phi < 1$ and consider $Y_t = \phi X_t + (1-\phi) X_{t-1}$.  $Y_t$ is a weighted average of lags of an AR(1) model.  Let's define $\xi = \phi \theta$
$Y_t = \phi\theta X_{t-1} + (1-\phi)\theta X_{t-2} + \phi \epsilon_t + (1-\phi) \epsilon_{t-2}$.
Some mild algebra (basically arranging things to make a $Y_{t-1}$ appear on the right hand side) puts this in the form
$Y_t - \epsilon_t = (\xi_1 Y_{t-1} + \xi_2 Y_{t-2}) + (\phi \epsilon_{t-1} + \phi^2 \epsilon_{t-2})$
Note that this is the sum of a lagged polynomial in $Y_t$ and a lagged polynomial in the noise vector, $\epsilon$.  This is an ARMA process.

relationship between ARMA and AR


Primefaces datatable cell editing new and old values

Question: i have a data table and i can not get the old and new value. i can only get the new value
why?
code that works on ajax event
<code>   <p:ajax event="rowEdit" listener="#{productMapBean.onEdit}"/>
</code>
backing bean:
<code>    public void onEdit(RowEditEvent event) throws SQLException {

    System.out.println("BEGIN:: onEdit");
    if (ds == null)
        throw new SQLException("Can't get data source");

    // get database connection
    Connection con = ds.getConnection();
    PreparedStatement ps = null;
    try {

        String myPreparedStatement = preparedStatements.getUpdateStmt();
        ps = con.prepareStatement(myPreparedStatement);

        ps.setString(1, ((MappingData) event.getObject()).getCode());
        ps.setString(2, ((MappingData) event.getObject()).getSubcode());
        ps.setString(3, ((MappingData) event.getObject()).getDestination());
        ps.setString(4, ((MappingData) event.getObject()).getMapped());
        ps.setString(5, mappingDataUpdate.getCode());
        ps.setString(6, mappingDataUpdate.getSubcode());
        ps.setString(7, mappingDataUpdate.getDestination());
        ps.setString(8, mappingDataUpdate.getMapped());

        int executeUpdate = ps.executeUpdate();

        System.out.println("row updated: " + executeUpdate + " - " + ((MappingData) event.getObject()).getCode() + " - " + ((MappingData) event.getObject()).getSubcode()
                + " - " + ((MappingData) event.getObject()).getDestination() + " - " + ((MappingData) event.getObject()).getMapped());
        System.out.println("row updated: " + mappingDataUpdate.getCode() + " - " + mappingDataUpdate.getSubcode() + " - " + mappingDataUpdate.getDestination() + " - "
                + mappingDataUpdate.getMapped());
        System.out.println("key : " + mappingDataUpdate.getRowkey());
        System.out.println("key2 : " + ((MappingData) event.getObject()).getRowkey());

    } catch (Exception e) {
        System.out.println(e.getMessage());
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getLocalizedMessage()));
    } finally {
        ps.close();
        con.close();
    }
    dataList = null;
}
</code>
code that should get the old value:
<code>   <p:ajax event="rowSelect" listener="#{productMapBean.onRowSelect}"/>
</code>
backing bean:
<code>   public void onRowSelect(SelectEvent event) {
    System.out.println("BEGIN:: onRowSelect");
    if(mappingDataUpdate==null){
        if (((MappingData) event.getObject()) != null) {
            mappingDataUpdate = ((MappingData) event.getObject());

            System.out.println("row: " + mappingDataUpdate.getCode() + " - " + mappingDataUpdate.getSubcode() + " - " + mappingDataUpdate.getDestination() + " - "
                    + mappingDataUpdate.getMapped());
        }
    }
}
</code>
the log say:
14:58:55,170 INFO  [stdout] (http-/0.0.0.0:8080-2) BEGIN:: onRowSelect
14:58:55,170 INFO  [stdout] (http-/0.0.0.0:8080-2) row: 1 - 1 - DTCC-DFA - q    <-- when i select the row
14:58:58,323 INFO  [stdout] (http-/0.0.0.0:8080-2) doFilter
14:58:58,340 INFO  [stdout] (http-/0.0.0.0:8080-2) BEGIN:: onEdit  <-- when i press the check mark on the cell editor
14:58:58,342 INFO  [stdout] (http-/0.0.0.0:8080-2) row updated: 1 - 1 - REGIS-TR - q  <-- are the same why?
14:58:58,342 INFO  [stdout] (http-/0.0.0.0:8080-2) row updated: 1 - 1 - REGIS-TR - q <-- are the same why?
14:58:58,343 INFO  [stdout] (http-/0.0.0.0:8080-2) key : 11REGIS-TRq
14:58:58,343 INFO  [stdout] (http-/0.0.0.0:8080-2) key2 : 11REGIS-TRq
14:58:58,359 INFO  [stdout] (http-/0.0.0.0:8080-2) doFilter
14:58:58,373 INFO  [stdout] (http-/0.0.0.0:8080-2) BEGIN:: onRowSelect  <-- This is called alone by jsf after check mark onEdit backing bean is called
14:58:58,386 INFO  [stdout] (http-/0.0.0.0:8080-2) doFilter
the question is Why the variable
<code>  mappingDataUpdate
</code>
do not hold the value!!! and it is resetted to the new value???
row updated: 1 - 1 - REGIS-TR - q  <-- are the same why?
row updated: 1 - 1 - REGIS-TR - q <-- are the same why?
in the code 1 refer to
<code> mappingDataUpdate.getCode()
</code>
and another refer to
<code> ((MappingData) event.getObject()).getCode()
</code>
why are the same?
Comment: can you tell me if i m right?? the code works but i do not understand why there was a wrong.
Answer: I think the problem is because mappingDataUpdate is serializable object
because doing :
<code>   public void onRowSelect(SelectEvent event) {
        if (((MappingData) event.getObject()) != null) {
            mappingDataUpdate = ((MappingData) event.getObject());
            this.destination = mappingDataUpdate.getDestination();
            this.mappedValue = mappingDataUpdate.getMapped();
            this.subProduct = mappingDataUpdate.getSubcode();
            this.product = mappingDataUpdate.getCode();
            System.out.println("row: " + mappingDataUpdate.getCode() + " - " + mappingDataUpdate.getSubcode() + " - " + mappingDataUpdate.getDestination() + " - "
                    + mappingDataUpdate.getMapped());
        }

}
</code>
it works.
Comment: can you tell me if i m right?? the code works but i do not understand why there was a wrong.


CSS slide animation with angularjs

Question: I'm trying to animate a div using ng-show with CSS3 transitions. There are 2 divs: One in the foreground and another hidden behind it. The hidden div should slide up when the user mouse's over the foreground div. It should also remain shown if the users cursor moves over the slide div. If the users cursor leaves the slide div or the foreground div, it should slide back down. It doesn't seem to work correctly though. Here's a plunker: http://plnkr.co/edit/C1RaDTOXwpEMECGMkt19?p=preview
Is the css correct?
div#cover {
  background-color: lightblue;
  width: 90px;
  height: 30px;
  position:absolute;
  bottom: 0px;
  z-index:10;
}

.slide {
  background-color: white;
  width: 90px;
  height: 30px;
  position:absolute;
  bottom: 0px;
  z-index:5;
}

.slide.ng-hide-add, .slide.ng-hide-remove {
    transition: bottom 1s ease;
}

.slide.ng-hide-remove-active {
    bottom: 30px
}

.slide.ng-hide-add-active {
    bottom: 0px
}

Any ideas?
Answer: You only need two states:

Shown
Hidden

Let the base slide class define the state for shown (30px from bottom):
.slide {
  background-color: white;
  width: 90px;
  height: 30px;
  position: absolute;
  bottom: 30px;
  z-index: 5;
  transition: 1s ease bottom !important;
  display: block !important;
}

When the expression used in the ng-show directive is evaluated to false the hidden state will be activated and the class ng-hide will be added to the element by Angular.
Use that class to decorate the base class and define the hidden state (0px from bottom):
.slide.ng-hide {
  bottom: 0;
}

This means the two states will have the following classes when active:

Shown: slide
Hidden: slide ng-hide

As you see the slide class is always present, which is why the transition is put there.
You must use !important on the transition otherwise if you move the cursor back and forth over the element Angular will override it with transition: none briefly, which will cause the transition to interrupt and the element to snap into its final position.
You must also use display: block !important in the slide class to override the default behavior of ng-hide, which is display: none.
Demo: http://plnkr.co/edit/WN8v2riSYhhMyOgbZiWO?p=preview
Note: Personally I wouldn't recommend using ng-mouseenter or ng-mouseleave for this. Everytime they trigger the entire digest cycle and all watchers will be executed multiple times. The alternative would be to create a directive that uses event listeners to add/remove classes manually.
Comment: Awesome, thanks for this! Just out of curiosity about final note, would changing the event to ng-mousedown just on the `cover` div prevent this problem?
Comment: You're welcome :) Yes, it should. The problem with `ng-mouseenter` and `ng-mouseleave` is that if you have a lot of them and a user moves the cursor across the screen, triggering multiple of them, you will have a bunch of unnecessary digest cycles. This can have a big impact on performance, especially on slower computers or mobile devices (unless your application is really thin of course). `ng-mousedown` is usually not triggered involuntarily as often.
Comment: I've used `$watch` here to register a watchExpression without a listener to `console.log` everytime one digest cycle runs: http://plnkr.co/edit/zn3L3mSy7asa6KtMi3yo?p=preview Try moving the cursor back and forth over the elements with the console opened and you will see how many of them are fired.

CSS slide animation with angularjs


PHP/MySQL: Count number of available tables

Question: I have a database $db_name that contains a slew of tables.  Many of them contain the name 'puzzle' (for example: 'puzzle1', 'puzzle2', 'puzzle3', etc.).  What command do I need to perform to count all of those tables and return an integer?
Comment: In addition to the duplicate above you would add the filter ``AND `TABLE_NAME` LIKE 'puzzle%'`` to the `WHERE` clause.
Answer: Pretty sure your answer is in here:
How do I get list of all tables in a database using TSQL?
Only extra thing is to get these in an array, check if it applies to your conditions (e.g. starts with "puzzle") and then return the total number of items you're left over with.
Comment: The tag is mysql...
Comment: If the link above isn't working, try the following SQL statement: `SELECT table_name FROM information_schema.tables where table_schema='your_database_name';` (from https://stackoverflow.com/questions/8334493/get-table-names-using-select-statement-in-mysql)
Comment: This is a comment or close vote / flag (possible duplicate), not an answer.


Como capturar eventos no Python?

Question: Eu gostaria de capturar as teclas clicadas pelo usuário através do IronPython. Eu entendo um pouco de C#, mas não estou entendendo como faria isso no Python.
Código:
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import KeyEventArgs, Form, Application, Button

class App(Form):
    def __init__(self):

        self.KeyUp = self.TeclaClicada #Não sei como faria, aqui está o erro.
        self.Text = "Capturar tecla"

    def TeclaClicada(self, key):
        print(key)

form = App()
Application.Run(form)

Comment: Possível duplicata de [Capturando as teclas pressionadas pelo usuário em Python no Linux](https://pt.stackoverflow.com/questions/145588/capturando-as-teclas-pressionadas-pelo-usu%c3%a1rio-em-python-no-linux)
Answer: self.KeyUp += self.TeclaClicada

Ou self.KeyDown ou self.KeyPress... depende da tecla que você quer capturar, algumas vão pra um evento, outras pra outro...
A sua função TeclaClicada tem que ter essa assinatura:
def TeclaClicada(self, e, args):
    key = e.KeyChar
    if key == ...:
        ...

Como capturar eventos no Python?


Modify existing block programmatically by block id

Question: I have a block with the id 'block-block-8'. In my template.php I would like to have a function that changes that block's content so I am able to add a dynamic "back to category link" (category needs to come frome the url) on my products page back to the category page.
Something like this:
function ga2012_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'block-block-8':
      $block = array(
        'content' => 'Back to $_GET["category"]',
      );
      break;
  }

  return $block;
}

Does someone has a working implementation of this code? Please ask me questions if I haven't been clear enough, thanks!
Answer: You might try with hook_block_view_MODULE_DELTA_alter which:

Performs alterations to a specific block
Comment: I enabled the PHP filter module and added the PHP code into the block via the admin interface. This works for me.
Answer: In your case, the best solution is to use hook_block_view_MODULE_DELTA_alter  as @Artur explained. But there is another way to to customize a custom bloc programmatically using an update function (inside a .install file) in drupal 7 by using:
$content = 'your new content';

$num_update = db_update('block_custom')
                ->fields(['body' => $content,])
                ->condition('bid', your_block_id, '=')
                ->execute();


Are multi-valued functions a rigorous concept or simply a conversational shorthand?

Question: In Brown and Churchill's book, the concept of multivalued functions is not discussed in a very rigorous way (if at all). But I can see that branch cuts have importance in complex analysis, so I want to clarify my understanding of multivalued functions.
Is there a rigorous development of the definition of a multivalued function somewhere, along with branch cuts? Or is the whole idea of a multivalued function just a way of saying, "Hey, there's no unique way of defining the logarithm function here, so we're going to use whatever is convenient at the time"? And if the latter, where does a rigorous understanding of branch cuts fit in? Or are they also more of an intuitive term rather than a real defined mathematical object?
If they are rigorous, would a multivalued function be something like $f: \mathbb{C} \to \mathbb{C}^\infty$? I've never seen an infinite dimensional space before so I don't really know how that is developed.
Comment: It's **rigorous and deep** to put it lightly. The way I'd say it is that the 'correct' domain for a complex function like, say, $\sqrt{z(z^2-1)}$ is not the complex plane but an appropriate (Riemann) surface: understood as a function on that surface, that square root is a single-valued function. (But that's a slogan, not an explanation!)
Comment: @Jeff Yes, it's possible to talk about multivalued functions that way but there's a reason we usually don't: As soon as we try, we find it's impossible to calculate anything with that definition. The size of the set of the sum of a few such functions explodes quite fast, for example. The Riemann surface viewpoint is better; it shows that what we're really doing is trying to invert a finite map and should look to construct a domain manifold for it to study.
Comment: Also, at the level of set theory, a multivalued function can be thought of as a regular function that takes values that are subsets of the domain.  This formalism isn't exactly the same as the Riemann surface way to make functions single valued, but I know very little about that way.
Comment: One possible definition is given [here](http://math.stackexchange.com/a/95352/5191), where I discuss them in connection to branch points.
Comment: @semiclassical It is a solution to the biharmonic with a jump / discontinuity in the first derivative along the positive x-axis (representing the branch cut). It represents an idealized line defect in a solid. http://en.wikipedia.org/wiki/Dislocation
Comment: I'm glad it's rigorous and deep! I'm looking around for a good source, but all I've found so far is this set of lecture notes from Berkeley/Cambridge - it's okay: http://math.berkeley.edu/~teleman/math/Riemann.pdf. Are there any good books which go into detail on this?
Comment: Thanks, I'll give it a read. You note that your explanation is non-standard. Does that refer to all of the definitions/some of them?
Comment: @Semiclassical While Riemann surfaces are more "natural" settings to study such "functions", there are many applications (e.g. the solution of boundary value problems) where the analysis in $C$ is more useful because the branch cut has a physical meaning. Volterra-type solutions to the biharmonic equation, for example.
Comment: @user_of_math: True: the conformal perspective definitely has its advantages in applications. (Though I'll admit I'm not familiar with the Volterra-type solutions you refer to---can you pass a link along?)
Answer: Multivalued analytic functions can be made (and have been made) a rigorous notion.
This notion is sometimes useful. But modern textbooks prefer not to use it, because it is hard to deal with rigorously. (What is a sum or product of multivalued functions?)
There are several substitutes:

To use only single valued branches. For this you need to restrict the region
(usually by making some "branch cuts"). This is the way most elementary textbook take.
To use sheafs (which can be considered a rigorous framework into which multivalued functions fit, though there are alternative approaches). This is the approach used in the standard graduate textbook of Ahlfors.
To translate everything to the language of functions on Riemann surfaces. This is perhaps the most useful approach, at least in one complex variable, which was proposed by Riemann.
Comment: Thank you. I will take a look at Ahlfors when I get a chance.
Comment: @AmadeusDrZaius [This Book](http://www.amazon.com/Theory-Functions-Parts-Dover-Mathematics/dp/0486692191), though old and not as comprehensive as Ahlfors, gives very nice  and concise explanations.
Comment: Yes, this is a very good book.
Comment: I'm not sure what this book by Ahlfors is. Could someone link to it, or give a more complete citation?
Comment: The book of Ahlfors is called Complex Analysis, (McGraw Hill, 1979, 3-d edition) and it is the standard textbook in the US universities.


What can be deduced from the following hypothesis test given the $p$ value?

Question: You want to find out whether a new medicine for flu is effective or not. You know that the general assumption is that an average flu last for about one
week. So, letting $t$ be the average disease duration, you formulate your null hypothesis as $H_0: t \geq 7$ vs. $H_1: t < 7$. Your test result returned a $p$ value of $0.05$.
Which of the following statements are correct?

After treatment with the new drug there is a 95% chance that a flu    will last less than 7 days.
In 95% of the cases, the flu will last less than 7 days.
The duration of the flu can be reduced by a factor of 0.05%.
Even if the new medicine was completely ineffective, the chances that the experiment would have produced the same result are 0.05%.
We have proven that the null-hypothesis H0 is wrong and your    medicine is effective.

Since the $p$ value is small we will reject the null hypothesis which is on an avg flu lasts more than or equal to 7 days. By that answer 1 is CORRECT and answer 5 as well. What about the rest? How do I decide that?
P.S this is the first time I touching stats. Please help!
Comment: IMHO, faulty or confusing statements of question and proposed answers prevent any sensible response.\\ I vote for five W's. \\ If new medicine has NO effect, then the probability of getting a T statistic smaller than or equal to the one observed is $0.05.$ So you (just barely) reject $H_0: \mu = 7$ in favor of $H_a: \mu < 7$ at the 5% level.
Comment: *"So, letting $t$ be the average disease duration, you formulate your null hypothesis as $H_0: t \geq 7$ vs. $H_1: t < 7$"* Reading in between the lines I can guess what is meant with this hypothesis. But being pedantic... what does $t$ mean? The average disease duration when the medicine is taken?
Comment: Welcome to CV. If this question relates to a class exercise, please see https://stats.stackexchange.com/tags/self-study/info and add the tag to modify the question accordingly.
Comment: thank you.. i went thru the  guidelines.
Answer: None of the options provided are true. This might be an example of the fairly common disease of statistics instructors not understanding p-values. Many other examples can be found. See this paper: https://bpspubs.onlinelibrary.wiley.com/doi/full/10.1111/j.1476-5381.2012.01931.x
Also Haller & Krause (2002).
For a significance test, what you know from the p-value of 0.05 is that there is pretty weak statistical evidence suggesting that the null hypothesis is false. For a hypothesis test your decision to reject the null or not would depend on whether your pre-defined critical cutoff (rejection region) was greater or less than 0.05. If you used the convention of p<0.05 as the cutoff then your result of p=0.05 would give the opposite decision from what you would get if you set the cutoff to p≤0.05!
Haller H, Krauss S (2002). Misinterpretations of significance: a problem students share with their teachers. Methods Psychol Res 7: 1–20.
Answer: As @MichaelLew said,none of the answers is 100% true. The question and answers are poorly worded.

Answer 1 is about the distribution of flu duration among people. The study is only about average length and you have no information about the distribution among different people.

Answer 2 is also about the distribution of flu duration among people, just asking it differently. Nothing in the problem gives a clue about the distribution.

Answer 3 is about relative duration of flu. Nothing in the problem gives you information about the durations or the relative duration.

Answer 4 is wrong because of "same result". P value is about same result or even more extreme result (or same or more extreme difference in the other direction, if two-sided p-value). Moreover, answer 4 incorrectly equates a probability of 0.05 with 0.05% (rather than 5%).

Answer 5 says "proven". Statistics can never absolutely prove in one study. Statistics is about probabilities.

As written therefore, all answers are wrong. But #4 the closest to being correct.
Comment: All 5 statements are so clearly misinterpretations of test outcomes, as others have said. On top of this, 3 and 4 include 0.05% when presumably they mean 5%.
Comment: @GrahamBornholt. Good point that I had missed. I incorporated it into my answer.
Comment: Another problem with answer 4, which I guess is supposed to be the correct answer, is that it speaks about the 'drug being (in)effective', but the effectiveness is not well defined. The hypothesis test is about the duration of the disease (probably when taking the drug). But with that interpretation of the test there is no proper control group. If the disease duration after taking the medicine is below 7 days then this does not need to be because the drug is effective, it can also be because the general assumption is false (in addition, that assumption 'about one week' is very imprecise).


Why are some place holders '@' and others '%'?

Question: For example:
watchdog('alerts', 'Message for %user was sent.', array('%user' => $user));

and
drupal_set_message(t('options: @options', array('@options' => $form_state['values'])));

Is there any difference?
Comment: This question is, for sure, incorrectly marked as a duplicate. That question (of which this one is NOT a duplicate) is about "Replacement tokens" in the "Message" module (= some technique used in combination with the Rules module), and has nothing to do with what the question is here is about.
Answer: Have a look into the function definition of the format_string()
 function which is used by the t() function:
Each type of placeholder has a way in which this function intrepretes it:
@variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

Comment: And even though there is no t() function in the first example, the message should use placeholders because it can be translated at a later point.


Show that the sequence $(1+N^2)/[N(1+N)]-5/6$ is positive and increasing

Question: I have the function
\begin{equation*}
    f(N)= \frac{1+N^2}{N(1+N)}-\frac{5}{6},
\end{equation*}
where $N\in\mathbb{Z}_{++}/\{1, 2\}$.
I want to show that $f(N)>0$ and that $f(N+1)>f(N)$ for all $N>3$ since $f(3)=0$.
Approach 1: Continuous Extension
Define a new continuous function $g$ on $x\in\mathbb{R}_{++}$, where
\begin{equation*}
    g(x)=\frac{1+x^2}{x(1+x)} \text{ and }  g'(x)=\frac{(x-1)^2-2}{x^2(1+x)^2}.
\end{equation*}
The numerator of $g'(x)$ has a positive root at $x=1+\sqrt{2}$.
Moreover, $\frac{d}{dx}[(x-1)^2-2]=2(x-1)>0$ for $x>1$.
Therefore, $g(x)$ is an increasing function for any $x>1$ and is positive for any $x>1+\sqrt{2}$.
Taken together, $g(x)>0$ for any $x>3$.
However, I'm not sure of how legitimate an approach this is or how to relate these results back to my integer function to write a proper proof.
Approach 2: Induction
Let $N=4$ then $f(4)=1/60$. Take $f(N)>0$ to be true, then I need to show that
\begin{equation*}
    f(N+1)=\frac{1+(N+1)^2}{(N+1)[1+(N+1)]}>\frac{5}{6}.
\end{equation*}
Apart from simplifying the above somewhat, I'm not sure what the next step(s) would be. In induction proofs that I have read, often the presumption that $f(N)>0$ would play a role in showing that $f(N+1)>0$, but I don't see a clear way to do that.
Approach 3: Difference or quotient
This seems more related to showing that $f$ is increasing than showing it's positive but looking at
\begin{equation*}
    \frac{1+(N+1)^2}{(N+1)[1+(N+1)]}-\frac{1+N^2}{N(1+N)}>0
\end{equation*}
or \begin{equation*}
    \frac{\frac{1+(N+1)^2}{(N+1)[1+(N+1)]}}{\frac{1+N^2}{N(1+N)}}>1.
\end{equation*}
Any help or advice would be most appreciated.
Comment: $f(N)$ is not an integer-valued function.  For example, $f(4)=1/60\not\in\mathbb{Z}$.
Comment: @RobPratt Thank you for the correction. I have adjusted the title accordingly.
Comment: A shorter name is *sequence*.
Comment: @RobPratt Ah that's interesting, I had not thought about it like that but of course you are right: $\{f(3), f(4), \ldots\}$ is a sequence. I'm implicitly using ideas from sequences in Approach 3, I think.
Comment: I don't see anything wrong with your first approach! All you need to do is note that the output of your continuous function is equal that of your original function for integer inputs and that since your continuous function is increasing for all inputs in the range $[3,\infty)$, so too is your original function (since its domain is a subset of your continuous function's)
Answer: The function $f: \mathbb{N} \rightarrow \mathbb{R}$ defined as $f(N) := \frac{1+N^2}{N(N+1)}$ can have its domain extended to the positive reals; indeed for each $x>0$ define $f(x) := \frac{1+x^2}{x(x+1)}$.
If $f'(x)$ is positive for all $x \ge x_0$ then $f$ is increasing function on $(x_0,\infty)$. Thus, for all real numbers $y',y>0$ with $y'>y$, the inequality $f(y') > f(y)$ holds. Thus, for all integers $N \ge x_0$ it follows that $f(N+1) > f(N)$ [indeed, set $y=N$ and $N+1=y'$ and note the previous sentence]. Thus, as you have shown that $f'(x)$ is positive for all $x \ge 3$, it follows that for all integers $N \ge 3$ the inequality $f(N) < f(N+1)$ holds.
So to show that $f(N)$ is at least $\frac{5}{6}$ for all positive integers $N$, all you need to do is check $f(1),f(2)$, and $f(3)$. Then if all of $f(1),f(2),f(3)$ are at least $\frac{5}{6}$, simply use the fact that $f$ is increasing to conclude $f(N)$ must be at least $f(3) > \frac{5}{6}$ for all other positive integers $N$, equivalently, all integers $N > 3$, as well as $N=1,2,3$.
Answer: Here's a simple approach that does not rely on calculus.  To see that $f(N)$ is positive, rewrite as $$f(N) = \frac{(N-2)(N-3)}{6N(N+1)},$$
which is $>0$ when $N>3$.
To see that $f(N)$ is increasing, compute
$$f(N+1)-f(N) = \frac{N-2}{N(N+1)(N+2)},$$
which is $>0$ when $N>2$.
Comment: Thank you very much, this is great and just the type of thing I was looking for!


how to solve this complex exponential integration ??

Question: During exercising  and example of Fourier Series , I encountered with an integration :
 $$ \frac{E\omega_o}{4\pi j}\int_{0}^{\frac{\pi}{\omega_o}}\Big[e^{-j\omega_o (n-1)t}-e^{-j\omega_o (n+1)t}\Big]dt  $$
But next line answer is written as :
$$ \frac{Ee^{-jn\frac{\pi}{2}}}{2\pi(1-n^2)}\Bigg( e^{\frac{-jn\pi}{2}}+e^{\frac{jn\pi}{2}} \Bigg) $$
But when I tried to solve this my answer became :
$$ \frac{E\omega_o}{4\pi j}\frac{1}{j\omega_o(1-n^2)}\bigg[(1+n)e^{-j\pi (n-1)} +(1-n)e^{-j\pi (1+n)} -2  \bigg] $$
Where is my problem is? I checked my solution many times but don't find any.
FYI: main signal $\ x(t)=0 $ ; when   $\ \frac{-\pi}{\omega_o}<t<0 $
& $\ x(t)=Esin\omega_o t $  ; when $\   0<t<\frac{\pi}{\omega_o} $
Answer: Let us consider the antideivative firt $$I=\int\Big[e^{-i\omega (n-1)t}-e^{-i\omega (n+1)t}\Big]dt$$ and integrate each term; then $$I=\frac{i e^{-i (n-1) t \omega }}{(n-1) \omega }-\frac{i e^{-i (n+1) t \omega }}{(n+1)
   \omega }$$ When you compute the integral, the value at $t=0$ is just $$\frac{i}{(n-1) \omega }-\frac{i}{(n+1) \omega }$$ and the value at $t=\frac \pi \omega$ $$\frac{i e^{-i \pi  (n-1)}}{(n-1) \omega }-\frac{i e^{-i \pi  (n+1)}}{(n+1) \omega }$$ So, after simplifications $$\int_{0}^{\frac{\pi}{\omega}}\Big[e^{-i\omega (n-1)t}-e^{-i\omega (n+1)t}\Big]dt=-\frac{2 i \left(1+e^{-i \pi  n}\right)}{\omega(n^2-1) }$$ and, for integer values of $n$, $e^{-i \pi  n}=(-1)^n$.
Answer: Hint: $$\int_{0}^{\pi/\omega_0}\left(e^{-j\omega_0(n-1)t}-e^{-j\omega_0(n+1)t}\right)dt\\=-j\left(\frac{1-e^{-j\pi(n-1)}}{n-1}-\frac{1-e^{-j\pi(n+1)}}{n+1}\right)\\=-j\left(1+e^{-jn\pi}\right)\left(\frac{1}{n-1}-\frac{1}{n+1}\right)$$ where I have used the Euler's formula $e^{\pm j \pi}=-1$. I hope this clears things.


FileMaker 17 Data API missing fieldData

Question: I'm doing a simple HTTP POST find to the new FileMaker 17 DataAPI /REST service:
<code>https://{{server}}/fmi/data/v1/databases/{{db}}/layouts/{{layout}}/_find
</code>
and passing this in the request body:
<code>{
    "query":
    [
    {"isActive":"=X", "omit":"false"}
    ]
}
</code>
I get back the following:
<code>{
    "response": {
        "data": [
            {
                "fieldData": {},
                "portalData": {},
                "recordId": "64420",
                "modId": "0"
            },
            {
                "fieldData": {},
                "portalData": {},
                "recordId": "64419",
                "modId": "0"
            },
            {
                "fieldData": {},
                "portalData": {},
                "recordId": "64413",
                "modId": "2"
            }
        ]
    },
    "messages": [
        {
            "code": "0",
            "message": "OK"
        }
    ]
}
</code>
But it appears that I'm only getting back the recordid's associated with the query and the fieldData for that item is missing? I not understainding why there is no column name/value in the fieldData?
I've been looking through: https://fmhelp.filemaker.com/docs/17/en/dataapi/index.html#perform-a-find-request but it's not helpful at all and makes no mention/nor provides a list of tags that can be passed alongside the "query" json array
Comment: Are there any fields on the layout your are querying?
Answer: Do you have the fields you want to access on the layout? FileMaker Data API will give you values from only the fields that you have physically added to the layout.
Have you tried fmRESTor? It's easier to learn and use especially for someone who has no or little experience with accessing FileMaker data from within PHP.

FileMaker 17 Data API missing fieldData


convert xml to excel with specific xml element using java

Question: <code><ns2:CategoryResponse xmlns:ns2="http://schemas.google.com/definitions/ps/v3" currentpage="0"         querydate="2013-09-17T02:33:08.080-04:00" resptime="69ms" resultsperpage="0" totalresults="1">
<category id="65">
   <product id="12304"/>
   <product id="462289"/>
   <product id="340287"/>
   <product id="378825"/>
   <product id="366310"/>
</category>
</ns2:CategoryResponse>
</code>
In the above xml context[sample.xml], I want to store the product ids from the sample.xml into Excel file using java. Please some on help on this.
Answer: you can take a look to this tutorial, it's little big long, but really great explanation.
xml to excel and viceVersa


Limit of A Fibonacci

Question: Let $P(x)$ be an $n^{th}$ degree-polynomial which is defined below for some odd natural number $n$. And let us denote the set of roots of $P$ by $\{r_1,r_2,r_3,\dots, r_n \}$.
$$\displaystyle P(x) = \sum_{m=0}^n F_mx^m $$
Let ${a_k}$ be a sequence defined by:
$$\displaystyle \frac{1}{a_k-r_ka_{k-1}} = r_{k}r_{k+1}\dots r_n $$
$$\forall k\leq n , k\in N^* \text{, with }a_0=1$$
Also, $\{F_m\} $ is the Fibonacci Sequence $(F_0=F_1=1)$ and the set of roots of $P$ also takes into account multiplicity, so this means that double roots may exist twice.
How do I find:
$$\displaystyle \lim_{n\to \infty} (a_n+1)F_{n+1} $$
Answer: Rearranging the given recursive formula:
$$\displaystyle a_k=r_ka_{k-1} + \frac{1}{\prod_{j=k}^nr_j} $$
In general:
$$\displaystyle a_k=B_ka_{k-1} + M_k $$
$$\displaystyle = B_kB_{k-1}a_{k-2} + M_{k-1}B_k +M_k $$
$$\displaystyle = B_kB_{k-1}B_{k-2}a_{k-3} + M_{k-2}B_kB_{k-1} + M_{k-1}B_k +M_k $$
$$= \dots $$
$$\displaystyle a_k = \Bigg(\prod_{p=1}^k B_p \Bigg) \Bigg( a_0 +\sum_{i=1}^k \frac{M_i}{\prod_{t=1}^i B_t} \Bigg) $$
Substitute:$ a_0=1 , B_k = r_k $ and $ M_k = \frac{1}{\prod_{j=k}^nr_j} $ :
$$\displaystyle a_k = \Bigg(\prod_{p=1}^k (r_p) \Bigg) \Bigg( 1 +\sum_{i=1}^k \frac{\frac{1}{\prod_{j=i}^nr_j}}{\prod_{t=1}^i (r_t)} \Bigg) $$
$$\displaystyle = \Bigg(\prod_{p=1}^k r_p \Bigg) \Bigg( 1 +\sum_{i=1}^k \frac{1}{r_i\prod_{j=1}^n r_j} \Bigg) $$
Let $k=n$:
$$\displaystyle a_n= \Bigg(\prod_{p=1}^n r_p \Bigg) \Bigg( 1 +\sum_{i=1}^n \frac{1}{r_i\prod_{j=1}^n r_j} \Bigg) $$
Note that $ \{r_1,r_2,\dots,r_n \}$ are the roots of $P(x) = \sum_{m=0}^n F_mx^m $.
$$\displaystyle \prod_{j=1}^n r_j = (-1)^n\frac{F_0}{F_n} = - \frac{1}{F_n} \;\;\;\; ( n \textrm{ is odd})$$
$$\displaystyle => a_n = -\frac{1-F_n \sum_{i=1}^n \frac{1}{r_i} }{F_n} $$
Now working on the sum :
$$\displaystyle \sum_{i=1}^n \frac{1}{r_i} $$
$$\displaystyle = \frac{\sum_{i=1}^n \frac{\prod_{j=1}^n r_j}{r_i}}{\prod_{j=1}^n r_j} $$
$$\displaystyle = \frac{\sum_{cyc} r_1r_2\dots r_{n-1} }{\prod_{j=1}^n r_j} $$
$$\displaystyle \sum_{cyc} r_1r_2\dots r_{n-1} = (-1)^{n-1}\frac{F_1}{F_n} = \frac{1}{F_n} $$
$$\displaystyle => \sum_{i=1}^n \frac{1}{r_i} = \frac{\frac{1}{F_n} }{-\frac{1}{F_n} } = -1 $$
Substitute back in $a_n$ :
$$\displaystyle a_n = -\frac{1+F_n}{F_n} $$
Now we do the limit:
$$\displaystyle \lim_{n\to \infty} (a_n+1)F_{n+1} $$
$$\displaystyle = - \lim_{n\to \infty} \frac{F_{n+1}}{F_n} $$
$$\displaystyle = -\phi $$

Limit of A Fibonacci


How to modify querystring using URL rewriting?

Question: I am having very less knowledge in URL rewriting, So not sure weather this can be done or not using URL rewrite?
I have a URL like
www.test.com/categroy.cfm?categoryid=12&weight=any&brandid=23
For weight parameter: if its value is 'any' i want to remove it from the url .
For brandid parameter: if brandid is 'any' remove it else replace with 'filter_brand=value'
Outpul like: www.test.com/categroy.cfm?categoryid=12&filter_brand=23
Is it possible ? If yes could anyone please show me an example. I am using IIS.
Comment: What are you using? IIS Rewriting? or ISAPI_Rewrite?
Comment: @Andrew: iiS rewriting.
Answer: Goolge iis rewrite query string
See the fourth result.
IIS URL Rewrite Module Query String Parameters


Jquery dragend events in jquery-dragarrange

Question: I'm usin this library:
https://github.com/vishalok12/jquery-dragarrange
I need to run a function when I'm done dragging the item.

Drag 1

Drag 2

Drag 3

Drag 4

$(function () {
    $('.draggable-element').arrangeable();
});

function dragEnd(){
    alert('Drag End');
}

Answer: Looking at the code there is a dragEndEvent property in options.
Try this:
$(function () {
    $('.draggable-element').arrangeable({
        dragEndEvent: function(){
             alert('Drag End');
        }
    });
});

That was a very quick scan through the code for the library you are using, not tested, but please let me know if it works!
UPDATE - just saw the section under "Optional Parameters" on the GitHub. I think that the dragEndEvent is not actually a call back but a named event. In other words, it triggers this event by name on drag end. The default is drag.end.arrangeable.
Try this instead:
$(function () {
    $('.draggable-element').arrangeable({
        dragEndEvent: "dragend"
    });
    $('.draggable-element').on("dragend", function(){
        alert("Drag End");
    });
});

Or just using the default, use:
$(function () {
    $('.draggable-element').arrangeable();
    $('.draggable-element').on("drag.end.arrangeable", function(){
        alert("Drag End");
    });
});

EDIT NUMBER TWO!
Sorry, this is what happens when posting answers without having chance to test code!
The drag.end.arrangeable event is triggered on the parent element, not the draggables! (I am not sure why the developer did it that way?)
$(dragElement).parent().trigger(dragEndEvent, [$(dragElement)]); <<< see - .parent()

So the code is:
$(function () {
$('.draggable-element').arrangeable();
$('#elements-container').on("drag.end.arrangeable", function(){
alert("Drag End");
});
});
You should also be able to write the second part as
$('.draggable-element').parent().on("drag.end.arrangeable", function(){
    alert("Drag End");
});

But I am not sure if this would create multiple bindings. For some reason I am having massive trouble with the internet today and testing things is simply failing. I made this JsFiddle to test : https://jsfiddle.net/jhartnoll/0ys9gbt6/ but it isn't loading properly my end due to my internet, but try it!
Comment: copying literally generates an error on the line:

$(dragElement).parent().trigger(dragEndEvent, [$(dragElement)]);
Comment: I have tried the 2 options and the trigger is not executed. Instead, inserting an alert in the file drag-arrange.js we see that the line is executed.

        $(dragElement).parent().trigger(dragEndEvent, [$(dragElement)]);
        alert("fnDragEnd");
Comment: Updated answer - if you're getting multiple bindings I would use a different library. Either it's me, my connection (not loading the files correctly) or there are some binding issues within that code, but I don't have time to test that!
Comment: thank you very much. for now I modify the library so that it works in my case


Existence of total order for every set

Question: please prove it from Compactness theorem for propositional logic.
Don't assume AC in any form.
I mean relation $<$ is total order for $X$ iff

trichotomy
transitivity
irreflexivity

are true about $<$ on $X$
Comment: "Don't assume AC in any form" ... except in the form of the compactness theorem, I guess?
Comment: @Alex: Obviously.  The point is to appeal to compactness, rather than to Zorn's lemma.
Comment: What does "plz" mean? Are you being charged by the letter and cannot write "Please"?
Comment: Oh I made a mistake.
Comment: And do you mean compactness for propositional logic or first-order logic?
Comment: Correctly, I meant that assume Compactness theorem only for propositional logic.
Comment: sorry for my English.
Comment: Please assume it instead of AC.
Answer: Consider the language that has propositional variables $p_{x,y}$ for any pair $x,y\in X$. It will effectively stand for $x<y$.
Now, our theory $T$ will be the combination of these three theories:

$\lnot p_{x,x}$ for all $x\in X$;
$p_{x,y}\lor p_{y,x}$ for all $x\neq y$; and
$p_{x,y}\land p_{y,z}\rightarrow p_{x,z}$ for all $x,y,z\in X$.

Use compactness to prove that $T$ is satisfiable: for any finitely many propositions, only finitely many variables are involved, and we can linearly order the set of necessary $x$'s to find a satisfying assignment for the variables.
So by compactness there is an assignment $\sigma$ for which $T$ is evaluated as true. Now define $x<y$ if and only if $\sigma(p_{x,y})=\rm True$, and prove that $<$ is a linear order.

Existence of total order for every set


How to check whether two sets contain the same objects

Question: I have a class IntegerType:
public class IntegerType implements DataType {

    private int value;

    public IntegerType(int value) {
        this.value = value;
    }

    @Override
    public NativeType nativeType() {
        return NativeType.INTEGER;
    }

    @Override
    public int size() {
        return Integer.BYTES;
    }

    @Override
    public Integer value() {
        return this.value;
    }

    @Override
    public boolean equals(Object o) {
        boolean result = false;
        if (o == null || o.getClass() != getClass()) {
            result = false;
        } else {
            IntegerType integerType = (IntegerType) o;
            if (this.value == integerType.value()) {
                result = true;
            }
        }
        return result;
    }
}

And I essentially want to check whether two sets containing instances of IntegerType are the same based on whether the instances have the same .value parameter:
IntegerType int1 = new IntegerType(1);
IntegerType int2= new IntegerType(1);
Set<IntegerType> set1 = new HashSet<>();
set1.add(int1);
Set<IntegerType> set2 = new HashSet<>();
set2.add(int2);

System.out.println(set1.equals(set2));

However running the above code prints out false. From what I understand it should print true since int1.equals(int2) is true. What am I missing here?
Answer: As the name suggests, HashSet requires you to override the hashCode method, which it uses to determine whether or not two objects could possibly be equal. Here is a possible implementation:
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + value;
    return result;
}

Demo


Convex function and local extrema problem

Question: Let $f$ be twice differentiable and strictly convex on $[a,b]$. Assume also that at a point $x_0 \in (a,b)$ the derivative $f'(x_0) = 0$. Show that $x_0$ must be a strict local minimum.
I find that when $x<x_0, f'<0$, and when $x>x_0, f'>0$. So if I can conclude that for all $x$ in the interval, $f(x) > f(x_0)$ and therefore $x_0$ must be a strict local minimum?
Comment: I think it depends on your definition of convexity: If you use the definition $f$ convex $\Longleftrightarrow f''>0$, then the result is immediate. What is your definition of convexity?
Comment: if f is convex, then f''> 0.
Comment: I hope you are allowed to use that if $x_0$ is a minimum of a differentiable function, then $f'(x_0)=0$. Now if $x_0$ is not a strict local minimum, you find a sequence $x_n\to x_0$ (as $n\to\infty$) of minima of $f$. Now the mean value theorem asserts that
$$
f'(x_n)-f(x_0)=f''(\xi)(x_n-x_0)
$$
for some $\xi$ between $x_n$ and $x_0$. Can you obtain a contradiction from here?
Comment: I missed a prime, $f(x_0)$ should be $f'(x_0)$ in the last formula, but I cannot edit it anymore, sorry.
Answer: Given Info: $f'(x_0)=0$, here $S=[a,b]$.
Prove: $x_0$ is a strict local minima $\implies f(x_0) < f(x) \forall \ x \in \mathcal{B}_{\delta}(x_0)$ for some $\delta > 0$ (if $x \neq x_0$).
Prop: If $f$ is a strictly convex function defined over the convex set $S$, then $f(x) > f(y) + f'(y)(x-y) \text{ if $x \neq y$ } \forall x \in S$ and $y$ is an interior point.
Sol:
From, the given data it is clear that $x_0$ is an interior point. Let say there is a $x \in \mathcal{B}_{\delta}(x_0)$, but $x \neq x_0$. So, from the properties of convex function,
$$f(x) > f(x_0)+f'(x_0)(x-x_0) \implies f(x) > f(x_0)$$.


How to identify a PHP variable is an array or not

Question: How to check whether the PHP variable is an array?
$value is my PHP variable and how to check whether it is an array?
Answer: echo is_array($variable);
https://www.php.net/is_array
Answer: php has function named is_array($var) which returns bool to indicate whether parameter is array or not
http://ir.php.net/is_array
Answer: is_array — Finds whether a variable is an array
http://uk.php.net/is_array
Answer: I'm adding a late answer here as I think I've got a better solution if people are using multiple array checks.
If you're simply checking a single array, then using PHP's is_array() does the job just fine.
if (is_array($users)) {
    is an array
} else {
    is not an array
}

However, if you're checking multiple arrays - in a loop for example - then there is a much better performing solution for this, using a cast:
if ( (array) $users !== $users ) {
    // is not an array
} else {
    // is an array
}

THE PROOF
If you run this performance test, you will see quite a performance difference:
<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>

THE RESULT
is_array  :  7.9920151233673
cast, === :  1.8978719711304

Comment: I'm sorry, but I'll stick with `is_array`. **It very precisely describes what it does.** The few microseconds you save on a single call is not worth the source code obfuscation. If you look at this code again in half a year you'll be scratching your head WTF you were trying to do here.


Are all matrices of order $n^2$ bijective linear transformations?

Question: My linear algebra book says that all matrices $T\in L(V,V)$ (of order $n^2$ if the dimension of $V$ is $n$) are linear transformations. Also, each such mapping is bijective.
Shouldn't only invertible matrices be such bijective linear transformations?
EDIT: I may have been confused. Is it the bijection between $T(V,V)$ and $F[n^2]$ that the book mayhave been talking about?
Thanks
Comment: Your edit is probably what the book is talking about. If you fix a basis of $V$, then each linear operator on $V$ has a unique matrix representation.
Answer: Only invertible matrices give bijective linear transformation because
for finite-dimensional vector spaces, rank-nullity theorem yields that
T is one-one if and only if T is onto.
Now, AX=0 gives X=0 whenever A is injective.


Are async methods Thread Safe?

Question: Let say i have an application that uses a database. And whenever this application starts it backups the database to some location. And this backup process takes too much time.
To make the gui responsive I would use async await. Like this;
<code>public async Task BackupDataBase(){

   using(SqlCommand command = new SqlCommand(@"BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'"), connection)
   {
       await command.ExecuteNonQueryAsync();
   }

}
</code>
My question is; Can my application use the same connection to query some other things without any need to lock? Or should i lock the connection while asynchronous method is working?
Comment: So surely your question is 'is `SqlConnection` thread safe?', not 'are async mathods thread safe?'.  Searching will give you lots of results for this.
Answer: Even though you new up a SqlConnection you are effectively requesting a possibly existing instance from  a connection pool maintained internally in the SqlConnection class.
Generally speaking it will not be blocking. You can limit the maximum pool size to one, but this would most likely cause most of your app to become very unresponsive and it would be suicide in a web app.
The sql server is generally good at keeping appropriate locks given the nature of your sql statement and my guess is that your code would work.
It is perhaps a little unconventional to make the backup from within your application though, and it would become a mess if your ever scaled the app horizontally to more than one Web server.
So how about a scheduled task on the sql server?

Are async methods Thread Safe?


What do you do when a string breaks or you drop your pick on stage?

Question: One of my nightmares when I'm on stage is breaking a string or losing my pick. The former has happened to me before once, and also once right before I had to go on stage.
Are there any tips my fellow guitarists might have for when they lose their pick, break a string, or anything else happens that interrupts you mid-song? Do have any tips for avoiding these incidents all together?
Comment: Sometimes you just gotta roll with these things
http://www.youtube.com/watch?v=opiMHTaUEaA
Answer: I recall seeing a show years ago. fIREHOSE was doing a "50 states in 50 days" tour, and this show was a triple bill with Madder Rose opening. Madder Rose's bassist popped his E string, and he just knocked the bassline up an octave, which really kicked the song into fifth gear. He then spent minutes trying to beg, borrow or steal a bass or bass string, which just knocked all the momentum out of the show.
Later, Mike Watt popped his G string. (I still have it.) He nodded to George Hurley, who started in on a drum solo. Maybe a drum solo isn't the most punk-rock thing ever, but it filled the space while Mike changed a string and tuned up. At the end of it, there's Mike Watt, Greg Norton (ex-Husker Du bassist) and me, watching George get his thing on, with Mike looking at me and nodding toward George, as if to say, "That's my drummer. Isn't he good?" And he was.
The point of it is, it happens. It happens to starting out opening bands and it happens to top-of-bill bands. Things fall apart. It's scientific. But there are a few takeaway points.
1) Be able to do without - The first bassist really took the song to the next level just by knocking the bass up an octave. Word is that Jeff Beck dropped a pick, started playing with fingers and decided to always go that way. There might be things you can't do by picking with fingernails, but maybe what you can do will work out for a while.
2) Have spares - the SEALs say "Two is one. One is none." Have spare strings. Have spare picks. Have spare cables. If you need it, have two in case one breaks. If you play a Floyd Rose, getting the balance back will take longer than a song, so bring a second guitar.
That being said, it's a good idea to have several spare windings on the tuner of Floyd Rose guitars, so if the break is near the bridge, you can unlock the bridge and the nut, run some more string, and get it back together fairly quickly.
3) Have a plan - In my story, Mike Watt went to the drum solo when he had to change strings. On the Dead Kennedys' Give Me Convenience or Give Me Death, there's a live track called "Night of the Living Rednecks" where, after East Bay Ray had a string break or something, the rhythm section went into a jazz groove while Jello Biafra told a story about being a punk being harrassed by rednecks, and it's my favorite track on that album. Anything is better than 5 minutes of silence while you try to get your act together.
4) Take it up a notch - 10s are a little sturdier than 9s, which is why I tend to go 10s.
5) Take it down a notch - Do you need to strum that hard? It may look like you're playing all intense, but there's only so hard you can pluck a string before it makes no difference. There's other sorts of stagecraft to look all hard and intense and be easier on your strings.
6) Don't play with knives - I used to have these Hot Licks brass picks from Dunlop. They're thin, and they sound bright and jangly, but they're metal and don't bend, unlike plastic thin picks. I was playing acoustic rhythm in an otherwise electric rock band, with in-ear monitors, and I simply could not hear myself unless I developed a strong picking technique, which I've been trying to dial back since. But I was carving the windings off my wound G string, because I was in effect sharpening this pick to get really sharp. I like it, and I use it on electric where I have a much more mellow strumming style because I have amplification backing me up, but I moved to an unwound G on an acoustic just so I wouldn't have to change strings so often, just because I didn't realize my pick was carving up my strings.
Other players may have other issues. Burrs in the saddle are common reasons why strings break. If you have a recurring string-breaking problem, the problem might be with your gear.
7) It is important - I saw Madder Rose two years later. They had another bassist. I don't know the story, but clearly, if you can play but you let the band down enough when they need you, they can find another person who can play.
Comment: another thouroughly earned +1. as another example, I also developed a very strong strumming style with bass, using anything up to 3mm big stubby picks. Never managed to break a string on stage but because of the strength I needed to strum like that, I've dropped the pick before from muscle fatigue. Tried to back it up with fingers, then grabbed one of the 5 picks duct taped to the scratchplate. Worked fine but I've since started using nice and bendy 1mm nylon picks and toned down the strumming. Also, I have a spare amp which was needed at my last gig. Two is one, one is none. great answer :)
Comment: Addendum: I've taken Billy Gibbons' position and gone down to .008s on my #1 guitar. I tend to play light, so I haven't had breakage issues.
Comment: [Here is a clip](https://m.youtube.com/watch?v=_jsHCHvp2_Y) of Stevie Ray Vaughan breaking a string and swapping guitars, *flawlessly*. I'm almost convinced he broke the string on purpose just to show off ...as off SRV needs any "tricks" to show off.
Answer: I've broken strings quite a few times while playing guitar leads.
I think how you react to that depends on the material. In my case I'm playing original songs, and the lead parts are largely improvised anyway. So I just keep playing on the other strings - no big deal.
I think if I was playing a cover song, I would still try and improvise the lead. I don't think most people would be bothered by that.
Most chords will sound OK if you are missing a string. Presumably the harmony will still come through with all of the other instruments.
If you were playing something quite specific - maybe even classical - well, you'll just have to switch guitars,  and maybe even halt the song whilst you do that. I always bring a spare guitar, and if I break a string I switch to it after the song has finished. You don't want to be re-stringing between songs if you can help it.
On losing picks: I've never dropped a pick once, but I keep an extra pick in my pocket "just in case". I think if you're dropping picks you must not be holding it correctly.
Most popular guitarists I see that tape all of the additional picks to the guitar, mainly do that so they can throw them to the audience during the show.
Comment: That's why I'm a hardtail kind of guy.
Comment: "Most chords will sound OK if you are missing a string". If you have a stop tailpiece. If you have a tremolo, you could go out of tune instantly, depending on the string.
Comment: @tinman, yeah that's true. It may depend on the guitar as well. My strat seems to stay (reasonably) in tune when I've lost a string. A cheaper guitar probably wouldn't. As you say, losing the heavier strings will probably knock it out of tune more as well.
Answer: Hiya!
Well, there's a phrase that a gigging guitarist gets familiar with: "shit happens".
It never hurts to be flexible and good at improvising.
Losing your pick: you can buy pickholders (they are inexpensive) that stick to either the side of your guitar, or on a microphone stand if you sing at all.
Failing that, i try to keep a couple of spare picks in my back pocket too.
String breaking:
I once broke a string on stage mid-song. you have a couple of options. one is to put the guitar down, pick up your backup guitar (if you brought one) and keep going.
another is to try re-calculating the song in your head without that string. you'll be surprised by how many rock songs you can actually re-work this way with little trouble. I played Wonderwall with no D string, and barely no-one noticed. if anything, you get rocknroll points for ripping the broken string off and throwing it down.
Anyway, this will hardly ever happen if you periodically and properly change your strings (say, maybe a week before gig time?). failing that, extra strings should always be in your gig bag :)
Sorry for the novel! It's just a relatable problem.
Cheers!
Comment: Exactly! And [this](http://www.wedgie.com/images/pickholder.jpg) is an example of pick holder, or [this](http://www.americanmusical.com/ProductImages/Large/p17238.jpg) one.
Comment: Unfortunately,if you are using a standard tremolo (not FR or other lockable type), if a string breaks you will go heavily out of tune.
Answer: Keep a spare guitar tuned up at the back of the stage, and keep spare picks everywhere you roam on stage.
I have once played a gig without a spare and when I snapped my B early on in a song I had no option but to bend up every chord and note until the rhythm guitarist had a little instrumental break and quickly fine tuned up to close enough.
Makes you think though - and helps you break into new tonal styles:-)
Answer: I keep a spare guitar tuned and on a stand where I can reach it fast. The last time a string broke while on stage I switched guitars immediately and was playing within seconds.
Yeah, it sounded different because I switched to my Les Paul, but that was better than dealing with the hassle of the guitar going out of tune because of the tremolo, and worrying about working around the missing string.
I keep two sets of strings, with some loose E and B strings in my case, along with some tools to fix loose screws or tighten jacks. See "What tools should every guitarist have?" for a similar discussion.
As far as picks, keep some in your pocket, and keep some on top of the amp. Get a pick holder for your microphone stand.
If you don't want unexpected things to mess you up you have to think about what could happen in advance, and figure out what you can do to avoid or minimize the problem.
Also think about what you'll do if a battery dies, if an amp tube dies, a fuse blows, a guitar or speaker cord gets stepped on and bends the plug....
Answer: For the picks, have spares around. They're cheap.
For the string breaks, I've seen 3 options.

Major artists like Melissa Etheridge have plenty of spare guitars (with staff to hand them off to her onstage) and the last time I saw her perform, she swapped guitars each song.
For (at least one) touring tiny/garage bands (the kind that play at bars/nightclubs in one city and might travel 20-30 miles to perform), I've noticed that the sound person turns down the mix on the guitarist with the broken string and they've just pretended to be playing (they didn't have spare strings in the van, so they did it again after the break).
I remember one jazz concert (I forget the name, I used to drink too much back in those days) and the guitarist just started transposing on the fly. I was close enough to see the broken strings (2 of them) and I was amazed.

I am terribly slow with restringing and tuning, so my tactic would be to have a spare instrument.
Answer: When it comes to a string breaking Nick Harper manages to turn the situation on its head by doing a party trick
He normally plays by himself with an acoustic and when a string breaks mid song (the way he plays this happens fairly often) he just changes it without stopping
He'll typically sing a few lines of the tune acapella with minimal playing while he gets a new string out of his back pocket and then he'll gradually start playing as much as he can until the string is on. He manages to get it on and up to tune really fast, It's quite amazing to see
Comment: I understand that Steve Goodman had a similar schtick for changing strings mid-song. I wish/hope there's video on Youtube. It's cool I want to be able to do that. But it won't work like that for Steve Vai, and if you're the sideman, not the frontman, it is best that the audience not even notice it happened.
Answer: I never break strings.. Must have a soft touch.  I have seen good pickers turn the break into part of the act...  Just keep on playing around the broken one.
As to picks, I almost never loose one either but nothing is worse than having the thing pop into the inside of your guitar....
Some guys who drop a lot of 'em buy those little stick-on pick dispensers... They're like the old change dispensers you kept in your car for toll booths.
Answer: I ask the guitar with other guitar players who have played before and will play after my group)) I didn't drop my picks before)
Answer: I always put some picks with gaffa tape on my mike stand, so that I can easily pluck one off in case one slips from my fingers.
Answer: major bands will swap guitars every song, with a roadie restringing the used one backstage (yes, that's fresh strings for every song!).
For those with smaller budgets and no roadies, having a spare guitar backstage and applying fresh strings to both instruments regularly will have to do.
For picks, have spares or do without. There's pick holders you can clip to your guitar strap or to microphones for that purpose.
Answer: I have a spring loaded pick holder taped with double-sided tape next to my bridge.
It is within easy reach to replace any dropped picks.
To prevent breaking strings I use a softer pick. I found that stiff picks although good for lead are not the best choice for strumming.
Answer: Have a joke or something clever to say to make the audience laugh[?]. Steven Wilson does that when he breaks a string in their "Arriving Somewhere" DVD during the last song Trains (string breaks around 4:00).
Answer: Eddie Van Halen uses a piece of double sided masking tape on the lower cutaway wing, to hold picks. So, if you're in the middle of playing, you can strum down with your thumb, and grab a pick on your way back up. Helps me while playing. Dropped my pick infront of 700 people. EVH saved me.
Answer: Depends on the style of music. If it is Rock, you keep going. Use the rest of the strings. Use your fingers instead of a pick. Proceed as if you did not even notice. Don't even acknowledge it as a problem. Outcomes may vary.
Answer: In rehearsal I used to keep playing if a string broke to get used to playing without the string. If it happens on stage reinvent the guitar part. I've occasionally found cool stuff under the gun, more often just got through it. I broke a string second song new years eve and played for an hour more remaking parts on the fly. The Audience didn't know and the drummer was amused as, because it didn't throw my time, it didn't bother him. Afterwards my hand hurt from the tension.


Unable to instal Sys Go package, I tried the normal way but it doesn't make sense. Please find below my Go env below

Question: I cannot get the GoLang Sys package installed.

Furthermore, below is my Go env:
GO111MODULE="auto"
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/zahidk/.cache/go-build"
GOENV="/home/zahidk/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/zahidk/gocode/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/zahidk/gocode"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.17.6"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build2915773640=/tmp/go-build -gno-record-gcc-switches"

I tried using go get -u golang.org/x/sys and GOPATH/src/golang.org/x/sys from the website (https://pkg.go.dev/golang.org/x/sys#section-readme) to install the sys package but for some reason it doesn't work. Furthermore in my src directory are all my GoLang files. That's it.
Comment: What does "it doesn't work" mean? Was the module added to your go.mod?
Answer: Your go env indicates you are using GOPATH mode (instead of modules):
GO111MODULE="auto"
GOPATH="/home/zahidk/gocode"
GOMOD=""

The error message indicates the editor GOPATH is /home/zahidk/GoLang which
is different to your go env (/home/zahidk/gocode). This likely explains why the downloaded code is
not found when developing via the editor.
You should ensure the GOPATH environment variable is set correctly everywhere, or migrate to modules.
Using modules is recommended if you don't have a specific need for GOPATH. Modules make it easier to manage dependencies and are likely better supported by your editor.

Using Go Modules
Getting started with Go -- interactive tutorial demonstrating modules in a new project.
Comment: Thanks, yes Go Modules work really well.


How to only reload current file in Emacs Haskell Mode

Question: In Emacs' Haskell-Mode, I can push ctrl-c ctrl-l to reload the current file in the REPL. Each time I do this, however, it compiles all the file's local dependencies (modules in the same folder), which takes a bit of time. Is there a simple way to reload only the current file/module and skip recompiling the others? It must be possible somehow, as my external dependencies don't need to be recompiled each time.
Comment: @LogicChains: it's on the list: https://github.com/haskell/haskell-mode/issues/807
Comment: just `:r` right in the `REPL` buffer should work
Comment: Emacs hot key is `C-c-l`.
Comment: Ah, great, that works fine. If you want to submit that as an answer I'll accept it. Surprised there's not an Emacs-Mode hotkey for it though.
Answer: If you switch to the REPL-Buffer and just reload (:r) it should work as expected.
Answer: Recently :reload got its own keybinding: C-c C-r.


Regex: match word that ends with "AM" (with case insensitive comparison)

Question: I need to compare text ends with "AM" using regex. With case insensitive input i.e.

AM
am
Am
aM

All should be valid scenario. I am trying below
myinput.match(/^\w*am\b$/)

But it is doing case sensitive comparison (i.e. for 'am' but not working for AM, Am, aM).
JSFiddle
Comment: `myinput.match(/^\w*am$/i)`
Answer: You need to add case intensive flag at the end:
myinput.match(/^\w*am\b$/i)

Edit: as per your comment
The issue with 07.15am is the first part of your regex. If you want to be strict then you could try:
/^(\w+)(\.\w+)\s?(am)$/i

This will match 07.15am, 07.15Am or 07.15 AM.
If you want to be a little looser you can make the second group optional.
/^(\w+)(\.\w+)?\s?(am)$/i

Also this wont work if you have anything before or after the string. I would suggest removing the ^$ boundaries.
/(\w+)(\.\w+)?\s?(am)/i

That should cover most cases.
Comment: `\b$` here is the same as `$`.
Comment: It is not working if input is: 07.15am

Regex: match word that ends with “AM” (with case insensitive comparison)


Windows server 2003 check disk fails

Question: I tried doing ntbackup and got a lot of errors saying there were corrupt files and eventually it would come to one that it could not deal with and abort.  This is what I get when running chkdsk:
<code>C:\Documents and Settings\Administrator>chkdsk c:
The type of the file system is NTFS.

WARNING!  F parameter not specified.
Running CHKDSK in read-only mode.

CHKDSK is verifying files (stage 1 of 3)...
725312 file records processed.
File verification completed.
2802 large file records processed.
0 bad file records processed.
0 EA records processed.
2 reparse records processed.
CHKDSK is verifying indexes (stage 2 of 3)...
10 percent complete. (18661 of 1888792 index entries processed)
File record segment 1960 is unreadable.
10 percent complete. (19199 of 1888792 index entries processed)
File record segment 1970 is unreadable.
File record segment 1971 is unreadable.
File record segment 1972 is unreadable.
11 percent complete. (35906 of 1888792 index entries processed)
Correcting error in index $I30 for file 6803.
Correcting error in index $I30 for file 6803.
Correcting error in index $I30 for file 6817.
Correcting error in index $I30 for file 6817.
16 percent complete. (173647 of 1888792 index entries processed)
File record segment 45733 is unreadable.
File record segment 45734 is unreadable.
File record segment 45735 is unreadable.
File record segment 45736 is unreadable.
File record segment 45737 is unreadable.
File record segment 45740 is unreadable.
File record segment 45741 is unreadable.
File record segment 45743 is unreadable.
File record segment 45746 is unreadable.
22 percent complete. (340222 of 1888792 index entries processed)
File record segment 129101 is unreadable.
37 percent complete. (772265 of 1888792 index entries processed)
An unspecified error occurred.
</code>
I already ran it with the repair option and it aborts using that as well.
A tech came in and replaced the drives.  He was able to get a disk image and move it.
It only moved the problems to a new disk.  We cannot restore from a backup because we recently build this system and do not have a backup and would like to avoid starting from scratch.
Also, I tried easy backup ultimate and that did not work either.
Another thing, I created a folder and created 7000 random files in it after the new drives were put in.  When trying to back it up, ntbackup did not fail, but did give me numerous corrupt file errors.  I would think if it was the drives, creating new files and backing them up would not give me errors unless the file system was trashed and somehow caused them to be wrong.  the files that it says are corrupt, I can open with an editor and save them.  They still come up as corrupt on the backup.  If I copy the files, the copies are corrupt as well.
Pretty weird.
I am looking for suggestions on the best way to proceed and how to trouble shoot the issue.
Answer: If you recently built this system and don't have backups, starting from scratch is exactly what you want to do.  Your filesystem seems to be suffering from massive corruption.  Even if chkdsk fixes it there maybe strange unexplainable errors later on from damaged OS files.
Imaging a corrupt filesystem is of course going to move the corruption with it.
I would start off by testing the server's RAM, raid controller and disks to make sure they aren't causing corruption.  Then wipe the drives and start over.  If you weren't doing backups yet that basically means the work so far setting it up had no value to you.  So start over and do it right.  And start backing it up right away.
Comment: I fear that is what we will need to do.  The client that I am working with procrastinated and did not provide a backup drive until they were live for 2 months, so we have production data that may cause a problem in this.  Was hoping to be able to fix the current system.

Windows server 2003 check disk fails


XML and DOM getting #text output

Question: I'm trying to read a Collada XML file by iterating through a child node list, and every other output reads #text.  What's this about?  My code:
<code>public void runTest() {
    File file = new File( "test.dae" );
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    }
    catch( ParserConfigurationException error ) {
        System.out.println( "--ParserConfigurationException: " + error.getMessage() ); return;
    }
    Document document = null;
    try {
        document = builder.parse( file );
    }
    catch( IOException error ) {
        System.out.println( "--IOException: " + error.getMessage() ); return;
    }
    catch( SAXException error ) {
        System.out.println( "--SAXException: " + error.getMessage() ); return;
    }
    Node node = document.getDocumentElement();
    String node_name = node.getNodeName();
    System.out.println( node_name );
    NodeList node_list = node.getChildNodes();
    for( int iterator = 0; iterator < node_list.getLength(); iterator++ ) {
        Node child_node = node_list.item( iterator );
        String child_node_name = child_node.getNodeName();
    System.out.println( "-- " + child_node_name );
    }
}
</code>
Answer: "#text" is simply the result of calling the getNodeName() method on a Text node. (As you will see if you look at the API documentation for org.w3c.dom.Node.) If you want the actual text contents of the node, you would use the getNodeValue() method.
And if you weren't expecting there to be any Text nodes, don't forget that even little bits of whitespace, like new-line characters, are treated as text.
Comment: Hmm. I'd expect there to be text in the text nodes. I just didn't expect getNodeName() to do anything other than to, well, get the node name. Here it seems like it moonlights as getNodeType() or whatever. Anyway, I'm not going to question why, there probably is a good reason. As of now I just have to add code like if( node_name == "#text" ) continue; to get what I want.
Comment: For future reference, there is a better way to go about getting just the elements. Check out the `getElementsByTagName` method of the `Element` interface. You can use `getElementsByTagName("*")` to get just the element children of a given element. It requires some casting to `Element` if you are looking through a NodeList, but it's worth it.

XML and DOM getting #text output


It has been shown that every open set in ℝ is the union of disjoint open intervals. Is this true for $ℝ^n$ in general?

Question: It has been shown that every open set in $\mathbb R$ is the union of disjoint open intervals. Is this true for $\mathbb R^n$ in general?
It seems to me that it is not, but I cannot think of an example.
Comment: I think the closest $\mathbb{R}^n$-counterpart would be: "every open set in $\mathbb{R}^n$ can be written (uniquely) as a countable union of disjoint connected open sets."  It's just the case that connected open sets in $\mathbb{R}$ are open intervals.
Comment: How are you defining *interval* in $\Bbb R^n$?
Comment: @AlexisOlson That's a different question, since there is no requirement of disjointness there.
Comment: I am defining an open interval in R^n as a product on n open intervals in R.
Comment: It is not true in general for $\mathbb R^n$, but we do have the slightly weaker (but still very useful) result that [every open set can be decomposed as a countable union of almost disjoint closed intervals](http://math.stackexchange.com/questions/640491/every-open-subset-o-of-bbb-rd-d-geq-1-can-be-written-as-a-countable-unio)
Comment: Looks like @BrianM.Scott has been answering this question for years. http://math.stackexchange.com/questions/435596/check-my-answer-prove-that-every-open-set-in-bbb-rn-is-a-countable-union-of
Comment: product of open intervals are rectangles.  An open disc is not a union of disjoint rectangles.
Comment: @Batominovski that captures the spirit of the question.  "intervals" was arbitrary and unimportant.  In 1-dimension connected open sets are intervals.
Answer: It's unclear what you mean by "interval" in a higher-dimensional context. Reasonable candidates include boxes ( = Cartesian products of open intervals) and open balls. However, here's a general result showing that almost any such claim will fail even in $\mathbb{R}^2$:
Let $\mathcal{O}$ be some family of open sets (e.g., all open boxes), and let $U$ be a connected open set which is not an element of $\mathcal{O}$ (e.g., $U$ is an open ball). Then $U$ cannot be written as a disjoint union of elements of $\mathcal{O}$. Why? Well, suppose it could - as $U=\bigsqcup A_i$. Fix some nonempty $A_i$ in particular. Since $U\not\in\mathcal{O}$, we have $A_i\subsetneq U$; so (why? this is where connectedness of $U$ gets used!) we can find a point $x$ on the boundary of $A_i$, which is in $U$. Then any open set at all containing $x$ has to intersect $A_i$. But $x\in A_j$ for some $j$, since $x\in U$! So $A_i\cap A_j\not=\emptyset$, contradiction.
EDIT: Or, as Bungo points out below, $A_i$ and $\sqcup_{j\not=i} A_j$ partition $U$ into two disjoint open sets, contradicting the assumption that $U$ was connected.
The key difference between the two-(or higher-)dimensional case and the one-dimensional case? In one dimension, the connected open sets are easy to classify - they're exactly the open intervals! In two dimensions, though, there are lots of connected open sets. Really, the theorem that works for all dimensions is

Any open set can be written as a disjoint union of connected open sets;

it's just that for $n=1$ this can be phrased in a particularly snappy way.
Comment: Maybe even simpler to note that that $A_i$ and $\cup_{n\neq i}A_n$ are disjoint nonempty open sets whose union is $U$, hence obtaining the contradiction that $U$ is disconnected?
Comment: @Bungo Yes, that's even simpler. Oh well. :P


Commute finite and infinite sum

Question: Let $a_{ij}\ge 0$ real numbers. Is it true that
$$\sum_{i=1}^n \sum_{j\in\mathbb{N}} a_{ij}= \sum_{j\in\mathbb{N}} \sum_{i=1}^n  a_{ij} $$
I am pretty sure it is true, but I can't prove it. Any hint - or counterexample?
Comment: I think the Monotone Convergence Theorem is of interest here.
Comment: I know, but I dont want to use any measure theorem. Is there an elementary proof?
Answer: Note that if $b_i,c_i\geq 0$ are sequences then
$$\lim_{i\to\infty}{(b_i+c_i)}=\lim_{i\to\infty}{b_i}+\lim_{i\to\infty}{c_i}$$
Applying this finitely many times gives us the result. (Note that the assumption of nonnegativity, or at least nonnegativity of the product of the two sequences, is required for this to hold in general).
Comment: Thanks very much, it was easy, I'm just dumb.
Comment: @AngeloRendina You're welcome.

Commute finite and infinite sum


What's the best way to scrape web page from android application

Question: I am working on android application to get some data from html webpage and parse it to be used in the application.
I tried to use Web-harvest, but it seems not fully compatible with android.
The Application should get the webpage, parse it, get the needed data, and use it in the app.
so whats the standard and recommended way to scrape html pages in android ?
Answer: I've been happy with using TagSoup and XOM to parse webpages on Android.  With both in your classpath, you'd do something like:
XMLReader tagsoup = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");
Builder bob = new Builder(tagsoup);
Document html = bob.build("http://www.yahoo.com");
Nodes images = html.query("//img");

for (int index = 0; index < images.size(); index++) {
    Element image = (Element) images.get(index);
    String src = image.getAttribute("src").getValue();
    // do something with it...
}

If the HTML you're scraping has a namespace, you'd do the below instead:
XPathContext context = new XPathContext("html", "http://www.w3.org/1999/xhtml");
Nodes images = html.query("//html:img", context);

Links:
XOM --> http://www.xom.nu
TagSoup --> http://ccil.org/~cowan/XML/tagsoup/
Of course, you'll have to catch possible exceptions on building the XML document from the Web page.


Am I uninstalling, installing Mysql the right way?

Question: I changed my.cnv and nobody can connect to mysql again. So I decided to reinstall mysql.
I did
sudo aptitude purge mysql-server

followed by
sudo aptitude install mysql-server

then I got this log:
root@ip-10-134-10-182:~# sudo aptitude purge mysql-server
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?

Then when I do
sudo aptitude install mysql-server

I am stuck in a line. Looks like I need to fully uninstall mysql first before continuing. How.
Then I finally do
root@ip-10-134-10-182:~# sudo aptitude install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  libhtml-template-perl{a} mysql-server mysql-server-5.1{a} mysql-server-core-5.1{a}
0 packages upgraded, 4 newly installed, 0 to remove and 38 not upgraded.
Need to get 0B/12.2MB of archives. After unpacking 29.7MB will be used.
Do you want to continue? [Y/n/?] Y
Writing extended state information... Done
Preconfiguring packages ...
Selecting previously deselected package mysql-server-core-5.1.
(Reading database ... 27052 files and directories currently installed.)
Unpacking mysql-server-core-5.1 (from .../mysql-server-core-5.1_5.1.63-0ubuntu0.10.04.1_amd64.deb) ...
Selecting previously deselected package mysql-server-5.1.
Unpacking mysql-server-5.1 (from .../mysql-server-5.1_5.1.63-0ubuntu0.10.04.1_amd64.deb) ...
Selecting previously deselected package libhtml-template-perl.
Unpacking libhtml-template-perl (from .../libhtml-template-perl_2.9-1_all.deb) ...
Selecting previously deselected package mysql-server.
Unpacking mysql-server (from .../mysql-server_5.1.63-0ubuntu0.10.04.1_all.deb) ...
Processing triggers for man-db ...
Processing triggers for ureadahead ...
Setting up mysql-server-core-5.1 (5.1.63-0ubuntu0.10.04.1) ...
Setting up mysql-server-5.1 (5.1.63-0ubuntu0.10.04.1) ...
120807  6:58:36 [Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
120807  6:58:36 [Note] Plugin 'FEDERATED' is disabled.
120807  6:58:36  InnoDB: Initializing buffer pool, size = 8.0M
120807  6:58:36  InnoDB: Completed initialization of buffer pool
120807  6:58:36  InnoDB: Started; log sequence number 2 4115700857
/usr/sbin/mysqld: File './mysql-bin.000005' not found (Errcode: 13)
120807  6:58:36 [ERROR] Failed to open log (file './mysql-bin.000005', errno 13)
120807  6:58:36 [ERROR] Could not open log file
120807  6:58:36 [ERROR] Can't init tc log
120807  6:58:36 [ERROR] Aborting

120807  6:58:36  InnoDB: Starting shutdown...
120807  6:58:42  InnoDB: Shutdown completed; log sequence number 2 4115700857
120807  6:58:42 [Note] /usr/sbin/mysqld: Shutdown complete

And after that it's just stuck there.
Answer: To remove mysql-server use: sudo aptitude remove mysql-server
if you just want to reinstall use: sudo aptitude reinstall mysql-server
Comment: You should be able to just call the aptitude reinstall command. If that fails, remove it and start all over.
Comment: I want to reinstall. Do I need to remove first?
Comment: I haven't got this problem at the moment but there have been several times in the past where I've wanted to reset a package and not known how to properly , resulting in one or two binned VMs, I'm going to remember this one!
Comment: Ya well.... I keep getting this lock that lock this bin that bin doesn't work and then hang.
Answer: 120807  6:58:36  InnoDB: Started; log sequence number 2 4115700857
/usr/sbin/mysqld: File './mysql-bin.000005' not found (Errcode: 13)
120807  6:58:36 [ERROR] Failed to open log (file './mysql-bin.000005', errno 13)
120807  6:58:36 [ERROR] Could not open log file

To know what does Error 13 mean:
# perror 13
OS error code  13:  Permission denied

So, it sounds like the above file is not owned by mysql user:
# chown -R mysql:mysql /path/to/data/dir

and try again.
Comment: Should I run as root?
Comment: Yes, you need root to change owner to other user.