@import sass directive doesn't work for me, (Undefined mixin)

Question: rails 3.2, bootstrap 3.
I use bootstrap sass gem and I can't do it work.
I have this error

Undefined mixin 'make-lg-column'.

in this file app/assets/stylesheets/exam.css.scss
...
.button-left{
  @include make-lg-column(4);
  display:inline;
  padding-top: 5px;
}
...

this is my application.css.scss
@import "bootstrap";
@import "exam";

if I add these lines to exam.css.scss it works. But I don't want do it
@import "bootstrap/variables";
@import "bootstrap/mixins";

Please any advice is welcome, thanks for your help.
Answer: Do you want to compile the "exam" file as a part of application.css?
If I understand right, you should rename your file exam.css.scss -> _exam.scss  and you don't need to add any other import.
it happens because exam.css.scss is a seperate file and compiler don't know anything about applications.css.scss
Answer: The mixin make-lg-column is defined within the bootstrap/mixins; file. In order to process the mixins file, you also need to provide the variables file. You can do 1 of 2 things:

Include the mixins and variables files within your exam.css.scss file even though it's not your preference.
You can copy the make-lg-column mixin out of the mixins file into the beginning of your exam.css.scss file.

.make-lg-column(@columns; @gutter: @grid-gutter-width){
  position: relative;
  min-height: 1px;
  padding-left:  (@gutter / 2);
  padding-right: (@gutter / 2);
  @media (min-width: @screen-lg-min) {
    float: left;
    width: percentage((@columns / @grid-columns));
  }
}

NOTE: You will have to redeclare your variables too.
Comment: Thanks for your help. I don't understand because I have to include `make-lg-column` again if [in this file of gem is included](https://github.com/twbs/bootstrap-sass/blob/master/vendor/assets/stylesheets/bootstrap/bootstrap.scss#L2-L3). It is a bit confusing for me.
Comment: I guess I'm not understanding your question then. Are you trying to compile `exam.css.scss` on it's own or compile it into `application.css.scss`? If you want to compile `exam.css`, you will have to redeclare your variables & mixins. If you only want to compile `application.css` then you shouldn't have to redeclare variable and mixins. It looks like you're trying to compile `exam.css` though, correct?
Comment: I want to compile `application.css.scss`. I'm following [this advice](http://pivotallabs.com/structure-your-sass-files-with-import/).
Comment: Do you have a file in your `bootstrap` folder that rolls up all your imports? I see you're calling `@import: "bootstrap";`. Do you have a `bootstrap.scss` file that includes all your bootstrap files?
Comment: According with [gem documentation](https://github.com/twbs/bootstrap-sass#sass) `@import "bootstrap";` include all of Bootstrap's styles, mixins and variables!. So only use it. It's rare because after I put underscore to exam.css.scss -> _exam.. It worked.
Comment: the underscore means that the file is gonna be imported and compiled after in the new file, without the underscore it will compile before and the import it


Bulk deleting from extension's localstorage by value?

Question: I'm using localstorage to track domain visits and their timestamp.
Here's how I'm setting it:
localStorage.setItem(`${domain[0]}`, JSON.stringify(Date.now()));

What code would I use to delete all rows with a timestamp that's older than 30 days so users don't end up with too much extra data that probably won't be used?
I've seen a lot of examples about deleting individual rows based on the key.  But I can't find anything related to bulk deleting based upon the values.
Answer: Enumerate all key/value pairs explicitly:
const cutOff = Date.now() - 30 * 24 * 3600 * 1000;
Object.entries(localStorage).forEach(([k, v]) => {
  const time = JSON.parse(v);
  if (time < cutOff) {
    delete localStorage[k];
  }
});

Comment: Is there a "best practice" for when this should be run or a way to control that?  For example, should it just be put in the background script and let it do it's thing?  Or be setup to just run once per day?
Comment: Once a day sounds fine. You can use chrome.alarms API for that or store the last cleanup's date in a separate key in localStorage.


Cannot return by const value from lambda

Question: I'm trying to construct a lambda that returns by const int, but the const qualifier is being discarded. In the following code, lam1 and lam3 are behaving as expected, but lam2 is not. Expected output is 0 1 1 but I get 0 0 1.
#include<type_traits>
#include<iostream>
using namespace std;

int main()
{
  int C{0};
  auto lam1 = [&]()->       int& {return C;};
  auto lam2 = [&]()-> const int  {return C;};
  auto lam3 = [&]()-> const int& {return C;};

  cout << is_const<remove_reference<decltype(lam1())>::type>::value << endl;
  cout << is_const<remove_reference<decltype(lam2())>::type>::value << endl;
  cout << is_const<remove_reference<decltype(lam3())>::type>::value << endl;
}

demo link: https://godbolt.org/z/xP4lYs
Comment: clang gives me this warning _"warning: 'const' type qualifier on return type has no effect [-Wignored-qualifiers]"_
Comment: Returning by const value is pointless.  It is exactly the same as returning by value.
Comment: @roro - Then you should have tried with a class type too then, the const would not have been discarded there.
Comment: simplicitly is not always clarity ;) This would be the only instance of `const` making any difference for primitives, so why would it matter... why dont you use a `struct foo {}` for the example?
Comment: @NathanOliver it is for primitives, but has utility for general types. I chose int here just for simplicity.
Answer: It's intended. Remember that decltype returns the type of an expression, possibly with a reference qualifier to match the expression's value category. lam2 returns a prvalue, and well...

[expr]
6 If a prvalue initially has the type "cv T", where T is a
  cv-unqualified non-class, non-array type, the type of the expression
  is adjusted to T prior to any further analysis.

There are no const prvalues of primitive type. Since you return a const int, and that's the type of the function call expression, the const is removed prior to further analysis (including decltype deducing the type of the expression).
For class types, that is not the case, because the cv-qualifiers can affect a class object's behavior.
Answer: Recall that it works this way for normal functions too.
That's by design, because returning built-ins by const value is pointless.
However, it is the decltype that is "removing" it (or, rather, allowing you to observe that it's removed when used in an expression) — the const is still part of the function's signature. If your example related to a class type rather than int, you might have observed something else (see previous link). :)


Solr Search: Searching in multiple fields with "AND" Search

Question: I'm a product owner for the search engine of an e-commerce company and I'm currently "discovering" Solr - since I've never worked with this engine before. Sorry in advance if I don't use the proper terminology.
I have the following typical use case: a user looks for "Apple iPhone". Data set contains fields like Brand = Apple, Product Name = iPhone, Product Type = Smartphone, Category = Smartphones, etc.
In our current setup and according to our external consultants, the engine delivers all results that contain either apple OR iPhone 8. In order to get all the Apple iPhones as results first, they recommend we create a new indexed property containing brand, product name, product type and category all in one and replace the individual properties (so Brand, Product Name, etc.) by this new one. According to them, Solr isn't able to provide an AND search ("look for all products that have apple AND iPhone in their data set").
Is this correct and would you handle this use case the same way?
I'm quite skeptical that Solr isn't able to look for Apple iPhone in separated properties and then deliver results that contain both terms in either indexed properties. The change they recommend also means we lose granularity since multiple fields are being concatenated in one. That also means we won't be able to boost each property separately anymore since they get replaced by the new one.
I'm aware my request might come accross as a "newbie" question but as a non-developper I still haven't been able to figure it out, and the consultants really seem to think that's the only way to handle this use case.
Thanks everyone for your help!
Answer: There isn't any reason to lose the granularity; usually you'll want to copy the fields (using the copyField instruction) into one or more fields to support different kinds of queries (this also allows you to score hits in the different fields with separate weights). That way you keep all your original fields, and you have a new, separate field that have all the content as a single search field.
Depending on your query use case, you might not need more than the edismax query handler and qf=Brand ProductName ProductType to query those fields, and set q.op=AND (or mm=<factor>) to get the behavior you want. If you're unable to match across fields using qf, use a field which have the different fields copied into it as the base match (i.e. add SearchField as the last field in qf as shown above), then boost hits in brand/name/etc. accordingly so exact matches for just "apple" gets scored higher.
Exactly what's considered a match will depend on the tokenization and filtering happening for the field.
Comment: Thank you very much for your answer! Will look into this!


How to return an Optional from MyBatis query

Question: Is there any way to get MyBatis to return an Optional<MyClass> instance rather than simply a MyClass instance?
Answer: Mybatis pre 3.5.0
Create custom ObjectFactory like this:
class OptionalAwareObjectFactory extends DefaultObjectFactory {

  public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
     if (Optional.class.isAssignableFrom(type)) {
        return Optional.fromNullable(Iterables.getOnlyElement(constructorArgs));
     } else {
        return super.create(type, constructorArgTypes, constructorArgs);
     }
  }
}

And configure it to be used in mybatis.xml:
 <objectFactory type="my.company.project.OptionalAwareObjectFactory"/>

Mybatis 3.5.0+
Since 3.5.0 Optional is supported natively as fankai pointed out.
Comment: Fantastic. Thank you for that.
Answer: Mybatis supports Optional return type officially now since 3.5.0, refer to http://blog.mybatis.org/2019/01/mybatis-350-released.html
Not sure how Roman's answer worked ... it might work in earlier version of Mybatis, as the method signature suggests, but apparently doesn't work with latest versions.


arduino servo and delay

Question: I have a servo that will sweep from 0 to 180 degrees then back to 0 however i cannot use the delay() function as i need the sweep to be interrupted by a motion sensor. I have written some code however the sweep is not smooth, the servo jumps around sometimes. What have i not done correctly? Thanks in advance
<code>int x = 0;

void pivot(){
for (pos = 0; pos <= 180; pos += 5) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo_2.write(pos);              // tell servo to go to position in variable 'pos'
//delay(15);
  for (x; x<10; x++)
  {
    delay(1);
    ping();
  }
  x=0;
 }
for (pos = 180; pos >= 0; pos -= 5) { // goes from 180 degrees to 0 degrees
myservo_2.write(pos);              // tell servo to go to position in variable 'pos'
//delay(15);
for (x; x<10; x++)
  {
    delay(1);
    ping();
  }
  x=0;
 }
}
</code>
Answer: I think the problem is simply that you are trying to sweep too fast.
180 degrees in increments of 5 is only 36 steps, so that's 72 there and back. With a 1 ms delay looped 10 times, you are trying to move the servo through its full range and back in 0.72 seconds. This is just a little faster than a typical RC servo can move. 0.24 seconds for 60 degrees is typical for a basic servo, so if your full range is about 120 it would take it roughly 1 second. That said, for all I know you may be using a fast servo with a 60 degree range.
The other possibility is that when you say not smooth you don't mean that it's jumping around randomly, but just that it's jittering. I would expect with 5 degree jumps every 10 ms you would get a little bit of jumping, 10 Hz is close to the frequency of a Harley idling and 5 degrees is too large of a movement to appear smooth at that speed.
Do you need the servo to stop during the 10 pings, or can it sweep continuously? If it can then I would decrease the number of pings per stop and proportionally decrease the step size. IE step 1 degree and ping 2 times.

arduino servo and delay


Unable to perform xAxis[0].setCategories & series[0].setData

Question: Hii All,
I am passing values dynamically for a chart, using set data and set categories method. I have attached the fiddle link, which loads a sample chart and a button, when clicked which sets the data and categories for the chart. The setData(yaxis) and setCategory(xaxis) is not workin for me.
http://jsfiddle.net/byfour/XUgAQ/13/
Please help!
Many thanks,
byfour
Answer: Your quoting the data as though it were a string;
var ydata = '[129.2, 144.0, 176.0, 135.6, 148.5, 216.4]';

whereas it should be an array:
var ydata = [129.2, 144.0, 176.0, 135.6, 148.5, 216.4];

If they are "incoming" as strings for some reason? you can convert them;
var ydata = '[129.2, 144.0, 176.0, 135.6, 148.5, 216.4]';
ydata = ydata.substr(1, ydata.length - 2).split(",");
chart.series[0].setData(ydata );


Configurar o index da imagem que receberá o style

Question: Tenho um grupo de imagens dentro de uma div:

Gostaria de saber o index de cada uma para usar na função abaixo:
$(document).ready(function(e) {

  $("div.slideShow div.contador span.contaSlide").click(function() {
      index = $(this).index();
      $("div.slideShow div.boxSlide img").css("opacity",0);
      $("div.slideShow div.boxSlide img").prop("index",index).css("opacity",1);
  });

});

Mas não dá certo. Já tentei como abaixo também mas o resultado é o mesmo.
$("div.slideShow div.boxSlide img").val(index).css("opacity",1);

Parece que essa parte não indica qual a figura que deve receber o style
.prop("index",index)

Eis o HTML

        <

        >

     1
     2
     3

Answer: Consegui:
  $("div.slideShow div.boxSlide img").eq(index).css("opacity",1);

Obrigado!


Is there such a thing as an order-$k$ RNN?

Question: In HMMs it's common to include edges from previous layers of the model. Looking back at the previous $k$ layers creates an order-$k$ Markov model.
Is this commonly done in RNNs? Have you ever seen this? What was the advantage for that specific application?
In probabilistic graphical models like HMMs, order-$k$ models can be reduced to order-1 models on transformed variables with higher-dimensional support (i.e., the tree decomposition of the order-$k$ graph). Is there a corresponding equivalence for order-$k$ RNNs, where the RNN accepts edges only from the previous layer, but where each layer has greater complexity?
Comment: This is doable, but it's not common. The assumption in an RNN is that the hidden state already carries with it information from all previous states, which isn't true in (e.g.) an HMM with the Markov assumption. I don't think it would have much value, unless you're trying to include a specific inductive bias of dependency on specifically $k$ steps back.
Answer: Turning my comment into an answer:

This is doable, but it's not common.
The assumption in an RNN is that the hidden state already carries with it information from all previous states. This isn't true in (e.g.) a $k$th-order HMM. By the Markov assumption, you absolutely can only look back $k$ steps.
I don't think the higher-order RNN would have much value, unless you're trying to include a specific inductive bias of dependency on specifically $k$ steps back. What you've provided is another avenue for information to flow, but unlike the HMM there was already one avenue.


Retrieve ID attr from div tags created 'on the fly'- $("" and use them in their click function

Question: I am creating div tags on the fly inside a for loop.
The divs are outputted nicely like a chess table and there is a unique id for each.
I just don't know how to retrieve it in its click function. 'this.id' or $(this).id doesn't work (I generally use it in $.each methods).
*How could I retrieve/refer to the id inside the click function ? *
I've posted a bigger code part width variables, but the main part is this:
$("
", {
    class: gridClass,
    id: cardID,
    click: function(e) {
        alert(this.id);
    }
});

more from the code:
var init = function() {
    //variable declaration
    var GRID_WIDTH = 2,
        GRID_HEIGHT = 2,
    var FACE_DOWN = 0;

    var cont = $("
", {
        id: 'container'
    });

    var c1 = "card";
    var c2 = "card cardfirstInRow";
    var gridClass = "";
    var cardID = "";
    // end variable declaration

    // creating DIV-s on the fly
    for (var x = 0; x < GRID_WIDTH; x++) {
        for (var y = 0; y < GRID_HEIGHT; y++) {
            y === 0 ? gridClass = 'card cardfirstInRow' : gridClass = 'card';
            cardID = controller.getCardID(); //returns a unique number converted to string

            $("
", {
                class: gridClass,
                id: cardID,
                click: function(e) {
                    alert(this.id);
                }
            }).appendTo(cont);
        }
    }
}

Comment: possible duplicate of [How can I get the ID of an element using jQuery?](http://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery)
Comment: `$('').addClass(gridClass).attr('id', cardID).on('click', function(ev) { alert(this.id) });`
Comment: Who the heck voted down on all correct answers ?! a troll !
Comment: You are right, that is a good solution. I used a different way of declaring the div with {} notation, as a result this was pointing to the Global Execution context - window. This was shown  when I debugged the code. So I can rearrange my code like you recommended, or I have just chosen a third solution click: function(e) {                     alert(e.target.id); I might run into problems with it latter, than I can still choose this solution
Answer: The problem is in your click function, not your creation of the div function. Because you are adding the div's to the DOM you need to use event delegation to capture the click event when it bubbles up -
$('body').on('click', 'div' function() {
    console.log( this.id );
});

Answer: e.target gives you the element (javascript object)
To get the id just use
var elemId = e.target.id;

Comment: Thank you ! You have delivered the solution !
Answer: try this
$(this).attr('id');
that is the method that returns an attribute value of an element using jQuery
Here is the Fiddle
Comment: I added values of the div attributes with an object {} notation,the click event was also inside, as a result 'this' was pointing to the Global Execution context - window. This was shown  when I debugged the code. There are several ways to solve the problem (as most of the time), see the first comment and the right answer.


100% code coverage with different PHP versions in Travis-CI

Question: I'm working on my pet-project Pipes and try to keep as close as possible to the 100% code coverage (I'm using Coveralls) for that).
The problem I'm facing is: how to get 100% code coverage with different PHP versions? As of now, my project doesn't contain version-specific code, but this is likely to change very soon.
I'd like to get a 100% code coverage for PHP 5.4 even if the generators related code would not be executed when testing against 5.4.
Can anybody offer a strategy or advice about how to keep my coverage statistics accountable?
Here's my .travis.yml:
language: php

php:
  - 5.6
  - 5.5
  - 5.4
  - hhvm

install:
  - composer require satooshi/php-coveralls:~0.6@stable

before_script:
  - curl -s http://getcomposer.org/installer | php
  - php composer.phar install --dev
  - mkdir -p build/logs

script:
  - phpunit --coverage-clover build/logs/clover.xml

after_success:
  - sh -c 'if [ "$TRAVIS_PHP_VERSION" != "hhvm" ]; then php vendor/bin/coveralls -v; fi;'

Here's my phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
    backupStaticAttributes="false"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    processIsolation="false"
    stopOnFailure="false"
    stopOnError="false"
    stopOnIncomplete="false"
    stopOnSkipped="false"
    syntaxCheck="false"
    bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory suffix="Test.php">./src</directory>
            <exclude>
                <directory>./docs</directory>
                <directory>./vendor</directory>
                <directory>./tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

PS: I know that Code Coverage is not a silver bullet.
Answer: Using another example I found, I discovered that @requires negatively impacts code coverage. For example:
<?php

require_once('class.php');

class FooTest extends PHPUnit_Framework_TestCase {
    /**
    * @requires PHP 5.5
    * @covers Foo::greater
    */
    public function testGreater() {
        $x = new Foo();
        $this->assertSame(2, $x->greater());
    }

    public function testLesser() {
        $x = new Foo();
        $this->assertSame(1, $x->lesser());
    }
}

<?php
class Foo {
    public function greater() {
        return 2;
    }

    public function lesser() {
        return 1;
    }
}

In my opinion, the @covers should force code coverage to mark the greater method as covered. But, it does not:


apache2 multiple virtual hosts with different ssl not working

Question: I generated certs using the following command
openssl req -new -newkey rsa:2048 -nodes -keyout rrr.key -out rrr.csr

I then created the following file ssl-001.conf in the sites-available folder
<VirtualHost _default_:444>
       DocumentRoot /var/www/html/endpoint/
       ServerName safcom.co.ke

       ErrorLog ${APACHE_LOG_DIR}/error.log
       CustomLog ${APACHE_LOG_DIR}/access.log combined

       SSLEngine on
       SSLCertificateFile    /home/xxxx/rrr.csr
       SSLCertificateKeyFile /home/xxxx/rrr.key
</VirtualHost>

Then changed ports.conf to this
<IfModule ssl_module>
    Listen 443
    Listen 444
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
    Listen 444
</IfModule>

Then restarted my server and it didn't work. What i am trying to achieve is to have my port 80 and 443 to run as normal but have an additional port 444 which has ssl. What am I doing wrong? My understanding is that you can have one certificate per ip or port!
Comment: What does `didn't work` mean? What is the exact error message you are getting? And why do you want do run http on the https default port 443? You can use different certificates on different named vhosts. The ports or IPs are irrelevant (for apache).
Answer: You created a Certificate Signing Request (CSR). What you need is either someone who signs this request (i.e. a Certificate Authority) or you can self-sign it (but it won't be trusted and you'll get a browser warning).
Self-signing is a rather simple process with openssl:
openssl x509 -in rrr.csr -out rrr.crt -req -signkey rrr.key -days 1001
After you did that, you'll have a file called rrr.crt. Just change rrr.csr in your config to rrr.crt and apache should start using your self-signed certificate.
See also this post: https://stackoverflow.com/questions/10175812/how-to-create-a-self-signed-certificate-with-openssl


Is it possible to call a custom module function in the theme template file?

Question: I created a custom module and there is a simple hello_world() function. Is it possible to call this function in the page template file?
Module file looks like this.
function choco_custom_newui_total_students(){
return 500;
}

function choco_custom_newui_preprocess_page(&$variables) {
    $variables['total_students'] = total_students();
}

page--front.tpl.php

<? echo $total_students?>

Comment: I can think of a list that you can check. [1] ensure `choco_custom_newui` is the module name. [2] see if `choco_custom_newui` module has been enabled. [3] run `print 'stop here'; exit;` and refresh the page to see if the preprocess function is really being implemented.
Comment: Thank you for the checks. It worked. Sorry the module was not enabled :)
Comment: Haha.. good to know.
Comment: You should call `choco_custom_newui_total_students()` but not `total_students()`
Comment: That's what i was trying to do since beginning. Why would we write the "preprocess_page" function if it was possible .. any ways , its not working.
Comment: Did you clear cache before running the preprocess function?
Comment: Drush cc all  , and cleared Drupal cache aswell.
Comment: I edit my answer with aditional information
Answer: You can do it, but it's not recommended, because in the Model-View-Controller pattern, your logic is in the Controller (in this case your module) and in the View (your .tpl file) you should only have code to show the values that comes from the Controller.
The idea is that all variables are prepared in template preprocess functions (in modules or in your template.php).
You can implement the hook_preprocess_page():
function YOUR_MODULE_preprocess_page(&$variables) {
    $variables['my_var'] = hello_world();
}

and in your page.tpl.php file you can now use $my_var to output the value set in your preprocess function:
echo $my_var;

Comment: thanks, i have updated my question with your code. Still i am unable to output any thing in the TPL file.
Comment: @codestings : bizarre .... despite your prior comment, you still accepted this answer ... Could it be that your module was not enabled? If so please add an extra comment here also, or just delete the prior comment. To Adrian: maybe refine your answer to explan WHY it is not recommended? Eg because you should not do so on Merci-giving-day?
Comment: @Pierre.Vriens I added a few lines if you want you can edit the answer too.
Comment: Why only a ***single*** line (there's room enough for an entire chapter ...). Moreover, I don't think I'll edit it, since I just used the opportunity to hijack your answer to post a new question I asked myself ... And BTW: ***MVC*** in mainframe-speak is an assembler instruction to perform a "**M**o**V**e **C**haracter" ... (though I realize that's another MVC-thing).


Integral operator and the kernel function

Question: Let $D$ be an open bounded set in $\mathbb{R}^{n}$. Let $p \in [1,\infty)$, and $q$ is the dual exponent to $p$.  Assume that $K : \mathbb{R} \times D \rightarrow \mathbb{R}$ is a bounded continuous function, and the function
\begin{align}
y \mapsto \int_{D} K(y,x) g(x) dx : \mathbb{R} \rightarrow \mathbb{R}, \hspace{1cm}(1)
\end{align}
is Lipschitz continuous for each $g \in L^{q}(D)$.
Prove that the vector valued map
\begin{align}
y \mapsto K(y,\cdot) : \mathbb{R} \mapsto L^{p}(D)
\end{align}
is Lipschitz continuous.
I was curious if someone could provide assistance on showing this is Lipschitz.  If we were asked to show the integral operator was Lipschitz we would start by applying Holder to (1), but I'm confused on showing the kernel is Lipschitz.
Comment: I guess $\Omega=D.$ I have impression that the uniform boundedness principle can be applied.
Answer: Roughly speaking, this is a consequence of the closed graph theorem and the duality.
Let ${\rm Lip}(\mathbb R)$ be the Lipschitz space on $\mathbb R$ which defined by $${\rm Lip}(\mathbb R)=\{f\in C(\mathbb{R}):\|f\|_{Lip}:=|f(0)|+\sup_{y\neq y'} \frac{|f(y)-f(y')|}{|y-y'|} <\infty\}.$$
It will be convenient to write $K_y(\cdot)=K(y,\cdot)$.
Consider the integral operator $V: L^q(D)\to \rm{Lip}(\mathbb{R})$ $$Vg(y)=\int_{D} K_y(x)g(x)dx.$$ The condition in your question ensure that $V$ is will defined. By the closed graph theorem, one can show that $V$ is bounded.
The argument is standard, I just point out the following two fact which will be used:

${\rm Lip}(\mathbb{R})$ is a Banach space. Proof

If $f_n$ converges to $f$ in $\rm{Lip}(\mathbb{R})$, then $f_n$ convergens to $f$ pointswise.

The boundedness of $V$ gives a postive constant $C$, such that $$\sup_{y\neq y'}\frac{|Vg(y)-Vg(y')|}{|y-y'|}\leq |Vg(0)|+\sup_{y\neq y'}\frac{|Vg(y)-Vg(y')|}{|y-y'|}=\|Vg\|_{Lip}\leq C\|g\|_{L^q(D)}.$$ This deduces, for any $y$, $y'\in \mathbb R$ it holds that
\begin{align}
\bigg|\int_D \big(K_y-K_{y'}\big)g dx\bigg|=\big|Vg(y)-Vg(y')\big| \leq C|y-y'| \cdot \|g\|_{L^q(D)}.
\end{align}
The proof is finished by the duality:
\begin{align}
\|K_y-K_{y'}\|_{L^p}=\sup \big|\int_D \big(K_y-K_{y'}\big)g dx\big|,
\end{align}
where the supreme is taken over all $g\in L^q(D)$ with norm less that 1.
Answer: The conclusion follows directly from the Baire category theorem.
Indeed let $T: L^q(D)\to C(\mathbb{R})$ be defined
by $$(Tg)(x)=\int\limits_D K(x,t)g(t)\,dt$$
Let
$$A_N=\left \{g\in L^q\,:\, \|g\|_q\le 1, \ {|(Tg)(x)-(Tg)(x')|\over  |x-x'|}\le N,\, x\neq x'\right\}$$
Then $A_N$ is a convex set.
The set $A_N$ is  closed in $L^q(D).$ Indeed, assume $\|g_n-g\|_q\to 0,$ where $g_n\in A_N.$ Then $\|g_n\|_q\to \|g\|_q.$
Moreover by the Holder inequality we get
$$(Tg_n)(x)\to (Tg)(x),\qquad x\in D$$
Thus $$|(Tg)(x)-|(Tg)(x')|\le N|x-x'|$$ i.e. $g\in A_N.$
By assumptions we have
$$ L^q(D)=\bigcup_{k=1}^\infty \bigcup_{N=1}^\infty kA_N$$
Therefore, by the Baire category theorem $kA_N$ has nonempty interior for some $k$ and $N.$
By convexity the set  $kA_N$ contains an open neighborhood of $0,$ i.e.
$$\{g\in L^q\,:\, \|g\|_q\le m^{-1}\}\subset kA_N$$
Then $$\{g\in L^q\,:\, \|g\|_q\le 1\}\subset kmA_N$$
Let $L_x=K(x,\cdot).$ By duality between $L^p$ and $L^q$ we have
$$\displaylines{\|L_x-L_{x'}\|_p=\sup\left \{g\in L^q(D)\,:\, \left |\int\limits_D [L_x(t)-L_{x'}(t)]g(t)\,dt\right |,\ \|g\|_q\le 1\right \}\\
=\sup\left \{g\in L^q(D)\,:\, \left |(Tg)(x)-(Tg)(x')\right |,\ \|g\|_q\le 1\right \}\le kmN|x-x'|}$$


Javascript to show/hide div not working properly

Question: I am relatively new to javascript coding, been doing html\css only, so I wrote this function in JS, that hides and shows a div,but it doesn't seem to work at all, can you tell me what am I doing wrong?
Javascript:

Below is the HTML code I'm working on:
<boutton onclick="click()">TEST CLICK</button>

Random text in here...

And also the STYLE tag:

Thanks for your help!
Comment: your button tag has a typo in the question. is it like that in your actual code?
Comment: You should really read up on how to ask a proper question. Your title is likely to draw NO attention as it is very weak and doesn't even explain your problem.
Comment: No the "button" is not like that in the actual html, sorry I misspelled it when I was writing the code in here.
Answer: Rename your onclick function to something else besides click()
example here i've simply renamed it to toggle() and you can see it working.
Comment: Thanks It did work, don't know why, but it did
Comment: calling it as window.click() should work too [info from here re: javascript function named click](http://stackoverflow.com/a/4389178/5360631)


Cherokee-like WebUI for nginx

Question: Is there any nginx module that will provide Cherokee-like web administration panel? It will be very helpful to manage virtual servers and another stuff.
I'm looking for it because I love nginx for this speed and simplicity but Cherokee has great management WebUI.
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q&A is hard, lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping) and the [FAQ] for more details.
Answer: I'm not aware of any nginx module, but there are some cPanel-like admin panels that support nginx.  Right off the top of my head, I know of Froxlor and ehcp.  I think cPanel supports nginx via a plugin and from some researching I did a few months back I read that Plesk was going to support it, as well.
Comment: I would not recommend to use cPanel with nginx! If you need an nginx GUI choose froxlor. I've reviewed the two most used modules adding nginx to cPanel and I was shocked by the lack of security in those concepts as well as the poor code quality. Besides this at least one of the just adds nginx as a proxy for the cPanel driven apache. So better choose a panel that supports it directly

Cherokee-like WebUI for nginx


A module or solution to build first time user walkthrough?

Question: Is there a module or existing solution out there that can be used to create first time user walkthroughs of a site? For example, a user logs in for the first time and gets redirected to a certain page and then can follow steps to learn the site etc etc. I have done some googling on the matter but as you can imagine the results are hold to filter when searching for terms like "guide", "walkthrough", "module", "new user" and so on...
Answer: The jQuery Joyride module would certainly be an option

This module provides Drupal integration with Zurb's Joyride Jquery plugin in order to provide a tour of different html elements on your Drupal site. Drupal integration is done via the Context module, which provides a way to control conditional calling of the joyride plugin and copy-and-paste method for adding specific tour code.

It wraps around the excellent jQuery Joyride plugin
Comment: Gotta confess...I only knew about Joyride, didn't know there was a Drupal module till I searched :P
Comment: And they had a konami code in their joyride!!! :)
Comment: Damn clive you know the module repositories well!
Comment: I dont have to look any further. That module is awesome


Why is the custom palette ignored in MUI?

Question: Using MUI 4.12 and I have set the type to dark and used CssBaseline which was the solution I have seen for other answers but still it seems the type is completely ignored.
import {React, Fragment} from 'react'
import {
    createTheme,
    ThemeProvider,
    makeStyles,
    Zoom,
    Fab,
    useScrollTrigger,
    Box,
    CircularProgress
  } from "@material-ui/core";
import CssBaseline from '@mui/material/CssBaseline';
import KeyboardArrowUpIcon from "@material-ui/icons/KeyboardArrowUp";

import "./App.css";
import Footer from "./Components/Footer/footer";
import { AppRouter } from "./Router/Router";

const theme = createTheme({
  palette: {
    type: "dark",
    primary: {
      main: "#d32f2f",
    },
    secondary: {
      main: "#ef5350",
    },
    inherit: {
      main: "white",
    },
  },
  overrides : {
    MuiTab : {
      textColorInherit : {
        opacity :1,
      }
    }
  }
});

function App(props) {
  return (
    <Fragment>

        <Box id="back-to-top-anchor" />
        <ThemeProvider theme={theme}>
        <CssBaseline/>
          <AppRouter />
          <ScrollTop {...props}>
            <Fab color="primary" size="small" aria-label="scroll back to top">
              <KeyboardArrowUpIcon />
            </Fab>
          </ScrollTop>
        </ThemeProvider>

    </Fragment>
  );
}

Answer: You're importing CssBaseline from @mui/material which is the package for MUI v5. In v5, MUI uses emotion instead of JSS (different style library internally), so your code doesn't work. You need to import the components from the same version to fix the problem:
V5
import { createTheme, ThemeProvider, CssBaseline, ... } from '@mui/material';

V4
import { createTheme, ThemeProvider, CssBaseline, ... } from '@material-ui/core';

Related answer

Material UI Dark Mode
Comment: Oh thank you! That was the issue, not sure how I managed to get two version of MUI I have been a react developer for about 30 minutes :)
Comment: @NathanSchwermann if you're creating a new project, you should use MUI v5 because there is a lot of breaking changes in the newer version. If you decide to update to v5 later, it can quickly become a chore because some breaking changes can't be automated by the codemod.
Comment: Thanks, yep I am updating it now. I hired someone to get me started and make a basic shell, sadly it seems I hired the wrong person for the job I'm basically having to redo everything they did at this point :/ I appreciate the help!


Using Neural Networks when target variable has huge deviation

Question: I have a dataset of 10 features which are in the small range between 0.5 and 1 exactly, while the target variable is between 75 and 9000 with a standard deviation of 350, now I need to use a Neural Network to perform regression on the data but I'm struggling with finding a suitable architecture to solve the issue I'm facing with discrepancy between the ranges of the input and output
Answer: If the output layer has a linear activation function this distribution shouldn't be a problem, but you can always just rescale the target variable by dividing by 350 or 9000 (to have a SD or a maximum of 1). To obtain predictions on the original scale, you can then just multiply them.
Comment: after days of experimentation, I found that things worked best with box cox transformation on the target variable, though I'm a bit suspicious of the results they might be too good to be true


how to get the hierarchical menu from mysql

Question: I have a table having hierarchical menus like
"id" "parent_id" "name"
1 0 menu
2 1 item1
3 2 item1_1
4 1 item2
5 4 item2_1
...
...

and I have 100s of menu items here. In order to get all items in an array I have to write a recursive function like this
getmenu function(parent_id = 1)
{
  $items = mysql_query("SELECT id FROM table WHERE parent_id = " + parent_id);
  while ($item = msyql_Fetch_assoc($items)) {
    ...here I put them in array and call recursive function again to get sub items...
    getmenu($item['id']);
  }
}

but this executes 100s of queries. Is this the best way to do this, to get hierarchical menus from database? Does this way loads mysql much?
Answer: $stmt = "SELECT id, parent_id FROM table";
$items = Array();
$result = mysql_query($stmt);

while ($line = mysql_fetch_assoc($result)) {
    $items[] = $line;
}

$hierarchy = Array();

foreach($items as $item) {
    $parentID = empty($item['parent_id']) ? 0 : $item['parent_id'];

    if(!isset($hierarchy[$parentID])) {
        $hierarchy[$parentID] = Array();
    }

    $hierarchy[$parentID][] = $item;
}

The root level will be $hierarchy[0]. Keys are items ids and values are all direct children.
Comment: Definitely this is a much much better solution than mine. Thanks a lot. But finally I decided to do something way different. To execute less SQLs I created a cron job that generates all menus in  format and dump them in static php files every 5 minutes. Then I just include them and apply css. Since it's not that time critical 5 minutes is enough, even 1 minute is fine too. Server load dropped from 80% to 4% . Nice :)
Comment: You are welcome. For your solution, this is a kind of "cache management". And indeed it helps a lot :) . You could have use [APC](http://www.php.net/manual/en/book.apc.php) too to store the hierarchy directly in memory.
Answer: Take a look at Nested Sets if you don't mind a little more complex solution. Nested Sets have a very good SELECT performance and I assume that selecting is more important here.
With the help of Nested Sets, complex hierarchical data can be managed in a very fashionable and elegant way.
Comment: I was going to suggest the same link, it's a very smart and elegant solution to the problem.
Comment: I didn't know that :) . Smart idea :). May be for the next version of the site.


Feedback Modal em tela de cadastro

Question: Boa noite!
Estou com uma dúvida em relação ao trabalho da minha faculdade em relação a feedback do tipo modal. Já fiz todo o código tanto em html e javascript (coloquei o alert pra ver se tava funcionando direito), mas gostaria de trocar alert pelo modal pra ficar mais bonito. Alguém poderia me ajudar a fazer a base do modal e colocando ele pra funcionar no javascript?

function validacao () {
    if (document.cadastro.nome.value == "") {
        alert ("Por favor, preencha o campo nome.");
        document.cadastro.nome.focus ();
        return false;
    }
    if (document.cadastro.sobrenome.value == "") {
        alert ("Por favor, preencha o campo sobrenome.");
        document.cadastro.sobrenome.focus ();
        return false;
    }
    if (document.cadastro.endereco.value == "") {
        alert ("Por favor, preencha o campo endereço.");
        document.cadastro.endereco.focus ();
        return false;
    }
    if (document.cadastro.datanascimento.value == "") {
        alert ("Por favor, preencha o campo data de nascimento.");
        document.cadastro.datanascimento.focus ();
        return false;
    }
    if (document.cadastro.cidade.value == "") {
        alert ("Por favor, preencha o campo cidade.");
        document.cadastro.cidade.focus ();
        return false;
    }
    if (document.cadastro.cep.value == "") {
        alert ("Por favor, preencha o campo cep.");
        document.cadastro.cep.focus ();
        return false;
    }
    if (document.cadastro.estado.value == "") {
        alert ("Por favor, preencha o campo estado.");
        document.cadastro.estado.focus ();
        return false;
    }
    if (document.cadastro.email.value == "") {
        alert ("Por favor, preencha o campo email.");
        document.cadastro.email.focus ();
        return false;
    }
    if (document.cadastro.senha.value.length < 8) {
        alert ("Por favor, preencha o campo senha com mais de 8 caracteres.");
        document.cadastro.senha.focus ();
        return false;
    }
    if (document.cadastro.cartao.value == "") {
        alert ("Por favor, preencha o campo cartão de crédito.");
        document.cadastro.cartao.focus ();
        return false;
    }
    if (document.cadastro.bandeira.value == "") {
        alert ("Por favor, preencha o campo bandeira.");
        document.cadastro.bandeira.focus ();
        return false;
    }
    if (document.cadastro.codseguranca.value == "") {
        alert ("Por favor, preencha o campo código de segurança.");
        document.cadastro.codseguranca.focus ();
        return false;
    }
}
<!DOCTYPE html>

        <title>Eco Aero - Viagens</title>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="node_modules/bootstrap/compiler/bootstrap.css">
        <link rel="stylesheet" href="node_modules/bootstrap/compiler/style.css">

                Eco Aero - Viagens
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSite">

                    </button>

                            Início

                            Sobre

                            Contato

                            Passagens Aéreas

                            Entrar

                            Inscrever-se

Faça seu cadrastro

                    <form name="cadastro" action="#" method="post" onsubmit="return validacao()">

                                Nome:
                                <input type="text" class="form-control" id="seuNome" placeholder="Nome" name="nome">

                                Sobrenome:
                                <input type="text" class="form-control" id="seuSobrenome" placeholder="Sobrenome" name="sobrenome">

                                Endereço:
                                <input type="text" class="form-control" id="seuEndereço" placeholder="Av.Paris, 54, Bonsucesso" name="endereco">

                                Data de Nascimento:
                                <input type="text" class="form-control" id="suaData" placeholder="DD/MM/AAAA" maxlength="8" name="datanascimento">

                                Cidade:
                                <input type="text" class="form-control" id="suaCidade" placeholder="Cidade" name="cidade">

                                CEP:
                                <input type="text" class="form-control" id="seuCEP" placeholder="00000-000" maxlenght="8" name="cep">

                                Estado:
                                <select id="seuEstado" class="form-control" name="estado">
                                    <option selected></option>
                                    <option>SP</option>
                                    <option>RJ</option>
                                    <option>MG</option>
                                    <option>ES</option>
                                    <option>PR</option>
                                    <option>SC</option>
                                    <option>RS</option>
                                </select>

                                Email:
                                <input type="text" class="form-control" id="seuEmail" placeholder="email@example.com" name="email">

                                Senha:
                                <input type="password" class="form-control" id="suaSenha" placeholder="Senha" name="senha">

                                Cartão de Crédito:
                                <input type="text" class="form-control" id="seuCartao" placeholder="0000-0000-0000-0000" maxlength="16" name="cartao">

                                Bandeira do Cartão
                                <select id="suaBandeira" class="form-control" name="bandeira">
                                    <option selected></option>
                                    <option>Mastecard</option>
                                    <option>Visa</option>
                                    <option>American Expresss</option>
                                    <option>Elo</option>
                                    <option>Sodexo</option>
                                </select>

                                Código de Segurança
                                <input type="text" class="form-control" id="seuCS" placeholder="000" maxlength="3" name="codseguranca">

                                <button type="submit" class="btn btn-outline-dark btn-lg btn-block">Cadastrar-se</button>

                    </form>

Eco Aero - Viagens

A melhor agência de viagens sobre medidas para todos os tipos de pessoas e gostos.Viaje com a gente e venha conhecer novos lugares, culturas e compartilhar as melhores imagens e guardar as melhores lembranças.

Menu

                        Início
                        Sobre
                        Contato
                        Passagens Aéreas

Social

                        Facebook
                        Twitter
                        Instagram

O sucesso não é garantido, mas o fracasso é certo se você não estiver emocionalmente envolvido em seu trabalho.

                        Biz Stone Fundador do Twitter

Comment: Ja tem um modal ou quer que a gente inclua um ? você quer que o modal apareça antes ou após envio ? ou apos processamento?
Comment: Vc quer usar modal do Bootstrap?
Comment: https://www.w3schools.com/bootstrap4/bootstrap_modal.asp
Answer: Se o objetivo é apenas avisar que o campo tem erro, acho mais interessante trocar a cor dele e adicionar uma mensagem em baixo. Alerts/modais são muito chatos e em questão de usabilidade é informação desnecessária, mas se mesmo assim quer usar:

showModal = function(mensagem, callback){
  //adiciona texto passado no corpo do modal
  $('#myModal').find('.modal-body').text(mensagem);
  //adiciona callback no botão (vai chamar a função passada)
  $('#myModal').find('.modal-footer .btn').click(callback);
  //Exibe modal
  $('#myModal').modal('show')
}

function validacao () {
    if (document.cadastro.nome.value == "") {
        showModal ("Por favor, preencha o campo nome.", function(){
          document.cadastro.nome.focus ();
        });

        return false;
    }
    if (document.cadastro.sobrenome.value == "") {
        showModal ("Por favor, preencha o campo sobrenome.", function(){
          document.cadastro.sobrenome.focus ();
        });
        return false;
    }
    if (document.cadastro.endereco.value == "") {
        showModal ("Por favor, preencha o campo endereço.", function(){
          document.cadastro.endereco.focus ();
        });
        return false;
    }
    if (document.cadastro.datanascimento.value == "") {
        showModal ("Por favor, preencha o campo data de nascimento.", function(){
          document.cadastro.datanascimento.focus ();
        });
        return false;
    }
    if (document.cadastro.cidade.value == "") {
        showModal ("Por favor, preencha o campo cidade.", function(){
          document.cadastro.cidade.focus ();
        });
        return false;
    }
    if (document.cadastro.cep.value == "") {
        showModal ("Por favor, preencha o campo cep.", function(){
          document.cadastro.cep.focus ();
        });
        return false;
    }
    if (document.cadastro.estado.value == "") {
        showModal ("Por favor, preencha o campo estado.", function(){
          document.cadastro.estado.focus ();
        });
        return false;
    }
    if (document.cadastro.email.value == "") {
        showModal ("Por favor, preencha o campo email.", function(){
          document.cadastro.email.focus ();
        });
        return false;
    }
    if (document.cadastro.senha.value.length < 8) {
        showModal ("Por favor, preencha o campo senha com mais de 8 caracteres.", function(){
          document.cadastro.senha.focus ();
        });
        return false;
    }
    if (document.cadastro.cartao.value == "") {
        showModal ("Por favor, preencha o campo cartão de crédito.", function(){
          document.cadastro.cartao.focus ();
        });
        return false;
    }
    if (document.cadastro.bandeira.value == "") {
        showModal ("Por favor, preencha o campo bandeira.", function(){
          document.cadastro.bandeira.focus ();
        });
        return false;
    }
    if (document.cadastro.codseguranca.value == "") {
        showModal ("Por favor, preencha o campo código de segurança.", function(){
          document.cadastro.codseguranca.focus ();
        });
        return false;
    }
}
<!DOCTYPE html>

        <title>Eco Aero - Viagens</title>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

                Eco Aero - Viagens
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSite">

                    </button>

                            Início

                            Sobre

                            Contato

                            Passagens Aéreas

                            Entrar

                            Inscrever-se

Faça seu cadrastro

                    <form name="cadastro" action="#" method="post" onsubmit="return validacao()">

                                Nome:
                                <input type="text" class="form-control" id="seuNome" placeholder="Nome" name="nome">

                                Sobrenome:
                                <input type="text" class="form-control" id="seuSobrenome" placeholder="Sobrenome" name="sobrenome">

                                Endereço:
                                <input type="text" class="form-control" id="seuEndereço" placeholder="Av.Paris, 54, Bonsucesso" name="endereco">

                                Data de Nascimento:
                                <input type="text" class="form-control" id="suaData" placeholder="DD/MM/AAAA" maxlength="8" name="datanascimento">

                                Cidade:
                                <input type="text" class="form-control" id="suaCidade" placeholder="Cidade" name="cidade">

                                CEP:
                                <input type="text" class="form-control" id="seuCEP" placeholder="00000-000" maxlenght="8" name="cep">

                                Estado:
                                <select id="seuEstado" class="form-control" name="estado">
                                    <option selected></option>
                                    <option>SP</option>
                                    <option>RJ</option>
                                    <option>MG</option>
                                    <option>ES</option>
                                    <option>PR</option>
                                    <option>SC</option>
                                    <option>RS</option>
                                </select>

                                Email:
                                <input type="text" class="form-control" id="seuEmail" placeholder="email@example.com" name="email">

                                Senha:
                                <input type="password" class="form-control" id="suaSenha" placeholder="Senha" name="senha">

                                Cartão de Crédito:
                                <input type="text" class="form-control" id="seuCartao" placeholder="0000-0000-0000-0000" maxlength="16" name="cartao">

                                Bandeira do Cartão
                                <select id="suaBandeira" class="form-control" name="bandeira">
                                    <option selected></option>
                                    <option>Mastecard</option>
                                    <option>Visa</option>
                                    <option>American Expresss</option>
                                    <option>Elo</option>
                                    <option>Sodexo</option>
                                </select>

                                Código de Segurança
                                <input type="text" class="form-control" id="seuCS" placeholder="000" maxlength="3" name="codseguranca">

                                <button type="submit" class="btn btn-outline-dark btn-lg btn-block">Cadastrar-se</button>

                    </form>

Eco Aero - Viagens

A melhor agência de viagens sobre medidas para todos os tipos de pessoas e gostos.Viaje com a gente e venha conhecer novos lugares, culturas e compartilhar as melhores imagens e guardar as melhores lembranças.

Menu

                        Início
                        Sobre
                        Contato
                        Passagens Aéreas

Social

                        Facebook
                        Twitter
                        Instagram

O sucesso não é garantido, mas o fracasso é certo se você não estiver emocionalmente envolvido em seu trabalho.

                        Biz Stone Fundador do Twitter

titulo

          <button type="button" class="close" data-dismiss="modal">×</button>

         O texto vai ser inserido aqui

          <button type="button" class="btn btn-success" data-dismiss="modal">OK</button>

https://www.w3schools.com/bootstrap4/bootstrap_modal.asp
https://getbootstrap.com.br/docs/4.1/components/modal/

Feedback Modal em tela de cadastro


Using Drupal 7 Rules, how to react to a file upload and change a node field?

Question: I have spent hours/days trying to figure out how to accomplish this in Drupal 7 using the Rules module, so I will greatly appreciate any help anyone can provide.
What I am trying to do:
When a user re-uploads a file to a node, the node should rollback from an Approved status to Pending Review. This requires some kind of automated rule that checks for when a file was updated.
Here's what I have:

A node called Data_set with a File field called data_set_file.
Data_set nodes also have a field called Status (e.g., Pending Review, Approved).

My problem:
When a user uploads and overwrites an existing attachment in the data_set_file field, I want the node's Status to change back from Approved (if already) to Pending Review. I am able to use Rules to check for when a user uploads a new file, but there are no rules conditions to check for which file or node file has been updated.
What I tried:
I created a "NOT Data Comparison" condition between node-unchanged:field-dataset-file:file:fid and (Equals/Negate) node:field-dataset-file:file:fid However, when updating the file, it did not register a change to the fid field (because it keeps the same fid). I also tried the file size field with no effect as well. When I tried the file's timestamp, it appeared to work at first until I realized that the timestamp updates every time, no matter what, that a user saves a node, regardless of whether or not a file was re-uploaded.
I may be going about this the wrong way. Anyone know what's the easiest way to accomplish this? Thanks a million!
Answer: Workflow

This module allows you to create arbitrary Workflows, and assign them
  to Entities.
Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.
Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).

How we use workflow module
Creating a Workflow
Editorial workflow with Rules
Comment: read its documentation
Comment: On second thought, I don't think the answer above actually answered the original question. The workflow module still uses rules and I need to know how to implement a condition based on a file upload. Regardless of whether or not I use the workflow module, I still need to solve the problem of *how* do you react to a file upload? Is there a way? The documentation does not mention anything about that.
Answer: SOLUTION. After searching online, I found the answer to my own question. I'm sharing this for anyone else with a similar problem:
The first part is to implement file events. There is a patch to the Rules module that adds file events to react on (after saving new file, after updating existing file, and before saving file).
Discussion thread: https://www.drupal.org/node/826986
Patch: https://www.drupal.org/files/issues/file_events-826986-22.patch

Copy the patch file to the rules module directory.
From the command line, change to ("cd") the rules module directory.
Enter: patch -p1 < file_events-826986-22.patch
On the Rules page (admin/config/workflow/rules) click "Add event" and
select the file event to add.

The next part is creating a rule to react to the file upload.
A problem is that the timestamp on files are updated for every save, not just when it is first uploaded. So, I first opened my custom File Type (in my case "Dataset") and added a custom field using the Date Field Type called Time Uploaded (field_file_time_uploaded). I also created a new rule to update this field when the file is uploaded. Note that this rule gets called on the file insert event, which happens before a node is saved.
Below is what the rule export looks like for file uploads:
<code>{ "rules_save_file_time_uploaded" : {
    "LABEL" : "File - Save Time Uploaded",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "file_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "file" ], "type" : "file" } },
      { "entity_has_field" : { "entity" : [ "file" ], "field" : "field_file_time_uploaded" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "file:field-file-time-uploaded" ],
          "value" : [ "site:current-date" ]
        }
      },
      { "drupal_message" : { "message" : "The [file:type] file was uploaded." } }
    ]
  }
}
</code>
This Time Uploaded field can then be used by other rules, like when saving a node, to see if the file was updated using a data comparison with the site's current datetime.


Kernels and the Sign Function

Question: I'm trying to define the kernel of the sign function ($sgn:S_n \to \left\{-1,+1\right\}$) for $S_4$.
Is the identity element of the range of the sign function +1?
Kind of confused.
Answer: Yes, {$-1,1$} is a (two-element) multiplicative group with identity element $1$,
so anything that gets mapped to $1$ is in the kernel.

Kernels and the Sign Function


Non-separability of normed spaces

Question: I would like some hints to decide when a normed space is separable or not. I really understood the definition and the classic examples of separable spaces but when I go to show that a space is non-separable, just I get lost.
Now, I'm trying to show that:

Let be $C([a,b])=\{f:[a,b]\to \Bbb{R} : f \text{ is limited}\}$, with $a<b$, and consider $C([a,b])$ with the metric
  $$d(f,g)=\sup_{x\in [a,b]}|f(x)-g(x)|.$$
  Show that $(C([a,b]),d)$ is non-separable.

I appreciate any help, thanks.
Comment: The set of functions which are zero except at *one* point, where the value is 1, is too big and its elements are too far apart for the space to be separable.
Answer: The idea is to mimic Cantor.
Suppose there exists a countable dense subset, say $\{f_n\}_{n \in \mathbb{N}}$.
Consider the sequence $x_n:=b-\frac{b-a}{n}$. Define the function $g(x)$ as follows:
Define $g(x_n)=a_n$, where $a_n=0$ if $f_n(x_n)>2$ or $f_n(x_n) <-2$, $a_n=4$ if $-2 \leq f_n(x_n) \leq 2$, and $g(x)=0$ in every other $x$. $g$ is clearly bounded. Note now that $d(g,f_n) \geq 1$ for every $f_n$, which contracits density of $\{f_n\}$.
OBS: Calling that space $C([a,b])$ can be misleading, since it is sometimes used for the continuous functions on $[a,b]$, which is a separable space (polynomials being dense).
Comment: Hi @AloizioMacedo, thank you for the advice and the help!
Answer: One of important theorems about separability of a normed space is:
Let  $X$ be normed topological vector space. If $X'$, the dual space of $X$,
be separable then $X$ is itself separable. You can use this for separability of normed spaces. It should be noted that the converse in not true.

Non-separability of normed spaces


Do growls interact with the harmony?

Question: Is the pitch of growls measurable or is it undefined (for example: bass drum and hi hat are both unpitched but you can tell the relative pitch)?
Both me and my friend have good ears and have been unable to tell the pitch that our vocalist is singing when growling, and I haven't found this topic raised anywhere on the internet.
EDIT: Reading a bit on wikipedia about unpitched percussion, I found the term 'inharmonicity' - in simple words it means that the sound produced doesn't interact with the harmony. I would like to know whether growls are harmonic or inharmonic, as it is possible to match pitch with growls but also with drums.
EDIT2: Another bit of information is that our vocalist sings in tune most of the time, with some chance of missing a few notes (when singing clean), but when he growls we can't tell wether he's in tune or not.
EDIT 3: Changed title from "Is growling pitched or unpitched?" to "Do growls interact with the harmony?", meaning, instead of if they have a fundamental pitch (Yes), if they interact with the harmony like clean vocals or don't interact with the harmony like drums (or somewhere in between like pizzicato which is both percussive and melodic).
Comment: What about James Hetfield's vocals? Definitely pitched, but I'm not sure if that counts as growling. My first thought is that some vocalists are more pitched than others.
Comment: James Hetfield doesn't growl, growling is the stuff you hear in extreme metal genres, for example gutturals or inhales. Could you explain what you mean by some vocalists being more pitched than others? Isn't it either you're pitched or unpitched?
Answer: Inharmonicity actually doesn't mean something doesn't interact with the harmony. It's only a measure for how strongly the sound deviates from a periodic signal (or equivalently, one with only integer-multiple sinuoid partials). Such periodic-signal sounds are particularly well-suited for interacting with harmony, but even very inharmonic sounds can, to some degree, do so (Gamelan music is pretty much entirely based on this). And vice versa, sounds with low inharmonicity can be used in a way that does not interact with the harmony (e.g. "siren" sound effects).
So, we really have two questions here:
1. Is growling inharmonic?
Well, there are different degrees of "growliness", but all growling certainly has some inharmonicity, that's what distinguishes it from clean singing. But it's also not completely inharmonic (like e.g. a china cymbal). To quantify this, look at a Fourier spectrum of a recording. For a clean voice, this will have well-separated peaks and nothing much else, roughly like†:

Source: https://www.clear.rice.edu/elec431/projects95/psquared/psquared.html
For a growled part there will be a much higher "noise floor" of inharmonicity, but I'm pretty sure you would still see some reasonably strong peaks, and they would probably still be spaced in integer ratio. Estimate sketch:

2. Does growling interact with harmony?
I think it can, in principle, but I don't really have evidence. I'd definitely say most metal singers don't use growling in a way that would interact with the harmony, and I don't know if you can even control the pitched components of growling in a way that would allow this. But if you sampled snippets of growled singing and triggered it with a keyboard to play, say, a Baroque cantata, I suspect it would sound more harmonious then you'd think (albeit completely weird).

†Spectrum analysers in music production are usually set up with logarithmic axes, which is more useful for mixing etc. purposes. But it means the spectrum will look inharmonic even if it's not: – the integer frequencies aren't equally-spaced anymore, and the noise floor appears much higher. If you try this out, be sure to set the spectrum to linear scale to properly see what's inharmonic and what's not.
Comment: The graphs helped me understand what I'm hearing - a note with a lot of "noise", similar to amp feedback in a way. The vocalist was able to sing different melodies using growl, and I have read an academic article about growl where it says that it's easier to control pitch when growling than when singing clean, because of some reason that I can't remember. I'm guessing that the reason it isn't used too melodically is because of the noise factor, but this could be an incredible experiment.
Answer: It's pitched because there is a core tone to a growl. Listen to what you hear the most of. Put the growl on a loop if possible. Sometimes if I'm really stumped on what a sound is, I'll take my tuner app that's on my phone and put it up to my speaker and I'll play the sound over and over until it picks something up.
When you think you've found the core tone, try to vocalize it and sing with the growl. There should be harmony. You could perhaps even try growling yourself and see if you can imitate the singer.
Comment: Drums have pitches too, but they are inharmonic. You can find the pitch of a drum or tune drums to pitches, but they do not interact with the harmony.
Comment: I doubt it has anything to do with drums being short sounds, as there are melodic instruments that create short sounds and are still melodic, but I think that the noise element is the answer to why they don't interact with the harmony. This is just a guess - but maybe growling is singing notes with loads of unmusical noise which causes it to be inharmonic.

Do growls interact with the harmony?


How to get request body to be populated

Question: I am doing a get response and in my api/cmsview it is not getting the object that my Axios is passing.
class CmsView extends Component {
  constructor(props) {
    super(props)

    this.state = {
        cmsObj: [],
        packageLid : props.location.state
    }
    var packageLid = this.props.location.state.packageLid
    console.log(packageLid.PACKAGE_LID) //this gets populated with data
    Axios.get('/api/cmsview', {packageLid})
    .then((response) => {
                this.setState({ cmsObj: response.data })
            })
   }
}

My packageLid does get populated with data, but when I do the Axios get:
in my cmsview.js
router.get('/', (req, res, next) => {
    console.log(req.body.packageLid.PACKAGE_LID)
}

my req.body.packageLid does not get populated. Any idea why? It just outputs "undefined"
Comment: I suggest that you edit the title. Your issue is in request.body not being populated on the server side.
Comment: Thanks. It will be much easier to understand for new followers to the thread. As for the issue, I do agree with Anil that you might be listening on the wrong route. What happens if you update to `router.get('/api/cmsview', (req, res, next) ...` ?
Comment: the router.get just never gets called if I update it to that @VlatkoVlahek
Answer: You need to put axios call in componentDidMount method.
componentDidMount() {
var packageLid = this.props.location.state.packageLid
console.log(packageLid.PACKAGE_LID) //this gets populated with data
Axios.get('/api/cmsview', {packageLid})
.then((response) => {
            this.setState({ cmsObj: response.data })
        })
  }
 }

Comment: Still getting undefined with this as well. Perhaps I cannot call req.body.packageLid.PACKAGE_LID ?
Comment: You are calling /api/cmsview from react and in api you have / . Fix it
Comment: the / gets called and /api/cmsview does not though. The problem is the object I am sending it, never gets populated

How to get request body to be populated


Is there a Kibana equivalent for Vespa Search?

Question: I want to be able to quickly make index, modify schema, feed test data, delete data, copy/clone index, run queries on the index from the web interface - just like I can do with Elasticsearch. Is there such tooling available? If not is it in plans?
I tried Vespa CLI - while it's handy, it is not feature complete.
Answer: https://github.com/vespa-engine/vespa/tree/master/client/js/app has a GUI for the query API. https://cloud.vespa.ai/en/cloning-applications-and-data covers cloning.
Schema development is easy using the https://docs.vespa.ai/en/schemas.html#intellij-plugin - as Vespa is built for safe deployments, a "deploy" must be done to activate schema changes, this is a simple and fail-safe workflow (and incompatible changes will emit a warning a stop the deployment)
Comment: We are working on that, not ready yet (must handle the security credentials), track blog.vespa.ai for progress
Comment: Thanks! Does Query Builder / GUI for the query API - come predeployed for Vespa Cloud users? Or if installed locally, can it be used against the Vespa cloud application instance?


How algebra differs in complex plane and cartesian plane?

Question: I noticed the difference first when I tried to convert the complex form of the equation of circle in cartesian form, this is how I approached-
$$\tag{1}|z-a|=r \qquad (\text{here},z= x+iy)  $$
I thought, $iy$ corresponds to $Y$-axis in the Cartesian plane,
and, my converted equation was this-
$$\tag{2}
                        |x+y-a|=r
$$
this was simple, then I went to proof
1)
$$
                                         |z-a|=r
$$
$$
                                        (z-a)^2= r^2
$$
$$
                                       z^2-2za+a^2=r^2
$$
Another form of it is- zz¯−z0¯z−z0z¯+(|z0|2−R2)=0, but I did not approach to that,
Now the prof of-

$$
                              |x+y|=r
$$
$$
                            x^2+2xy+y^2=r^2
$$
this looks very similar to 1. But, it does not give a circle, when I plot it. The 2xy seems to get in my way of circle.
another thing that I learned is-
iy.i= -y
it is a 90-degree tilt of y
but in the cartesian plane, you have to multiply -1.
<code>                         y.(-1)=y
</code>
I lack information in this field, I want to know how the cartesian plane is different from the complex plane? what distinguishes them?
how to make a connection with the complex geometry and cartesian geometry?
Comment: You have been around for months. Haven't you yet noticed that you are supposed to use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) around here?
Comment: (2) should be $|x+iy-a|=r$. And for complex numbers, $|z-a|^2\ne(z-a)^2$. And that's where I stopped reading.
Comment: thank you very much, i did not know that, there I saw another proof which is very different-
|z−a|2  =r2

   (z−a)(z'−a')=r2

       zz'−az−a'z'+aa'=r2,
and I think it can not be compared with the cartesian equation,
Comment: I don't know what you mean, and you are not helping me by insisting on writing r2 when you could just as easily and far more correctly write $r^2$. Learn MathJax, please, the sooner the better. Also, until you correct the errors I pointed out, I don't intend to look any further into your work.
Comment: See https://studymath.github.io/assets/docs/real_complex_bash.pdf
Answer: One of the differences is $|z|^2 \ne z^2$ for most complex numbers $z$. Take $z = i$ as an example: $$z^2 = i^2 = -1 \ne 1 = 1^2 = |z|^2.$$
I think that you misunderstood the concept of an absolute value for complex numbers which led to several mistakes in your proof. One possible definition goes as follows: for any complex number $z = x + iy$ $$|z| = \sqrt{x^2 + y^2}.$$ The absolute value of a complex number is also sometimes called its norm to highlight the difference from real numbers.
Using this definition the proof becomes simple: first, shift $a$ to $0$ so that we don't have to worry about it, then (for $r \ge 0$ ofc) $$|z| = r \iff \sqrt{x^2 + y^2} = r \iff x^2 + y^2 = r^2,$$ which is exactly the equation of a circle in a real plane.
Comment: is there any form of equation of circle in real number, using modulus?
Comment: @ALvees afaik, the modulus is only useful for the equation of a circle in a _complex_ plane. Wikipedia has an [extensive list](https://en.wikipedia.org/wiki/Circle#Equations) of circle equations in different coordinates, you can refer to it


What statistical test is appropriate for a pretest/posttest experimental/control group study?

Question: I thought this would be a relatively straightforward question, but I'm having difficulty finding a decisive answer. Let's say I'm planning to run a study to test the effectiveness of a new type of pain medicine with 100 participants, who will be randomly divided into an experimental group and a placebo group with 50 participants each. I will measure the 50 individuals in each group on a Likert-type pain scale at the beginning of the study (pretest) and again after taking either the medication or a placebo for a month (posttest). What would be the most appropriate statistical test to use to test if there is a significant difference between the impact of the medication vs. the placebo for the two groups (i.e., if the medication was effective at reducing pain)?
Many thanks!
Answer: I'll say that, if the hypothesis is that the drug is more effective than the placebo, for instance, that it'll reduce the score in the Likert scale significantly more.
You could first transform the Pre and Post medication score, into a single score which would be the difference between the two. Thus a significant difference between the two groups, with this score, would mean a significant improvement of the feeling of pain.
So let's say that the scale is from 1 to 10, with 10 meaning having a lot of pain and 1 having none. You would like to have a significant reduction of the pain, thereby, a negative difference when computing the Post-test score minus the Pre-test score.
Plus you would like that difference to be inferior compared to the placebo (i.e. that the people rate their pain as less important with medication than with placebo).
So with this in mind, a one-tailed independent t-test, should do the job.
If the assumptions of the t-test aren't met, you could still use a Mann-Whitney U, or apply some transform to the data.
Answer: One good idea could be to look up recent work for Phase 3 registration trials (which get a lot of scrutiny by regulators such as the US FDA and get planned with a lot of attention to detail by the pharmaceutical companies running the studies) that used the particular endpoint (or very similar ones).
A very simple model could be a linear regression model for the numeric post-treatment score with treatment as a factor in the model and the numeric baseline score as a covariate. The biggest difficulties with this could be:

Some assumptions for linear models might be so badly violated that it matters (many small deviations don't really matter). E.g. the regression residuals might be very non-normal or the errors might be larger in the middle of the Likert scale than at the ends etc. Ideally, one knows from previous studies whether a linear regression approach is okay (it's always a bit problematic to test assumptions in the study one is analyzing) and it might even be that people have done simulation studies with realistic settings for the exact outcome scale you are interested in.
Even if the model fits quite well, what do you do about those that do not have a score at the end. This is a huge topic in itself and almost independent of the choice of model (see e.g. this guidance). Options include that we assume people are similar to other people with similar covariate values (including that the treatment continued for them even though we did not get to see the final outcome - or perhaps we want to know what would have hypothetically happened if they had finished their treatment) and we could then e.g. do multiple imputation (i.e. you impute, say, 100 datasets and then analyze each, then you aggregate the results - this is nicely handled by standard software). If it's that those that stop treatment would then be like similar people in the control group, then approaches like "jump-to-reference" could be an option.

An alternative is to model the actual ordinal outcome. Frank Harrell has recently talked a lot about this (e.g. here) and has cited some papers on this (such as this one and there's also this). The main advantage is that it attempts to model the actual data generating process and allows adjustment for the baseline score. You can have a look around the data methods forum that Frank Harrell champions and the discussions tagged as "ordinal" on there. That might be a really good place to post a question on how to implement such an ordinal analysis in case you do not find all your questions answered, yet. Point (2) regarding the simple linear model of course still does not go away and needs to be dealt with.
Further alternatives that are less popular include

Rank-based methods, but in their basic version they do not make it easy to adjust for the pre-test score. Forming the difference of pre- vs. post is also not that satisfactory, because a change of +2 on a 10 points scale is possible from a baseline of 5, but not from a baseline of 9 (and even when it's possible may mean very different things), an ordinal model can reflect that a lot better.
Simple dichotomization (aka "responder analysis") of the outcome (e.g. >5 vs. <=5, or improved by 2 points or achieved score of 9 or 10 etc.), where one could group those that don't finish treatment with those that did not achieve a good outcome (composite estimand strategy). Then a logistic regression with the baseline socre as a covariate could be used. However, this is usually a terrible idea, because you throw away a lot of information by reducing all information to a yes vs. no.
Comment: Great answer. Quick question that comes from this - when you use a proportional odds model for an ordinal outcome do you get the same efficiency gains from baseline adjustment that you get in linear regression? Presumably no?
Comment: I don't know for sure (simulate & try it out...), but my guess is that: 1) because the scale is ordinal, there is just less information in the baseline than for a truly continuous baseline (i.e. this does not change whether the analysis model is a linear regression or an ordinal model, it's just about what data you have) 2) how much adjustment helps depends on how well the specified model approximates the drug data generating process - e.g. if you manage to truly write down the "true" DGP with an ordinal model conditional on the baseline, a linear model should not in some sense do better.


Dominant finite morphism and finite algebraic extension

Question: I don't know how to prove the following proposition.

If two varieties $X$ and $Y$ are irreducible,  a morphism $\phi: X \rightarrow Y$ is dominant and finite, then $K(X)$ is a finite algebraic extension of $\phi^*K(Y)$.

Here, $\phi^*: K[Y] \rightarrow K[X]$ sends a function $f \in K[Y]$ to $f \circ \phi \in K[X]$. A morphism $\phi$ of irreducible varieties is called dominant if $\phi(X)$ is dense in $Y$. It is called finite if $K[X]$ is an integral over $\phi^*K[Y]$.
Is the following more general statement true?

$R_1$ is a domain, which is integral over its subdomain $R_2$. $F_1$ and $F_2$ are respective fields of fractions. Then $F_1/F_2$ is a finite algebraic extension.

This extension must be algebraic. But I think the finiteness is not so obvious.
Comment: Note that $R_2 \otimes_{R_1} F_1$ is a field (it's integral over the field $F_1$ because localization preserves integrality). This is thus $F_2$. Since this is finite over $F_1$ as base-change preserves finiteness, QED.
Comment: (As Qiaochu observes, the more general statement is false: the above comment proves it only when $R_2/R_1$ is finite. Otherwise, you could take for instance $\mathbb{Z}$ and its integral closure in $\overline{\mathbb{Q}}$.)
Comment: @Akhil Mathew: Thank you very much!
Answer: That isn't the correct definition of finite; you need that $K[X]$ is a finitely-generated module over $K[Y]$ (which implies, but is strictly stronger than, integral), and that gives you the correct general statement. The general statement as you've written it is false; just take $R_1$ to be the algebraic integers and $R_2$ to be $\mathbb{Z}$.
Comment: @ShinyaSakai: For example, the integral closure of $k[y]$ in its fraction field is integral over $k[y]$ but not a finitely-generated module.
Comment: Thank you very much! Now I know what's wrong with the too general statement. The definiton for finiteness I have written is applicable for affine varieties, I think. But I still don't understand why "$K[X]$ is a finitely-generated module over $K[Y]$" is stronger than "$K[X]$ is integral over $K[Y]$"...
Comment: Thank you very much. I think I misunderstood your meaning. However, in page 31 of James Humphreys' Algebraic Linear Algebra (GTM21), I see "Let $\phi: X \rightarrow Y$ be a morphism of affine varieties. If $K[Y]$ is integral over the subring $\phi^*K[Y]$, we call $\phi$ finite. " I don't know if these two definitions coincide under the condition of affine varieties.
Comment: @ShinyaSakai: in any case that is not the definition of finite used in scheme theory (see for example http://en.wikipedia.org/wiki/Finite_morphism ). Perhaps the two are equivalent for affine varieties, but I can't think of a proof off the top of my head.
Comment: Thank you very much. I think I should be more careful for the original definitions from now on.


How do I read these sets of notes?

Question: I came across this sheet music pdf in the link of a YouTube video and I can't understand what these notes are. Can someone explain how one reads and plays the notes ( on a guitar) in the red box and blue box?
Edit: what are the brackets surrounding the circled head of 8th note?
Answer: In the red box, two independent voices are notated, but on guitar you may play both simultaneously in harmony.
The blue box is also two independent voices but both voices are on the same note. On guitar you may just consider them single notes. Perfect unisons are possible on guitar but they are usually a stretch when out of context.
The bracketed notes are a ghosting of the first phoneme /th/ in they. The notation indicated its tone is indeterminately lower when compared with the next, standard note.
Comment: So for the notes in the red box, I just play the Gand D notes together? And the blue box is just playing the F note?
Comment: I would add one thing to this.  Sometimes in classical guitar pieces a unison is indicated for a note that matches an open string.  In this case you can play the fretted note and the open string at the same time.  Clearly in this case that is not possible.  This is not a guitar piece, this is vocals on harmony.
Comment: Yes that is how I would go about playing those.

How do I read these sets of notes?


undefined reference to function called 'full_adder(BIT A, BIT B, BIT Ci, BIT *Co)'

Question: I am a CS student learning how to program in C. I have 3 files and a Makefile. I have

logic.c logic.h main.c

the top of logic.c is:
 #include "logic.h"
//use this function in 4 bit adder
//BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co);
int adder(int O1, int O2,  BIT carryIn, BIT *carryOut){
printf("in adder");
return 0x0;
}

BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co){
BIT S = FALSE;
    //implementation of if else's based on Truth Table

    if((A==FALSE)&&(B==FALSE)&&(Ci==FALSE)){
        S=FALSE;
        *Co = FALSE;
    }

    return S;
}

the top of main.c is:
 #include "logic.h"
BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co);

in main.c I have my main function, at the bottom of main function I have :
 assert((full_adder(FALSE,FALSE,FALSE,&Co)==FALSE) && (Co==FALSE));
        adder(FALSE,FALSE,FALSE,&Co2);
    return 0;

I am getting the error:
 main.o: In function 'main': main.c:158: undefined referenceto 'full_adder'

collect2: ld returned 1 exit status

make: *** [pa3] Error 1

./bscript: line 3: pa3: command not found

This is homework, but I have spent a good deal of time on this problem and am looking for some help. I have the correct return type for adder, full_adder, and I declare the function in the top of both logic.c and main.c.
The questions that did not answer my question were:

Undefined Reference to a function
"Undefined reference to function" error

Any help is appreciated.
EDIT:
logic.c is getting compiled and it does create a logic.o file.
EDIT: my prof says that I cannot edit logic.h
EDIT: makefile:
# Makefile template for CS 270 (specialized for PA3)

# List of files
C_SRCS      = main.c logic.c
C_OBJS      = main.o logic.o
C_HEADERS   = logic.h
OBJS        = ${C_OBJS}
EXE         = pa3

# Compiler and loader commands and flags
GCC         = gcc
GCC_FLAGS   = -g -std=c99 -Wall -O0 -c
LD_FLAGS    = -g -std=c99 -Wall -O0
# Target is the executable
pa3 : $(OBJS)
    @echo "Linking all object modules ..."
    $(GCC) $(LD_FLAGS) $(OBJS) -o $(EXE)
    @echo ""
# Recompile C objects if headers change
${C_OBJS}:      ${C_HEADERS}
# Compile .c files to .o files
.c.o:
    @echo "Compiling each C source file separately ..."
    $(GCC) $(GCC_FLAGS) $<
    @echo ""

# Clean up the directory
clean:
    @echo "Cleaning up project directory ..."
    rm -f *.o $(EXE) core a.out
    @echo ""

EDIT: I compile my code with the script:
#!/usr/bin/sh
make
pa3

Comment: I'm assuming they'll all want you to post the makefile
Comment: Are you actually implementing `full_adder`?
Comment: please show how you compile your code? show your makefile?
Comment: @H2CO3 I think you mean 'am I making a logical representation of a full adder?' Yes. Many not gates and and gates and ultimately I will be making a 4 bit adder.
Comment: At least my answer makes no changes to the `logic.h` file. I just included a trimmed down version of it to show where things should go, nothing more. Have you tried the suggested change to `logic.c` and `main.c`?
Answer: First of all, separate definitions from declarations:
logic.h:
#ifndef _LOGIC_H_
#define _LOGIC_H_

/* Define BIT as before */

int adder(int O1, int O2,  BIT carryIn, BIT *carryOut);
BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co);

#endif

logic.c:
#include <stdio.h>
#include "logic.h"

int adder(int O1, int O2,  BIT carryIn, BIT *carryOut){
  printf("in adder");
  return 0x0;
}

BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co){
  BIT S = FALSE;
  //implementation of if else's based on Truth Table
  if((A==FALSE)&&(B==FALSE)&&(Ci==FALSE)){
    S=FALSE;
    *Co = FALSE;
  }

  return S;
}

main.c:
#include "logic.h"

int main(int argc, char* argv[]) {
  /* Do your stuff */
  return 0;
}

Now things are where they should be and your logic.h supplies the needed information to the compiler.
Your makefile should not need any fancy stuff with only these three files.
This needs to be done via the makefile:
gcc -c -o main.o main.c
gcc -c -o logic.o logic.c
gcc -o main main.o logic.o

(The logical problems that you have in your full_adder are left for your to solve...)
Answer: I have seen linkers not-find/find functions depending on the order of the object files.
In your makefile you may want to try changing the order:
C_OBJS      = logic.o main.o

I declare the function in the top of both logic.c and main.c.

The function prototype
BIT full_adder(BIT A, BIT B, BIT Ci, BIT *Co);

should only occur once, in logic.h.
The error you are getting is from the linker.
You may want to just try and compile/link it outside the Makefile:
gcc -c logic.c
gcc -o main main.c logic.o


Prove: $\int_{0}^{1} \frac{e^x}{x^{2}+1}dx\le e -1 $

Question: Prove: $\int_{0}^{1} \frac{e^x}{x^{2}+1}dx\le e -1 $
this isn't really a computable integral, But the only idea I have in mind is that:
derivative from $x=0$ to $x=1$ of:  $\frac{d}{dx}\left({e^x}-{x})\right) = e -1 $, but I would still have to compute $\frac{e^x}{x^{2}+1}$,
because I'm not sure the derivatives will be sufficient in order to prove the inequality.
Comment: $\int_{0}^{1} \frac{e^x}{x^{2}+1}dx < \int_0^1 e^x dx =  e -1$
Comment: Use $x^2+1\geq 1$
Answer: Because of $\frac{1}{x^2+1}\leq 1$ for all $x$, we have $$\int_0^1 \frac{e^x}{x^2+1}dx\leq \int_0^1 e^x dx= e-1.$$
The inequality $\frac{1}{x^2+1}\leq 1$ follows from $x^2+1\geq 1$. This inequality is not very sharp though: The integrals equals, roughly, 1.271 whereas the upper bound is $e-1=1.718$.
Answer: A better bound can be achieved by applying the Integral Chebyshev inequality to $f(x) = \frac{1}{1+x^2}$ and $g(x) = e^{x}$. Since $f$ and $g$ are of opposite monotonicity on $[0, 1]$,
$$
 \int_0^1 \frac{e^x}{1+x^2} \, dx \le \int_0^1 \frac{1}{1+x^2} \, dx \cdot \int_0^1 e^x \, dx = \frac{\pi}{4} (e-1) \approx 1.3495 \, .
$$
Answer: The most direct approach to this question is Triangle Inequality for Integrals. Below I provided a helpful link.
https://proofwiki.org/wiki/Triangle_Inequality_for_Integrals
Let us start by applying the inequality: $$\Biggl \lvert \int_{0}^{1} \frac{e^x}{x^2+1}dx\Biggl\rvert \space \leq \space \int_{0}^{1} \Biggl| \frac{e^x}{x^2+1}\Biggl|dx$$ Since we know that the function $\frac{e^x}{x^2+1}$ is positive-valued on the real line, we have: $$\int_{0}^{1} \Biggl| \frac{e^x}{x^2+1}\Biggl|dx = \int_{0}^{1} \frac{e^x}{x^2+1}dx$$ By the help of a simple algebraic fact $\frac{1}{1+x^2} \leq 1 \space \forall \space x \in \Bbb R$, it is easy to deduce that: $$\int_{0}^{1} \frac{e^x}{x^2+1}dx \space  \leq \space \int_{0}^{1} e^x dx=[e^x]^{1}_{0}=e-1 $$
In conclusion: $$\bbox[yellow] {\int_{0}^{1} \frac{e^x}{x^2+1} dx \space \leq \space e-1 }$$
Comment: What is the purpose of applying the triangle inequality if the integrand is positive?


Any way to disable poi using the jquery-ui-map plugin?

Question: I'm trying to disable poi markers in a mobile page i'am working on.  It looks like the gmap-constructor should accept the style option.  But I can't get it to work so far.
 $('#map_canvas').gmap({styles:[{featureType:"poi",elementType:"labels",stylers:[{visibility:"off"}]}]});

Any ideas?  I know this can be done without using the plugin.  I was just hoping to get it working without going that route.
Answer: try this
$('#map_canvas').gmap({'center' : mapdata.origin,
    'mapTypeControl' : true,
    'navigationControl' : true,
    'navigationControlOptions' : {'position':google.maps.ControlPosition.LEFT_TOP},
    'styles':[{'featureType': "poi.business",
        'elementType': "labels",
        'stylers': [
          { 'visibility': "off" }]}]

mapdata.origin has the lat and long.


Close process using a file on windows

Question: I would want to close all the programs which are using a file on Windows. I've an example of what I want on Linux :
<code>pids=`lsof | grep $fic | grep -v "grep" | tr -d '\t' | cut -d" " -f2`
</code>
Thanks!
Comment: Just a side-note, the above command can be simplified: `lsof FILENAME | awk 'NR>1{print $2}'`
Comment: See OpenFiles command. NB Windows doesn't maintain this info as standard (except network opened files). You have to turn it on using openfiles command and reboot. Look at list or csv format options for full path of file.
Answer: Please change tag from bash to batch
and Install Handle
This will solve the purpose

Close process using a file on windows


Equivalence relation on $\mathbb C[x]$ and $\operatorname{card}\left(\mathbb C[x]_{/ \sim}\right)$

Question:
An equivalence relation $\sim$ on $\mathbb C[x]$ is defined in the
  following way:
Two polynomials $p,q\in\mathbb C[x]$ are equivalent if their
  zero-points sets are equal.
Prove $\sim$ is an equivalence relation and find
  $\operatorname{card}\left(\mathbb C[x]_{/ \sim}\right)$

My attempt:
Let $S:\{\alpha_1,\ldots,\alpha_k:\alpha_i\in\mathbb C\}$ be zero-points set of two polynomials $p,q\in\mathbb C[x]$. Then:
$$(x-\alpha_i)\mid p\;\land\;\;(x-\alpha_i)\mid q\;\;\forall i\in\{1,\ldots,k\}$$
It can be proven very easily the relation is reflexive, symmetric & transitive, so I didn't have any problems with that part.
I'm concerned about my statement I didn't know how to prove concisely:
$$\operatorname{card}\left(\mathbb C[x]_{/ \sim}\right)=\operatorname{card}(\mathbb C)=\operatorname{card}(\mathbb R^2)=\operatorname{card}(\mathbb R)=2^{\aleph_0}=\mathfrak c$$
Is that true, and if so, how can I prove it?
This task appeared on our elementary math 1 exam, so I haven't been introduced to tools regarding measure that I saw in most of the posts. Thank you in advance!
Answer: For any set $X$, let $X^{<\omega}$ denote the set of finite subsets of $X$. It can be shown that if $X$ is infinite, then $X$ and $X^{<\omega}$ have the same cardinality.
You can get a bijection from $\Bbb{C}[x]/{\sim}$, the set of equivalence classes of $\sim$, to $\Bbb{C}^{<\omega}$, the set of finite subsets of $\Bbb{C}$. Just map each finite subset $\{\alpha_1,\alpha_2,\ldots,\alpha_n\}\subseteq\Bbb{C}$ to the equivalence class of $\prod_{i=1}^n(x-\alpha_i)$. Note that the empty set gets mapped to the equivalence class of the constant polynomial $1$.
Hence we have that
$$card(\Bbb{C}[x]/{\sim})=card(\Bbb{C}^{<\omega})=card(\Bbb{C})=2^{\aleph_0}.$$


How to wrap a whole view in a tpl file?

Question: I created a view and I'd like to wrap it with a link in a template file. I've never worked with custom template files for views, so I've no idea where to start.
How can I do this?
Answer: In views under advanced->theme you can see template naming conventions you can use. Copy the views-view.tpl.php to your themes templates folder and rename it to one of the suggested names in views->advanced->theme. Clear your cache and the template will be used. Now you can alter the output of the whole view.
You can also do this for the fields as a whole, or a specific field.
Mind that views has so much power through UI that you seldom need to go through themefiles.
Wrapping the views field(s) in a link can be done also by rewriting field output.
Comment: I dont think cache clear works for views. In views->advanced->theme you have to rescan templates. Only then it works, this is message:
_Important! When adding, removing, or renaming template files, it is necessary to make Drupal aware of the changes by making it rescan the files on your system. By clicking this button you clear Drupal's theme registry and thereby trigger this rescanning process. The highlighted templates above will then reflect the new state of your system._
Comment: @MantasKaranauskas: Clearing caches worked for me, but thanks for your comment. :)
Comment: Clearing cache clears also the themeregistry.

How to wrap a whole view in a tpl file?


Autenticação / Permissões com MEAN Stack

Question: Estou estudando o MEAN stack, estou gostando bastante, e estou desenvolvendo aplicações simples, porém, não consegui achar algo que realmente me ajudaria a entender melhor sobre a autenticação e permissões utilizando o MEAN, e como ficaria meu banco.
Agradeceria muito se alguém conseguisse me ajudar, um link de um source demo, um material que não fosse de difícil compreensão ajudaria muito.
Agradeço a todos desde já.
Comment: Veja se pode ajudar: http://www.ibm.com/developerworks/br/library/wa-mean5/
Comment: Você está usando algum framework?
Se tiver usando mean.js, na pasta serve de cada módulo você controla boa parte das permissões em route e policy.
No client mas pasta route tem a opção também.
Answer: Lucas, o MEAN utiliza o Mongo, Node e Angular. Além disso você pode fazer a autenticação de várias formas. Com o Angular você poderá aplicar um Interceptador e após validar as informações em seu servidor através de uma requisição get, se retornar 401 você poderá encaminhar o usuário para uma página de "Não autorizado".
O paradigma de persistência no MongoDb é um pouco diferente do que estamos acostumados no banco de dados relacional.
Talvez esses dois links te ajudem:
Autenticação Passport no NodeJs
Interceptadores no angular js
Qualquer coisa é só falar.