Sylow subgroups/subgroup lattices in algebraic topology?

Question: One of my professors this semester very graciously offered to give me some projects to work on over the summer, and I happily accepted his offer. The only (minor) drawback is that my interests lie in topology, while his lie in Sylow subgroups and subgroup lattices (among other group theoretic topics). Algebra is my weakest subject, so it will be great to work more in it. However, I was wondering if anyone knew of any connections between Sylow subgroups and techniques in algebraic topology so that I could have some extra motivation when working through the various problems he gives me this summer!
I truly appreciate any insight you may be able to offer!
Comment: There are many connections between group theory and the fundamental group (what is in a name). It is a fact that any finitely presented group occurs as the fundamental group of a CW complex of a two dimensional space. Maybe you can explore how/when the Sylow subgroups arise as fundamental groups of certain subspaces?
Comment: Thank you @ThomasRot! This would be a great way for me to explore the connection between the two areas in a way that I could grasp quickly and play around with!
Comment: Note that I do not know anything about Sylow subgroups, so I don't know if this really leads to anything very interesting. You can also look at a similar problem in other categories (e.g. any finitely presented group occurs as the fundamental group of a four dimensional manifold and you can try to play the same game.) Another topic could be to look at the the correspondence between covering spaces and fundamental groups and see what this implies for the sylow subgroups
Comment: I think at the very least it will help build my intuition with Sylow subgroups (along with fundamental groups and covering spaces), which is always a good thing! It will be a perfect place to start!
Answer: You could take a look at Homotopy properties of the poset of nontrivial p-subgroups of a group by Daniel Quillen and the many later papers citing this article. Alternatively find a chapter in Stephen D. Smith's book Subgroup Complexes that interests you. Finally you could also look at the work of Dave Benson by either picking an article from his Groups, Representations and Cohomology Preprint Archive or a chapter from his books titled "Representations and Cohomology".
Comment: Thank you for all of the wonderful resources! I can't wait to delve into them and hopefully tell my professor about them as well (maybe we'll be able to study some of the papers--that would be wonderful)! I really appreciate you taking the time to link to all of the resources as well--thank you so much!


Como incluir propriedade do dateInterval dentro de uma variável

Question: Depois de conseguir a diferença de tempo entre dois campos input time (vide esta pergunta), não sei agora como faço para colocar estes valores dentro de variáveis, para assim poder utilizá-los em outras funções.
O var_dump da variável $intervalo (que guarda o dateInterval) é:

object(DateInterval)#3 (15) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(0) ["h"]=> int(5) ["i"]=> int(18) ["s"]=> int(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> int(0) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }

(em negrito acima estão os campos que interessam)
Então tentei algo como:
$hora = $intervalo[h];

ou
$hora = $intervalo["h"];

ou
$hora = $intervalo['h'];

Mas acho que o [h] não é um vetor... A pergunta é: como colocar a propriedade [h] em uma variável?
Pesquisei na página do manual, mas meu inglês não é lá estas coisas, então não resolveu.
Answer: A primeira palavra do var_dump mostra object então para acessar suas propriedades utiliza-se o operador seta ->.
pode obter o valor da seguinte forma:
$hora = $intervalo->h;

ou ainda:
$hora = $intervalo->format('diferença de horas: %h');

Lista dos parâmetros validos para format
Comment: Perfeito, valeu mesmo!


release mode error, but not in debug mode

Question: My code runs fine in debug mode but fails in release mode.
Here's a snippet of my code where it fails:
LOADER->AllocBundle(&m_InitialContent);
while(!m_InitialContent.isReady())
{
    this->LoadingScreen();
}

AllocBundle() will load the content contained in m_InitialContent and set it's ready status to true when it is done. This is implemented using multithreading.
this->LoadingScreen() should render a loading screen, however at the moment that is not implemented yet so the function has an empty body.
Apparently this might be the cause of the error: If I give the function LoadingScreen() one line of code: std::cout<<"Loading"<<std::endl; then it will run fine.
If I don't, then the code gets stuck at while(!m_InitialContent.isReady()) It never even jumps to the code between the brackets (this->LoadingScreen();). And apparently neither does it update the expression in the while statement because it stays stuck there forever.
Does anyone have any ideas what might be causing this? And if so, what might the problem be?
I'm completely puzzled.

EDIT: Additional code on request
member of ContentLoader: details::ContentBundleAllocator m_CBA;
    void ContentLoader::AllocBundle(ContentBundle* pBundle)
    {
        ASSERT(!(m_CBA.isRunning()), "ContentBundleAllocator is still busy");
        m_CBA.Alloc(pBundle, m_SystemInfo.dwNumberOfProcessors);
    }

void details::ContentBundleAllocator::Alloc(ContentBundle* pCB, UINT numThreads)
{
    m_bIsRunning = true;
    m_pCB = pCB;
    pCB->m_bIsReady = false;

    m_NumRunningThrds = numThreads;
    std::pair<UINT,HANDLE> p;
    for (UINT i = 0; i < numThreads; ++i)
    {
        p.second = (HANDLE)_beginthreadex(NULL,
                                          NULL,
                                          &details::ContentBundleAllocator::AllocBundle,
                                          this,
                                          NULL,&p.first);
        SetThreadPriority(p.second,THREAD_PRIORITY_HIGHEST);
        m_Threads.Insert(p);
    }
}

unsigned int __stdcall details::ContentBundleAllocator::AllocBundle(void* param)
{
//PREPARE
    ContentBundleAllocator* pCBA = (ContentBundleAllocator*)param;

//LOAD STUFF [collapsed for visibility+]

   //EXIT===========================================================================================================
        pCBA->m_NumRunningThrds -= 1;
        if (pCBA->m_NumRunningThrds == 0)
        {
            pCBA->m_bIsRunning = false;
            pCBA->m_pCB->m_bIsReady = true;
            pCBA->Clear();
    #ifdef DEBUG
            std::tcout << std::endl;
    #endif
            std::tcout<<_T("exiting allocation...")<<std::endl;
        }

    std::tcout<<_T("exiting thread...")<<std::endl;
    return 0;
}

bool isReady() const {return m_bIsReady;}

Comment: You at least need to show the code of AllocBundle() and isReady().
Comment: I'm not sure whether this is correct or how to best explain it in an answer but your reading of the m_bIsReady is probably not being read from memory due to compiler optimisations. You should probably use an OS synchronisation object for that, like a manual reset event or condvar, rather than a POD and (hoping) that the threads do not optimise the access away and perform full reads and writes through the CPU caches into memory.
Comment: @tinman it's quite a bite, sec
Comment: and of course you need to tell us (with the source code) what is going on in the background threads
Comment: If it's some memory error it may help running it through valgrind... or whatever commercial Windows tool does the same thing. Those will catch some errors that show up only in release mode even while running in debug.
Comment: You have several preprocessor directives in your code. Check if these code parts are properly initialized in release mode.
Comment: xcrypt: that's a lot of code. Would you do us a favour and remove all except the parts essential for the problem?
Comment: @Vlad There's actually a lot more code I'm not showing that is also essential for the problem. That's why I didn't show it intially, I thought the most important part was in the small snippet above.
Comment: @xcrypt: I am afraid all the code dealing with textures etc is perhaps not relevant for the question. The only relevant parts are that that start/finish the threads and inform the other code about completion.
Comment: @Vlad as you wish, I removed it.
Comment: @xcrypt: thanks, now it's clearer.
Comment: @tinman could you elaborate a bit further on that? I'm not sure what you're actually saying.
Comment: @xcrypt: I was trying to say what Vlad has put in his answer.
Answer: When you compile your code in Debug mode, the compiler does a lot of stuff behind the scenes that prevents many mistakes made by the programmer from crashing the application.  When you run in Release, all bets are off.  If your code is not correct, you're much more likely to crash in Release than in Debug.
A few things to check:

Make sure all variables are properly intialized
Make sure you do not have any deadlocks or race conditions
Make sure you aren't passing around pointers to local objects that have been deallocated
Make sure your strings are properly NULL-terminated
Don't catch exceptions that you're not expecting and then continue running as if nothing had happened.
Comment: This has always bothered me. IMHO we should have no safe-guards on in debug so that we crash as often as possible and have safe-guards in release so that if something still slipped by we would not crash. But, i know, everything has its computational time and even the safe-guards cost performance...
Comment: RedX:  I like developing in Debug because the safeguards are helpful sometimes.  But you can develop in release, too.  Just turn off optimizations, and the debugger will more or less work as expected.
Answer: You are accessing the variable m_bIsReady from different threads without memory barriers. This is wrong, as it may be cached by either optimizer or processor cache. You have to protect this variable from simultaneous access with a CriticalSection, or mutex, or whatever synchronization primitive is available in your library.
Note that there might be further mistakes, but this one is definitely a mistake, too. As a rule of thumb: each variable which is accessed from different threads has to be protected with a mutex/critical section/whatever.
Comment: @xcrypt: look at this article about the whole issue and importance of locking: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf (interesting things start from 5th page)
Comment: @xcrypt: I am afraid, no, volatile is not sufficient. Some form of a memory barrier is still needed. Consider the citation from the page 10 of the article above: "though the Standard prevents compilers from reordering reads and writes to volatile data within a thread, it imposes no constraints at all on such reorderings across threads"
Comment: @xcrypt from the article (end of section 5): `Unfortunately, this all does nothing to address the first problem: C++'s abstract
machine is single-threaded, and C++ compilers may choose to generate
thread-unsafe code from source like the above, anyway.`
Comment: @msam: I can bet volatile is not enough. Consider the case when the value is not flushed from the processor cache. In presence of several processors and absence of memory barriers, the different threads' view on memory is not guaranteed to be consistent.
Comment: I don't see how this might be causing a problem? It's not guarded, no, but evetually it will reach 0 and the part `m_bIsReady==0`  will trigger just as intended?
Comment: @xcrypt: No, the optimizer can cache the value in the main thread.
Comment: From what I understood, I don't explicitely need a lock, making the datamember `volatile` might be sufficient?
Comment: @xcrypt: I would propose to try and see whether adding critical section (http://msdn.microsoft.com/en-us/library/ms885212.aspx) around will do. (You seem to be using pure WinAPI.)
Comment: @xcrypt: sorry, wrong link, you need http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608.aspx (although should be almost the same)
Comment: sorry for bothering you again, but this: http://stackoverflow.com/questions/4557979/when-to-use-volatile-with-multi-threading states that volatile is actually useless for multithreading in C++. What am I supposed to believe? In the article you linked volatile is used to ensure singleton thread-safety, but this link tells me that it is useless?
Comment: @xcrypt: I second the idea that volatile is useless :( The both citations above confirm that. Although volatile _may_ work for some compiler and compilation settings, in general it doesn't guarantee thread safety.
Comment: @msam oh yes, I've been shown that part about 10 times, but it doesn't state volatile is useless. There is nothing in the article that states something like that, only that volatile alone is not enough on multiprocessor systems. And Thanks, Vlad
Comment: Volatile also seems to be useful for multithreaded programming albeit not to replace memory barriers of any kind, but to indicate an object's value might change at any time. `volatile bool m_bIsRunning; while (m_bIsRunning)` If you don't put volatile there it might get optimised away by the compiler
Answer: from a quick look m_NumRunningThrds doesn't seem to be protected against simultaneous access so if (pCBA->m_NumRunningThrds == 0) might never be satisfied.
Comment: It always gets there. I can see that because of the write to the console. `std::tcout<<_T("exiting allocation...")<<std::endl;`


What is the closure of x = y in the river metric?

Question: Let the metric space be $\mathbb{R}^2 $ with the river metric, where the river is located on the x-axis.
The subset considered is $A = \left \{ (x, y) \in \mathbb{R}^2: x=y \right \}$. What is the closure of the set?
I understand that the closure of the set is the intersection of all the closed sets that contain A, however, I have problems with imagining what it looks like in this metric.
EDIT: The jungle river metric is a metric where you move as if were supposed to follow the river when walking from one point to another, unless they are located in the same line perpendicular to the river. Here's a quick visual guide.
Comment: I think you should specify what the river metric is, because I don't think it is very widely used.
Comment: @Mjd : and $d((x,y_1),(x,y_2)) = |y_2-y_1|$, hence it is a world with a river and many uncrossable valleys perpendicular to it, and the limiting case : the number of valleys $\to \infty$, when $x_1 \ne x_2$ two points don't lie in the same valley
Comment: I think the river metric has $d(\langle x_1, y_1\rangle, \langle x_2, y_2\rangle) = |y_1| + |x_2-x_1| + |y_2|$.  (Go from the first point perpendicularly to the river, go along the river, then go to perpendicularly to the second point.)
Comment: for that metric the curve $x= y$ is a set of isolated points ? not so different to the set of rationals in $[0,1]$ with some weird metric making two rationals always "very far", and its closure is itself ?
Answer: The easiest way to approach the question is to determine what $\epsilon$-balls around different points look like when $\epsilon$ is small.
Consider a point $p=\langle x,y\rangle$ with $y\ne 0$: if $\epsilon\le|y|$, the open $\epsilon$-ball centred at $p$ is $$\{x\}\times(y-\epsilon,y+\epsilon)\;.$$ It's not too hard to show that if $p\notin A$, then $p\notin\operatorname{cl}A$.
That leaves points on the $x$-axis. Can you work out what the $\epsilon$-ball centred at one of these points looks like? In case you get completely stuck, I've left a qualitative description in the spoiler-protected block below.

 It's square rotated so that two of its corners are on the $x$-axis, and the other two are directly above and directly below the centre.

If the point on the $x$-axis is not the origin, can you find an $\epsilon$-ball around it that is disjoint from $A$?
Comment: The epsilon approach really made me understand this problem, thank you!
Comment: @Angelika: You're welcome!


integral curves a circle

Question: If i need to find a first-order differential equation whose integral curves consist of all circles through the points  $(1,1)$ and $(-1,-1)$.
Why the circles that pass through $(1,1)$ and $(-1,-1)$ have their center in the straight line $y=-x$?
Comment: I love the sincerity and the humilty, hence I have not copy to write an answer. Here you have the answer: https://www.stumblingrobot.com/2016/01/31/find-a-first-order-differential-equation-whose-integral-curves-are-all-circles-through-11-and-1-1/
Answer: The general equation of a circle with its centre at $(a,b)$ and radius $r$ is given by:
$$
(x-a)^2 + (y-b)^2 = r^2.
$$
Impose the condition that it passes through $(1,1)$ and $(-1,-1)$:
$$
(1-a)^2 + (1-b)^2 = r^2,
$$
$$
(1+a)^2 + (1+b)^2 = r^2.
$$
Cancelling $r^2$ leads to:
$$
b = -a,
$$
which means that our general equation for the circle is:
$$
(x-a)^2 + (y+a)^2 = r^2.
$$
This implies that the centre of the circle lies at $(a,-a)$, which in turn tells us that all allowed centres lie along the line $y = -x$.
Further, we can write $r^2$ in terms of $a$, using e.g. the fact that it passes through $(1,1)$:
$$
r^2 = (1-a)^2 + (1+a)^2 = 2(1+a^2)
$$
So the equation of the circle becomes:
$$
(x-a)^2 + (y+a)^2 = 2(1+a^2). (*)
$$
which we can rearrange to make $a$ the subject:
$$
a = \frac{2-x^2-y^2}{2(y-x)}
$$
Now, to find the first-order differential equation whose integral curves consist of these circles we have to perform implicit differentiation on ($*$). This yields:
$$
2(x-a) + 2(y+a)\frac{dy}{dx} = 0 \implies \frac{dy}{dx} = \frac{a-x}{y+a}
$$
Put the expression for $a$ into the above and the answer follows.
Answer: The slope should be negative reciprocal of line through points  $(1,1),(-1,-1)$ or perpendicular bisector of AB as shown, center must be on $ x+y=0$

Radius squared of variable circle =$ h^2+h^2 + (h/\sqrt 2)^2 =5 h^2 /2, $ say
The circle has equation
$$ (x-h)^2+(y+h)^2=  5 h^2/2 $$
$$ x^2+y^2- 2 x h + 2 y h =h^2 /2 \tag 1 $$
Solve for $h$ in terms of $(x,y)$
$$ h= 2(y-x) \pm \sqrt{6x^2+6y^2-8 xy} = Q(x,y) \;say\tag 2 $$
needs to be checked; either sign is acceptable as center stays on $x+y=0 $.
Differentiate wrt $x$
$$ 2x +2yy'-2h + 2 hy'=0 \tag 3 $$
or
$$\frac{dy}{dx}=\frac{x-Q(x,y)}{y+Q(x,y)} \tag 4 $$
so that no constant $h$ is left in the final ode.
Answer: Hint:
The equation of a general circle with center $(x_0, y_0)$ is given by
$$(x-x_0)^2+(y-y_0)^2=r^2$$
Implicit differentiation will lead to
$$2(x-x_0)dx + 2(y-y_0)dy = 0$$
$$\implies \dfrac{dy}{dx}=\dfrac{x-x_0}{y-y_0}.$$
Now, you simply need to parameterize the center of the circles $(x_0, y_0)$. Use the equation of the circle and plug in your points that lie on the circle.

integral curves a circle


Gridsearch for SVM parameter estimation

Question: I'm currently experimenting with gridsearch to train a support vector machine. I understand that, if I have parameter gamma and C, the R function tune.svm performs a 10-fold cross validation for all combinations of these 2 parameters.
Since I did not know how to start, I tried to get some information about it, for example wikipedia2 suggests values that are not linear, e.g. C in the range {10, 100, 1000}.
So far I use the examples from my second wikipedia link, which is:
gammas = 2^(-15:3)
costs = 2^(-5:15)

Which results into 399 combinations.
This takes very, very long (~2000 samples). For example for the kernel "radial" my best result is gamma = 0.5 and cost = 2.
Couldn't I get the same result if I just used values like (1, 2, 3, 4, ... 10) for costs and (0, 0.5, 1, 1.5, 2) for gammas? I know this example is constructed because I already know the result.
My question:
But why this exponential scale?
There are so many values between 0 and 1 that I think this is a waste of computation time and only so few very big numbers that it couldn't find a very exact result anyway. It would only make sense for me if this was used to find a smaller range, let's say we then know the best cost is 2^3 and then we search around that. But it's nowhere mentioned that is performed that way.
Comment: That is exactly why grid search is a poor method to find optimal parameters. You may want to check out libraries that provide dedicated optimization methods, like [Optunity](http://docs.optunity.net).
Answer: The reason for the exponential grid is that both C and gamma are scale parameters that act multiplicatively, so doubling gamma is as likely to have roughly as big an effect (but in the other direction) as halving it.  This means that if we use a grid of approximately exponentially increasing values, there is roughly the same amount of "information" about the hyper-parameters obtained by the evaluation of the model selection criterion at each grid point.
I usually search on a grid based on integer powers of 2, which seems to work out quite well (I am working on a paper on optimising grid search - if you use too fine a grid you can end up over-fitting the model selection criterion, so a fairly coarse grid turns out to be good for generalisation as well as computational expense.).
As to the wide range, unfortunately the optimal hyper-parameter values depends on the nature of the problem, and on the size of the dataset and cannot be determine a-priori.  The reason for the large, apparently wasteful grid, is to make sure good values can be found automatically, with high probability.
If computational expense is an issue, then rather than use grid search, you can use the Nelder-Mead simplex algorithm to optimise the cross-validation error.  This is an optimisation algorithm that does not require gradient information, so it is pretty straightforward to use for any problem where grid-search is currently used.  I'm not an R user, but Nelder-Mead is implemented in R via optim.
Comment: The first paragraph explained very well what was unclear to me, I couldn't find that piece of information (about the scaling).
Comment: Has the piece you mention in paragraph 2 been published yet?
Comment: no, sadly rejected, am re-writing to accommodate reviewer's comments.
Answer: This is called the "parameter tuning" issue for SVMs.  One of the easiest approaches is to take the median of each for the greatest levels of class prediction accuracy obtained as you go through the CV folds.
Also, as a rule of thumb, use a simpler classifier to determine if your data are linearly separable.  If k-nearest neighbor (kNN) or linear regression works better, then you shouldn't use a more expensive (computationally) approach like SVM.  SVM can be easily overused, so make sure you evaluate linear regression, kNN, linear discriminant analysis, random forests, etc.

Gridsearch for SVM parameter estimation


bootstrap 3 navbar list items overlap with navbar brand

Question: I have a problem with BS3 navbar, when i change the size of the screen, navbar list items goes behind navbar brand image.
I would like navbar items to collapse into hamburger menu before they reach navbar brand. How can I achieve that?
Here is my HTML code:

 <!DOCTYPE html>

     <meta charset = "UTF-8">

     <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

     <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

     <link rel = "stylesheet" type = "text/css" href = "navbarProb.css"/>

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

        </button>

listItem1

listItem23

         listItem3

listItem4

listItem5

listItem6

listItem

listItem

         listItem

listItem7

listItem

listItem

listItem

listItem

listItem

listItem8

listItem9

listItem10

Thanks!
Answer: @j.b
Bootstrap converts the navigation to hamburger below 767px and in your expected scenario, it should convert after 1021px which is not possible if you want to make it possible you have to write a media query @media (max-width: 1021px) and your hamburger code.
let me know if you need anything.
Comment: Hello Atul, thanks for getting involved! when i change media query in my css to @media (min-width:1021px) {
  .navbar-right {
    position: absolute;
    right: 10px;
  }
} , navbar items drop down to second row when they reach navbar brand...
Comment: you don't have to put CSS absolute you just need to put the hamburger code.


django template conditional extend

Question: I have a very specific issue. I'm using a maintenance mode to get a built-in 503 view. I can customize the template in any way I want. I got it working, however I want the template to extend the admin base template when the request.path is /admin. When it isn't it should extend the normal base template.
I tried it with this:
{% if '/beheerpaneel' in request.path %}
    {% extends "admin/index.html" %}
{% else %}
    {% extends "base.html" %}
{% endif %}

but that gives me a template syntax error, because the extend tag must be first. After some googling it seems I need to handle this in the view.. but there is no view, its built-in. Anyone know a way around this? In the future I also wanna do this with the 404 and 500 pages etc.
Comment: Does this help? https://stackoverflow.com/questions/11412948/jinja2-render-template-without-extend
Answer: You should do that in the context. So in your view, you can work with:
def my_view(request):
    if '/beheerpaneel' in request.path:
        template_base = 'admin/index.html'
    else:
        template_base = 'base.html'
    # …
    return render(request, 'your-template.html', {'template_base': template_base})
and then render this with:
{% extends template_base %}

Comment: I don't have a view to work with, it's built-in

django template conditional extend


How can I get a video meta data using Qt phonon?

Question: I want to get the bitrate of a video. And I use Qt Phonon to achieve this goal.
Since there is a class called Phonon::MediaObject and provide a method called metaData(),I use that method but the result shows zero. Here is my code, I wonder why and how can I get the metadata such as bitrate in qt with Phonon
    QString source="E:\\sh.mp4";
    Phonon::MediaObject media;
    media.setCurrentSource(Phonon::MediaSource(source));
    QMap <QString, QString> metaData = media.metaData();
    int trackBitrate = metaData.value("bitrate").toInt();
    qDebug()<<trackBitrate;

The result is 0 all the time
Comment: Did you try dumping all the keys/values from that map to see what it actually contains?
Comment: the size of the map is 0...I don't know why.
Answer: I just figured this out myself.

Meta data in video files do not contain bitrate. It only contains extra information about the media that don't have any effect on playback. So even if Phonon::MediaObject::metaData() worked without loading the video, it will not help you.
I ended up using libformat, part of ffmpeg library to get the bitrate. Here's the code.

If you copy and paste this, it should work.
Download FFMpeg here: http://dranger.com/ffmpeg/tutorial01.html
This first tutorial will tell you how to link: http://dranger.com/ffmpeg/tutorial01.html
#include <QString>
#include <QMultiMap>

#include <stdio.h>

#include <libavformat/avformat.h>
#include <libavutil/dict.h>

void processMedia(const char* mediaFile)
{
  AVFormatContext *pFormatCtx = NULL;
  AVDictionaryEntry *tag = NULL;

  // Register all formats and codecs
  av_register_all();

  // Open video file
  if(avformat_open_input(&pFormatCtx, mediaFile, NULL, NULL)!=0)
    return;

  // Retrieve stream information
  if(av_find_stream_info(pFormatCtx)<0)
    return;

  //Get Bitrate
  float bitRate = pFormatCtx->bit_rate;

  //Get Meta
  QMultiMap<QString, QString> metaData;
  while ((tag = av_dict_get(pFormatCtx->metadata, "", tag,
          AV_DICT_IGNORE_SUFFIX)))
  {
    QString keyString(tag->key);
    QString valueString(tag->value);
    metaData.insert(keyString, valueString);
    printf("%s=%s\n", tag->key, tag->value);
  }

  // Close the video file
  av_close_input_file(pFormatCtx);
}

Answer: When you set the data source, the MediaObject enters the LoadingState. At that point, metadata might not yet be available.
The object emits a metaDataChanged signal when the metadata is ready. You should react to that signal and only attempt accessing the metadata once it has been emitted.
Comment: Thank u first, that's the problem I think. If I want to get the meta data without play the video, I mean without let it show on the widget, what  shall I do? Or how can I get the meta data using Qt? Thank u very much.


UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 127: unexpected end of data

Question: I have a problem decoding some characters, the error is like this:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 127: unexpected end of data

Below is my code, 'response' variable is JSON
response = requests.post('LINK-TO-API', headers=headers, data=data)
result = ""
for i in response:
    result += i.decode('utf-8')

whats wrong with my code? Thanks
Comment: I suggest you dump the `JSON` to a file before decoding and post it. You might see problem as well.
Comment: We can't see what the remote sent you and whether or not it was supposed to be in UTF-8 at all. You should probably [edit] your question to provide more details. See also https://meta.stackoverflow.com/questions/379403/problematic-questions-about-decoding-errors
Comment: as @kabanus said, you should dump it to json first, otherwise you won't have a clear idea what the server sends
Answer: 0xD0 (0b11010000) is one of many bytes that indicate the start of a multi-byte sequence in UTF-8. The number of 1s before the first 0 indicate the length of the sequence*. The bits after the first 0 are part of the encoding of the code point.
Basically, the iterator of the response has cut a two byte encoding in half. You should read the entire contents of the response before trying to decode it. eg.
bytes_ = b''
for chunk in response:
    bytes_ += chunk
result = bytes_.decode('utf8')

* bytes starting 10 indicate a continuation byte in a multi-byte sequence rather than a 1-byte encoding.
Comment: You are assuming that the result is UTF-8 in the first place.
Comment: True, the text could be encoded using a different encoding. However, it's not a terrible assumption either, given the ubiquity of UTF-8 and streetCoder3127917 explicitly decoding the bytes as such. But then the problem occurred at index 127, which would seem like an unnaturally short packet, and so suggests it really was the end of the data.


Probability Theory : Elementary Events and Sample Space?

Question: Kolmogorov's axioms specify a set of elementary events $E$ which is the sample space in modern theory.  He then specifies a field of probability which is the power set of $E$.  The axioms state $P(E) = 1$ and to construct a field of probability all the elementary events of $E$ are assigned probabilities.
My question is why does some of the modern literature and problems exclude specification of the elementary events and probability for each elementary event?  There is also no specification of the sample space.

For instance, I'm reading the following problem and keep asking myself:  "What is the sample space?"  "What are the elementary events and their probabilities?".  Is this information not required?  Thanks
Answer: This doesn't say that you must specify these events, only that this is an example of "the simplest fields in probability." You can define them in this way if your universe only contains a small number of random variables with finite support, but in general it is not a very useful construction (it won't help you handle normal random variables, for example).
In general, it is very rare that you have to explicitly construct the probability space. For almost any modeling or computational question, and most theoretical questions, you usually just assume that there exists a probability space $\left(\Omega,\mathcal{F},P\right)$ with abstract elements $\omega\in\Omega$, but in the analysis you work with events and distributions related to random variables. The only time you would ever have to really assign some specific meaning to $\omega$ is if you were designing some kind of abstruse counterexample.


Submit data to an array on another page using JQuery and AJAX

Question: I have this form. At the moment, it submits to my cart.php.
<form action="cart.php?ID=<?=$row['id'];?>&salec=<?=$row['sale'];?>"
       method="POST">

   <input type="hidden" name="hidden_name" value="<?=$row['title'];?>">

   <input type="hidden" name="hidden_price" value="<?=$row['price'];?>">

   <input type="hidden" name="hidden_list_price" value="<?
   =$row['list_price'];>">

   <input type="hidden" name="collect" value="<?=$row['collection'];?>">

Quantity

   <input type="text" name="quantity" value="1" maxlength="1"
    class="quantity">

   <input type="hidden" name="himg" value="<?=$row['image'];?>">

   <input type="submit" class="button" name="cartbtn" value="Add to Cart">
</form>

It submits to this array that I have in my cart.php:
$_SESSION['shoppingcart'] = array (

        'salec' => filter_input(INPUT_GET, 'salec'),
        'id' => filter_input(INPUT_GET, 'ID'),
        'name' => filter_input(INPUT_POST, 'hidden_name'),
        'list_price' => filter_input(INPUT_POST, 'hidden_list_price'),
        'price' => filter_input(INPUT_POST, 'hidden_price'),
        'quantity' => filter_input(INPUT_POST, 'quantity'),
        'collect' => filter_input(INPUT_POST, 'collect'),
        'img' => filter_input(INPUT_POST, 'himg')

);

This works fine. I need to submit this form data to the cart.php array without the redirect (action).
I tried this jQuery and Ajax, but it is not working.
$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#hidden_name").val();
        var price = $("#hidden_price").val();
        var list_price = $("#hidden_list_price").val();
        var quantity = $("#quantity").val();
        var img = $("#himg").val();
        var collect = $("#collect").val();

 $.ajax({
            type: "POST",
            url: "cart.php",
            data: dataString,
            cache: false,
            success: function(result){
                alert(result);
            }
 });

When I do this:
function pre_r($array){
    echo '
';
        print_r($array);
    echo'
';
}

pre_r($_SESSION) ;

It shows me that the data has not been added to the array. It doesn't redirect me - which is what I want - but it also doesn't add the info into the array. What am I doing wrong?
Comment: you have to [event.preventDefault()](https://api.jquery.com/event.preventdefault/) . Right now your form is submitting, then the ajax is performed (probably not anymore, because you already 'redirect' to cart.php before the ajax)
Comment: _but_ `datastring` is not defined anywhere!?
Answer: if the form works fine when submitted without ajax then you need to submit the form as it is in the Ajax block also:
$("#myform").on('submit', function(e){
    var form = $(this);
    $.ajax({
        type: form.attr('method'),
        url:  form.attr('action'),
        data: form.serialize(),
        cache: false,
        success: function(result){
            alert(result);
        }
    });
    e.preventDefault();
});

Comment: make sure your form id="myform"
Comment: thanks for the answer but unfortunately, this does not work. I made sure the forms id ="myform". This succeeds in not redirecting me, but it also does not add the form data to the array.
Comment: @K.Doe Using `serialize()` will send exact same data as the original submit process. Inspect request in browser dev tools network to see if status is 200 and to see exactly what gets sent. Also does your alert fire?
Comment: @charlietfl hi, the code is 200(ok). It shows all of the correct form data, query parameters when the submit button is clicked. It just, for some reason, does not add the data to the array
Comment: @charlietfl oh yes, I get the alert as well
Comment: have you started the session before calling $_SESSION? "session_start();"
Answer: Hi I will try to help you .I will tell you i m new in this industry so i m still learning :) but i will start with :
1.changing that input type submit with type button.
``
`$(document).ready(function(){
$("#myform").click(function(){
    var name = $("#hidden_name").val();
    var price = $("#hidden_price").val();
    var list_price = $("#hidden_list_price").val();
    var quantity = $("#quantity").val();
    var img = $("#himg").val();
    var collect = $("#collect").val();`

$.ajax({
        type: "POST",
        url: "cart.php",
        data: {
      name:name,
      price: price,
      list_price: list_price,
      quantity: quantity,
      img: img,
      collect: collect

     },
        cache: false,
        success: function(result){
            alert(result);
        }

});
See if you have some error into console hope this may help you
ps if you want to make a post request with jquery you can do that in a easy way

$.post( "cart.php", {name:name,
          price: price,
          list_price: list_price,
          quantity: quantity,
          img: img,
          collect: collect } );


Access item url in views-view-fields.tpl.php

Question: I'm using views-view-fields.tpl.php to theme the output of a content type.
What I need to do is the below, except I don't know how to get 'url_for_this_item' without either printing all the variables and referencing it in a long array lookup, ie like $fields[smth][ddd][0][44][ui][uri].
Is there a simple, clean way to get the url in the template?  I have tried outputting a link but then views still insists on giving the full link with an closing tag on the end.  Of course, I can parse this and remove the closing tag but it just seems too hacky.  Is there not a better way?
print '';
    print $fields['title']->content;
    print $fields['field_this']->content;
    print $fields['field_that']->content;
print '';

I want to to get the url for
Comment: could you explain your content structure a bit. and what are all these fields?
Answer: If I understood it right, you can simply add a new field in Views which holds the URL to the item. And then in the template file you can print this field as you described in you question.
Answer: use <?php  print $fields['uri']->content; ?> to print the URL of the particular field. However this works when you have the File:path field added in your views


Alternative to .htaccess compression with Boost

Question: My hosting provider doesn't support mod_deflate directives in .htaccess to provide compressed HTTP responses.
I am using Drupal 7 with Boost and wish to compress HTML, CSS and JS responses.
Is there another alternative to doing this with .htaccess?
Comment: Hopefully @mikeytown2 will see this as I am pretty sure he still maintains Boost.
Answer: Core should support .gz for CSS & JS. This requires .htaccess rules though. For core they should already be included.
Looks like I never got around to gzip for Boost for 7.x. You can follow the issue here
http://drupal.org/node/1416214
Comment: My statement from [#54](https://drupal.org/comment/7268440#comment-7268440) still applies: "I think the patch from #53 should get in."


SAP pegar o valor text

Question: Bom dia, estou com um problema, espero que alguem possa me ajudar.
Tenho uma tabela no SAP.
Preciso capturar o valor da coluna Qtd.Pç

pela gravação do sap script trouxe essa linha
session.findById("wnd[0]/usr/cntlALV_RECEBE/shellcont/shell").setCurrentCell 0,"QTDPEC"

0 = 1º linha
"QTDPEC" = nome da coluna
Tentei colocar
x = session.findById("wnd[0]/usr/cntlALV_RECEBE/shellcont/shell").setCurrentCell 0,"QTDPEC".text

msgbox = x
Da erro
session.findById("wnd[0]/usr/cntlALV_RECEBE/shellcont/shell").text

msgbox = x
Da erro
Não retorna nenhum valor.
Answer: Use: getcellvalue
Ficaria assim:
session.findById("wnd[0]/usr/cntlALV_RECEBE/shellcont/shell").getcellvalue(0,"QTDPEC")

Até.
Comment: Eu uso esse getcellvalue quando é tabela. o resto uso .text mesmo

SAP pegar o valor text


How to calculate the value of $\sum\limits_{k=0}^{\infty}\frac{1}{(3k+1)\cdot(3k+2)\cdot(3k+3)}$?

Question: How do I calculate the value of the series $$\sum_{k=0}^{\infty}\frac{1}{(3k+1)\cdot(3k+2)\cdot(3k+3)}= \frac{1}{1\cdot2\cdot3}+\frac{1}{4\cdot5\cdot6}+\frac{1}{7\cdot8\cdot9}+\cdots?$$
Comment: The answer is $\frac{\pi\sqrt3}{12}-\frac{\ln3}{4}.$
Comment: I have changed the formatting of the title so as to
[make it take up less vertical space](https://math.meta.stackexchange.com/a/9686/290189) --
this is a policy to ensure that the scarce space on the main page is distributed evenly over the questions.
See [here](https://math.meta.stackexchange.com/a/9730) for more information. Please take this into consideration for future
questions. Thanks in advance.
Answer: By making use of the integral
$$\int_{0}^{1} \frac{(1-x)^2}{1-x^3} \, dx = \frac{1}{2} \, \left(\frac{\pi}{\sqrt{3}} - \ln 3 \right)$$
one can take the following path.
\begin{align}
S &= \sum_{k=0}^{\infty} \frac{1}{(3k+1)(3k+2)(3k+3)} \\
&= \sum_{k=0}^{\infty} \frac{\Gamma(3k+1)}{\Gamma(3k+4)} = \frac{1}{2} \, \sum_{k=0}^{\infty} B(3, 3k+1),
\end{align}
where $B(n,m)$ is the Beta function, which leads to
\begin{align}
S &= \frac{1}{2} \, \sum_{k=0}^{\infty} \, \int_{0}^{1} t^{2} \, (1-t)^{3k} \, dt \\
&= \frac{1}{2} \, \int_{0}^{1} \frac{t^{2} \, dt}{1- (1-t)^{3}} \\
&= \frac{1}{2} \, \int_{0}^{1} \frac{(1-x)^{2} \, dx}{1- x^3} \hspace{15mm} x = 1 - t \\
&= \frac{1}{4} \, \left(\frac{\pi}{\sqrt{3}} - \ln 3 \right).
\end{align}
Comment: How do we justify exchanging the limit of the series and the integral here? AFAIK, the convergence of the series isn't uniform on [0,1].
Answer: The answer is $\frac{\pi\sqrt3}{12}-\frac{\ln3}{4}.$
See the similar problem (problem 2) here:
http://www.imc-math.org.uk/imc2010/imc2010-day1-solutions.pdf
Answer: You can calculate the partial sum using
$$
\frac{1}{(3k+1)(3k+2)(3k+3)}=\frac{1}{2}\frac{1}{3k+1}-\frac{1}{3k+2}+\frac{1}{2}\frac{1}{3k+3}
$$
Comment: Partial decomposition. For example the coef before $1/(3k+1)$ is $$a=\frac{1}{(-1+2)(-1+3)}=\frac{1}{2}$$. Hope i did not make mistakes for the rest.
Comment: @Atmos and? There is not any cancellation and the partial sum does not have any closed form. I would be surprised if you can calculate it, just using the decomposition.
Comment: Where does this come from?
Comment: Ah, I see. Thanks for the clarification.
Comment: you can't use this directly: all individual terms are divergent.
Comment: @dezdichado I've said the partial sum, read please.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[10px,#ffd]{\ds{%
\sum_{k = 0}^{\infty}{1 \over \pars{3k + 1}\pars{3k + 2}\pars{3k + 3}}}} =
{1 \over 27}\sum_{k = 0}^{\infty}
{1 \over \pars{k + 1/3}\pars{k + 2/3}\pars{k + 1}}
\\[5mm] = &
{1 \over 6}\
\underbrace{\sum_{k = 0}^{\infty}\pars{{1 \over k + 1/3} - {1 \over k + 2/3}}}
_{\ds{\underbrace{H_{-1/3} - H_{-2/3}}
_{Euler\ Reflection\ Formula:\\ \ds{=\ \pi\cot\pars{\pi/3} =\root{3}\pi/3}}}}\ +\
{1 \over 6}
\underbrace{\sum_{k = 0}^{\infty}\pars{{1 \over k + 1} - {1 \over k + 2/3}}}
_{\ds{H_{-1/3} - H_{0}}}\quad
\pars{~H_{z}:\ Harmonic\ Number~}
\\[5mm] = &\
{\root{3} \over 18}\,\pi + {1 \over 6}\,H_{-1/3}
\end{align}

Moreover, $\ds{H_{-1/3} = H_{2/3} - 3/2\ \pars{~recurrence~}}$.

  $\ds{H_{-1/3} = \overbrace{\braces{3\bracks{1 - \ln\pars{3}}/2 + \root{3}\pi/6}}^{\ds{H_{2/3}}}\ -\ 3/2 =
-3\ln\pars{3}/2 + \root{3}\pi/6}$. The $\ds{H_{2/3}}$ value is
  given in a table. Otherwise, it can be evaluated by means of the
  Gauss Digamma Theorem.

Finally,
\begin{align}
&\bbox[10px,#ffd]{\ds{%
\sum_{k = 0}^{\infty}{1 \over \pars{3k + 1}\pars{3k + 2}\pars{3k + 3}}}} =
{\root{3} \over 18}\,\pi +
{1 \over 6}\bracks{- {3\ln\pars{3} \over 2} + {\root{3} \over 6}\,\pi}
\\[5mm] = &\
\bbx{\root{3}\pi - 3\ln\pars{3} \over 12} \approx 0.1788
\end{align}


Fitch Exercise 8.31 Proof

Question: I am working on this proof and I have set it up. I'm not sure how I should proceed or if I am doing it correctly so far Thank you!
The first 3 lines before the horizontal line are the premises!

1: enter image description here
Comment: Could you post the original question as well?
Comment: The first 3 lines are the predicates!
Comment: @JasonWu You mean the premises?
Comment: @spaceisdarkgreen yes sorry I mean premises
Comment: A better outline to proceed from would be to prove horned from contradiction rather than magical, and then horned immediately implies magical. (Magical has no involvement in anything else, so will only clutter things up.) Actually, by that same token, you should just proceed to prove "not mortal or mammal" from the first premise.
Comment: I'm not sure I understand. I understand the clutter aspect but I thought I need to use those to prove Magical(c)
Comment: You do, but "magical" follows immediately from "horned" by implication elimination. And "horned" follows immediately from "(not mortal) or mammal" by implication elimination. So all you really need to do is prove "(not mortal) or mammal". Only the first premise is relevant to that end. If you use excluded middle to split it up into cases of "mythical" and "not mythical", then either way "(not mortal) or mammal" holds.
Comment: @JasonWu To use $\lor$ Elim, you also need to prove $My(c)\lor\neg My(c)$, after that your approach works
Comment: Oh I see, I didn't know the law of excluded middle. I want to continue with what I have now even thought it's sort of cluttered but I am assuming we have to start a subproof with not((not mortal) or mammal) and then 2 more nested sub proofs of each and use v elim to derive a contradiction?
Comment: (You have to address me with @ if you want me to get notified). You can start by showing "Mythical or (not mythical)" (this is an instance of excluded middle) and use $\lor$-elim from there. Proving excluded middle is a good exercise.
Answer: Follows your set up, here is another approach:
$$\boxed{\begin{align}
&\text{My(c):=Mythical(c)}\\
&\text{Ma(c):=Mammal(c)}\\
&\text{Mo(c):=Mortal(c)}\\
&\text{Ho(c):=Horned(c)}\\
&\text{Mg(c):=Magical(c)}\\
\end{align}}$$

Here is how to continue with what you have and finish the proof use $\lor$ Elim:

That proved $My(c)\lor\neg My(c)$ now we can use $\lor$ Elim.

Which will take a little more works.
Answer: $\def\fitch#1#2{\begin{array}{|l}#1\\\hline #2\end{array}}\def\magic{\operatorname{Magical}}\def\mythic{\operatorname{Mythical}}$
Your basic idea is okay, but you cannot use $\vee$-elimination unless you have a disjunction; that is $\mythic(c)\vee\neg\mythic(c)$
If you cannot use the Law of Excluded Middle to assert this, then you can modify the proof to use another negation introduction.
$$\small\fitch{~\vdots}{\fitch{\neg\magic(c)}{\fitch{\mythic(c)}{~\vdots\\ \bot}\\\fitch{\neg\mythic(c)}{~\vdots\\ \bot}\\\color{red}\bot\quad\color{red}{\vee\mathsf E\text{ invalid}}}\\\neg\neg \magic(c)\quad\neg\mathsf I\\\magic(c)\qquad\neg\neg\mathsf E}\qquad\qquad\fitch{~\vdots}{\fitch{\neg\magic(c)}{\fitch{\mythic(c)}{~\vdots\\ \bot}\\\neg\mythic(c)\qquad\neg\mathsf I\\~\vdots\\ \bot}\\\neg\neg\magic(c)\quad\neg\mathsf I\\ \magic(c)\qquad\neg\neg\mathsf E}$$
Answer: Here is an easy way to fix the proof: keep the subproof that assumes $Mythical(c)$ and ends with $\bot$. Close this subproof using $\neg \ Intro$ to get $\neg Mythical(c)$, and now you can do all the steps you originally did inside the subproof that assumed $\neg Mythical(c)$ to get to $\bot$, as desired. In other words, there is no need for two separate subproofs, and hence no need to prove the Law of Excluded Middle either.

Fitch Exercise 8.31 Proof


How to build a widget which launches an android application?

Question: I have built a custom android application for Galaxy Note.
Is there a way to launch the application through a large widget which takes up approximately full size of the screen ?
Any help is appreciated. Thanks
Answer: try this -
<code>PackageManager pm = getPackageManager();
try
{
    String packageName = "com.example.package";
    Intent launchIntent = pm.getLaunchIntentForPackage(packageName);
    startActivity(launchIntent);
}
catch (Exception e1)
{
}
</code>


backend db setup for an app with geographically diverse users

Question: The in-house developed software where I work connects directly to a mysql server here in our office via our devexpress orm (XPO). Performance is great.
We're opening another office... cross country. Performance: not so great. The requirement is that the software be as responsive in both offices as it is in this office and that the data from one office be available to the other 'in real time'.
Something of this scale is totally new to me. I'm not averse to bringing in a consultant who's done something like this before, but I'd like to get a good picture of the options first. I'm sure that this is a common situation.
Is replication a good idea? Is it fast enough? stable enough?
Are there development patterns that tackle this kind of situation if replication won't work?
Heck, I'm not even sure how to tag this, so if someone knows better... please, feel free to re-tag
EDIT > Details about the data
I guess, compared to some enterprise software, we're not moving lots of data. The software manages customer accounts, appointments etc. and each user works on about 2-5 separate accounts/minute (50 users currently, 200-400 after planned expansion), updating data each time.
The real-time aspect comes into play when someone in office A creates an appointment for someone in office B who, ideally, needs to be able to view its details near immediately (<2 mins). That said, each record usually only gets mutated a maximum of 5 times a day. But that's only what I suspect; I don't actually have any usage statistics on me.
Answer: One of you're last resorts is of course to make sure that all heavy duty work is done in background threads such that the GUI thread is never blocked.
Having real-time data depends on the data, I miss a detailed description such as how much data are we talking about per request (i.e. how large are the objects), how fast is you're internet connection (could be the bottle neck?), is the mysql server and all infrastructure in between that you control well configured? How static/dynamic is the data, if the real-time data gets mutated one time a day or it gets mutated a zillion times a day is important for the "solution"
Comment: updated to clarify the kinds and amounts of data being used, and how often it's mutated. The network connection we currently use is a 5mb line, which could be the slow point, but as of this instant, it only supports 3 users in the remote office.
Answer: You can't use asynchronous replication in both directions without creating replication conflicts which are impossible to resolve and break things.
Therefore, your obvious choice is to use read/write splitting - have the application do noncritical reads from a (readonly) local DB, and direct all writes to the master. The disadvantage of this is that it will mean that you can't immediately read back your own writes.
MySQL replication isn't perfect and requires some effort to set up and continuous monitoring to maintain; you must frequently check the data are the same in the slaves. Some queries get replicated incorrectly; you'll need to understand those and avoid them.
Comment: Thanks for all of your input. Using your answer and the mysql docs I've decided to attempt read/write splitting. Now it's just a matter of convincing the ORM to do the same (DevExpress.XPO).


KD-160 Kohler piano audio outputs not working

Question: at our worship place we have a KD-160, Kohler digital piano, and it currently has an external mic hooked up to our PA system. I want to get it connected straight into our PA system via the output L/mono and R on the rear panel. I can't seem to get any sound out of it though. Unsure why.
Per the manual, "PAGE 13 - AUDIO OUTPUT CONFIGURATION" it looks like each track\virtual sound needs to be assigned to a physical output (i.e. Left&Right).
Done that, but there is no audio coming out to the PA system. However there is audio when using the output 1 and 2.
The problem is that the piano speakers are switched off with this option. The pianist finds it important to hear himself through the speakers of the piano and to be able to control the volume from his end when desired. I guess with all the different volunteers, they all use different levels at the fader and it is inconsistent for the pianist.
I did try to use the left/mono and right outputs but nothing comes out of it. Since the output 1 and 2 are working, meaning the back panel is working, I know there is an issue on the left/mono and right outputs.
Any suggestions?
I have read that some folks solder something in the headphone jack output and use that, but I would not know how to.
It would sound way better if it was connected to our PA system, thank you.
Answer: My first thoughts were to use a cheap headset, that would still allow everything else to be heard, maybe only using one earpiece. Plugged into the headphone outlet.
The second would involve a monitor speaker (foldback) which could have any mix the player wanted, but that would involve  extra cables, and perhaps a powered monitor for the pianists.


Radius of a wheel based on parametric equations

Question: I am working on a question and I don't have the slightest idea where to begin. Any nudge in the right direction would be very helpful.
Here is the question:

A bicycle wheel has radius R. Let P be a point on the spoke of a wheel at a distance d from the center of the wheel. The wheel begins to roll to the right along the x-axis. The curve traced out by P is given by the following parametric equations:
$x=22\theta-15sin(\theta)$
$y=22-15cos(\theta)$
What must we have for R and d?
Answer: We measure the angle $\theta$ as the angle that a line from the center of the wheel to the point $P$ makes with the negative $y$-axis.  Without Loss of Generality, the point $P$ is at $(0,R-d)$ when $\theta =0$.
As the center of the wheel moves to the right by a distance $x_C$, the wheel has traveled a distance $R \theta$.  Therefore, the parametric equation for the center of the wheel is simply $x_C=R\theta$ and $y_C=R$.
If we observe the motion of $P$ from the frame of reference of the center of the wheel, we observe simple circular motion.  Thus, from the center of the wheel the parametric description of the motion of $P$ is $x=-d\sin \theta$ and $y=-d\cos \theta$.
Putting the two motions together we have
$$\begin{align}
x&=R\theta -d\sin \theta\\\\
y&=R-\cos \theta
\end{align}$$
Thus, $R=22$ and $d=15$.
Answer: Lets find $d$ first. Our point is moving with simple harmonic motion in the vertical direction, and it has a maximum of $22+15 = 37$ and a minimum of $22-15 = 7$. So, its distance from the centre of the wheel is $d = (37 - 7)/2 = 15$.
After the wheel has made one full revolution, the point $P$'s $x$-coordinate has moved from $0$ to $22\cdot 2\pi$. This must be the same as the circumference of the wheel. So, $R=22$ must be the radius of the wheel.
Comment: Wow! This way of doing it is surprisingly simple and easy to comprehend. Thanks!


Prove geodesics are straight lines if Riemann tensor is identically zero.

Question: Suppose that $R^{a}_{bcd}\equiv 0$ in all of our manifold $M$ (in which we assume zero torsion). Prove that all geodesics are straight lines.
I tried using Ricci's identity: $X^i_{;jk}-X^i_{;kj}=R^i_{mkj}X^m$ but expanding the right side and equating to zero only led me to the expression for $R$ in terms of the connection coefficients $\Gamma$.
I was hinted that I might use the parallel transport property along a circuit or that in a torsionless setting, $\nabla_X\nabla_X Z=R(X,Z,X)=0$. My problem lies in the fact that I don't entirely understand that last equation, and most references on the subject make use of properties of a Riemannian metric on the manifold, concept not yet introduced at this point in my course.
All and any help would be appreciated.
Comment: It seems strange the metric tensor hasn't been introduced to you yet
Comment: Not necessarily: in plane polar coordinates the Christoffels don't vanish, even though the geodesics remain straight lines.
And even if I was working in a coordinate system in which what you said was true, how does one prove that a vanishing Riemann tensor implies vanishing Christoffels? That was my initial line of attack.
Comment: I'm sorry, vanishing of the Riemann tensor only implies that there exists some coordinate system where the connection vanishes
Answer: The result is false. A quick class of counterexamples is the following: consider any diffeomorphism $f:\mathbb R^n \to \mathbb R^n$. Let $\delta$ be the Euclidean metric on $\mathbb R^n$. Then the pullback metric $f^*\delta$ is a flat metric on $\mathbb R^n$ in which the geodesics typically aren't straight lines.
I realize that this answer perhaps contains technical language that you haven't yet seen, but you will learn about metrics and pullback soon in your class (I hope!). Furthermore, the above paragraph is a point that seems to be missed by a lot of students, so keep it in mind for the future
:-)
Comment: Pullbacks and pushforwards are not a problem. At this point we we're discussing the metric-independent geometry of spaces so metrics are not used up to this point (and in the desired problem).
On whether or not this result is false, several books (among which is Schutz's Geometrical Methods of Math. Phys., see section 6.10) state that a space is flat if and only if the Riemann tensor is identically zero, though there might be some unsaid assumptions, and they use a variant of the geodesic deviation equation to "prove it".


How can i convert entity relations from corenlp to ontology?

Question: I want to create an ontology for news dataset. My task is to convert entity relations from corenlp to ontology.
I have extracted relations using Stanford corenlp.
for k in range(0,50):
    text = df['event_summary'][k]
    print('sentence:'+text+ '\n')
    output = nlp.annotate(text, properties={"annotators":"tokenize,ssplit,pos,depparse,natlog,openie",
                            "outputFormat": "json",
                             "openie.triple.strict":"true",
                             "openie.max_entailments_per_clause":"1"})
    result = [output["sentences"][0]["openie"] for item in output]
    for i in result:
        for rel in i:
            relationSent=rel['subject'],rel['relation'],rel['object']
            print(relationSent )
            print('\n')
            df['Entity Relation'][k]= relationSent

My output looks like this:
sentence:U.S. fast-food restaurant chain Chick-fil-A warns that a security > breach may have leaked credit card details of 9

('security breach', 'leaked', 'credit card details of 9')

sentence:The Palestine Authority signs a treaty to join and participate in the International Criminal Court. (Wall Street Journal)

sentence:The Eurasian Economic Union between Russia

sentence:Vietnam's new marriage law goes into effect

('Vietnam', 'has', 'new marriage law')

Now I want to convert these relations to ontology.
Answer: One of the main questions you need to answer when building an ontology is "What inferences will you like from the ontology?". From the information you provided, I cannot answer that question. Hence the reason why it is not that easy to tell you how to build an ontology for the given sentences.
What seems more realistic to me is to place these sentences in an RDF triple store. Since RDF data is stored as <subject, predicate, object>, it matches the retrieved sentences very well. I.e., ('Vietnam', 'has', 'new marriage law') will become <Vietnam, has, new_marriage_law>. The advantage of doing this is that you can query the RDF data with SPARQL.
Comment: Thank you for your help. Thing is I have extracted triples using corenlp now I need to convert these triples into RDF format. I am confused here how can I convert these triples to RDF in python?


How to uninstall one site of a multi-site?

Question: Things are bit messed up in one of my sites, partly because of modules that did not clean up after themselves when I disabled them and partly because I tried to clean up for them, which of course, only partially worked.
So I want to remove this site and start it over again with a fresh install. But I don't see anything on how to uninstall or remove a site.
(This is a development environment, of course!)
Thanks for your help.
Answer: Nothing to it as long as they have separate databases:

Deactivate the virtualhost pointing at your site and restart apache
Backup and delete the database for that site
Backup and delete the site folder inside Drupal_root/sites where Drupal_root is your core Drupal repository

Then rebuild however you please.


Multiple dimension scale development - validation using SEM

Question: I'm developing a scale for measuring customer experience. Based on the principal component analysis I established that it has three components (11 items). Now I need to validate it by relating it to customer satisfaction and loyalty scores using SEM (like in study 6 in Brakus, J. J., Schmitt, B. H., & Zarantonello, L. (2009). Brand experience: what is it? How is it measured? Does it affect loyalty?. Journal of marketing, 73(3), 52-68.).
I have no clue how to combine the three components into one experience score that I can later correlate with satisfaction and loyalty scores. Right now I did the following:

created a new variable - sum of the items for each component
multiplied that by the score from principal component analysis

model <- ' # measurement model
            Experience =~  TC1*Component1 + TC2*Component2 + TC3*Component3
            # regressions
            satisfaction ~ Experience
            loyalty ~ Experience '
fit <- sem(model, data=df)
My questions:
How do I combine the three components from my PCA to get the Experience score? Is the way I included the factor scores correct?
Comment: What is your question?
Comment: Questions are: How do I combine the three components from my PCA to get the Experience score? Is the way I included the factor scores correct?
Sorry for missing them at first.
Answer: See this 2022 Journal of Retailing article for the most latest procedural information on scale development. This is an open-access article.
Start with Table 1, which provides an overview of all the steps that the authors have conducted in this customer experience scale development study.
To answer the specific question (i.e., how to combine scores from component/factors to get an overall experience score), this study has developed the overall omnichannel customer experience construct (i.e., OCX) a higher-order composite model. They have used SmartPLS for assessing the structural model.
The article also provides an extensive web appendix with procedural information.


Why does the OLS estimator simplify as follows for the single regressor case?

Question: I was reading in "A Guide to Econometrics" that given $Y = X \beta + \epsilon$, the variance covariance matrix of $\beta^\text{OLS}$ is given by $\sigma^2 (X' X)^{-1}$ where $\sigma^2$ is the variance of the error term...
it then says that in the case of a single regressor $y = \beta_1 + \beta_2 x$, that this simplifies to $\sigma^2 / \sum(x-\bar{x})^2$. I don't quite see this. Isn't the matrix $X$ in this case still a two by two matrix? Namely:
$$
X =
\left(
\begin{array}{cc}
1 & x_1 \\\
1 & x_2
\end{array}
\right)
$$
How are we getting something like $\sum(x-\bar{x})^2$ ?
Comment: Clearly the book was talking about the variance of the slope, i.e. $\beta_2$. The covariance of $(\beta_1,\beta_2)$ is still $2\times 2$ matrix as Charlie demonstrated.
Comment: Also $X$ is usually $n\times k$ matrix, with $n$ being number of observations, $k$ being the number of right hand side variables including the constant. In your case $k=2$. The matrix $(X'X)^{-1}$ is then usualy $k\times k$ matrix, in your case $2\times 2$.
Answer: Multiply $X^\prime X$:
$$\begin{align*} \left[ \begin{array}{cc} 1^\prime 1 & 1^\prime x \\ x^\prime 1 & x^\prime x \end{array} \right] \end{align*}$$
Take the inverse (see here):
$$\begin{align*} \frac{1}{Nx^\prime x - (1^\prime x)^2}\left[ \begin{array}{cc} x^\prime x & -1^\prime x \\ -1^\prime x & N \end{array} \right] \end{align*}$$
Note that
$$\begin{align*}\sum{(x_i - \bar{x})^2} = \sum{x_i^2} - N \bar{x}^2.\end{align*}$$
Looking at the lower right corner of the matrix, we have
$$\begin{align*}\frac{N}{N\sum{x_i^2} - \left(\sum{x_i}\right)^2}=
\frac{1}{\sum{x_i^2} - \frac{1}{N}\left(\sum{x_i}\right)^2} =       \frac{1}{\sum{x_i^2} - N \bar{x}^2} = \frac{1}{\sum{(x_i - \bar{x})^2}}.\end{align*}$$
Multiplying by $\sigma^2$ gives the variance of the slope coefficient.
Comment: (+1) The first formula (for $X'X$) still contains typos... (but the rest of the analysis is correct).
Comment: aargh, I was composing my answer when notification came :) The third equation has an error by the way.
Comment: Hm I clearly saw the earlier version with an error, but SE probably merged the revision. Now everything is ok. The error was that $\frac{1}{N}$ was besides the first term in the right hand side.
Comment: @Charlie Thanks a lot! That was crystal clear! I won't not have a notebook by my side the next time I read stats...


Display chart before receive datas - ChartJs - Refresh every second

Question: I tried to display a Doughnut Chart in my website with data from a csv files. But the problem is, when I reload the page, there is no data and no doughnut, but when I go to another page (without same path) and I come back on the correct page, the doughnut appears, but I have an error:
"ng-charts configuration error, data or datasets field are required to render chart undefined."
Moreover, like data change every second, how to refresh the chart every time ?
Thanks a lot, i try everything i found on the 4 firsts pages of google, but nothing...
The HTML CODE :

    <canvas baseChart
            [chartType]="chartType"
            [datasets]="chartDatasets"
            [labels]="chartLabels"
            [colors]="chartColors"
            [options]="chartOptions"
            [legend]="true"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
    </canvas>

My TS file :
import {Component, OnInit, OnDestroy} from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label} from 'ng2-charts';
import { LineService } from '../services/line.service';
import {ActivatedRoute} from '@angular/router';
import { SingleLineComponent } from '../single-line/single-line.component';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-trp-graph',
  templateUrl: './trp-graph.component.html',
  styleUrls: ['./trp-graph.component.scss']
})
export class TrpGraphComponent implements OnInit, OnDestroy{

  lineSubscription: Subscription;
  trpHorraire: number;
  trpPoste: number;
  chartType: ChartType;
  chartDatasets: Array<any>
  chartLabels: Array<any>;
  chartColors: Array<any>;
  chartOptions: any;

  constructor(private lineService: LineService,
              private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.chartIt();
  }

  _focusedData$ = combineLatest(
    this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
    this.route.params.pipe(filter(x => !!x.id), map(x => x.id -1))
  ).pipe(
    map(([csvs, id]) => csvs[id])
  );

  gestionData(): void {
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpHorraire = x.trpHeureReel);
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpPoste = x.trpPosteReel);
  }

  async chartIt() {
    await this.gestionData();

    this.chartType = 'doughnut';
    this.chartDatasets = [
      {data: [this.trpHorraire, 100 - this.trpHorraire], label: 'TrpHorraire'}
    ];
    this.chartLabels = ['TRP HORRAIRE'];
    this.chartColors = [
      {
        backgroundColor: ['rgb(0, 133, 86)', 'rgb(78, 107, 124)'],
        hoverBackgroundColor: ['rgb(30, 163, 116)', 'rgb(108, 137, 144)'],
        borderWidth: 2,
      }
    ];
    this.chartOptions = {
      responsive: true
    };
  }

  chartClicked(e: any): void { }
  chartHovered(e: any): void { }

  ngOnDestroy(): void {
    this.lineSubscription.unsubscribe();
  }

}

So, by changing page, the data is display, but not at the first load on the correct page.
Any help is usefull,
Thanks a lot.
Answer: I solved my problem, just by writing the variable in the html code and not in the ts.
I hope it's helpful.
See the code :
  <ng-template class="trpChart" #vertH>
    <canvas baseChart
            [chartType]="chartType"
            [datasets]="[
              {
              data: [this.trpHoraire, 100 - this.trpHoraire], label: 'TrpHoraire'
              }
            ]"
            [colors]="[{
              backgroundColor: ['rgb(130, 230, 0)', 'rgb(255, 255, 255)'],
              hoverBackgroundColor: ['rgb(185, 30, 30)', 'rgb(225, 225, 255)'],
              borderWidth: 1
            }]"
            [options]="{
              responsive: true,
              cutoutPercentage: 80,
              title : {
                display: true,
                text: 'TRP HORAIRE',
                fontSize: 25
              }
            }"
            [legend]="true"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
    </canvas>
  </ng-template>

For the TS, it's this :
import {Component, OnInit, OnDestroy} from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label} from 'ng2-charts';
import { LineService } from '../services/line.service';
import {ActivatedRoute} from '@angular/router';
import { SingleLineComponent } from '../single-line/single-line.component';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-trp-graph',
  templateUrl: './trp-graph.component.html',
  styleUrls: ['./trp-graph.component.scss']
})
export class TrpGraphComponent implements OnDestroy{

  lineSubscription: Subscription;
  lineSubscription2: Subscription;
  trpHoraire: number;
  trpPoste: number;
  chartType: ChartType;
  chartDatasets: Array<any> = [];
  chartColors: Array<any>;
  chartOptions: any;

  constructor(private lineService: LineService,
              private route: ActivatedRoute) {
    this.chartIt();
  }

  _focusedData$ = combineLatest(
    this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
    this.route.params.pipe(filter(x => !!x.id), map(x => x.id -1))
  ).pipe(
    map(([csvs, id]) => csvs[id])
  );

  gestionData(): void {
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpHoraire = x.trpHeureReel);
    this.lineSubscription2 = this._focusedData$.subscribe(x => this.trpPoste = x.trpPosteReel);
  }

  gestionColor() {
    if(this.trpHoraire < 50) {
      return 'rgb(225, 37, 27)';
    }
    else if(this.trpHoraire >= 50 && this.trpHoraire < 80) {
      return 'rgb(255, 182, 0)';
    }
    else {
      return 'rgb(130, 230, 0)';
    }
  }

  async chartIt() {
    await this.gestionData();
    await this.gestionColor();

    this.chartType = 'doughnut';
    /*this.chartDatasets = [
      {data: [this.trpHorraire, 100 - this.trpHorraire], label: 'TrpHorraire'}
    ];*/
    //this.chartLabels = ['TRP HORRAIRE'];
    this.chartColors = [
      {
        backgroundColor: ['rgb(130, 230, 0)', 'rgb(255, 255, 255)'],
        hoverBackgroundColor: ['rgb(30, 163, 116)', 'rgb(225, 225, 255)'],
        borderWidth: 1,
      }
    ];
    this.chartOptions = {
      responsive: true,
      cutoutPercentage: 80,
      title : {
        display: true,
        text: 'test'
      }
    };
  }

  chartClicked(e: any): void { }
  chartHovered(e: any): void { }

  ngOnDestroy(): void {
    this.lineSubscription.unsubscribe();
    this.lineSubscription2.unsubscribe();
  }

}


Int vs Double on Python

Question: I'm in stats class right now and I wanted to know if it makes a difference if you generate a number each digit at a time vs every digit at once, so I wrote some code...
<code>from random import randint
import math

total1 = 0
total2 = 0
for i in range(100000):
    temp = 0
    for j in range(7):
        temp += randint(0,9)*math.pow(10,j)
    total1 += temp
    total2 += randint(0,9999999)

print "avg1 = ", total1/100000
print "avg2 = ", total2/100000
</code>
When I ran the code, avg1 was always a decimal and avg2 was always a whole number. I don't understand why total1 is being considered as a double since I only ever added integers to it...
Comment: The result of `math.pow` is a floating-point number, not an integer, and it's being added to `total1` (through `temp`).
Comment: There is an easier way to answer the question. Since in the second method, each digit is drawn independently from the others, the probability distribution over all the numbers will be the product of the distributions of each digit. You are drawing each digit uniformly, so the their product will also be uniform, over the cross-product of all of their domains. That cross-product is the space of all 7-digit positive integers, so the two approaches must yield the same distribution. So only an implementation error could result in them (the distributions) being different.
Answer: According to the python documentation, the math.pow function returns a floating point number. This is going to implicitly cast the temp variable to be a float as well:
https://docs.python.org/2/library/math.html
Because total1 is implicitly cast as a float, while total2 is consistently used as an int, total1 will return a decimal and total2 will return a whole number.
Comment: what is the syntax to make avg2 not round?
Comment: As an aside, it is important to remember that the / operator in python will not implicitly cast your integers to a double or float. Thus you will receive a rounded answer for total2/100000 while you get a more exact answer for total1/100000
Comment: Your comment is true in Python 2 but not in Python 3. I tried in Python 3.4.2 and `type(1000/5)` gives ``.
Comment: declaring `total1 = 0.0` and `total2 = 0.0` will initialize them as doubles. You can also explicitly cast them while dividing by: `print "avg1 =  ", float(total1/100000)`. See [here](http://stackoverflow.com/questions/2958684/python-division)
Comment: Also, `from __future__ import division`.

Int vs Double on Python


Remove text from toolbar while open search view

Question:
I don't want this text while click on search in toolbar.
Below is my menu item.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:title="@string/search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always" />

</menu>

This is my onCreateOptionsMenu in Activity
override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        val search = menu.findItem(R.id.action_search)
        val searchView = search.actionView as SearchView
        searchView.queryHint = "Search in everywhere "
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }
            override fun onQueryTextChange(newText: String?): Boolean {
//                adapter.filter.filter(newText)
                return true
            }
        })
        return super.onCreateOptionsMenu(menu)
    }

Very confuse with this. need some help. Thanks in advance for your answer.
Comment: at first place use             app:actionViewClass="androidx.appcompat.widget.SearchView"
.....show more code how you handle  it in your activity or fragment
Comment: There is no code in activity or fragment. some thing that change is in menu file.
Comment: update your gradle files to the last version
Comment: @Mohmmaed-Amleh it's already upto date.
Answer: Just add searchView.maxWidth = Integer.MAX_VALUE  this line in my code and it work for me.
override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        val search = menu.findItem(R.id.action_search)
        val searchView = search.actionView as SearchView

        searchView.maxWidth  = Integer.MAX_VALUE  // add this line to your code.

        searchView.queryHint = "Search in everywhere "
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }
            override fun onQueryTextChange(newText: String?): Boolean {
//                adapter.filter.filter(newText)
                return true
            }
        })
        return super.onCreateOptionsMenu(menu)
    }

Answer: getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");

Comment: Thanks for answering. but this will remove my title at all. I only remove my title while search view is open.
Comment: add this line when search view open getSupportActionBar().setTitle("");
Comment: No it's manage from menu file. so I can't get it in activity. there is changes in menu file with showAsAction this is not solution for me.
Comment: Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others.


How to set up kvm vm on separate nic from host in Ubuntu Server 20.04

Question: I am trying to figure out how to setup a vm in Ubuntu Server 20.04 with kvm, but I am not having much luck.
The goal is to have the host on the 192.168.20.x network and the vm on the 192.168.10.x.
I have two physical nic's available, so I would think I could use nic1(enp4s0) for the host and nic2(enp8s0) for the vm, however I have not figured out a way to do that just yet.
I was able to achieve this with VirtualBox in Ubuntu 16.04 with ifupdown and a configuration of iface eth1 inet manual, but I don't know what the equivalent is in the netplan yaml file.  I have tried the following for my yaml file and the second nic shows as up when I run the ip a command, but nothing is returned when running ping -I enp8s0 www.google.com and when trying to install the vm, it can't connect to the network.
00-installer-config.yaml contents:
network:
version: 2
renderer: networkd
ethernets:
    enp4s0:
    dhcp4: true
    dhcp6:  false
    enp8s0: {}

I believe my issue is with the configuration of the enp8s0 nic, but I could be wrong.  I have to think there is some way to use nic2(enp8s0) for the vm, I'm just not sure how to do it with kvm and netplan.  I've dabbled with setting nic2 as a pci passthrough, but I would like to avoid that if possible.  If that is truly the only way to get this to work, then I will explore that option but I wanted to ask first.  Any and all help is greatly appreciated.  Thank you.
Comment: If you want to dedicate the NIC to a particular VM, then passthrough is exactly what you want. Avoiding it doesn't make sense.
Answer: network:
  version: 2
  renderer: networkd
  ethernets:
    enp8s0:
      dhcp4: no
      dhcp6: no

  bridges:
    br2:
      interfaces: [enp8s0]
      dhcp4: no
      addresses: [192.168.10.10/24]
      gateway4: 192.168.10.1
      nameservers:
        addresses: [192.168.10.1]

or try to use Linux bridge, for example:
brctl addbr br2
brctl addif br2 enp8s0
ip addr add dev br2 192.168.10.1/24
ip link set up dev br2

In this article for more KVM networking configuration examples.


How to increase memory usage to specific level for certain time duration

Question: How can I reduce available free memory to certain level for specific time duration?
I've total of 16GB memory where free memory is more than 90%. I want to reduce free memory to 5% and have it in this state for about 120seconds
to check memory usage
vmstat -s

to reduce free memory
tail /dev/zero

Answer: You can use stress-ng.
This line command will use 90% of your memory.
stress-ng --vm-bytes $(awk '/MemAvailable/{printf "%d\n", $2 * 0.9;}' < /proc/meminfo)k --vm-keep -m 1
Change the 0.9 to any value (must remain as a decimal). It signifies the percentage.


submanifold with same homology

Question: Suppose $M$ is a manifold without boundary, and $N\subseteq M$ is any submanifold, possibly with boundary. If $H_*(N)\cong H_*(M)$, is it necessarily true that $N\cong M$?
Comment: (Things beecome more interesting if you assume that, say , $M$ is a closed manifold)
Comment: Do you mean to say  homotopically equivalent?
Comment: @MarianoSuárez-Alvarez I suggest an answer for your case, just have a look :)
Comment: Yes I assume closed, and homeomorphic, but homotopy equivalent is ok as well.
Answer: No, you can take a point in $R^n$.
Comment: Sorry, forgot to say M is compact without boundary.
Answer: I assume that you want to know whether $M,N$ are homotopically equivalent or not.
First consider a $\epsilon$-neighbourhood of $S^1\vee S^1\vee S^2$ inside $\mathbb R^3$ as our manifold $M$. And consider $N= T^2 $(torus) inside $M$. ( we can do so since $M$ is $3-$dim manifold and torus can be embedded in $\mathbb R^3$). So $H_*(M)=H_*(N)$ but they are not homotopically equivalent. (WHY?)
Now as Mariano suggest what can we say if we know $M$ is closed?
In that case if $M\neq N$ then $N$ is deformation retract onto at least a $n-1$-dim CW-complex. In that case $M,N$ cannot be homotopically equivalent, becasue $H_n(M,\mathbb Z_2)= \mathbb Z_2$ but $H_n(N,\mathbb Z_2)=0$.
Comment: Ok now I see. Cell structure and fundamental class. Thanks.
Comment: @guest you should edit your question, and write it properly

submanifold with same homology


Firebase addValueEvent listener consuming memory if data is in large amount

Question: Thanks in advance.
<code>global.getDatabaseReference().child(ApplicationConstants.TOPIC_DB).child(Util.getSelectedBoard(context)).child(Util.getSelectedClass(context)).child(Util.getSelectedLanguagePackage(context)).child("CategoryId_1").child(subject).child(ApplicationConstants.TOPICS).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                try {

                    topicContentArrayList = new ArrayList<>();
                    HashMap<String, HashMap<String, String>> modelHashMap = null;
                    int pos =0;
                    for (DataSnapshot single_ : dataSnapshot.getChildren()) {
                        modelHashMap = new HashMap<>();
                        HashMap<String, String> innerTopicNode = (HashMap<String, String>) single_.getValue();

                        innerTopicNode.put("mastery", "0");
                        innerTopicNode.put("enabled", innerTopicNode.get("Display"));
                        innerTopicNode.put("currentLevel", "1");
                        innerTopicNode.put("flag", "Done");
                        innerTopicNode.put("score", "0");

                        modelHashMap.put(pos + "", innerTopicNode);
                        pos++;
                        topicContentArrayList.add(modelHashMap);

                    }
                                     } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

                Util.dismissdataDialog();
            }
        });
</code>
Here is the memory error
Background partial concurrent mark sweep GC freed 277003(9MB)
It is blocking the UI and I'm unable to perform click action for some time.
Please Help me to get out from this issue.
Answer: That is the normal behaviour when you trying to get large amount of data. If you want to avoid errors like this, you should consider loading your data in small chunks. To achieve this, you can filter your data using one of the methods that are provided by Firebase.
Comment: Have you tried my solution above, is there everything alright?
Comment: Thanks Alex for the answer but its not meet my requirement.
This is working fine now but stuck with another issue is What if I have to call the above code in loop having size 50.

In that case it is blocking the UI.
Comment: If you are stuck with another issue (other than this), please post another fresh question, so me and other users can help you. Regarding this issue, have you tried loading your data in small chunks? Please also note, that Firebase Database client, already runs all network operations in a background thread. This means that all operations take place without blocking your main thread. Do you think that my answer helped you for the initial issue?
Comment: No. It did not help me to get out from that.


Solvability of Perelman's $\mathcal W$ system.

Question: How to show the system have solution ? $R_{ij}$ is ricci tensor, $R$ is scalar curvature. I feel this is complex question, because I have little knowledge about PDE. So, if it is complex, just tell me what I should read ? I try to find answer in Evans' PDE book, but I am not sure. Whether the 11 chapter of Evans' PDE can resolve this question ?
The below system is from 206 page of this paper.

\begin{cases}
\frac{\partial g_{ij}}{\partial t}=-2R_{ij} \\
\frac{\partial f}{\partial t}=-\Delta f+|\nabla f|^2-R+\frac{n}{2\tau} \\
\frac{\partial \tau}{\partial t}=1
\end{cases}

I try it. Under some initial condition. I can get $\tau=\tau_0+t$. Besides, $\frac{\partial g_{ij}}{\partial t}=-2R_{ij}$  has short-time solution, according to the 1.2 of this. So, it just be whether $\frac{\partial f}{\partial t}=-\Delta f+|\nabla f|^2-R(t)+\frac{n}{2(\tau_0+t)}$ has solution. Because $\tau_0 >0,t\ge0$,and $R(t)$ is smooth...
Comment: You definitely need a solid background in PDE. I would strongly advise also to familiarize yourself with pseudo differential operators. In order to understant the paper you have gave a link, you need thirst of all to understant the ricci flow (Hamilton introduced it and investigated the solvability of it).
Comment: Thanks your advise, I will work hard.
Answer: There is an answer about your question.Let $\tau=t_0-t$, $u=e^{-f}$, then the nonlinear equation will become a linear equation.


After installation of Drupal commons-7.x-3.13 in windows. I got this type of error?

Question: I am using Drupal Commons-7.x-3.13 module to install in windows. After installation I can't logged my site.
Please help anybody. I am in critical situation.
Answer: You need to allocate more memory. There is not enough for mysql to run. There is an entire handbook page dedicated to this common issue. See https://drupal.org/node/259580
Comment: Your answer is correct. It's worked for me.
Answer: Edit your my.cnf file.
In case of linux you need to use : vim /etc/mysql/my.cnf
Tweak/decrease these values as required.
wait_timeout = 600
max_allowed_packet=500M

and restart mysql
sudo /etc/init.d/mysql restart


Get an element inside two tags and looping through multiple variable

Question: So I have a price that I get as a variable but I keep getting "USD 60" where I want just "60". After that I need to loop through multiple variables(price and quantity) then write two sentences. "An order was placed with a quantity of 2 and price of 60" "An order was placed with a quantity of 5 and price of 20." This is as close as can get it but the loop isn't working.

                2

            5

USD 60.00
USD 20.00

var price = document.getElementsByClassName('v1_shop_cart_articles_col_price').getElementByTagName('span')[1].innerHTML;
var qty = document.getElementsByClassName('v1_shop_cart_articles_col_qty');

for(var i=0; i<qty.length; i++) {
    document.write('An order was placed with a quantity of '+
                    parseInt(qty[i].innerHTML, 10) + price +
                   '.');
    }

Comment: here is a codepen http://codepen.io/anon/pen/CAask
Answer: http://codepen.io/anon/pen/hKafl
without a table, your td's weren't showing up - so your qty and price arrays were empty. also, when you were trying to get the price value, weren't accessing a specific element in the price array.


Change or turn off the default rss in Piranha cms

Question: I have created a website with piranha CMS and a custom routing class. The links in the RSS flow is now broken. Can I change or turn off the default RSS solution?
I tried to solve this problem by creating a controller that returns an RSS feed with the correct links. In RouteConfig I added this map route:
routes.MapRoute (
                 name: "rss"
                 url: 'rss'
                 defaults: new {controller = "RSS", action = "Index"},
                 namespaces: new [] {"onceuponatime.Controllers"}
             );

But when http://mywebsite.com/rss called, it's still the default solution that is shown.
Answer: When the application starts a number of default request handlers are registered, among them the RssHandler. You can disable it by adding the following statement in you startup code, like Global.asax.cs:
Piranha.Application.Current.Handlers.Remove("RSS") ;

This will disable the default implementation and let you handle calls for /rss yourself.


Is the function sequence of the form $f_{n}(x) = (x - x^{2})^n$ pointwise convergent?

Question: I believe that the sequence converges pointwise, but not uniformly. My reasoning is as follows:
By the way, the functions $f_n$ are defined in $[0, 1]$.

if $x \in \{0, 1\}, f_n(x) = 0^n = 0$, so you could pick any $N \in \mathbb{Z^+}$ and the distance from the limit of $f(x)$ would be $0$ in both cases, and thus less than any $\epsilon > 0$.

However, if $x \in (0, 1)$, then the choice of $N$ is dependent on $x$ as well as the choice of $\epsilon$. Therefore, the sequence is pointwise convergent and not uniformly convergent as uniform convergence requires the choice of $N$ to be independent of $x$.

I determined the value of $N$ and it seems like the proof works out. However, all functions $f_n$ would have a maximum, so I believe uniform convergence may also be possible.
I'd appreciate any thoughts you have on my "proof".
Comment: Were you able to find the x-value of the maximum?
Comment: The point I was attempting to make is that, if you were able to find the maximum and see the x-value of the max doesn't depend on $n$, then in this case (non-negative functions converging to zero) pointwise convergence and uniform convergence are the same.
Comment: Yeah, the answers were helpful in finishing the thought I had.
Comment: $(x-x^2)^n=x^n(1-x)^n$. This gives you convergence point wise. However you also get uniform convergence on $[0,1[$ by noticing that $x(1-x)<\frac14$ for al $0\leq x\leq 1$.
Answer: Your argument is fine, but the convergence is also uniform.
Suppose that $x\leq\frac12$. Then, crudely,
$$
(x -x ^2)^n\leq x ^n\leq\frac1{2^n}.
$$
And if $x\geq\frac12$, then $1-x\leq\frac12$ and
$$
(x-x^2)^n=\big((1-x)-(1-x)^2)^n\leq\frac1{2^n}.
$$

Alternatively, you can use calculus to find that your functions have a maximum at $x=\frac12$ and so $(x-x^2)^n\leq \frac1{4^n}$.
Comment: Thank you for the alternative approach!
Answer: Actually, the convergence is uniform. For each $x\in[0,1]$, $0\leqslant x-x^2\leqslant\frac14$, and therefore $0\leqslant f_n(x)\leqslant\frac1{4^n}$. So, if $\varepsilon>0$, you just take some $N\in\Bbb N$ such that $\frac1{4^n}<\varepsilon$ and then, for each $n\geqslant N$ and each $x\in[0,1]$, $0\leqslant f_n(x)<\varepsilon$.
But your proof of the fact that $(f_n)_{n\in\Bbb N}$ converges pointwise to the null function is correct.
Comment: @PriyamTurakhia That specific $N$ only works if $\varepsilon \leq 1$, but if $\varepsilon > 1$, $\frac{1}{4^n} < \varepsilon$ holds for any $n\in\mathbb{N}$.
Comment: Can I state that "some N" in the proof? Or should I specify an N?
Comment: If you want to be on the safe side, take $N=\left\lceil-\log_4\varepsilon\right\rceil$.
Comment: I found it a bit confusing that N can be negative, but it doesn't seem to affect the proof, thank you very much


How to find in a node template file that node is loaded directly or from 'node_load' function?

Question: I want to check, in a node template file (node-node-type.tpl.php), that code is executing because of a direct request from a user visiting a node page or from calling node_load function in somewhere else?
EDIT:
the problem was 'Number of posts on main page' option in 'Post settings'. its value was 30 (I don't remember why I set it to its maximum value but I'm sure there was a reason that wasn't related to it's true functionality I think it triggers something else).
now that we know problem is from 'Number of posts on main page' option how I
can I fix it?
why this option invokes node template file despite the fact that I use a custom page.tpl.php which doesn't call node_view at all?
Comment: @sepehr `node_load()` doesn't ever invoke the node template file. It's a function for loading a node, it has zero connection to the theme layer. I think you're getting it confused with `node_view()`, which _does_ invoke the node template file
Comment: @ninjascorner a node template file executes: 1- when a user see that specific node type(=content type) page e.g. node/nid 2-when there is a call to node_load(nid).Now in node-node-type.tpl.php how can I check that?
Comment: Please, explain WHY. Maybe we can find better solution :)
Comment: Can you please elaborate your question? Thanks
Comment: `node_load` is a core function no node can be loaded without this call.
Answer: Edit: I realise after writing the answer that I sound rather negative. Sorry about that, but I can't phrase this in a positive fashion.
Answer: First, and foremost, you are mixing logic, with output. The template should not have logic in it, and should absolutely not care about why it was called.
When a user visits node/1, core will call node_load(1). This is in no way different from calling node_load(1) anywhere else.
A node template does also not execute as a direct result of loading a node. Templates are used when the theme layer renders a node, which is the completely other end of the response.
You can, in theory, call debug_backtrace() to get the call stack, and from there figure out more information about from where node_load was called, but there is almost certainly exactly 0 valid use-cases for this. I guarantee that you do not want to go down that path, and even considering it means that something is seriously wrong.
I have built Drupal-sites professionaly for years now, and have done some really, really ugly hacks during that time. Neither of them would come anywhere near analysing the stacktrace, in the theme layer.
Comment: For debug and exploration purposes [Devel](http://drupal.org/project/devel)'s `ddebug_backtrace()` can be used too.
Answer: node will displayed after creating renderable array via node_view(node_load($nid)). so if there is somewhere where you render node yourself, you can pass extra variable to node_view and catch it in node--node-type.tpl.php
another solution is using context module, where you can set static variable and get it in node--node-type.tpl.php then unset it again
context_set('mynamespace', 'customrender', true);

print drupal_render(node_view(node_load($nid))); //and in node--node-type.tpl.php context_get('mynamespace', 'customrender');

context_set('mynamespace', 'customrender', false);