How do I add attributes to CSS in theme.info?

Question: I'm try to add a stylesheet switcher.  This requires the following CSS files to be included on the site.
<link rel="stylesheet" type="text/css" href="styles1.css" title="styles1" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles2.css" title="styles2" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles3.css" title="styles3" media="screen" />

theme.info reference some CSS files. How can I a rel and title attributes?
stylesheets[all][] = common/css/small.css
stylesheets[all][] = common/css/medium.css
stylesheets[all][] = common/css/large.css

Answer: Since Drupal will use CSS aggregation (and doesn't have support for adding extra attributes via the info file or drupal_add_css), you will have to print out the style sheets yourself. This can be done with theme functions or by creating the markup in the html.tpl.php


What is the reason for pitch inflation?

Question: There's this phenomenon among instrumentalists to constantly raise the pitch of the concert A. This generally occurs among string players, since the range of tunings for woodwinds, for example, is often severely limited or nonexistent. Wikipedia (or rather, one of its editors) claims the reason for this is:

This "pitch inflation" seemed largely a product of instrumentalists' competing with each other, each attempting to produce a brighter, more "brilliant", sound than that of their rivals. (In string instruments, this is not all acoustic illusion: when tuned up, they actually sound objectively brighter because the higher string tension results in larger amplitudes for the harmonics.) This tendency was also prevalent with wind instrument manufacturers, who crafted their instruments to play generally at a higher pitch than those made by the same craftsmen years earlier.

Out of curiosity, I started browsing through the edit history; the above quote has existed in (almost) its current form on another page since 2006, and the information can be dated back to September 2002. The rationale seems to make sense, but it's very tenuous to make that claim without backing it up, especially since it was made by some editor 7 years ago.
I tried to find some actual research in this field, but my searches at scholar.google.com were fruitless, as were searches of various online databases.
So, basically, is it true that pitch inflation can be attributed to the sound sounding more "brilliant" at higher frequencies? And if so, what makes it sound that way?
Comment: I suspect that _History of Performing Pitch: The Story of "A"_ by Bruce Haynes discusses this.
Comment: There seems to exist a counter-movement, mainly supported by singers, but also instrumentalists arguing for richer overtones, as can be seen [here](http://www.schillerinstitute.org/programs/program_brainin_6_6_90.html#Unique_Experiment).
Comment: @guidot I could see why singers hated it, because of the strain on their voices, but I never really knew that there were many instrumentalists against it as well for reasons other than timbre issues on aerophones.
Comment: Whilst all the above may be true, how does the phenomenon stand against growing numbers of electric guitarists who seem to be doing the exact opposite, i.e. tuning down, often many semitones. For string players, if the tighter strings do give a more brilliant sound, then why don't they use slightly thicker strings which would have to be strung tighter.Surely the effect would be the same?
Answer: Variations in pitch and tuning systems stem all the way back to Renaissance / pre-Renaissance.  Before a standard tuning system was codified, musicians in each city basically had their own tuning system, and instrument makers were limited with what they could do.  The result was that if musicians from different towns / cities met, they wouldn't be able to play with one another as their instruments were not in tune.
Once technology increase, tuning systems were able to be consistent across countries - thereby improving consistency of sound and instrument creation.
To this day, pitch still continues to vary, though it is purely by choice relating to preferred aesthetics.  For example, here in the US, "A" is tuned to 440hz, while in Europe, it may be 442 or higher.  The reason for this is exactly the question you posed in your post - that Europeans desire a slightly more brilliant sound.  Pitch inflation itself cannot be attributed to an ensemble's brilliant sound, but it can be attributed to an ensemble's desire for a more brilliant sound.
So, how does it work?
It is the same reason why audio engineers boost higher frequencies on cymbals for the extra bright, crisp sound.  It works through the way sound waves resonate.
I will omit all the figures and pictures that would make this explanation easier, and unfortunately only provide a very brief overview for sake of time.
Think about the overtone series.  On a string, touching the string at specific nodes will generate different divisions of the wave that still divide evenly into the original vibration of that string.  Let us say that you now have a second string, tuned slightly higher, but for all intents and purposes is perfectly in tune with itself.  Played by itself, it will still yield all of the same overtones from the same string divisions, however, when compared to the original string, the sound waves of each string resonating openly will not align.  Since the second string is tuned slightly higher, its sound waves will be sounding ever so slightly faster than the original string.  This discrepancy between strings causes the second string to stand out over the first, creating what most musicians consider to be a more "brilliant" sound.
While I have never heard of individual musicians doing it, it is certainly possible for some orchestras.  In the US, in a professional orchestra, they are looking for as homogenous a sound as possible.  An individual performer preferring to not tune with the group would not have a job very long.  Generally, an orchestra will decide what the entire group will tune to, and in my experience it has little to do with "out doing" another musician, and more to do with achieving preferred aesthetics.  After all, there are many other ways to better "out do" another group.
Lastly, I must correct the quoted paragraph in the OP and say that tuning a string higher does not objectively give more amplitude to higher overtones.  Technically, since the string tuning is changed, it actually gives you a completely different overtone series.  However, since that series so closely relates to the original series, it gives the impression of amplification.  Again, recording engineers use this technique and others to create a more "full" sound.
Hope that helps.
Comment: U.K. and a lot of U.S. use 440, however, Boston Symphony and New York Phil. apparently use 442.Europe, you're right, uses mainly 442.German and Austrian symphony orchestras apparently tune to 443.  Funny, the bands I play with in France tune to 440 ! And modern musicians playing Baroque music end up at 415, to emulate the tuning of the time.This makes some instruments play a semitone lower than normal.
Comment: Yeah, I didn't mean _individual_ musicians, but rather _instrumental_ groups (as opposed to singers, many of whom have railed against such practices), but I guess I didn't make my thoughts clear. Regardless, thanks for pointing me in the right direction.
Comment: A = 440 Hz in U.K. and most of Europe
Comment: Really? I thought it was Europe that used 442 Hz and above, and only the U.S. used 440.
Comment: To my knowledge, 440 Hz is the standard all around the world. However, individual orchestras indeed frequently choose to play in a different pitch.
Answer: In an amateur group the pitch rising usually starts in the woodwind and brass.
Amateur brass and woodwind players who do not do any practise between rehearsals (the vast majority of amateur players) usually go sharp due to tired embouchures during rehearsals.
I have in the past played in many amateur orchestras where this has happened and it did not start in the string section.  At least one orchestra had a woodwind and brass section that at the end of a concert could finish up much sharper than the strings.
Comment: I was talking about tuning the entire orchestra to a higher frequency _on purpose_. But yeah, I've noticed the same tendency for amateur aerophone players to go sharp.
Answer: Besides the psychological considerations, a minor but potentially significant physical point: when one tunes "up" a string instrument, one must finish by tightening the string to avoid introducing slack. If there is a delay between the string being in tune and the perception of its being in tune, at which point the increase in tension is stopped, the error will be incremental but always positive (more tension, ever so slightly too sharp). Compound this minor error over the course of centuries of iterations, in combination with psychological considerations, and one ends up with significant pitch inflation.

What is the reason for pitch inflation?


How to selectively make a colour in three.js canvas transparent?

Question: I have a three.js canvas generated from liquidfun.js.
.
For some reason, the canvas is not transparent. Is there a way to selectively make a color in the canvas fully transparent(in this case, the whitish background),after having painted the whole canvas? I tried setting context.clearColor(0, 0, 0, 0) but it didn't make any difference.
Answer: you probably need to post some code.
If you're using the same code from the liquidfun website it's not using WebGL directly it's using three.js so you'd need to set the color by finding the three.js renderer and calling renderer.setClearColor. You'd also need to initialize three.js with an alpha channel when you create your rendered
var renderer = new THREE.WebGLRenderer({alpha: true});

Example:

// shouldnt be a global :(
var particleColors = [
  new b2ParticleColor(0xff, 0x00, 0x00, 0xff), // red
  new b2ParticleColor(0x00, 0xff, 0x00, 0xff), // green
  new b2ParticleColor(0x00, 0x00, 0xff, 0xff), // blue
  new b2ParticleColor(0xff, 0x8c, 0x00, 0xff), // orange
  new b2ParticleColor(0x00, 0xce, 0xd1, 0xff), // turquoise
  new b2ParticleColor(0xff, 0x00, 0xff, 0xff), // magenta
  new b2ParticleColor(0xff, 0xd7, 0x00, 0xff), // gold
  new b2ParticleColor(0x00, 0xff, 0xff, 0xff) // cyan
];
var container;
var world = null;
var threeRenderer;
var renderer;
var camera;
var scene;
var objects = [];
var timeStep = 1.0 / 60.0;
var velocityIterations = 8;
var positionIterations = 3;
var test = {};
var projector = new THREE.Projector();
var planeZ = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
var g_groundBody = null;

var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;

function printErrorMsg(msg) {
  var domElement = document.createElement('div');
  domElement.style.textAlign = 'center';
  domElement.innerHTML = msg;
  document.body.appendChild(domElement);
}

function initTestbed() {
  camera = new THREE.PerspectiveCamera(70
    , windowWidth / windowHeight
    , 1, 1000);

  try {
    threeRenderer = new THREE.WebGLRenderer({alpha: true});
  } catch( error ) {
    printErrorMsg('
Sorry, your browser does not support WebGL.
'
                + '
This testbed application uses WebGL to quickly draw'
                + ' LiquidFun particles.
'
                + '
LiquidFun can be used without WebGL, but unfortunately'
                + ' this testbed cannot.
'
                + '
Have a great day!
');
    return;
  }

  threeRenderer.setClearColor(0, 0);
  threeRenderer.setSize(windowWidth, windowHeight);

  camera.position.x = 0;
  camera.position.y = 0;
  camera.position.z = 100;
  scene = new THREE.Scene();
  camera.lookAt(scene.position);

  document.body.appendChild( this.threeRenderer.domElement);

  this.mouseJoint = null;

  // hack
  renderer = new Renderer();
  var gravity = new b2Vec2(0, -10);
  world = new b2World(gravity);
  Testbed();
}

function testSwitch(testName) {
  ResetWorld();
  world.SetGravity(new b2Vec2(0, -10));
  var bd = new b2BodyDef;
  g_groundBody = world.CreateBody(bd);
  test = new window[testName];
}

function Testbed(obj) {
  // Init world
  //GenerateOffsets();
  //Init
  var that = this;
  document.addEventListener('keypress', function(event) {
    if (test.Keyboard !== undefined) {
      test.Keyboard(String.fromCharCode(event.which) );
    }
  });
  document.addEventListener('keyup', function(event) {
    if (test.KeyboardUp !== undefined) {
      test.KeyboardUp(String.fromCharCode(event.which) );
    }
  });

  document.addEventListener('mousedown', function(event) {
    var p = getMouseCoords(event);
    var aabb = new b2AABB;
    var d = new b2Vec2;

    d.Set(0.01, 0.01);
    b2Vec2.Sub(aabb.lowerBound, p, d);
    b2Vec2.Add(aabb.upperBound, p, d);

    var queryCallback = new QueryCallback(p);
    world.QueryAABB(queryCallback, aabb);

    if (queryCallback.fixture) {
      var body = queryCallback.fixture.body;
      var md = new b2MouseJointDef;
      md.bodyA = g_groundBody;
      md.bodyB = body;
      md.target = p;
      md.maxForce = 1000 * body.GetMass();
      that.mouseJoint = world.CreateJoint(md);
      body.SetAwake(true);
    }
    if (test.MouseDown !== undefined) {
      test.MouseDown(p);
    }

  });

  document.addEventListener('mousemove', function(event) {
    var p = getMouseCoords(event);
    if (that.mouseJoint) {
      that.mouseJoint.SetTarget(p);
    }
    if (test.MouseMove !== undefined) {
      test.MouseMove(p);
    }
  });

  document.addEventListener('mouseup', function(event) {
    if (that.mouseJoint) {
      world.DestroyJoint(that.mouseJoint);
      that.mouseJoint = null;
    }
    if (test.MouseUp !== undefined) {
      test.MouseUp(getMouseCoords(event));
    }
  });

  window.addEventListener( 'resize', onWindowResize, false );

  testSwitch("TestWaveMachine");

  render();
}

var render = function() {
  // bring objects into world
  renderer.currentVertex = 0;
  if (test.Step !== undefined) {
    test.Step();
  } else {
    Step();
  }
  renderer.draw();

  threeRenderer.render(scene, camera);
  requestAnimationFrame(render);
};

var ResetWorld = function() {
  if (world !== null) {
    while (world.joints.length > 0) {
      world.DestroyJoint(world.joints[0]);
    }

    while (world.bodies.length > 0) {
      world.DestroyBody(world.bodies[0]);
    }

    while (world.particleSystems.length > 0) {
      world.DestroyParticleSystem(world.particleSystems[0]);
    }
  }
  camera.position.x = 0;
  camera.position.y = 0;
  camera.position.z = 100;
};

var Step = function() {
  world.Step(timeStep, velocityIterations, positionIterations);
};

/**@constructor*/
function QueryCallback(point) {
  this.point = point;
  this.fixture = null;
}

/**@return bool*/
QueryCallback.prototype.ReportFixture = function(fixture) {
  var body = fixture.body;
  if (body.GetType() === b2_dynamicBody) {
    var inside = fixture.TestPoint(this.point);
    if (inside) {
      this.fixture = fixture;
      return true;
    }
  }
  return false;
};

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  threeRenderer.setSize( window.innerWidth, window.innerHeight );
}

function getMouseCoords(event) {
  var mouse = new THREE.Vector3();
  mouse.x = (event.clientX / windowWidth) * 2 - 1;
  mouse.y = -(event.clientY / windowHeight) * 2 + 1;
  mouse.z = 0.5;

  projector.unprojectVector(mouse, camera);
  var dir = mouse.sub(camera.position).normalize();
  var distance = -camera.position.z / dir.z;
  var pos = camera.position.clone().add(dir.multiplyScalar(distance));
  var p = new b2Vec2(pos.x, pos.y);
  return p;
}
body {
        font-family: Monospace;
        background-color: #f0f0f0;
        margin: 0;
        overflow: hidden;
        background-color: red;  /* just in case image doesn't load */
        background-image: url(https://i.imgur.com/v38pV.jpg);
        background-size: cover;
    }

      <select id="tests" onchange="testSwitch(this.value)">
        <option value="TestDamBreak">Dam Break</option>
        <option value="TestDrawingParticles">Drawing Particles</option>
        <option value="TestElasticParticles">Elastic Particles</option>
        <option value="TestImpulse">Impulse</option>
        <option value="TestLiquidTimer">Liquid Timer</option>
        <option value="TestParticles">Particles</option>
        <option value="TestRigidParticles">Rigid Particles</option>
        <option value="TestSoup">Soup</option>
        <option value="TestSoupStirrer">Soup Stirrer</option>
        <option value="TestSparky">Sparky</option>
        <option value="TestSurfaceTension">SurfaceTension</option>
        <option value="TestTheoJansen">Theo Jansen</option>
        <option value="TestWaveMachine" selected="selected">Wave Machine</option>
      </select>

If on the other hand you are using WebGL directly then by default a canvas has alpha and its clear color is 0,0,0,0 so if you're not seeing transparency that's something you've done on your own code or whatever library you're using to setup WebGL.
Note: There are other issues you should be aware of with WebGL, canvas and transparency
Comment: Thanks a lot man. Yes, I am using the liquidfun code from the website(removed the mouse event listeners and added some of my own code in the testbed and renderer codes). Setting {alpha: true} in the initializing statement and making the alpha argument 0 in the renderer.setClearColor method just did the trick for me. Thanks a lot again, and I am indebted.


Order of statements in the Delta-Epsilon Limit definition

Question: So the definition of Limit I see is
$$\lim_{x \to a}f(x) = L$$ means:
for all $\epsilon >0$, there exists a $\delta >0$ such that $$0<|x - a| < \delta \Rightarrow |f(x) - L| < \epsilon $$
I was wondering if modifying the definition to: Limit exists when for all $\delta >0,$ there exists a $\epsilon > 0$ such that
$0<|f(x) - L| < \epsilon $ $\Rightarrow |x - a| < \delta$
would cause any problem.
Because to me it seems like this definition should also work except it does seem a lot harder when it comes to the actual proving part.
Can this flipped version of the limit definition also work? Why did mathematicians define in this order?
Comment: This is _not_ answered by the questioned linked above: There are many ways of reordering the symbols used in the $\epsilon-\delta$ definition of continuity and this question uses:(a) $\forall \delta>0 \exists \epsilon>0: 0<|f(x)-L|<\epsilon \implies |x-a|<\delta$, were the linked question considers (b) $\forall \delta>0 \exists \epsilon>0:  |x-a|<\delta \implies 0<|f(x)-L|<\epsilon$ (though it switches the roles of $\delta$ and $\epsilon$ which is a cause for confusion). Thus there are functions which are continuous which do not satisfy (a) while any locally bounded function satisfies (b).
Answer: That is not equivalent to the usual definition. For instance, if $f\colon\Bbb R\longrightarrow\Bbb R$ is the constant function $L$, then $\lim_{x\to a}f(x)=L$ (for any $a\in\Bbb R$), according to the usual definition. But not according to your definition.
Comment: (+1) ... but what is $f$ is locally invertible?
Comment: "but what is f is locally invertible?" way too huge an assumption to make the definition meaningful.  But if so you must find the region within which it is invertible and restrict your $\delta$ $\epsilon$ within it.
Comment: If $f$ is locally invertible and its domain is an interval, then it seems that those definitions are equivalent, yes.
Comment: @fleablood Indeed.  But with that overly restrictive condition, the statements are equivalent.
Comment: $\sin$ is locally inverable.   But $|f(x) - L| < \epsilon \not \implies |x-a| < \delta$.  Instead $|f(x) - L| < \epsilon \implies \exists k\in \mathbb Z;$ either $|(2\pi k +x)-a| < \delta$ or $|((2k+1)\pi-x)-a| < \delta$.  I think we need the entire function to be invertible .... Or am I missing what "locally invertable" means?
Comment: @fleablood The function $\sin$ is not locally invertible near, say, $\frac\pi2$.
Comment: but in the areas not near $\frac \pi 2 + k\pi$?  Does locally invertible at $x=a$ mean there is a neighborhood $N_a$ of $a$ so that $f$ restricted to $N_a$ is injective? Or does locally invertible mean that there is a neighborhood $E_{f(a)}$ of $f(a)$ so that the preimage of every point in $E_{f(a)}$ is a singleton (or empty) [i.e. $f$ restricted to $f^{-1}(E_{f(a)}$ is injective]? If the former $\sin x$ is locally invertable except at extrema. If the latter only functions that sometimes pass the "horizontal line test" are locally invertable.
Comment: I had in mind your first option. So, indeed, $\sin$ is locally invertible at every $a\notin\left\{\frac\pi2+k\pi\,\middle|\,k\in\Bbb Z\right\}$.
Answer: Huge problems.
Basic issue.  We hone in on the function by honing in on the image of the function by honing in on the domain.  We can't hone in on the domain by honing in on the function because the function needn't be invert-- it may fail the horizontal line test-- and we have point in the image close together that are miles apart in the domain.
Example a constant function.  Or the periodic $\sin$ function where $|f(x) - L| < \epsilon$ would not mean $|x-a| < \delta$ as $x$ may be multiples of $2\pi$ distant for $a$.  So $|f(x)-L| < \epsilon \not \implies |x-a| < \delta$.
... Now that counter-intuitive aspect that confuses every student (except the students who lie) is that it seems if we are honing in one the domain ($\delta$) to hone in on the image, should we start with the $\delta$??? Doesn't starting with the $\epsilon$ seem backwards.
And .... yes, it seems that way, but if you draw enough pictures and practice enough you will see that we must work backwards by establishing "acceptable error" range in the final image and finding the intial input range to produce the acceptable error.  That's the only way it'll work.  The wording sound backwards... but it's how it must be.

We start with the "acceptable error" range in the end result, to retrofit and finish with ant initial input range.

That's why it's $\epsilon$ first, then $\delta$ and not the other way around.
And if you are confused, rest assured every student before you either was equally confused at one time or are is lying about it.
Comment: From drawing pictures, it just seems like I can find the satisfying interval of the image from the arbitrary interval in the domain. I am talking about the pictures of graphs that are used to explain the epsilon-delta limit concept. On those pictures, the lines from epsilon interval are drawn first then the lines of delta interval. It seems intuitive that I can also start the line from any delta interval and connect those lines to epsilon interval. [link](https://tutorial.math.lamar.edu/classes/calcI/DefnOfLimit_Files/image001.png)
Comment: Yes, ... but it's backwards engineering... to me, that seems to be the best way to think of it.
Comment: Sorry, I don't understand what you mean by backwards engineering here?
Comment: I mean simply that the *idea* of a limit is that if you get arbtrarily close to $a$ (that is $|x-a|<\delta$ then you get arbtrarily close to $L$ (that is $|f(x)-L| < \epsilon$).  It's the tweaking of $x$ and $\delta$ that causes the tweaking of $f(x)$ and $\epsilon$.  But to set this in motion we must *first* establish an error range of $\epsilon$ for which we set the input range of $\delta$.  We use the ouptut to establish the input.... reverse engineering.


PHP-CPP Include arquivo dentro da extensão

Question: Estou desenvolvendo uma extensão php com PHP-CPP, onde eu preciso fazer um include de um arquivo php dentro da extensão, estou fazendo isso para proteger o código. Estou tentando deste modo:
Php::Value HomeController () {
std::string source = "";
source += "<?php\r\n";
source += "namespace App\\Http\\Controllers\\ajax;\r\n";
source += "use Illuminate\\Http\\Request;\r\n";
source += "use App\\Http\\Requests;\r\n";
source += "use App\\Http\\Controllers\\Controller;\r\n";
source += "class HorarioController extends Controller {\r\n";
source += "protected $page = \"ajax.horario\";\r\n";
source += "public function index(){\r\n";
source += "return $this->view;\r\n";
source += "}\r\n";
source += "}\r\n";

Php::Value val = Php::call("base64_encode", source);
std::string retorno = val;
retorno = "data://text/plain;base64,"+retorno;

return retorno;
}

mas se a pessoa remover o "data://text/plain;base64," e usar o base64_decode tem acesso a minha classe.
Tentei deste modo também:
void HomeControllerInclude () {
std::string source = "";
source += "<?php\r\n";
source += "namespace App\\Http\\Controllers\\ajax;\r\n";
source += "use Illuminate\\Http\\Request;\r\n";
source += "use App\\Http\\Requests;\r\n";
source += "use App\\Http\\Controllers\\Controller;\r\n";
source += "class HorarioController extends Controller {\r\n";
source += "protected $page = \"ajax.horario\";\r\n";
source += "public function index(){\r\n";
source += "return $this->view;\r\n";
source += "}\r\n";
source += "}\r\n";

Php::Value val = Php::call("base64_encode", source);
std::string retorno = val;
retorno = "data://text/plain;base64,"+retorno;

Php::call("include", retorno);
}

Mas recebo o seguinte erro: Invalid call to include
Observação: Estou utilizando este método pois é o mais seguro que conheço, os demais possuem dezenas de métodos para fazer engenharia inversa.
EDIÇÃO:
Acabei achando uma função no PHP-CPP que faz o include, é a função Php::include() ela funciona perfeitamente com arquivos php, mas quando eu tendo utilizar o include com o data://text/plain;base64, não recebo nem uma mensagem de erro e não faz o include, o que será?
Php::Value HomeControllerInclude () {
    std::string source = "";

    source = "<?php class novo { public static function coco() {  return 20; } }";

    Php::Value val = Php::call("base64_encode", source);
    std::string retorno = val;

    retorno = "data://text/plain;base64,"+retorno;

    return include(retorno);
}

Comment: Eu não tenho certeza, mas acho que o erro ocorre porque `include` não é uma função e sim um "language-construct" do PHP.
Comment: Verdade, acabei achando uma função do PHP-CPP que faz o include, mas acabei me deparando com um problema, vou editar a pergunta.
Answer: O Php::include é usado apenas pra incluir arquivos reais e provavelmente não suporta o protocolo data: que geralmente (se não unicamente) usado pra aplicações html.
Note que no github o metodo include tenta ler um arquivo:
Value include(const char *filename)
{
    // we can simply execute a file
    return File(filename).execute();
}

O correto provavelmente seria usar Php::eval, veja como é o source dele:
Value eval(const char *phpCode)
{
    // we have a script for this
    return Script(phpCode).execute();
}

O código deve ficar algo como:
Php::Value HomeControllerInclude () {
    std::string source = "";

    source = "<?php class novo { public static function coco() {  return 20; } }";

    return eval(source);
}

Ou:
return Php::eval(source);

Pode ocorrer do <?php afetar o eval, então use assim:
return eval("?>" + source);

Comment: Fiz exatamente como me mostras, mas recebo a mensagem: PHP Parse error:  parse error in Unknown on line 1
Comment: Resolvi o problema, removi o " + source);`
Comment: Também funcionou. Muito obrigado, me ajudou muito.


Auto populate dropDownListRow form field in yii from database

Question: I have a form having some multi select dropdowns in yii. I have to auto populate the selected values in that multi select box when comes to edit the data. I am fetching the data and passing it inot view file, but am not sure how can i populate the values in the dropdown. please help me
Here is the code for the multi select drop down
echo $form->dropDownListRow($modelDomain, 'domain_id',  $domain, array('title' => Yii::t('main', 'SELECT_DOAMIN'),'multiple'=>true ,'style' => 'width:250px;height:150px;'));

Answer: For multiple select you need to use 'options' parameter:
echo $form->dropDownListRow($modelDomain, 'domain_id',  $domain, array('title' => Yii::t('main', 'SELECT_DOAMIN'),'multiple'=>true ,'style' => 'width:250px;height:150px;', 'options' => array(
1 => array('selected' => 'selected'),
2 => array('selected' => 'selected'),
)));

Where 1 and 2 are domain ids taken from the $_POST;
You can do this in the action:
$post = $this->getRequest()->getPost('ModelName');
$selectedDomains = $post['domain_id']; // this should be an array or selected values
$selected = array_fill(0, count($selectedDomains), array('selected' => 'selected')); // this constructs the 'options' value from view
$selectedOptions = array_combine($selectedDomains, $selected) // this is the 'options' array with selected values as keys and htmlOptions as values

Also, the code is untested and you need to do your validations and other logic stuff yourself.


Accents and special characters in MySQL

Question: I have got a problem with accents and special characters such as: ñ, ç...
I use the following code to introduce data on a MySQL DB:
$artist = mb_convert_encoding(mb_convert_case($_POST["artist"], MB_CASE_TITLE), "UTF-8");
$title = mb_convert_encoding(mb_convert_case($_POST["title"], MB_CASE_TITLE), "UTF-8");
$name = mb_convert_encoding(mb_convert_case($_POST["name"], MB_CASE_TITLE), "UTF-8");

$query = $db->prepare("INSERT INTO songs (artist, title, name) VALUES (?, ?, ?)");
$query->execute(array($artist, $title, $name));

An example that fails (artist of the song / title of the song / ádam gracia). This is inserted as:
Artist Of The Song / Title Of The Song / Ãdam Gracia)

The worst of it is that locally (localhost), works perfectly, on my hosting, it gives the above output. The same happens with ç, ñ, etc..
I have tried changing encoding options at php my admin, but I don´t know what to do...
Thank you all!
Comment: @aris, changing the sql database charset, it was in latin ci, now it is in utf8_spanish_ci. Same problems
Answer: try to set the charset in the connection like :
new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf-8", $dbUser, $dbPass);

Comment: Ok, im stupid enough and I just saw that the connection file for the hosting does NOT contain this last bit (charset=utf-8)... Sorry for the problems jeje.

Accents and special characters in MySQL


How to find a basis of a vector space?

Question: Let $P_4(R)$ denote the set of all polynomials with degree at most 4 and coefficients in $R$. I was attempting to find a basis of $U=\{p\in P_4(R): p''(6)=0\}$. I can find one by taking the most basic approach. Basically start with $p(x)=a_0+a_1x+a_2x^2+a_3x^3+a_4x^4$. Then differentiate this polynomial twice and factor the differentiated version so that one of its root is 6. Then integrate the factored version twice and get the general description of an element of $U$. Then write that in terms of the standard basis of $P_4(R)$ and choose the free variables and construct a basis of $U$.
My question, is there a clever way to find a basis of a given vector space? How could one simplify this process of finding a basis?
Answer: $1, x-6, (x-6)^2, (x-6)^3, (x-6)^4$ forms a basis of $P_4(\mathbb R)$, as we can find the Taylor expansion of any polynomial around $6$.
For $p(x)=\sum_{n=0}^4 a_n(x-6)^n$, $p''(6)=0$ is equivalent to $a_2=0$. Now it should be clear that a basis is given by $1, x-6, (x-6)^3, (x-6)^4$
Comment: Thanks for the answer. That is a really nice approach!
Answer: Just because you called what you did "the most basic approach", let me add what I think is the most basic approach. (As opposed to for example the more elegant approach in the first answer.)
$U$ is the kernel of the linear map $p\mapsto p''(6)$. If you write $p(x)=a_0+a_1x+a_2x^2+a_3x^3+a_4x^4$ you express $p$ in terms of the basis of $P_4(R)$ that consists of the monomials. Now $p''(6)=0$ becomes
$$2a_2+ 36a_3 + 432a_4 = 0.
$$
The solution space of this is a four dimensional sub space of $R^5$ (we do not forget $a_0$ and $a_1$). You write down a basis of this in the way that you have learnt and then use the corresponding elements of $P_4(R)$ as a basis of $U$.
This is the solution that you should be able to come up with without thinking. It is always good to find a clever solution (and looking for a convenient basis is definitely something that one should do), but I also find it important to know when it is not necessary to be clever.
Btw, I suppose that $R=\mathbb R$, otherwise the solution space is only four dimensional if $2\ne 0$.
Comment: @Seeker, i only mentioned the linear map for context, you can ignore that sentence. The point is that you get a homogeneous linear equation, and even systems of linear equations will have been discussed at that point, I suppose.
Comment: I agree. But these questions were in a chapter before linear maps. Linear maps haven't been introduced yet.
Comment: Yeah I should have thought about that but didn't. Thanks for the answer!

How to find a basis of a vector space?


Fast 404 showing page not found

Question: I have enabled fast_404 and added the following line in settings.php
/**
* Fast 404 settings:
*/
// This path may need to be changed if the fast 404 module is in a different location.
include_once('./sites/all/modules/fast_404/fast_404.inc');

# Disallowed extensions. Any extension in here will not be served by Drupal and
# will get a fast 404.
$conf['fast_404_exts'] = '/^(?!robots).*\.(txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

# Array of whitelisted URL fragment strings that conflict with fast_404.
$conf['fast_404_string_whitelisting'] = array('cdn/farfuture', '/advagg_');

# Default fast 404 error message.
$conf['fast_404_html'] = '<title>404 Not Found</title>
Not Found

The requested URL "@path" was not found on this server.
';

# Call the extension checking now. This will skip any logging of 404s.
fast_404_ext_check();

# Check paths during bootstrap and see if they are legitimate.
# By default, a very plain 404 page is used, because usually errors like this are shown to browsers that only look at the headers. Uncomment this link to use a custom 404 page; this page needs to be in your docroot.
#$conf['fast_404_HTML_error_page'] = './page_not_found.html';

# By default, the custom 404 page is loaded only for path checking. Load it for all 404s with the below option set to TRUE, especially if you are only using fast_404_ext_check().
$conf['fast_404_HTML_error_all_paths'] = FALSE;

$conf['fast_404_path_check'] = TRUE;
fast_404_path_check();

If I access the wrong path it shows page not found. If I access the path http://example.com/news/test. It shows page not found, but it is a valid path. and admin menu also breaks after adding above lines.
Answer: A year late but since I just ran into all these and no answer has been given then here is how I made things work:

Verify that your settings.php has the correct include path.
include_once('./sites/all/modules/fast_404/fast_404.inc');
// You may be using something like
include_once('./sites/all/modules/contrib/fast_404/fast_404.inc');
Setting the following to TRUE, I found out, does not work with some path aliases:
$conf['fast_404_path_check'] = FALSE; // If set to TRUE some aliases do not work
Regarding admin menu there is a line of code in admin_menu.module that if you change then it works. Current version is line 66. You are looking for:
$items['js/admin_menu/cache/'] = array(
// Change it to
$items['js/admin_menu/cache/%'] = array(
I enabled fast_404_ext_check() and fast_404_path_check() without any issues. Do remember that fast_404_path_check() only works with MySQL.

Remember to flush caches after changing 3.
Hope this helps anyone that bumbs into these issues.

Fast 404 showing page not found


Finding maximum combination of keys that share the same value

Question: Here is my table:
CREATE TABLE ABC(
 key NUMBER(5),
 val NUMBER(5)
 );

insert into ABC (key, val) values (1,1);
insert into ABC (key, val) values (1,2);
insert into ABC (key, val) values (1,3);
insert into ABC (key, val) values (2,3);
insert into ABC (key, val) values (1,4);
insert into ABC (key, val) values (2,4);
insert into ABC (key, val) values (2,5);
insert into ABC (key, val) values (3,5);
insert into ABC (key, val) values (1,6);
insert into ABC (key, val) values (2,6);

Desired Output:

I want to find the maximum pairs of keys that share the same value, and list them, in the above example the maximum pairs of keys that occur in the table are (1,2) which share values (3,4,6)
Answer: Please try as below:
select ab,val from (
select rank() over( order by cnt desc) rn, ab, val ,cnt
from (
select listagg(key,',')  within group(order by val) ab,val,
count(1) over (partition by (listagg(key,',')  within group(order by val))) cnt
from abc
group by val
having count(*) > 1))
where rn = 1;

Comment: Hi Pradeep Garg, Is there a way to get it without the listagg?
Comment: @StackOne, I used listagg because i am not sure if number of keys will be constant. It can be combination of 3 keys also
Comment: It has to be the maximum pairs, In my example 1,2 has the maximum pairs. there is 1 pair for 2,3 and 0 pairs for 1,3
Comment: I am trying to say if there is below data:0 insert into ABC (key, val) values (3,3);
insert into ABC (key, val) values (3,6);
insert into ABC (key, val) values (3,4); so 3 keys (1,2,3) will have maximum rows. That I am asking if there will always 2 keys or number of keys can be different
Comment: Yes, in that case the output should display (key,key1,key2,val) (1,2,3,3 ) (1,2,3,4),(1,2,3,6)
Comment: @StackOne - because number of column are dynamic, thats why i used listagg.
Answer: You can use self join and analytical function as follows:
Select * from
(Select t.key, tt.key as key1, t.val,
        Count(distinct val) over (partition by t.key, tt.key) as cnt
  From your_table t join your_table tt
    On t.val = tt.val and t.key < tt.key)
Order by cnt desc
fetch first 1 row with ties;

In oracle 11g, fetch clause is not supported. So you should use dense_rank as follows:
select key, key1, val from
(select key, key1, val,
dense_rank() over (order by cnt desc) as dr  from(
Select a.key, b.key as key1, a.val,
        Count(distinct a.val) over (partition by a.key, b.key) as cnt
  From abc a join abc b
    On a.val = b.val and a.key < b.key) )
    where dr = 1;

http://sqlfiddle.com/#!4/40106f/15
Comment: Hi Popeye, The last line of the code give me an error, I have attached a link. http://sqlfiddle.com/#!4/40106f/11
Comment: You are getting error as fetch clause is introduced in oracle 12c


Distance of point on ellipse from focii

Question:
Let $P( \alpha, \beta)$ be a point on the ellipse $ \frac{x^2}{a^2} + \frac{y^2}{b^2}=1$ where foci are $F_1$ and $F_2$. Then $(PF_1 - PF_2)^2= ?$

I went for a brute for approach, the focii are located at $(\mp ae,0)$ so the distance of point from the general focus is given as:
$$ d = \sqrt{ (\alpha  \pm ae )^2 + \beta^2} = \sqrt{\alpha^2 +(ae)^2 \pm 2 \alpha a e + \beta^2}$$
Now, I use the parameterization $ \alpha = a \cos \theta $ and $ \beta = b \sin \theta$, this leads to :
$$ \sqrt{a^2 + b^2 + (ae)^2 \pm 2 a^2 \cos \theta e} \ \  \color{red} *$$
Further I use the property that $(ae)^2 = a^2 -b^2$,
$$ \sqrt{2a^2 \pm 2a^2 \cos \theta e} =a \sqrt{2} \sqrt{1 \pm e \cos \theta}$$
Substituting $ \cos \theta = \frac{\alpha}{a}$
$$ a \sqrt{2} \sqrt{ 1 \pm e \cos \theta} =  \sqrt{2a} \sqrt{a \pm e \alpha}$$
I'm not quite sure how to proceed anymore...
In the book it was given that the distance of point from focus is given $(a \pm e \alpha)$, did I make mistake? How do I correctly proceed?
Comment: Oh damn that was stupid of me, nice catch, thank you @Tavish!
Comment: There's an error at the point I've marked.
Answer: After the parameterization, the expression becomes $$\sqrt{a^2 \cos^2 \theta +(a^2-a^2 e^2) \sin^2 \theta +(ae)^2 \pm 2ea^2 \cos \theta} \\ = \sqrt{a^2 +a^2e^2 \cos^2 \theta   \pm 2ea^2 \cos \theta   } \\ = a\sqrt{1 +(e\cos \theta)^2 \pm 2e\cos\theta} \\ = a(1\pm e\cos\theta) \\ = a \pm e\alpha$$

Distance of point on ellipse from focii


GCM Push notification not working on HTC explorer v 2.3.5 in android

Question: I have implemented GCM push notification in my android application. server side is php. I am getting all push notification messages on most of devices, but I can not get any notification on HTC explorer android version 2.3.5. I have tested other HTC device with version 4.0 as well as other samsung devices and its working fine. Please give me solution for this.
Comment: do you have a SIM in your phone?
Comment: yes. i have SIM and I am using WI-Fi for internet access.
Answer: 1.Check whether there is google account added on that device.(Settings->Add Account). This account should not be same as the one you used to create the API project in Google API console.
2. In some cases the GCM - SERVICE_NOT_AVAILABLE will be response while registering the device, so make sure that the device is registered and it got the token the GCM server.
<code>public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
        if (intent.getStringExtra("registration_id")!=null){
            //add log here
        }
        String error = intent.getStringExtra("error");
        if (error!=null){
        //add log here
        }
    }
}
</code>


How to compute robust standard errors of the coefficients in multiple regression?

Question: So I know that to find the coefficients of the BLP of some data is to use the formula,
$$\vec{\beta} = [{\bf X}^{T}{\bf X}]^{-1}{\bf X}^{T}{\bf Y}.$$
However, I also want to find the variance, and I see this formula, classified as "non-parametric" and "robust" one:
$$\hat{V}[\vec{\hat{\beta}}] = [{\bf X}^{T}{\bf X}]^{-1}{\bf X}^{T}\text{diag}[({\bf Y}-{\bf X}\vec{\beta})^{2}]{\bf X}[{\bf X}^{T}{\bf X}]^{-1}.$$
However, the equation that I have comes from some notes that don't explain all of what is meant here.  First of all, I don't understand what is meant by $({\bf Y}-{\bf X}\vec{\beta})^{2}$ because the stuff inside the power is a vector--how do you square a vector?  Coordinate-wise?
Moreover, I'm not sure what is meant by "diag".  Is that the diagonalization of the matrix, i.e. the diagonal matrix of its eigenvalues?  I'm computing this in R and R has a canned command for selecting the diagonal elements from a matrix--is that what this is supposed to be?
I have another confusion about this.  If you use this for a BLP with two variable terms and collect 10 data points, for instance, then $\bf X$ will have dimensions 10x3 and since ${\bf X}^{T}$ is to the left of the diag(...) factor, this must have 3 rows.  Since $\bf X$ occurs to its right, then the diag(...) factor must have 3 columns.  But in that case, the result of this computation will be a $3 \times 3$ matrix.  Since it's supposed to tell me the variance of the coefficients, I don't see how I would interpret this result.
Comment: Are you sure you mean "multivariate" regression? Multivariate means that you have several response variables, i.e. $Y$ is a matrix, not a vector (and $\beta$ is a matrix). If response is univariate, then it is called "multiple" regression.
Comment: I see--in that case, yes, it's not multivariate regression but multiple regression.
Answer: The expression you have is for White's heteroskedasticity-robust variance estimator. The expression in the central parantheses gives the residual vector, and the squaring is done element-wise (so that you get the vector of squared residuals). Diag means creates the diagonal matrix which has the vector of squared residuals along it's diagonal, and zeroes as the off-diagonal elements.
As for your second question, you're right that the variance matrix will be a $k \times k$ matrix, where $k$ is the number of parameters (including the constant). The diagonal elements of this matrix give the variances of the parameter estimates, while the off-diagonal elements give the covariances between the different parameter estimates. This matrix is more properly called a variance-covariance matrix.
Edit: the standard OLS model requires a homoskedasticity assumption, i.e., that the variance of the error term is independent of the covariates. The robust estimator discussed above relaxes this assumption, allowing for heteroskedastic errors. This is why the robust estimator includes the full vector of squared residuals, while the standard OLS variance estimator simply uses the overall variance of the residuals.
Comment: Can you comment on how this formula is different from the "standard" one $\sigma^2 (X^\top X)^{-1}$?
Comment: Thanks @Addem. If standard_error could comment on all that in their answer, it would turn the answer into a really useful one. I will save my upvote until then :)
Comment: @amoeba It is commented on in my notes that the equation I'm using is robust while that one is not.  This one is classified by the author as non-parametric while the one you wrote is called the "classical" version.  It is criticized for having unrealistic assumptions about the interpretation of the parameters.


RedirectToAction em JavaScript não funciona

Question: Após uma validação eu chamo o controller (Perfil) na action (Adiciona) para adicionar um novo registro através de javascript.
Se der certo a inserção eu dou RedirectToAction para o index deste mesmo controller passando o id do perfil que acabei de cadastrar, porém nada acontece!
JavaScript:
function validaFormulario() {
    var formularioValidado = false;

    formularioValidado = validaFormulario();

    if (formularioValidado) {
        var perfil = obtemPerfilDoFormulario();
        $.ajax({
            type: 'POST',
            url: '/Perfil/Adiciona',
            data: {
                "perfil": perfil
            },
            async: false,
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    }
}

Controller:
public ActionResult Adiciona(Perfil perfil)
{
    PerfilDAO perfilDAO = new PerfilDAO();
    perfil.UsuarioId = usuario.Id;
    perfilDAO.Adiciona(perfil);

    EnviaEmailRecebimentoCadastro(perfil.Email);

    EnviaEmailAtivacaoDeConta(perfil.Email);

    return RedirectToAction("Index", "Perfil", perfil.Id);
}

Consegui contornar o problema enviando o id do perfil por Json e fazendo manualmente o redirecionamento pelo javascript adicionamento o retorno "success".
Esta abordagem estaria correta? Estou iniciando em desenvolvimento web e queria uma orientação sobre essas "boas práticas". Afinal, o RedirectToAction do meu controller deveria funcionar. Onde cometi o erro?
Código com o problema contornado:
Controller enviando Json:
public ActionResult Adiciona(Perfil perfil)
{
    //restante do codigo

    return Json(perfil.Id);
}

Javascript com success:
    $.ajax({
        type: 'POST',
        url: '/Perfil/Adiciona',
        data: {
            "perfil": perfil
        },
        async: false,
        success: function (data) {
            var id = JSON.parse(data);
                window.location.href = "/Usuario/Lista/" + id;
        },
        error: function (xhr, status, error) {
            alert(error);
        }

Comment: Você está adicionando a anotação [HttpPost] em cima da Action adiciona?
Comment: Acredito que seja isso mesmo, HttpPost pois o window.location.href = "/Usuario/Lista/" + id; é um GET, quando você não adiciona a anotação [HttpPost] em cima da sua Action automaticamente por padrão ela é um [HttpGet]. Tenta adicionar isso em cima da sua Action [HttpPost] e vê se trouxe resultado.
Comment: Da uma olhada nessa pergunta https://stackoverflow.com/questions/11767911/mvc-httppost-httpget-for-action
Comment: @leonardo, na verdade o 'window.location.href = Usuario/Lista/" + id' functiona! O meu problema é no controller, onde ele não redireciona para a view Index do controller Perfil. O httpPost neste caso é explicito na chamada assíncrona $.ajax com o type: 'POST'.
Comment: Mas ele chega a passar no ActionResult Adiciona ? porque esse método ao meu ver é um GET, se você instrui o server-side a executar um Post ele vai procurar o Post, posso estar errado... mas ja aconteceu comigo, ele chega a executar a action?
Comment: @LeonardoBonetti ele executa sim... Estou debugando e ele passa pela action Adiciona sim. O problema é que quando ele cai na linha  'return RedirectToAction("Index", "Perfil", perfil.Id);' ele não absolutamente nada...
Comment: Ahhhh, agora eu entendi.
Comment: @LucasFerriani E nem deve fazer. **Este é o comportamento esperado**.
Answer: Sua primeira premissa está bem errada.
Ao fazer uma requisição assíncrona para o server-side, você deveria retornar dados ou qualquer coisa que fosse possível de tratar pelo lado cliente usando JavaScript, fazer um redirecionamento não causará efeito nenhum.
A segunda ideia é a melhor forma de fazer o que você pretende. Nela é feita a requisição Ajax para o servidor, o mesmo retorna o dado para que o cliente (JavaScript) se encarregue do redirecionamento.
Comment: essa era a resposta que eu queria ter. No caso, existe algum jeito de eu somente chamar o controller sem esperar nenhum retorno e deixar que ele se encarregue de fazer o redirecionamento? Do mesmo modo que ele funciona quando tenho no html um form com o atributo action="/Controler/Action" e clico no botão submit?
Comment: Não, jovem. Porque o JS não vai fazer nada um código de redirecionamento.
Comment: muito obrigado man! :)


ArrayList de Objetos + Herança

Question: Tudo bem pessoal estou com uma dúvida sobre herança, por exemplo:
    List<Carros> carros = new ArrayList<>();
    Chevete chevete = new Chevete();
    chevete.acelerarMuito(); //Até aqui ok
    carros.add(chevete);//Adicionando chevete numa lista de carros
    carros.get(0).??? //Não consigo mais usar o método acelerar

Como proceder? A minha intenção é ter uma List com objetos herdados, mas preciso usar os métodos específicos de cada um acessando pelo .get(index)
Não quero criar uma List para cada modelo de carro.
Suponha que o método acelerarMuito so existe no chevete, por isso não criei na classe Carro.
Comment: Olha, se bem entendi, você quer guardar subtipos na mesma lista e acessar métodos exclusivos deles a partir da lista. Isso irá te dar problema! A partir do momento que você generaliza o tipo da lista, não há como garantir se o objeto Carro é Chevete, Corsa, ou seja lá o que for. Se precisa de mais especifico, torne o método comum a todos, na superclasse. Uma solução, bem porca aliás, seria checar se o objeto atual acessado é uma instância de chevete, e em caso positivo, forçar o cast, mas não me recordo bem agora se o java permitirá isso.
Comment: `Carros` pode ser uma interface com os métodos que você quer disponibilizar de forma genérica. Na classe `Chevete` você implementa a interface.
Answer: Tem 2 formas de se fazer isso.
A classe Carros possui o metodo acelerar() astrato possuindo implementação em cada modelo de carro:
public abstract class Carro {
   public abstract void acelerar();
}

Ou você precisará de um cast para o modelo específico de veículo ao utilizar o método:
if (carros.get(0) instanceof Chevete) {
   ((Chevete)carros.get(0)).acelerar();
}

Como todo carro acelera, a primeira abordagem faz mais sentido nesse exemplo, mas podem haver métodos específicos de um determinado modelo, aí a segunda se aplica.
Comment: `preciso usar os métodos específicos de cada um acessando pelo .get(index)` -  acho que você não leu este trecho da pergunta.
Comment: Percebi sim, por isso sugeri a segunda abordagem com o cast `((Chevete)carros.get(0)).acelerar();`
Comment: O cast neste caso não é garantido, haja visto que ele mesmo disse que guardará subtipos diferentes na lista.
Comment: Ele teria que garantir o tipo específico através de um `if (carros.get(0) instanceof Chevete)` para poder usar o cast sem riscos. Do contrário apenas utilizando o método na superclasse.
Comment: Na verdade não. Por meio de uma abordagem por interfaces da pra fazer isso. mas foge ao escopo da duvida.
Comment: Certamente interfaces fazem sentido pois seria possível definir metodos de um conjunto de modelos, como CarrosEsportivos ou algo do genero. Mas ainda assim cairia no problema de um List genérico e seria necessário um cast para a interface para os métodos poderem ser utilizados.

ArrayList de Objetos + Herança


Sum the first n^3 how provide with using mathematical induction?

Question: I having next formula and need solving with helps mathematical induction.
$\sum_{i=1}^n i^3 = \biggl(\frac{n(n+1)}{2}\biggl)^2$
My next steps in solving the task:
a)I check the validity of this assertion for n = 1
$\sum_{i=1}^1 1^3 = \biggl(\frac{1(1+1)}{2}\biggl)^2$ = $1$
b)Next, I try to prove the following assertion for n + 1
$\sum_{i=1}^n i^3 = \biggl(\frac{n(n+1)}{2}\biggl)^2$ = $\sum_{i=1}^n i^3$ + $(i + 1)^3$ = $\biggl(\frac{n(n+1)}{2}\biggl)^2$ + $(n+1)^3$ = $\biggl(\frac{n(n+1)}{2}\biggl)^2$ + $(n+1)^3$ = $\biggl(\frac{n(n+1)}{2}\biggl)^2$ + $(n+1)^3$
c)I right solving ? Or have problems ?
Comment: What is the induction hypothesis? Is it not $$\sum\limits_{i=1}^{n} i^3 = \biggl(\frac {n(n+1)} {2}\biggl)^2?$$
Comment: Maybe try an easier induction problem first, to get used to induction and manipulating series, since it seems that's part of where the problem is, so better to practice first with easier algebra. For example, you could try the following problems, using induction: $$\begin{align} 1)  \quad \sum_{i=1}^{n} i &= \frac{n(n+1)}{2} \\ 2) \quad  \sum_{i=1}^{n} i^2 &= \frac{n(n+1)(2n+1)}{6}.\end{align}$$
Comment: Thank you very much. I need to dig a little algebraic manipulations.
Comment: And again, thank you very much for explaining how to do with algebraic manipulations.
Comment: I know the solution to this hypothesis, but I didn't know why it was that way, so by examining a more complicated example, I could understand more or less what mathematical induction is. But I still decide her that you offered me and put my decision here to you.
Answer: Your induction step makes no sense; random indices seem to be coming in when not referenced, and you have not made an induction hypothesis, which is key to the proof. It would help you to write more words and focus less on expressing everything symbolically.
An induction proof has three main steps:

Base Case (which you seem to have no issue with)
Induction Hypothesis (assume the proposition holds for some $n=k$ where $k$ is larger than the base case)
Induction Step (verify, on the premise that your hypothesis holds, that it implies that $k+1$ holds too)

Thus, here, you assume that the $n=k$ case holds, i.e.
$$\sum_{i=1}^k i^3 = \left( \frac{k(k+1)}{2} \right)^2$$
Now, we want to verify that
$$\sum_{i=1}^{k+1} i^3 = \left( \frac{(k+1)(k+2)}{2} \right)^2$$
This is easy to verify since, pulling out the $(k+1)^{th}$ term from the sum,
$$\sum_{i=1}^{k+1} i^3 = (k+1)^3 + \sum_{i=1}^{k} i^3$$
Applying our induction assumption to the summation on the right, which we assume to hold, we have now that
$$(k+1)^3 + \sum_{i=1}^{k} i^3 = (k+1)^3 + \left( \frac{k(k+1)}{2} \right)^2$$
From here, it's a matter of making algebraic manipulations to show that
$$(k+1)^3 + \left( \frac{k(k+1)}{2} \right)^2 = \left( \frac{(k+1)(k+2)}{2} \right)^2$$
as desired. I'll leave the process of doing so to you.
Comment: Thank you very much. I need to dig a little algebraic manipulations.
Comment: And again, thank you very much for explaining how to do with algebraic manipulations.
Answer: You need to show that
$$
\sum_{i=1}^{n+1} i^3 = \left( \frac{(n+1)(n+2)}{2}\right)^2,
$$
using as an hypothesis that
$$
\sum_{i=1}^{n} i^3 = \left( \frac{n(n+1)}{2}\right)^2.
$$
So,
\begin{align*}
\sum_{i=1}^{n+1} i^3=& \sum_{i=1}^n i^3 + (n+1)^3=  \left( \frac{n(n+1)}{2}\right)^2 + (n+1)^3\\
=& (n+1)^2\left( \frac{n^2}{4}+n+1\right)=\frac{(n+1)^2}{4}(n^2+4n+4)\\
=&\frac{(n+1)^2(n+2)^2}{4} = \left( \frac{(n+1)(n+2)}{2}\right)^2
\end{align*}
Comment: Thank you very much. I need to dig a little algebraic manipulations.
Comment: And again, thank you very much for explaining how to do with algebraic manipulations.


Using Chi-Square to test normality.

Question:
This is a sample question we received. I can't really figure out how to statistically show that this data is normally distributed. We are to used the chi-square method and these are the steps we are to follow:

Use the hypothesized distribution to create expected values for each bin.
Use the observed and expected values to create a chi-squared value.
Compare this computed chi-squared value with the chi-squared value from a table, using the appropriate number of degrees of freedom for this problem and the significance level.
Based on the relationship between the computed chi-squared and the table's chi-squared values, accept or reject the hypothesis.

I have never used this method and was wondering if someone could show me how to work through a problem like this. Thanks!
Answer: The chi-squared test is pretty easy to use:
You are told that the engineer has determined that the mean is 10mm and stdev is 0.1 mm. This is all the information you need to specify a normal distribution.

The chi-squared test is based on turning your null hyopthesis into a multinomial distribution, which is a generalization of the binomial distribution (where there are only 2 outcomes). Here, the possibilities are your "bins", where the probability assigned to each "bin" $p_i$ is equal to the probability that a normally distirbuted random variable's value would fall in that bin. As a rule of thumb, if you have N data points, you want to size your bins such tat $Np_i \geq 5$.
Once you have your bins, you calculate the expected number of observations you would have in each bin $E_i$, assuming that your data actually come from a $Normal(10mm,(0.1mm)^2)$ distribution: $E_i=Np_i$.
Now you just need to count the actual number of observations in each bin ($O_i$).
For each bin, you want to form the statistic: $S_i=\frac{(O_i-E_i)^2}{E_i}$
Calculate the Chi-squared statistic $\chi^2 = \sum S_i$
Now here comes the theoretical part: It turns out that when the data actually do come from the multinoimial distribution you constructed (using the underlying hypothesized normal distribution) then the distribution of $\chi^2$ is asymptotically $\chi^2_{k-1}$ where k is the number of bins.
Now, just compare the value of the $\chi^2$ to the $1-\alpha$ percentile of the $\chi^2_{k-1}$ distirution to see if you will reject (i.e., $\chi^2 > 1-\alpha$ percentile of the $\chi^2_{k-1}$)
Comment: Thank you for the help. I have done everything up to point 7. I am not sure where to find the 95th percentile of the X^2(k-1) distribution. I have my X^2 but do not know what to compare it to. Thanks again!
Comment: @user126582 Tables or computer options are readily available: http://keisan.casio.com/exec/system/1180573197

Using Chi-Square to test normality.


Running two different exes from UWP

Question: I managed to run a .exe file at startup using the answer given here:
Running an EXE from C# using UWP
However, I need to run another executable when my UWP app is closed. Does anybody know how to do this? Is there a way to link two different exes to the FullTrustLauncher? Or maybe there is a way to parameterize the usage of this FullTrustLauncher? I know the launch async function can be parameterized, but I have no idea what there parameters are for. So, an example would be nice.
Cheers!
Comment: See this https://stackoverflow.com/questions/46008948/how-to-launch-a-full-trust-desktop-bridge-app-from-uwp-with-arbitrary-paramete
Answer: That parameter cannot be used to customize things like what you think. Also UWP apps lifecycle has already wrote something like this:
"There is not an event to indicate that the user closed the app."
So if you really need to do something like this, maybe:
1. You can detect the user's close "X", see this doc: https://learn.microsoft.com/en-us/uwp/api/windows.ui.core.preview.systemnavigationmanagerpreview
2. Like Ipsit Gaur's link showed, follow Stefan's advice to create extra exe to read command strings.
However in general your request is not a good request. Or even it will leads a bad user experience in my mind.

Running two different exes from UWP


Proof for intersection of right cosets being the empty set

Question:
Either $Hg = Hb$ $\vee$ $Hg \cap Hb \neq\varnothing $

Assume to the contrary that $Hg\cap Hb\neq \varnothing $
Then, $x = hg \exists h \in H \wedge x=hb\exists h\in H$
so, $x=hg =hb$
Recall that:

$Hg=H$ IF and Only If $g\in H$

Indeed, $g\in H$ (can be proven)
$Hx=\left ( Hh \right )g=Hg \subset H$
$Hx=\left ( Hh \right )b=Hb\subset H$
Therefore, $Hg=Hb$
I was given an alternative proof but wonder if this is equally valid.
Comment: $x = hg$ for some $h \in H$, and $x = hb$ for some $h \in H$, but not necessarily the same $h$, so you cannot conclude that $hg = hb$.
Comment: Or you can show that the defining relation $\sim$ is an equivalence relation: $x\in G\sim y\in G\Leftrightarrow xy^{-1}\in H$
Answer: It is usually NOT true that $Hx = H$ ($x$ may not lie in $H$).
You'd want to proceed like this:
Suppose $x = h_1g = h_2b$.
Let $z$ be any element of $Hg$. Then $z = hg$ (we don't know which $h \in H$, it turns out it doesn't matter, all we will use is that it lies in $H$).
Now $h_1h^{-1}z = h_1h^{-1}(hg) = h_1g = h_2b$.
It therefore follows that $z = (hh_1^{-1})(h_1h^{-1}z) = (hh_1^{-1})(h_2b) = (hh_1^{-1}h_2)b$.
Since $hh_1^{-1}h_2 \in H$ by closure, $z \in Hb$, and thus $Hg \subseteq Hb$.
A similar argument (which I leave to you) shows $Hb \subseteq Hg$, which will then prove the equality.


Is this Simpson's Paradox on the Titanic data set?

Question: With the well known "Survival of passengers on the Titanic" data set I get a strange behaviour by plotting the fare vs. the age (see below). Without a constraint on Pclass the correlation is positive. In contrast for all Pclasses the correlations seems to be negative.
I assume that's a form of "Simpson's Paradox". But I am not sure. How can this behaviour best explained for this special case?
<code># df is a pandas dataframe with the titanic data set
# see https://www.kaggle.com/c/titanic

import seaborn as sns
sns.jointplot("Age", "Fare", df, kind='reg')
</code>

<code>sns.lmplot("Age", "Fare", df, col="Pclass")
</code>
Comment: Looks to me like the linear fit is so poor that the direction is almost irrelevant.
Answer: Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation in simple words seems clear: Although inside each class there is a slight tendency of decreasing fares with age, people in lower classes tend to be younger. That is, younger people tend to travel in lower classes and therefore younger people tends to pay lower fares.
About the fact that people is younger in the lower classes, you can see in the plot that there are a lot of children (age<18) in 3rd class, less of them in 2nd class (clearly less people in 0-20 than in 20-40), and very few children in 1st class. Comparing the 40-60 and 60-80 bands with the 20-40 band would also show that people tend to be younger in lower classes.
In summary: Yes, it is an occurrence of the Simpson's paradox. Younger people tend to travel in lower classes and therefore younger people tend to pays lower fares, even if they tend to pay a little more than older people in the same class.
And just a as a side comment: this one is not the only occurrence of Simpson's paradox in the Titanic dataset. In https://select-statistics.co.uk/blog/hidden-data-and-surviving-a-sinking-ship-simpsons-paradox/ or https://www2.stat.duke.edu/courses/Fall12/sta611/SimpsonsParadox.pdf another one is noticed.


Use single values added by field-collection module in Views?

Question: I've already found this question, but it doesn't really help me out, maybe I just don't understand it (I've got the latest version of the module). How to integrate Field collection module in Views?
I have my own content type called "Gallery", for this, I created a field-collection which consists of an image and caption. Now I try to create my own view, first one, only to show the thumbs, and then one, showing the big image and the caption.
But how can I access only one field of the field-collection? I can find this field:
Content: Gallery and caption
or this one:
Content: Gallery and caption:delta (Gallery and caption (field_gallery_and_caption:delta))
but how do I access only the image field? and which type of display should I select?
Answer: I've recently done this before. It's really easy, you can create a Node type view. Then you just add the field collection field that's attached to your node as a Relationship, in your case "Content: Gallery and caption".
Then after you've added the relationship, when you click "Add" on the fields, your field collection fields will be available to select. Their names will start with "Field collection item: *".
If you're using Node reference field inside your field collection then you need to add one more relationship. See this issue and #2 comment for solution.
Answer: Did you add the field_collection relationship to the view?
You will need the relationship to access collections as individual fields.
Comment: For this i have to select the view-type Field collection item, right? Because trying to generate a view of type content, i don't get this relationship. But how to connect the the repeating field_collection fields to the unique fields of my gallery (like title, tags for the gallery...). Thanks!
Answer: To add to the answer, when you add the FieldCollection as a relationship, you choose the FieldCollection's name from the list of relationships. I had thought I was looking for something saying "field_collection" and couldn't find any reference to "collection".
Once I realized that I just had to pick my FieldCollection by name it all worked as described. I lost many hours chasing that tiny distinction. Hope this helps someone else like me.


"Posting date" format cannot be localized

Question: Website: http://grausig.info
Drupal version: 8.3.5
PHP: 5.6
Theme: Bartik
Language: only German language installed (to avoid /de/ in URLs)
Modules: only "Tayonomy menu" and "Markdown filter"
Installation: early of 2017 from scratch
Cache rebuild: "drush cr" used all the time after having changed something
I cannot change the Drupal 8 posting date format of articles and book pages into a German format (day before month). It seems to use the "Default medium date". The posting dates at the abstracts on the starting page remain always English (month before day):
http://beginnersmind.de/pics/scrshots/FrontPage.png
But I already changed "Default medium date" into German style such that day comes before month.
admin/config/regional/date-time/formats/manage/medium looks good:
http://beginnersmind.de/pics/scrshots/DefaultMediumDate.png
But: admin/config/regional/date-time always shows the wrong date pattern by ignoring the modification:
http://beginnersmind.de/pics/scrshots/DateAndTime.png
"drush cr" does not help. I always get month before day.
Update:
I was able to verify this behaviour with a clean new and empty Drupal 8.3.5 install!
Without having the German language installed I am able to edit the English date format.
admin/config/regional/date-time shows the configured patterns.
However, after having installed and activated German it is not possible to change the date-time format any more.
The name of the day turns into German, but the date pattern does no longer reflect the configured state.
Note: The meaning of the date 07/10/2017 depends on the language:
- English: July 10, 2017
- German: Oct 7, 2017
So it is confusing for readers if an English date format is applied to a German text.
Questions:

Did I miss any necessary config action?
Is this a bug?
Comment: It might be that at some moments Drupal is not completely language aware.... I have issue with translations going wrong as well. Can you switch back to English, remove German, clear caches, re-enable German, go to date settings and set a pattern for each language on the localization tab, or do you already have lots of content? You can configure dates with the UI only.
Comment: This does not work. If I go back to *only* English, the patterns on the date and time survey page won't change no matter how I edit them.
Answer: I assume this is a bug since the behaviour occurs also at a fresh Drupal installation without any content. A bug report was filed. It contains a step-by-step instruction to reproduce the problem.
Workarounds for mono-lingual sites where the English date pattern won't fit:

Modifying twig files which obviously means sub-theming. I am not shure whether this works on non-English sites
Leaving the Language module inactive. Date patterns remain editable with the frontend. But e.g. to translate the "submitted by" of posting dates one has to modify node.html.twig which again means subtheming. This works for me.

Edit Oct 11, 2017: The best workaround for non-English monolingual sites known to me and tested by me is: Directly install the target language! Never install English or you may be lost! This can be done with the language selection menu during web install after having loaded the Dupal code. I proceeded as follows to install Drupal 8.4:

In the shell: Go to the webroot directory.
In the shell: drush dl drupal --drupal-project-rename=directoryname
In the shell: cd ./directoryname
In the shell: composer install
In the browser: call the URL of the site
In the browser: follow install instructions and choose your language

Note: As a result the core modules "Configuration Translation" and "Content Translation" were not enabled but "Interface Translation" and "Language" were enabled. It is now possible to edit the date and time patterns.
Note 2: I do not recommend to use "drush site-install"!


Formatting issue with IE6 working well with IE 6+

Question: I have my site working perfectly in IE 6+ but it looks weird in IE 6 or IE 5.5, as I can't ignore the users with IE6 because still around 6% of traffic occur from this version. I am looking forward to have the alternate.
With my some research I came to know that by setting haslayout property, I can solve out formatting issue, but I consider myself extremely poor in CSS and hence I need a help of yours to rectify this issue.
You can find the URL below& you can see it's behavior in IE6, just in case if you are unable to test you can check it by viewing the source, please share your suggestions.
URL: http://anujtripathi.net/BlogListing.aspx?Id=2
Comment: Warning. My antivirus says that this site contains threat
Comment: That's strange, could you please let me know what kind of threat it is telling. I am not using any active x control, it's simple asp.net controls and widget from twitter [I can't blame them], and one visitor info widget. & that's it. I am surprise to know why this has happened and curious at the same time to know the reason.
:O
Comment: Hey, just help me in this.. if my system has any virus , can it effect the application that I have developed in asp.net. Please let me know. it's a very crucial issue that you have found out & I want to rectify i ASAP because I & my users have been never encountered with this issue. Even I opened my site from my company which is using Maccafe [which used to be updated weekly] & I have never recieved any message. Please let me know the name of your antivirus.
Comment: Object: `http://anujtripathi.net/rionded_corners.inc.js`; Infection: `JS:Illredir-CB [Trj]`. Same with /js/jquery-1.2.3.min.js. My antivirus: Avast 5.0.507.
Comment: Ok, it seems to be error with the rounded corner Js file and jquery-1.2.3.min.js, but I don't know why it is showing infected sign as I have gathered them from " http://jquery.com/ ". Any guess or idea why this has happened ?
Comment: This link may help, once you figure out the correct CSS: http://stackoverflow.com/questions/2863136/what-is-the-best-way-to-deal-with-ie-compatibility-issue
Answer: Your code (default.css):
<code>.bg1 {
    padding: 0 7px 20px 0px;
    border-top: 1px solid #FFFFFF;
    background: #FFFFFF url(images/img4.gif) repeat-x;
        width: 95%;
}
</code>
Try shrinking down 95% to like around 92%.
You can use a IE6 hack like so:
<code>.bg1 {
  padding: 0 7px 20px 0px;
  border-top: 1px solid #FFFFFF;
  background: #FFFFFF url(images/img4.gif) repeat-x;
  width: 95%;
}

* html .bg1 {
  width: 92%; /* Star Html Hack IE6 only */
}

*+html .bg1 {
  width: 93%; /* Star Html Hack IE7 only */
}
</code>
But I highly recommend learning the right way and looking at the link below for organizing CSS for cross browser compatibility:
What is the best way to deal with IE compatibility issue?
Answer: I would look at your border widths, margins and paddings. It looks like your content is being pushed down because there isn't enough horizontal space. For a quick check, make your main container a little longer and see if the content shifts up.


Vega how to create charts that dynamically resize & how to change x-axis?

Question: am trying to figure out how to use vega in a web app.
From what I am seeing it looks like it is possible to resize the chart size but I am not entirely sure how to go about it? Would I have to manually change the json object that vega is working off or is there an easier way?
Also, I am having a bad time trying to customize the x-axis. I have date that ranges from 0-potentially thousands. Would like to be able to dynamically set the tick data for the x-axis (by tick data I mean how the x axis increments.. part of my confusion I'm sure is that I don't know what vega means by tick, etc.).
BTW, I'm using angular for the front-end with ng-vega to put the "spec" for vega onto the scope.
Answer: <code>{
   "signals":[
      {
         "name":"width",
         "init":"isFinite(containerSize()[0]) ? containerSize()[0] : 200",
         "on":[
            {
               "update":"isFinite(containerSize()[0]) ? containerSize()[0] : 200",
               "events":"window:resize"
            }
         ]
      }
   ]
}
</code>
Please have a look in sample
<code>{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "autosize": {"type": "fit", "contains": "padding"},
  "background": "white",
  "padding": 5,
  "height": 200,
  "style": "cell",
  "data": [
    {
      "name": "source_0",
      "url": "data/seattle-weather.csv",
      "format": {"type": "csv", "parse": {"date": "date"}, "delimiter": ","},
      "transform": [
        {
          "type": "formula",
          "as": "month_date",
          "expr": "datetime(0, month(datum[\"date\"]), 1, 0, 0, 0, 0)"
        },
        {
          "type": "formula",
          "as": "month_date_end",
          "expr": "datetime(0, month(datum[\"date\"])+1, 1, 0, 0, 0, 0)"
        },
        {
          "type": "aggregate",
          "groupby": ["month_date", "month_date_end"],
          "ops": ["mean"],
          "fields": ["precipitation"],
          "as": ["mean_precipitation"]
        },
        {
          "type": "filter",
          "expr": "(isDate(datum[\"month_date\"]) || (isValid(datum[\"month_date\"]) && isFinite(+datum[\"month_date\"])))"
        }
      ]
    }
  ],
  "signals": [
    {
      "name": "width",
      "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 200",
      "on": [
        {
          "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 200",
          "events": "window:resize"
        }
      ]
    }
  ],
  "marks": [
    {
      "name": "marks",
      "type": "rect",
      "style": ["bar"],
      "from": {"data": "source_0"},
      "encode": {
        "update": {
          "fill": {"value": "#4c78a8"},
          "x2": [
            {
              "test": "!isValid(datum[\"month_date\"]) || !isFinite(+datum[\"month_date\"])",
              "value": 0
            },
            {"scale": "x", "field": "month_date", "offset": 1}
          ],
          "x": [
            {
              "test": "!isValid(datum[\"month_date\"]) || !isFinite(+datum[\"month_date\"])",
              "value": 0
            },
            {"scale": "x", "field": "month_date_end"}
          ],
          "y": {"scale": "y", "field": "mean_precipitation"},
          "y2": {"scale": "y", "value": 0}
        }
      }
    }
  ],
  "scales": [
    {
      "name": "x",
      "type": "time",
      "domain": {
        "data": "source_0",
        "fields": ["month_date", "month_date_end"]
      },
      "range": [0, {"signal": "width"}]
    },
    {
      "name": "y",
      "type": "linear",
      "domain": {"data": "source_0", "field": "mean_precipitation"},
      "range": [{"signal": "height"}, 0],
      "nice": true,
      "zero": true
    }
  ],
  "axes": [
    {
      "scale": "x",
      "orient": "bottom",
      "gridScale": "y",
      "grid": true,
      "domain": false,
      "labels": false,
      "maxExtent": 0,
      "minExtent": 0,
      "ticks": false,
      "zindex": 0
    },
    {
      "scale": "y",
      "orient": "left",
      "gridScale": "x",
      "grid": true,
      "tickCount": {"signal": "ceil(height/40)"},
      "domain": false,
      "labels": false,
      "maxExtent": 0,
      "minExtent": 0,
      "ticks": false,
      "zindex": 0
    },
    {
      "scale": "x",
      "orient": "bottom",
      "grid": false,
      "title": "date (month)",
      "labelFlush": true,
      "labelOverlap": true,
      "encode": {
        "labels": {
          "update": {"text": {"signal": "timeFormat(datum.value, '%b')"}}
        }
      },
      "zindex": 0
    },
    {
      "scale": "y",
      "orient": "left",
      "grid": false,
      "title": "Mean of precipitation",
      "labelOverlap": true,
      "tickCount": {"signal": "ceil(height/40)"},
      "zindex": 0
    }
  ],
  "config": {"background": "white"}
}
</code>


Procmail variable to command

Question: Maybe stupid question, but I can't find it anywhere. I have a variable in procmail (eg $SUBJECT) and I need to push it to some shell command. Something like:

# in /etc/procmailrc
SUBJECT="^(XX-)?Subject: ?"

# in user defined procmailrc file
FORMAIL=/usr/bin/formail
:0 fhw
| ${FORMAIL} -A 'X-Subject-Is: $SUBJECT'

But it save me a header X-Subject-Is: $SUBJECT, not with Subject line.. Is there any way, how to push variable to shell command?
Answer: The command is subject to the regular shell variable replacement rules, so just try replacing the single quotes with double quotes.
| ${FORMAIL} -A "X-Subject-Is: $SUBJECT"

Procmail variable to command


Fix div position with a responsive width after scrolling

Question: My goal is to show a div as position fixed after certain scrolling and display the div element with a responsive width.
In the example below the script works, but I would like to have the same width (responsive) as the orange elements.
.fixed {
  position: fixed;
  top: 0px;
  z-index': 10000;
}

Example
Comment: If you fix the typo in your CSS (the extraneous `'`) then the code seems to do what you need
Comment: here: `z-index': 10000;`
Answer: Fix the typo at z-index and increase the width to 420px;
.fixed {
  position:fixed;
  top: 0px;
  z-index: 10000;
  width: 420px;
 }

Demo : http://jsfiddle.net/y5fo1emc/33/
Answer: I couldn't find a CSS solution for the responsive width. RahulB's answer works but only using a fixed width. Here's a responsive JS solution, adding a function on window resize:
function resizeFixed() {
    var orWidth = $('.wrapper .group .span_4_of_4').width();
    $('.fixed').css('width', orWidth);
}

Demo: http://jsfiddle.net/Treeindev/4k93t136/1/
Comment: Thanks to all of you for the help. Treeindev solution solved my responsive issue.
Answer: Try this

 I will be fixed after scrolling

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

    $(document).ready(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.box-inner').addClass('fixed');
        } else {
           $('.box-inner').removeClass('fixed');
        }
    });
});

live demo - http://jsfiddle.net/grinmax_/y5fo1emc/37/


What's the proper way to handle error result in promise object?

Question: Say there's a promise object:
return new Promise((resolve, reject) => {
            request.post(options, (err, res, body) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(body);
                }
            });
        });

There's an error property in the callback, I can use reject() to handle it. But with the body, I can get either {ok: 1} or {ok: -1}. So how should I handle this error result?
I think I can just resolve() the body, and check the result in then(). Or I should check the result immediately and put the bad result into reject()?
Answer: In my experience, you probably don't need to pass on the body as such, but rather the interpretation of whether the command succeeded or not. So try this
return new Promise((resolve, reject) => {
            request.post(options, (err, res, body) => {
                if(err) {
                    return reject(err);
                }
                if (body.ok == -1) return reject('bad news');

                return resolve('good news');

            });
        });

and then you use this as:
funcAboveThatReturnsPromise()
.then( () => res.sendStatus(200).end() )
.catch( err => res.sendStatus(500).send(err) )

Comment: Thanks. And if I need to send response to browser, with the error message should I send it with `status(200)` or `status(500)`? Could you give me some advices?
Comment: You should ideally ask a new question for this, but I have updated my answer
Answer: An error in your body should be considered what it is - an error -, and thus reject. Although ideally the server should return an error status code.Here's what I would do if you can't modify the server:
return new Promise((resolve, reject) => {
        request.post(options, (err, res, body) => {
            if(err) {
                reject(err);
            } else if (body.ok === -1) {
                reject(new Error('error'));
            else {
                resolve(body);
            }
        });
    });

Comment: Oh yes, the server does return an error code and a error message. I just use ok as a sample. Thanks
Comment: Thanks. And if I need to send response to browser, with the error message should I send it with `status(200)` or `status(500)`? Could you give me some advices?
Comment: Error codes have a meaning. Send a 400 if a parameter is missing, 404 if the resource is not found, 403 if user needs special (e.g. admin) rights, etc. Browse this list and pick the one most appropriate for each case: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes


How to backup File system

Question: I used sudo rm -r /etc/apt and my apt folder in file system got deleted because of which i am not able even to use Internet in terminal also.can any body suggest me how to back up my apt folder in file system
Answer: Little late to run backups now. Generally you should be backing up your important data before you destroy it.
I would suggest, in the following order:

reinstall
copy /etc/apt from an identically-configured machine
debootstrap a debian install into a directory somewhere, install the necessary packages (check your package manager log for clues), then copy back /etc/apt
Answer: I am a bit confused as to why you would be unable to use the Internet in your terminal - /etc/apt/ (essentially) only governs how you retrieve new Debian packages.
Can you still do a 'ping www.google.com' from the command line? If that does not work, you have issues that go beyond a lost /etc/apt/
You should be able to recreate a working /etc/apt relatively easily - the only thing that you can't live without is /etc/apt/sources.list.
There are also two directories that apt requires, but they can be empty.
Try the following:
mkdir -p /etc/apt/apt.conf.d/
mkdir -p /etc/apt/sources.list.d/
echo 'deb http://ftp.us.debian.org/debian/ stable main' > /etc/apt/sources.list

In the last line, change 'stable' to whatever you are using, and add 'non-free' and/or 'contrib' at the end of the line, if needed.
Then do an apt-get update, and you should be back in business.
You'll still have to add any extra repositories you had in your sources.list, and and deb-src line corresponding to the  deb line, but the basics should be covered.
Good luck!

How to backup File system


Create an image of a CentOS system

Question: I provide a server (and site) to a client via Rackspace Cloud Hosting, and my client wants to now host the entire thing within his own account.
Since it's not possible to just transfer the ownership, I need to somehow create an image of the machine via SSH which I can then use on a new server.
Is this possible, and does anyone know of a way of doing this.
Note
I am talking about virtualised machines here, but I only have access to the virtualised partition and not the system as a whole.
Answer: You should be able to use the snapshot facility to produce the image, and then issue a request to rackspace to re-assign the snapshot to another account.
I would advise you query this within a ticket first.
Failing that you could spin an image using the same OS (CentOS6 based on you tag) and use rsync to copy files across the servicenet connection as it does not incur band width charges.
Answer: See https://serverfault.com/a/367844/113375
This will work perfectly for you ...
On the source VM instance ...
sudo su
cd /
tar cvpzf backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/backup.tgz --exclude=/mnt --exclude=/sys /

On the target machine (dedicated or VPS)
tar xvpfz backup.tgz -C /

And make sure any dirs excluded are re-created
mkdir proc
mkdir lost+found
mkdir mnt
mkdir sys

Comment: Yeah, there is no reason why this should not work... And stop all processed except SSHD before this and you'll be fine. After this, reboot the machine and this is it.
Answer: Uhhh... The best is to ask support first or just rise ticket and open chat so they might help.
If not, as I know this myself, you would need to write yourself a script, which would transfer the image between two cloud files accounts, and you would need to use a cloud files api for this. Snapshots are saves in cloud files.
This would help:
http://www.rackspace.com/knowledge_center/content/cloud-files-uploading-large-files
You can use pay as you go temp server the way that you download the image to it first (so it's bigger), then upload with segmenting to another cloud files account.
But, this is very likely not to work for security reasons. I read once that you cant copy image in the same datacentre, but form UK to US that would work.

Create an image of a CentOS system


Removing last character of JSON object

Question: I'm looking for a way to remove the last character of a line of JSON, provided it's not a curly brace.
I've a whole file of JSON but for some reason some of the lines end with a few spaces and then a 0. I'm trying to remove the 0 if it appears, or skip that line if it doesn't.
For example: Ignore this:
{"menu": {
  "id": "file",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
    ]
  }
}}

And remove the 0 from this:
{"menu": {
  "id": "file",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
    ]
  }
}} 0

I've tried using:
line = line.rstrip('0')

But it doesn't seem to be doing anything.
Comment: By "line", do you really mean a line of text? For example, could there be a `0` after `"file",`? And what happens if the JSON is formatted in a weird way, so there's a `0` at the end of a line, but the `0` is actually part of the JSON?
Answer: You can use regular expressions:
import re
re.sub(r'0$', '', line)

Comment: Never ceases to amaze me how quickly you can get answers on here. Thanks, works perfectly.
Answer: Ok, it does not work, because you have the last character is not 0 but \n or \r\n.
So, you need
line = line.rstrip().rstrip('0')

Removing last character of JSON object


How to limit ssm documents accessible by a iam role for start automation using tags?

Question: I have a iam role which has access to start automation. I want to limit the documents it can access by using tags.
I have added this policy but it's not working.
<code>    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ssm:StartAutomationExecution"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Deny",
            "Action": "ssm:StartAutomationExecution",
            "Resource": [
                "arn:aws:ssm:*:*:document/*",
                "arn:aws:ssm:*:*:automation-definition/*:$DEFAULT"
            ],
            "Condition": {
                "StringNotEquals": {
                    "ssm:resourceTag/Role": "${aws:PrincipalTag/Role}"
                }
            }
        }
    ]
}```

</code>
Answer: This condition is not supported for the StartAutomationExecution operation.
See https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awssystemsmanager.html


How do I properly remove "Powered By Drupal"?

Question: How do I remove the "Powered By Drupal" string that is displayed on the site footer?

Does it involve PHP coding?
Answer: Use this technique
go to yoursite/admin/structure/block
you will see the "Powered by Drupal" as a block

Choose - None - it will go away and you can create your own block with your own footer information
Answer: Unset the "Powered by" block from the block admin (admin/structure/block). If the theme has hard-coded this, you'll have to remove it from the appropriate template.
Comment: Normally, that is a standard block Drupal core defines, but it could be as well hard-coded in a theme template, so +1 for mentioning that.
Answer: It is just like any other block on your website:
1) Hover over it, you will find a small settings icon will appear.
2) click on that and then configure block.
3) it will take you to the configuration page of that block.
4) from here you disable the block by change its region to none.
5) Save your block. Voila!
Comment: This requires the Contextual Links module to be enabled, which may not be the case depending on the profile chosen during install.


db_select get value of the field

Question: I have order form with field reference number. when a new order is submitted i need to get the last reference number. I did something similar long time ago in Drupal 7 but now i need to do it in Drupal 8 and i don't know how. I noticed that fields in database are written as 'node__field_ref_number'
DRUPAL 7
$query = db_select('field_data_field_order_reference_number', 'f');
$query->condition('f.bundle', 'order', '=');
$query->fields('f', array('field_order_reference_number_value'));
$query->orderby('field_order_reference_number_value','DESC');
$query->range(0, 1);
$query->execute();
$result = $query->execute();
$record = $result->fetchAssoc();
//drupal_set_message('previous order №: ' .print_r($record['field_order_reference_number_value'], true));
$title =($record['field_order_reference_number_value']) + 1;
//drupal_set_message('order №: ' .print_r($title, true));
$form_state['node']->field_order_reference_number['und'][0]['value'] = $title;
$form_state['node']->title= 'reference number ' .$title;

So far i can get only nid of nods of that type (content_type_order)
DRUPAL 8
$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'content_type_order');
$results = $query->execute()->fetchAll();
drupal_set_message('value' .print_r($results, true));

Comment: Take a look to this question
 [Help with database query](https://drupal.stackexchange.com/questions/266956/help-with-database-query/266961#266961)  it may give you a clue how you can do it.
Answer: If I understood correctly, this snippet would get you the number:
use Drupal\Core\Database\Database;

$query = \Drupal::database()->select('node__field_order_reference_number', 'f');
$query->fields('f', ['field_order_reference_number_value']);
$query->orderBy("revision_id", 'DESC');
$query->range(0, 1);
$last_order_reference_number = $query->execute()->fetchCol()[0];

If you need to further understand the database schema related to your field, you could try these commands:
mysql> show tables like '%order_reference_number%';
+----------------------------------------------+
| Tables_in_drupal8 (%order_reference_number%) |
+----------------------------------------------+
| node__field_order_reference_number           |
| node_revision__field_order_reference_number  |
+----------------------------------------------+
2 rows in set (0.00 sec)

mysql> describe node__field_order_reference_number;
+------------------------------------+------------------+------+-----+---------+-------+
| Field                              | Type             | Null | Key | Default | Extra |
+------------------------------------+------------------+------+-----+---------+-------+
| bundle                             | varchar(128)     | NO   | MUL |         |       |
| deleted                            | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                          | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                        | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                           | varchar(32)      | NO   | PRI |         |       |
| delta                              | int(10) unsigned | NO   | PRI | NULL    |       |
| field_order_reference_number_value | varchar(255)     | NO   |     | NULL    |       |
+------------------------------------+------------------+------+-----+---------+-------+
7 rows in set (0.23 sec)

mysql> select * from  node__field_order_reference_number;
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | field_order_reference_number_value |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| page   |       0 |        17 |          28 | en       |     0 | 123                                |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
1 row in set (0.00 sec)

Answer: you can try
$query = \Drupal::database()->select('node_field_data', 'n');
$query->fields('n', array('nid', 'title'));
....

or you can try with Drupal::entityTypeManage
$entity = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
$entity ->condition('type','node_type');
$nids = $entity->execute();

db_select get value of the field