text:
Q: Opencv munmap error I am trying to implement the following code:
#coding=utf8

from opencv.cv import *
from opencv.highgui import *

# Avame kaamera
capture = cvCreateCameraCapture(0)

while True:
    frame = cvQueryFrame(capture)
    cvShowImage("Aken", frame)
    char = cvWaitKey(33)

but I am getting some kind of a munmap error. Can anyone point me to the direction of the problem that might be occurring in my coding?

mmap: Invalid argument
  munmap: Invalid argument
  munmap: Invalid argument
  munmap: Invalid argument
  munmap: Invalid argument
  Unable to stop the stream.: Bad file descriptor
  munmap: Invalid argument
  munmap: Invalid argument
  munmap: Invalid argument
  munmap: Invalid argument
(Aken:2782): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap",
(Aken:2782): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap",
(Aken:2782): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap",
(Aken:2782): Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap",

A: Can you try this code with the newer interface so you don't have to worry about release and possibly other details? I'm assuming you have a new enough version to use cv2. The code below is from another SO answer I made.
import cv2

capture = cv2.VideoCapture()
cv2.namedWindow("Aken",1)
capture.open(0)
while True:
    frame = capture.read()[1]
    cv2.imshow("Aken", frame)
    if cv2.waitKey(30) == 27: break #`escape` key to stop capture
cv2.destroyWindow("Aken")

A: The capture procedure could have failed, so it's a good practice to check the return of the call:
capture = cvCreateCameraCapture(0)
if not capture :
    print "Error loading camera"
    # Should exit the application


text:
Q: Unpacking a Maybe on Lists describing Deltas (and is it a Good Idea in the First Place?) As a newcomer to Haskell I'm reading StackOverflow top rated questions, new questions, etc. and today there was this one:
Haskell: min distance between neighbor numbers on a list
I thought "well, I'll try that without looking at the answers".  For starters, I wrote:
neighborsDistance [] = []
neighborsDistance [a] = []
neighborsDistance (x:y:xs) = abs (x - y) : neighborsDistance (y:xs)

Then I could do minimum neighborsDistance [2,3,6,2,0,1,9,8] => 1.
But I didn't much care for how the edge cases worked, so I thought perhaps I'd try using Maybe.  I'd need a way to adapt the recursive rule to tolerate a "maybe" value so I looked on Hoogle at Data.Maybe and found fromMaybe...which looked like it did what I wanted:
neighborsDistance [] = Nothing
neighborsDistance [a] = Just []
neighborsDistance (x:y:xs) = Just (abs (x - y) : fromMaybe [] neighborsDistance (y:xs))

But that gave me a not in scope: fromMaybe error.  Main question would be "why didn't that work?"
Another question is just generally about Haskell mindsets when looking at something like this.  Is this a bad use of Maybe?  Why does head throw an exception when called on an empty list vs return a Maybe type?
The question I got the problem from was trying to unify distance calculation with the minimum operation.  I'm assuming that you can break it out like this without losing significant efficiency (such that it will compose with minimum, or maximum, or whatever)?

A:
But that gave me a not in scope: fromMaybe error. Main question would be "why didn't that work?"

You need to import Data.Maybe (fromMaybe) at the top of your file.
The Prelude itself does do an import Data.Maybe to get the definitions of Maybe, Just, and Nothing.  But it does the import inside a module 'where' clause, and exports only those three definitions.  So the less common functions have to be manually imported.

Is this a bad use of Maybe? Why does head throw an exception when called on an empty list vs return a Maybe type?

Usage of head is generally regarded as non-ideal. The Safe package provides headMay, which does return a Maybe.
On the other hand, I think returning a Maybe [Int] is unnecessary here. The empty list already encodes the idea of there being no valid result. In fact, it's used commonly enough as a Maybe that we have maybeToList and listToMaybe. Wrapping it in a Maybe means you need to spend more effort 'unwrapping' the value.

I'm assuming that you can break it out like this without losing significant efficiency (such that it will compose with minimum, or maximum, or whatever)?

In most cases, yes. Haskell has short-cut fusion.

A: You main question can be answered in one line, you are probably missing:
import Data.Maybe

But why the whole stress with using a Maybe value? Because this problem has a clear answer for any list of length >= 2, you do not need to use a maybe type. A maybe type is generally only used when it is not sure whether the function will return a result or not, such as in this case.

Another question is just generally about Haskell mindsets when looking at something like this. Is this a bad use of Maybe? Why does head throw an exception when called on an empty list vs return a Maybe type?

Think about it: If you had a safe head which is implemented as the listToMaybe function in the Data.Maybe package, you would have to handle the empty case too which is not what head is intended to do (which is extract the first element of a list).
For further information about head and empty lists, you should look here as it already has been discussed.

I'm assuming that you can break it out like this without losing significant efficiency (such that it will compose with minimum, or maximum, or whatever)?

Yes you can do that in Haskell, its pretty neat. As a hint: the ($) and (.) operators are you best friends regarding this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluating Fourier coefficients to complete a Laplace equation solution While solving a PDE problem involving the Laplace equation in 3D, I arrive at the following summation relation when i substitute the only non-homogeneous boundary condition available
$$
\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}A_{n,m}\cos(\frac{n\pi x}{L})\cos(\frac{m\pi y}{l})\sqrt{\frac{n^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}\sinh\bigg(w\sqrt{\frac{n^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}\bigg) = p_h\bigg(\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}A_{n,m}\cos(\frac{m\pi y}{l})\cos(\frac{n\pi x}{L})\cosh\bigg(w\sqrt{\frac{n^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}\bigg) - \sum_{m=1}^{\infty}\sum_{n=1}^{\infty} \frac{A_{n,m}b_h}{b_h^2 + n^2 \pi^2 }\cos(\frac{m\pi y}{l})\cosh\bigg(w\sqrt{\frac{n^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}\bigg)\bigg[b_h\cos(\frac{n\pi x}{L}) + n\pi\sin(\frac{n\pi x}{L}) \bigg]\bigg)
$$
I need to find the Fourier coefficients here, denoted by $A_{n,m}$.
Known
As a starting point i know that if $\cos(\frac{m\pi x}{L})$ and $\cos(\frac{n\pi y}{l})$ is multiplied on the RHS and LHS of the whole equation i could use the known orthogonality of
$\int_{0}^{L} \cos(\frac{n\pi x}{L})\cos(\frac{m\pi y}{L})$ and $\int_{0}^{L} \cos(\frac{n\pi x}{l})\cos(\frac{m\pi y}{l})$
But the problem is, I will get a term like $\int_{0}^{L} \cos(\frac{m\pi x}{L})\sin(\frac{n\pi x}{L})$.
I do not know what to do with this term. Additionally, I have another doubt as to how the $A_{n,m}$ occurring on both sides of the equation are to be handled. Also, I have done 2D problems but how to handle this 3D case ? Is a double integration required ?
Note
The question asked has its origin as follows:-
From a solution of the form
$$
        T(x,y,z)=\sum_{m=1}^{\infty}\sum_{n=1}^{\infty}A_{n,m}\cos(\frac{n\pi x}{L})\cos(\frac{m\pi y}{l})\cosh\left(\sqrt{\frac{n^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}z\right).
$$
with bc(s) as:
$\frac{\partial T(0,y,z)}{\partial x}=\frac{\partial T(L,y,z)}{\partial x}=0 $
$\frac{\partial T(x,0,z)}{\partial y}=\frac{\partial T(x,l,z)}{\partial y}=0$
$$\frac{\partial T(x,y,-w)}{\partial z}=p_h\bigg( T(x,y,-w) -  \frac{e^\frac{-b_h x}{L}b_h}{L}\int e^\frac{b_h x}{L}T\mathrm{d}x \bigg) $$
$
\frac{\partial T(x,y,0)}{\partial z} = 0.
$
Extra information
From the physical problem available at hand the following is too known:-
$$\frac{\partial T(0,y,-w)}{\partial z}=p_h\bigg( T(0,y,-w) -  T_i\bigg) $$

Attempt
Multiplying both sides by $\cos(\frac{k\pi x}{L})$ and $\cos(\frac{j\pi y}{l})$  assuming that the series converges, converting the summation to an integration, first for $x$ and then for $y$, followed by using orthogonality.
$$
\sum\sum A_{n,m}\sqrt{()}\sinh(w\sqrt{()})\bigg(\frac{L}{2} \vee n=k\bigg)\bigg(\frac{l}{2} \vee m=j\bigg) = p_h\bigg[\sum\sum A_{n,m}\cosh(w\sqrt{()})\bigg(\frac{L}{2} \vee n=k\bigg)\bigg(\frac{l}{2} \vee m=j\bigg)- \sum\sum\frac{A_{n,m}b_h^2}{b_h^2 + n^2 \pi^2}\cosh(w\sqrt{()})\bigg(\frac{L}{2} \vee n=k\bigg)\bigg(\frac{l}{2} \vee m=j\bigg)\bigg]
$$
leads to
$$
A_{k,j}\sqrt{()}\sinh(w\sqrt{()})\bigg(\frac{L}{2}\bigg)\bigg(\frac{l}{2} \bigg) = p_h\bigg[A_{k,j}\cosh(w\sqrt{()})\bigg(\frac{L}{2}\bigg)\bigg(\frac{l}{2}\bigg)-\frac{A_{k,j}b_h^2}{b_h^2 + n^2 \pi^2}\cosh(w\sqrt{()})\bigg(\frac{L}{2}\bigg)\bigg(\frac{l}{2}\bigg)\bigg]
$$
Hence, $A_{k,j}$ needs to be evaluated. But still I have the problem of $A_{k,j}$ cancelling out from the resulting equation.

A: I admit that I had failed to check this at the start: you have $A_{m,n}$ on both sides. One solution to your original equation is just $A_{m,n} = 0$ for all $m,n$. And in fact, that is the only solution.
To see this, multiply by $\sin\left(\frac{k\pi x}L\right)$ and take the $\int_0^{2L}\ \ dx$ integral of both sides (note the $2L$ - you have to integrate over a full period, and that is $2L$, not $L$). Every term with $\cos\left(\frac{n\pi x}L\right)$ in it becomes $0$. And the only $\sin\left(\frac{n\pi x}L\right)$ term that survives is $n = k$. Now, $\int_0^{2L}\sin^2\left(\frac{k\pi x}L\right)\,dx = L$, so the result is
$$0 = -p_h\left[\sum_{m=1}^{\infty}\frac{A_{k,m}b_h}{b_h^2 + k^2 \pi^2 }\cos(\frac{m\pi y}{l})\cosh\left(w\sqrt{\frac{k^2\pi^2}{L^2}+\frac{m^2\pi^2}{l^2}}\right)k\pi L \right]$$
Then we multiply through by $\cos\left(\frac{j\pi y}l\right)$ and take the $\int_0^{2l}\ \ dy$ integral, which similarly leaves us with
$$0 =-p_h\left[\frac{A_{k,j}b_h}{b_h^2 + k^2 \pi^2 }l\cosh\left(w\sqrt{\frac{k^2\pi^2}{L^2}+\frac{j^2\pi^2}{l^2}}\right)k\pi L \right]$$
$\cosh$ is never $0$. If we assume that $p_h, b_h, L$, and $l$ are all non-zero, this solves to $A_{k,j} = 0$.
Either you have an error in deriving the equation posted, or else your solution is $0$.


text:
Q: What is the point of heightmaps? I've been pondering this question awhile now... many 3d engines support advanced terrain rendering using quadtrees, LOD... all the features you expect. But every engine I've seen loads height data from heightmaps... grayscale bitmaps. I just can't understand how this is useful - each point in a heightmap can have one of 256 values. But what if you wanted to model Mt. Everest? with detail of 1 meter, or even greater? That's far outside the range of 256. Of course I understand that you can implement your own terrain format to achieve this, but I just can't see why heightmaps are so widely used despite their great limitations.

A: Heightmaps are very lightweight, very fast to load, and can be generated procedurally fairly easily.  They also use quite a small footprint for memory.
They're used a lot because they're easy and fast, and handle many scenarios well.  That being said, they're not useful for every scenario, and not a fully generalized terrain format.

A: From a viewpoint of displaying graphics, the greatest precision that normally matters is (in simple terms) a single pixel in the final display1. Given the resolution of a typical current monitor, having another couple or three bits for the height map would be nice -- but for most geometry, it's not really necessary. In particular, even though a single pixel pretty much defines the greatest precision for which you have a lot of use, drawing Mt. Everest so its height is actually wrong by two or three pixels isn't really a major problem for most people most of the time.
It comes down to this: the idea that you'd want to use a precision of one meter for a height map of Mt. Everest is simply a mistake -- a need (or even use) for that level of precision is right on the border between rare and nonexistent. At the same time, using a relatively dense format like one byte per pixel generally means quite a bit -- less storage and less bandwidth leading to faster displays.

*

*Technically with anti-aliasing, sub-pixel resolution can and does mean something -- but while it matters a lot for things like smoothing lines that would otherwise look quite jagged, for something like getting the height of a mountain correct, it doesn't mean nearly so much. In fact, as far as most people care most of the time, it's completely meaningless.

A: Heightmap Pros:

*

*Look like real terrain from a distance.

*Very easy to compute height at any x, y assuming z is up. This is useful for moving players, collision detection, and physics.

*Easy to edit in a paint program.

Heightmap Cons:

*

*Use memory inefficiently when there are large flat areas (constant height).

*Use rendering hardware inefficiently when there are large flat areas.

*Can't represent steep or overhanging terrains.

*Can only represent square areas.

A:
But what if you wanted to model Mt. Everest?

You'd use something else. Clearly, if every engine you've encountered uses heightmaps, it works just fine for them. No need to overcomplicate things if the simple solution works for you.

A: Another plus with heightmaps is that in general it avoids the overhang issue which makes aspects of physics and movement harder.  But even with a hightmap, you can have other geometry that could create overhangs.
Also, texturing can be simpler as long as the height doesn't vary too much causing stretching.

A: Heightmaps have the advantage that has direct hardware support (texturing), and it can be draw using existing painting tools (even specialized).
Of course, depending on the format of the information stored in the heightmap, some rendering doesn't looks like it should be, but because heightmaps are actually used in the wrong situation.
As enhancement, heightmap pixels could be stored in a 16 bit floating number (half float) or a 32 bit float, allowing to have higher ranges and precision allowed with an 8 bit pixel with fixed precision.


text:
Q: use a usb docking station over powerline I have a computer in a room away from my living room and I was thinking is it possible to for example use a docking station such as this (which has these inputs : HDMI, DVI, USB, VGA,....) which combines all these inputs into a usb and then use powerlines to connect that into my computer. My final goal is to have usb/ethernet/hdmi all from my PC connected to my living room via powerlines.
dockinng station :
http://www.amazon.com/Plugable-UD-3900-Universal-2048x1152-Ethernet/dp/B00ECDM78E/ref=lp_778660_1_1?s=pc&ie=UTF8&qid=1398981745&sr=1-1
and connect the output usb to a powerline usb connector such as (or better brands with usb 2.0)
http://www.amazon.com/NETGEAR-Powerline-200Mbps-PassThru-Adapter/dp/B009WG6LLA/ref=sr_1_3?s=electronics&ie=UTF8&qid=1398983611&sr=1-3&keywords=powerline+usb
So I can use it to attach keyboard, mouse and also use hdmi tv to it?
-There are also more powerline adaptors with 2 or 3 ethernets rather than usb ports. Is it possible for example to use a usb hub and then usb to ethernet convertor and then plug it into powerline adaptor and then get those usbs back at my computer.
thanks

A: No, thats not really how this works. The USB port is meant for running a small subset of 'local' devices from the powerline networking device. This is closer to the storage/printer USB ports on a router, than a USB over IP device (which is essentially what you're looking at). It does not do 'true' usb over IP - it simply runs the device locally and shares it out.
You could plug in a USB over IP device to a regular, cheaper homeplug device and use that the way you are expecting this to work


text:
Q: Javascript email validation is not working even though the email is valid I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this

    <form class="forms" id="login-form" onsubmit="return false" novalidate>

Log In

            Your Email:
            <input type="email" id="email" name="email" required>

        <button class="wide-buttons" type="submit">Log In</button>

Need an account? Click here to sign up!

      </form>
      <form class="forms" id="register-form" onsubmit="return false" novalidate>

Register

            Your Email:
            <input type="email" id="register-email" name="register-email" required>

        <button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>

Already have an account? Click here to log in!

      </form>

Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.

A: It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
  regEmailError.textContent = "You must enter a valid email address";
}

To:
const registerEmail = document.getElementById('register-email');

if (!registerEmail.validity.valid) {
  regEmailError.textContent = "You must enter a valid email address";
}

and it should be ok
Edit1: Ofc you can declare registerEmail above event listener


text:
Q: Cleanup small commits on master branch Git time! My master branch goes trashy last time. I overslept and didn't create a branch for my minor fixes and made some commits. I have this:
(R1)<---(R2)<---(c1)<---(c2)<---(c3)             master
 Rx - releases
 cX - some fixes

I would like to have something like this on separate branch:
(R1)<---(R2)                                     master
          \
           \<---(c1)<---(c2)<---(c3)             last-fixes

And next merge this to master with --no-ff:
(R1)<---(R2)<-------------------------(R3)       master
          \                          /
           \<---(c1)<---(c2)<---(c3)/            last-fixes

How to make this in simple steps?

A: You can make a new branch at your current position, reset master to a previous commit, and then merge it with --no-ff
git branch last-fixes
git reset R2 --hard
git merge last-fixes --no-ff

A: First, make sure you are on the branch master.
git checkout master

Then create a branch for your fixes
git branch last-fixes

Now reset master to where it should be
git reset --hard <R2>

And you can merge your merges
git merge --no-ff last-fixes


text:
Q: Percentage calculation JS I'm trying to get the percentage of a total, which is the sum of 3 different fields.
In practice, the calculation should be: var p_carb = (carb * 4) / (kcaltot); but kcaltot is not detected like the other variables, so I cannot perform the calculation.
I am a fan and not a pro, I don't know JS very well, can anyone give me directions on how to perform this calculation?
I should get the percentage of the Kcal fields.
Thanks everyone for any answers.

calculate = function() {
  var carb = document.getElementById('carb').value;
  var pro = document.getElementById('pro').value;
  var fat = document.getElementById('fat').value;

  //Kcal Macro
  var kcal_carb = (carb * 4);
  document.getElementById('kcal_carb').value = kcal_carb.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " Kcal";

  var kcal_pro = (pro * 4);
  document.getElementById('kcal_pro').value = kcal_pro.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " Kcal";

  var kcal_fat = (fat * 9);
  document.getElementById('kcal_fat').value = kcal_fat.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " Kcal";

  //Kcal Percentage
  var p_carb = (carb * 4) / (kcaltot);
  document.getElementById('p_carb').value = p_carb.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " %";

  var p_pro = (pro * 4) / (kcaltot);
  document.getElementById('p_pro').value = p_pro.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " %";

  var p_fat = (fat * 9) / (kcaltot);
  document.getElementById('p_fat').value = p_fat.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " %";

  //Kcal Totali
  var kcaltot = (4 * carb) + (4 * pro) + (9 * fat);
  document.getElementById('kcaltot').value = kcaltot.toLocaleString('it-IT', {
    maximumFractionDigits: 0
  }) + " Kcal/day";

}
```

Carbs

Pro

Fat

  <input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="m_field" maxlength="3" id="carb" name "pro" placeholder="150g" form="macro" onchange="calculate()" required/>

  <input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="m_field" maxlength="3" id="pro" name "pro" placeholder="150g" form="macro" onchange="calculate()" required/>

  <input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="m_field" maxlength="3" id="fat" name "pro" placeholder="150g" form="macro" onchange="calculate()" required/>

  <input type="text" class="m_field" id="kcal_carb" name="kcal_carb" placeholder="0 Kcal" min="1" form="macro" readonly/>

  <input type="text" class="m_field" id="kcal_pro" name="kcal_pro" placeholder="0 Kcal" min="1" form="macro" readonly/>

  <input type="text" class="m_field" id="kcal_fat" name="kcal_fat" placeholder="0 Kcal" min="1" form="macro" readonly/>

  <input type="text" class="m_field" id="p_carb" name="p_carb" placeholder="0 %" min="1" form="macro" readonly/>

  <input type="text" class="m_field" id="p_pro" name="p_pro" placeholder="0 %" min="1" form="macro" readonly/>

  <input type="text" class="m_field" id="p_fat" name="p_fat" placeholder="0 %" min="1" form="macro" readonly/>

  <input type="text" class="kcal_res" id="kcaltot" name="kcal_res" placeholder="0.000 Kcal/Day" min="1" form="macro" readonly/>
  Kcal total

<form action="" id="macro">
</form>

https://jsfiddle.net/snake93/zcdq2vx9/78/

A: I think this will solve your problem. First you have to move the code where you define the variable "kcaltot" to be above/before the lines where you actually use it.
Secondly you have to multiply the percentage by 100 to go from decimal to percent. For example 0.2 to 20%.
//Kcal Totali
var kcaltot = (4*carb) + (4*pro) + (9*fat); // Define the variable before you use it!
document.getElementById('kcaltot').value = kcaltot.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal/day";

//Kcal Percentage
var p_carb = (carb*4)/(kcaltot) * 100; // <-- Multiply by 100 to go from decimal to percent!
document.getElementById('p_carb').value = p_carb.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " %";

var p_pro = (pro*4)/(kcaltot) * 100; // <-- Multiply by 100 to go from decimal to percent!
document.getElementById('p_pro').value = p_pro.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " %";

var p_fat = (fat*9)/(kcaltot) * 100; // <-- Multiply by 100 to go from decimal to percent!
document.getElementById('p_fat').value = p_fat.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " %";


text:
Q: How to edit a shared component from parent's HTML in angular 6 child.component.ts
//ignoring all imports

@component({
   selector: 'app-child',
   template: './child.component.html'
})

import class ChildComponent {

   //logic not of use

   public isData: boolean = false;
}

child.component.html
<input type="text" value="xyz" [readonly]="isData">

parent.component.ts
//ignoring all imports

parent.component.html
<app-child></app-child>

Here, I wanted to use the child component inside parent but I don't want the input field readonly, rather changing it inside child I want to change it inside parent so that my child component should not gets disturbed.
How would I achieve it?

A: You should provide some parameter in child component which turn on/off read only property - e.g.
child.component.html
<input type="text" value="xyz" [readonly]="isData || onlyForRead">

child.component.ts
@Input('onlyForRead') onlyForRead: boolean;

parent.component.html
<app-child [onlyForRead]='false'></app-child>

A: You can query (get references) to all child components nested in the parent by using
@ViewChildren(ChildComponent) dataItems: QueryList<ChildComponent>

or get reference to only 1:
@ViewChild(ChildComponent) dataItem: ChildComponent;

Then you can subscribe and control the sate of each individual component from parent:
this.dataItem.isData = true // or false.

A: You can achieve with few simple steps:
In Child-Component.ts file:
import {Input} from '@angular/core';

@Input('isData') isData;

In parent-Component.html file:
<app-child isData="true"></app-child>


text:
Q: symfony twig batch reference to array error I use the following twig to generate items per row
{% for row in products|batch(3, 'No item') %}

        {% for product in row %}

        {% endfor %}

{% endfor %}

inside of row loop where I output details about product I have referencies to functions where I pass the product array like

but this code does not work if I use batch I get the following error
getProductUrl() must be of the type array, string given

A: 1 - You can't use a function in twig unless you define it in a custom twig extension Doc Here.
2 - If the url is one from your route, you should use path function from Twig.
3 - Else, If your custom method (productUrl) is defined in Product entity, Make sure variable product inside the loop is an instance of Product class. You can access to the method as product.productUrl.
Let us know if you need something else.


text:
Q: django: how to display ManyToManyField in html file? I want to display ManyToManyField in Django in html page.
This code is in the models.py file:
class Keyword(models.Model):
    keyword     = models.CharField(max_length=20, null=True)
    rank        = models.IntegerField(null=False)
    dateCreated = models.DateField(auto_now_add=True)

    def __str__(self):
        return '#' + self.keyword

class Article(models.Model):
    CATEGORY = (
        ('programming', 'programming'),
        ('language', 'language'),
        ('other', 'other')
    )

    title       = models.CharField(max_length=200, null=False)
    image       = models.ImageField(null=True)
    content     = models.TextField(null=False)
    category    = models.CharField(max_length=45, null=False, choices=CATEGORY)
    dateCreated = models.DateField(auto_now_add=True)
    keyword     = models.ManyToManyField(Keyword)

    def __str__(self):
        return self.title

and in the views.py:
def articles(request):
    article = Article.objects.all()
    keyword = Keyword.objects.all()
    context = {
        'keyword': keyword,
        'article': article
    }
    return render(request, 'articles.html', context)

and in the html file:
{% for item in article %}

    {{item.id}}
    {{item.title}}
    {{item.image}}
    {{item.content}}
    {{item.category}}
    {% for key in item.keyword.all %}
    {{key}}
    {% endfor %}

{% endfor %}

But nothing is shown in the keyword section in the html output. what do I do?

A: {% for item in article %}

    {{item.id}}
    {{item.title}}
    {{item.image}}
    {{item.content}}
    {{item.category}}

         {% for key in article.keyword.all %}
          {{key}}
         {% endfor %}

{% endfor %}

A: try this
you have to pass a related name on your model
class Article(models.Model):
    CATEGORY = (
        ('programming', 'programming'),
        ('language', 'language'),
        ('other', 'other')
    )

    title       = models.CharField(max_length=200, null=False)
    image       = models.ImageField(null=True)
    content     = models.TextField(null=False)
    category    = models.CharField(max_length=45, null=False, choices=CATEGORY)
    dateCreated = models.DateField(auto_now_add=True)
    keyword     = models.ManyToManyField(Keyword, related_name='keyword')

    def __str__(self):
        return self.title


text:
Q: Corda Accounts - Ability to move an account to a different host node In the Corda accounts library, in order to change the host "ownership" of the account from one node to another, one would need to change the Host in the AccountInfo state to the new host (node), along with share all vault states relevant to this account.
AccountInfo doesn't have an Update command (AccountInfo commands), meaning you cannot change the host once it is created.

*

*Has this feature been excluded for any reason?  Are there any plans to introduce an Update command (with supporting flows)?

*What steps would be involved in a move/transfer (host ownership)? And what are the potential caveats around this implementation?

A: Amol there will be work done on this in the future but as of now, there are two options which could help you resolve your issue.

*

*Set up a new account on the new node. Generate new key(s) for the new account. Spend all the states from the old account to this new account.

*If you control the all the keys used to participate in your states and can migrate them to the new node then you just need to import the key pairs somehow and then copy all the states across from the old node to the new node.
Hope that helps.


text:
Q: Create a 3d numpy array whose entries increase in the given direction Given a shape (n,m,k) and a nonzero vector (u,v,w) with entries in {-1,0,1}, I would like to create a numpy array of shape (n,m,k). The entries of the array should start at 1 and increase in the direction of the vector.
Although I am specifically asking for 3d arrays, let me illustrate with 2d examples:
(n,m) = (3,4) and (u,v) = (-1,0) gives:

4 3 2 1
4 3 2 1
4 3 2 1

(n,m) = (4,3) and (u,v) = (1,-1) gives:

1 2 3
2 3 4
3 4 5
4 5 6

I can create them using nested for loops, but I am wondering if there is a faster solution since I will be working with larger arrays.

A: Here is a method using stride_tricks. Works for arbitrary number of dimensions.
from numpy.lib.stride_tricks import as_strided

def pp(dims,strides):
    dims,strides = np.asarray(dims),np.asarray(strides)
    aux = np.arange(1,(dims-1).sum()+2)
    return as_strided(aux[(dims-1)@(strides==-1):],dims,aux.strides*strides)

Examples:
>>> pp((2,3),(-1,0))
array([[2, 2, 2],
       [1, 1, 1]])
>>> pp((2,3,4),(-1,-1,-1))
array([[[7, 6, 5, 4],
        [6, 5, 4, 3],
        [5, 4, 3, 2]],

       [[6, 5, 4, 3],
        [5, 4, 3, 2],
        [4, 3, 2, 1]]])

Note that the convention for y-axis is it starts at top and goes down. If you want otherwise you'd have to flip it.
Also note that the arrays produced are non-contiguous views, if you want to modify them better make a copy.


text:
Q: Nivo Slider - Responsive/Centered Caption I've downloaded and implemented the Nivo Slider on my website. Since implementing it, I've found a few bugs, but I'm looking for help with getting my caption centered on the screen.
Margin:auto usually works for this to ensure a div is always centered (I think..) - but I can't get it to work with my site..
My HTML:
<!DOCTYPE html>

    <title>Max Klimmek - Portfolio, Clothing, Travel</title>
      <link rel="stylesheet" href="css/normalize.css">
      <link rel="stylesheet" href="css/style.css">
      <link rel="stylesheet" href="fonts/font-awesome-4.5.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" />

      <meta name="viewport" content="width=device-width">

Home

Portfolio

Clothing

Gallery

Resume

Simple.
 Clean.

My CSS for the caption:
    .nivo-caption1 {
    position: absolute;
    margin:auto;
    top: 5%;
    overflow:hidden;
    background:none;
    font-family: 'Gotham';
    color:#FFF;
    font-weight:bold;
    font-size:50px;
    line-height:44px;
    text-align:center;
    text-transform:uppercase; /* converts text to UPPERCASE */
}

If I remove the Margin-Top the caption doesn't even appear.. I've added margin:auto to all the other divs that contain this caption/slider.
Anyone got any ideas of how I could ensure the nivo-caption is always centered even when I resize the browser window?
Attached is a photo of how it looks now..
Any help would be great!
Thanks,
Maxenter image description here

A: The reason margin:auto isn't working for this particular case is two-fold.

*

*You need to have a width set.

*The caption is being positioned absolutely and this will override it. Even if you do set a width, it won't matter in this case.

It's ok to position it absolutely for the slider. I don't think it would work out too well if you didn't. All that needs to be done here is to set the left attribute on the caption so that it pushes the caption over to the center of the screen.
In order to do this you would need to calculate the difference between the width of the slider and the width of the caption and divide the result in half. This will give you the correct amount. It looks like the slider spans the full width of the page, so we would need to calculate this difference dynamically because when the window size changes, so does the width of the slider. We'll need a little help from javascript to accomplish this.
Something like this might help:
function centerCaption(){
    var caption = $('.nivo-caption');
    caption.css('left', ($('#slider').width() - caption.width()) / 2);
}
Here is a slimmed down working example:
https://jsfiddle.net/sm1215/ma645ao8/2/

A: When you fix your class name, I believe that if you set a width to your div and then use margin-left:auto and margin-right:auto, the element should center.
.nivo-caption {
width:300px;
margin-left:auto;
margin-right:auto;
}

This assumes you don't have other elements that force that element to not be able to move.

A: So I found a solution to my problem. I'm not sure if it's the correct way things should be coded, but it works.. If anyone can see how my code might cause issues in the future, please let me know.
I added some bits of code to the css and it solved everything.
My HTML is exactly the same as above:
<!DOCTYPE html>

    <title>Max Klimmek - Portfolio, Clothing, Travel</title>
      <link rel="stylesheet" href="css/normalize.css">
      <link rel="stylesheet" href="css/style.css">
      <link rel="stylesheet" href="fonts/font-awesome-4.5.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" />

      <meta name="viewport" content="width=device-width">

Home

Portfolio

Clothing

Gallery

Resume

Simple.
 Clean.

The New CSS for the NivoCaption container:
/* Caption styles */
.nivo-caption {
    position: absolute;
    justify-content: center;
    margin-left: -150px;
    margin-top: -200px;
    width: 100%;
    font-family: 'Gotham', sans-serif;
    color:#FFF;
    font-weight:bold;
    font-size:45px;
    line-height:44px;
    text-align:center;
    text-transform:uppercase; /* converts text to UPPERCASE */
}

.nivo-caption1 {
    position: absolute;
    margin: auto;
    margin-top:5px;
}

The pieces I added to ensure center alignment were:
justify-content: center;
margin-left: -85px;
margin-top: -200px;
width: 100%;

Now I just have to figure out solutions to the other bugs with this slider:

*

*pauseTime not being applied to all slides.

*Delay on caption load.

Cheers for your helps guys!
Max


text:
Q: How to calculate percentage across a subset of column I originally asked this question here:-
https://datascience.stackexchange.com/questions/113526/need-help-with-calculating-percentage-across-a-subset-of-column
I need help with calculating % on a subset of data that I have. I am sharing the sample code below for the data:-
dff4 <- data.frame(stringsAsFactors = FALSE, check.names = FALSE,
    Region = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B",
        "C", "C", "C", "C", "C"),
Brand = c("B1", "B2", "B3",
        "B4", "B5", "B1", "B2", "B3", "B4", "B5", "B1", "B2",
        "B3", "B4", "B5"),
`2018` = c(2923, 2458, 2812, 2286,
        1683, 1085, 2805, 3214, 1059, 1866, 3280, 2481, 2016,
        1230, 1763),
`2019` = c(2497, 2306, 2264, 3602, 3381,
        1778, 2470, 2249, 2297, 3264, 1071, 2345, 3815, 3685,
        1381),
`2020` = c(3458, 1448, 2033, 1021, 2275, 1527,
        1316, 2229, 3029, 1054, 3590, 2978, 2633, 3531, 2608),
`2021` = c(1496, 2196, 1448, 2344, 3853, 3499, 1681, 3282,
        1693, 2102, 2235, 2007, 3796, 3394, 2421),
`2022` = c(3759,
        3371, 2908, 3222, 1720, 2862, 3767, 2544, 3299, 3961,
        1030, 1268, 2652, 3656, 3053))

Created on 2022-08-15 by the reprex package (v2.0.1)
I want to calculate the % share of Brand B1 by different regions across all columns. So the steps would be like taking a % on parent total like we do in Excel pivot.
I tried using the below code, however it calculates the % on the sum of the total column not the subset of the column REGION.
dff4 %>% mutate(across(where(is.double), ~./sum(.), .names = "perc_{.col}"))
Created on 2022-08-15 by the reprex package (v2.0.1)

I also tried running the code below which gives me the exact answer that I want however I can not replicate it across the columns without writing the code for each column from 2018 to 2022 separately.
transform(dff4, percent = ave(dff4$`2018`, dff4$`Internal region`,
    FUN = prop.table))
Created on 2022-08-15 by the reprex package (v2.0.1)

Any help would be appreciated.

A: I think what you're looking for is to group_by region first:
dff4 <- dff4 %>%
  group_by(Region) %>%
  mutate(across(`2018`:`2022`, ~ ./sum(.), .names = "perc_{.col}"))


text:
Q: At least 2 different letters in regex What regex checks if there are at least two different letters in a string?
For instance:

*

*aa -> Not match

*ab -> Match

*a -> Not match

*012 -> Not match

A: You need exactly 2 chars, where the second is not the first:
^(.)(?!\1).$

See live demo.
Breakdown:

*

*^ start

*(.) captures the first char as group 1

*(?!\1) a negative look-ahead that asserts the following character is not the same as the first character

*. a character

*$ end

To restrict the match to only letters (upper or lower case):
^([a-zA-Z])(?!\1)[a-zA-Z]$

A: If "different" just means "separate" and you only want letters from the English alphabet, this should do the trick. The following regex will find match strings with at least two English letters:
.*[a-zA-Z].*[a-zA-Z].*

*

*.* matches 0 or more of any character except a newline character

*[a-zA-Z] matches any character in English alphabet case-insensitively

If you want a regex that matches strings with at least two different English letters, this one satisfies that criteria:
.*([a-zA-Z])(?!\1).*([a-zA-Z]).*

*

*(regex stuff) creates a "capturing group" whose result is referenceable by later tokens

*(?!\1) is a negative lookahead that asserts no capturing group can match the result of the first capturing group

*\1 is a backreference that matches the result of capturing group #1

You can test these here: https://www.regextester.com/


text:
Q: How to check widevine DRM present on the Android Device I am making an app in which I have to check whether Google Widevine DRM present in the Android device or not.
How to check that programatically?
Thanks in Advance

A: The Android DRM framework provides a method to check which DRM systems are available -
String[] engines = mDrmManager.getAvailableDrmEngines()

The names returned can be a bit confusing but if you play around with it you should see what you are looking for.
Its worth being aware that there are different levels of Widevine depending on how the DRM keys are protected and whether the playback is all secure within hardware.
There are also two general types of Widevine - Widevine classic on older devices and Widevine Modular on newer devices.
You can see some detail on how to determine the level for Widevine Classic here:

*

*https://support.google.com/widevine/answer/6072714?hl=en

A: We can use this method for getting the particular widevine security level for any android device https://developer.android.com/reference/android/media/MediaDrm#getPropertyString(java.lang.String)
shortcode snippet to illustrate the documentation.
val widevineKeyDrm = MediaDrm(C.WIDEVINE_UUID)
val securityLevel = widevineKeyDrm.getPropertyString()

PS. the constant C.WIDEVINE_UUID is picked up from here https://github.com/donparapidos/ExoPlayer/blob/master/library/src/main/java/com/google/android/exoplayer2/C.java

A: I found the solution the by exploring the ExoPlayer library
private boolean isWideVineDRMAvailable()
{
    return  MediaDrm.isCryptoSchemeSupported(C.WIDEVINE_UUID);
}

C is the constant class available in ExoPlayer library.


text:
Q: Core Plot: Are "setLabelingPolicy:CPTAxisLabelingPolicyNone" and "setMajorGridLineStyle:majorGridLineStyle" Mutually exclusive? I am trying to draw custom labels and Grid lines over Y-Axis,
If I set the Label Policy CPTAxisLabelingPolicyNone, and add custom labels to Y-Axis, I could get the desired labels drawn on Y-Axis.
[yAxis setLabelingPolicy:CPTAxisLabelingPolicyNone];

However I couldn't get Grid lines working.
[yAxis setMajorGridLineStyle:majorGridLineStyle];

If I remove Label Policy None, then I could get Grid lines.
Wondering what could be the solution?
Code for setting Y-Axis labels:
NSMutableArray *yLabels = [NSMutableArray arrayWithObjects:@"None", @"Awake", @"Light",@"Middle",@"Deep", nil];
NSMutableArray *customLabelsY = [NSMutableArray arrayWithCapacity:[yLabels count]];
for (int loc=1; loc <= 4; loc++)
{
    CPTAxisLabel *newLabelY = [[CPTAxisLabel alloc] initWithText: [yLabels objectAtIndex:loc] textStyle:textStyle];
    newLabelY.tickLocation = [[NSDecimalNumber numberWithInt:loc] decimalValue];
    newLabelY.offset = yAxis.labelOffset + yAxis.majorTickLength;
    [customLabelsY addObject:newLabelY];
}
[yAxis setAxisLabels:[NSSet setWithArray:customLabelsY]];

A: With CPTAxisLabelingPolicyNone, your app must provide tick locations (major and/or minor) if you want tick marks and/or grid lines. They are independent of the labels, so you can label locations that don't have tick marks and/or skip some of the tick locations when creating labels.

Edit:
Keep track of the locations when creating your labels and set the majorTickLocations when done.
NSMutableSet *locations = [NSMutableSet set];

for (int loc=1; loc <= 4; loc++) {
    // create labels

    [locations addObject:@(loc)];
}

yAxis.majorTickLocations = locations;


text:
Q: Problem with "No View Found.." when working with Settings Preference Rookie developer here.
Trying to learn with SharedPreference and Settings Options. I´m facing error message with View No found for fragment.
This is my code related with the issue; I have been checking for similar issues through this site but my knowledge is very basic to get oriented to solve the problem.
thanks in advance for your comments!
In my Activity;
override fun onOptionsItemSelected(item: MenuItem): Boolean {
   val id = item.itemId
   when (id) {
       R.id.action_settings -> {

           supportFragmentManager
               .beginTransaction()
              .replace(R.id.action_settings, MySettingsFragment())
               .commit()
       }
       else -> return super.onOptionsItemSelected(item)
   }
       return super.onOptionsItemSelected(item)
   }

MySettingsFragment
package com.khaxapplication.rfid_api_zebra.utilities

import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat
import com.khaxapplication.rfid_api_zebra.R
class MySettingsFragment : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)
    }
}

fragment_settings.xml layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".utilities.MySettingsFragment">

</FrameLayout>

Error Message obtained
2020-11-08 19:35:55.979 20322-20322/com.khaxapplication.rfid_api_zebra E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.khaxapplication.rfid_api_zebra, PID: 20322
    java.lang.IllegalArgumentException: No view found for id 0x7f080041 (com.khaxapplication.rfid_api_zebra:id/action_settings) for fragment MySettingsFragment{8621cad} (9e68a7a2-fa38-432f-b3f2-e368c60dae30) id=0x7f080041}
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
        at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
2020-11-08 19:35:56.010 20322-20322/com.khaxapplication.rfid_api_zebra I/Process: Sending signal. PID: 20322 SIG: 9

Adding full MainActivity.class
package com.khaxapplication.rfid_api_zebra

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.khaxapplication.rfid_api_zebra.utilities.MySettingsFragment

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        val fab: FloatingActionButton = findViewById(R.id.fab)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
     }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId
    when (id) {
        R.id.action_settings -> {

            supportFragmentManager
                .beginTransaction()
               .replace(R.id.action_settings, MySettingsFragment())
                .commit()
        }
        else -> return super.onOptionsItemSelected(item)
    }
        return super.onOptionsItemSelected(item)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

}

Layout for activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

A: Whatever layout you are using for your Activity does not have a View with ID "action_settings" in it.
If "fragment_settings.xml" is what you were using for your activity, you need to give the FrameLayout an ID property.
Since R.id.action_settings exists, you must have it in one of your layout files somewhere. Maybe you have applied the wrong layout in your activity.


text:
Q: What does it mean to contract the indices of a Lorentz matrix? The metric tensor in SR obeys the transformation law (I am using Schutz's bar notation for different  frame indices):
$$\eta_{\bar{\alpha}\bar{\beta}}=\Lambda^\mu_{~\bar{\alpha}}~\Lambda^\nu_{~\bar{\beta}}~\eta_{~\mu\nu}$$
If I'm not wrong, the second Lorentz matrix can be contracted with the metric like so:
$$\eta_{\bar{\alpha}\bar{\beta}}=\Lambda^\mu_{~\bar{\alpha}}~\Lambda_{~\mu\bar{\beta}}$$
This seems wrong since the Lorentz matrix elements are usually written with one upper and one lower index, and I don't understand how $\Lambda_{\mu\bar{\beta}}$ could be written in a matrix representation.
From various sources, I am also told that the above equations are equivalent to matrix multiplication with the transpose of $\Lambda$:
$$\eta=\Lambda\cdot\eta\cdot\Lambda^T$$

*

*Does contracting the Lorentz matrix transpose it?

*What are the differences between $\Lambda^\mu_{~\bar{\nu}}$, $\Lambda^\bar{\mu}_{~\nu}$, $\Lambda_{\mu\bar{\nu}}$ and $\Lambda^{\mu\bar{\nu}}$? Which of them are inverses and which are transposes?

A: First a brief introduction to tensors. An $(r,s)$ tensor $t$ on a $K$-vector space $V$ is just a multilinear map from $s$ copies of $V$ and $r$ copies of the dual vector space
$V^*$ to the underlying field $K$:
$$t:\underbrace{V^*\times...\times V^*}_{r-times}\times\underbrace{V\times...\times V}_{s-times}\to K$$
The dual vector space is just the set of all linear maps from $V$ to $K$. The set of all
$(r,s)$ tensors on $V$ is commonly denoted $T^r_s(V)$.
Ok, how do we get from these vectors and linear maps to these numbers $g_{\mu\nu}$ that
we're working with?
Well, we do what we always intuitively do namely, choose a basis. Say we chose some basis
$\{e_i\}\subset V$ on our vector space, we can now express every vector $v\in V$ as a
linear combination of these basis vectors: $v=v^ie_i$.
The $v^i\in K$ are basically numbers and the position of the index so far is just convention. We can now do the same for the dual vector space, with a particularly clever choice of basis $\{e^i\}\subset V^*$, such that $e^{i}(e_j)=\delta^i_j$. Again, the position of the index is just convention in order not to mix up vectors and dual vectors, as these are fundamentally different objects!
With this index convention, we would now write the components of a vector as $v^i$ and of a dual vector as $v_i$.
For the tensors, it is very similar:
$$
t(w_k^{(1)}e^k,...,w_l^{(r)}e^l,v^i_{(1)}e_i,...,v^j_{(s)}e_j)=w_k^{(1)}...w_l^{(r)}v^i_{(1)}...v^j_{(s)}t(e^k,...,e^l,e_i,...,e_j)
$$
The $t(e^k,...,e^l,e_i,...,e_j)\equiv t^{k...l}_{i...j}$ are again just numbers, independent of what vectors and covectors the tensor is acting on (just the basis we chose). Similarly to the vectors and covectors, we can also express the tensor in terms of its components:
$$
t = t^{k...l}_{i...j}e_k\otimes...\otimes e_l\otimes e^i\otimes...\otimes e^j
$$
Ok now, what happens when we choose a different basis $\{b_i\}\subset V$ and a corresponding dual basis $\{b^i\}\subset V^*$? Since our new basis vectors (and new basis covectors) are still elements of the same underlying (dual-)vector space, we can express them as some linear combination:
$$b_i = A_i^je_j \qquad \text{and} \qquad b^i=B^i_je^j$$
Similar to above, we can view the numbers $A_i^j$ and $B^i_j$ as components of a tensor:
$$
A=A_i^je_j\otimes b^i \qquad \text{and} \qquad B=B^i_jb_i\otimes e^j
$$
note: In physics, we typically don't view these transformations as tensors, however in
I think this is quite useful for our discussion here. For more information see, e.g. (Is Lorentz transform a tensor?)
Now lastly what does contracting two tensors actually mean? Tensor contractions are really just defined for an individual tensor and are linear maps $C^k_l:T^r_s(V)\to T^{r-1}_{s-1}(V)$ defined by:
$$
T^{\nu_1...\nu_r}_{\mu_1...\mu_s}e_{\nu_1}\otimes...\otimes e_{\nu_r}\otimes e^{\mu_1}\otimes...\otimes e^{\mu_s}\\ \mapsto
T^{\nu_1...\nu_r}_{\mu_1...\mu_s} e^{\mu_l}(e_{\nu_k})
e_{\nu_1}\otimes...\otimes e_{\nu_{l-1}}\otimes e_{\nu_{l+1}}\otimes...\otimes e_{\nu_r}\otimes e^{\mu_1}\otimes...\otimes e^{\mu_{k-1}}\otimes e^{\mu_{k+1}}\otimes...\otimes e^{\mu_s})
$$
But thats no problem, since we can make one tensor out of two using the tensor product.
In your particular case we have the "tensor" $\Lambda=\Lambda^{\nu}_{\mu}e_{\nu}\otimes b^{\mu}$ and the tensor $\eta=\eta_{\mu\nu}e^{\mu}\otimes e^{\nu}$:
$$
\eta\otimes\Lambda = \eta_{\mu\nu}\Lambda^{\alpha}_{\beta}e^{\mu}\otimes e^{\nu}\otimes e_{\alpha}\otimes b^{\beta}
$$
and
$$
C^{\alpha}_{\nu}(\eta\otimes\Lambda)=\eta_{\mu\nu}\Lambda^{\alpha}_{\beta}e^{\nu}(e_{\alpha})e^{\mu}\otimes b^{\beta} = \eta_{\mu\nu}\Lambda^{\nu}_{\beta}e^{\mu}\otimes b^{\beta}\equiv \Lambda_{\mu\beta} e^{\mu}\otimes b^{\beta}
$$
In GR (and SR) space-time is a Lorentzian manifold $L$, the vector space of interest is the tangent space $T_pL$ at some point $p\in L$ and the tensors you're considering have special meaning, however (as always) the maths doesn't care too much about the physics.

A: Note that $\Lambda$ is not itself a tensor. It is a matrix of transformation coefficients.
A tensor is well-defined in the absence of any specified frame, and its components can be defined in one frame or another. The Lorentz transformation, by contrast, is used to calculate how tensor components change from one frame to another.
Contracting one up- and one down-index on a second-rank tensor gives a zero-rank tensor, which is to say an invariant scalar. Contracting one up- and one down-index on a non-tensor such as $\Lambda^a_{\; b}$ will give some sort of mathematical result, but it is not guaranteed to be a quantity of any particular interest. Similarly, the combination of metric with $\Lambda^a_{\; b}$ can be used to get a quantity with all indices down, but it is not a tensor and it is best not to play these index gymnastics with non-tensors. Just let $\Lambda^a_{\; b}$ be what it is.
For a second-rank tensor, lowering the first index corresponds to pre-multiplying by the metric in matrix language; lowering the second index corresponds to post-multiplying by the metric. The transpose operation corresponds to reversing the order of the indices (N.B. without moving them up or down). For example
$$
\Lambda^a_{\; \mu} \Lambda^b_{\; \nu} F^{\mu\nu}
= \Lambda^a_{\; \mu}  F^{\mu\nu} \Lambda^b_{\; \nu}
= \Lambda^a_{\; \mu}  F^{\mu\nu} (\Lambda^{\! \rm T})^{\;\; b}_{\nu}
$$
and in matrix notation this combination can be written
$$
\Lambda F \Lambda^{\! \rm T}
$$

A: This took me quite a while to get at the beginning of relativism class but this may help: a general matrix multiplication like we all know it looks like this: $$[A][B] = \sum a_{ri}b_{ir}$$
Now the relativity version with einstein summation convenction would make this matrix multiplication look like this:
$$[A][B] = a_{\nu\sigma}b^{\sigma\nu}$$
As you see this is the same as the previous statement with just the summation symbol dropped, and thus with the first index representing the row and the second representing the column. Now there are possibly people who have an explanation for how a (2,0) (i.e 'covariant') tensor is different from a (0,2) (i.e 'contravariant') tensor, however I just keep the rule in my head that you can only contract covariant with contravariant indices, and thus apply a metric of the form $g_{\mu \mu}$ ($g^{\mu \mu}$)  if it is necessary to lower (rise) indices. To get to the form of matrices it is necessary to convert the tensor back to a matrix-form by contracting it with a metric. I will use the minkowski metric $\eta$ here for the demonstration. This brings us back to your question, your equation can be written as:
$$\Lambda_{\sigma\alpha}\eta^{\mu \sigma}\Lambda^{\nu\sigma}\eta_{\beta\sigma}\eta_{\mu\nu} = \Lambda_{\sigma\alpha}\eta_{\beta\sigma}\Lambda^{\nu\sigma}\delta^{\sigma}_{\nu} = \Lambda_{\nu\alpha}\eta_{\beta\sigma}\Lambda^{\nu\sigma} \stackrel{\nu \leftrightarrow \beta}{=}  [\Lambda]\cdot[\eta]\cdot[\Lambda]^T$$
Where I've used the fact that
$$\eta^{\mu\sigma}\eta_{\beta\sigma} = \delta^{\mu}_{\sigma}$$
And just basic rising and lowering of indices via:
$$\Lambda^{\mu}_{\;\alpha} = \Lambda_{\sigma\alpha}\eta^{\mu \sigma} \text{ and } \Lambda_{\mu}^{\;\alpha} = \Lambda^{\sigma\alpha}\eta_{\mu \sigma}$$
I could've made an index mistake somewhere but I hope this gives a kind of understanding and I hope it helps.


text:
Q: How to check the multiple permission at single request in Android M? I want to use the

*

*android.permission.CAMERA

*android.permission.WRITE_EXTERNAL_STORAGE

in single request using
ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode);

But my problem is at time I request only one permission,
I read about group-permission,But it's work for only Same group which one decided by Developer, Like CONTACT_GROUP : read_contact,write_contact etc.
I want create the custom group permission which ask me only one request & provide me only one response.
Thanks

A: You can ask multiple permissions (from different groups) in a single request. For that, you need to add all the permissions to the string array that you supply as the first parameter to the requestPermissions API like this:
requestPermissions(new String[]{
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        ASK_MULTIPLE_PERMISSION_REQUEST_CODE);

On doing this, you will see the permission popup as a stack of multiple permission popups. Ofcourse you need to handle the acceptance and rejection (including the "Never Ask Again") options of each permissions. The same has been beautifully explained over here.

A: There is no hack available at this stage to circumvent asking for permissions from different groups together. That is the nature of how android has developed runtime permissions, to give users a choice of which permissions to accept. Of course not accepting all permissions required by an app, may make the app fail to work properly.
CAMERA and WRITE_EXTERNAL_STORAGE are both regarded as dangerous permissions, and in separate groups, thus both requiring a runtime permission request.
Once permission is granted for a particular group, it does not need to be requested again for the lifetime of the app run, or until it is revoked if given as a default setting.

The only thing you can do is ask the user to accept the decisions as default, which can be revoked, by using "never ask again"

A: I had the same issue and stumbled on this library.
Basically you can ask for multiple permissions sequentially, plus you can add listeners to popup a snackbar if the user denies your permission.

A: For multiple permission you can use this code :
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

private void insertDummyContactWrapper() {
    List<String> permissionsNeeded = new ArrayList<String>();

    final List<String> permissionsList = new ArrayList<String>();
    if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
        permissionsNeeded.add("GPS");
    if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
        permissionsNeeded.add("Read Contacts");
    if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
        permissionsNeeded.add("Write Contacts");

    if (permissionsList.size() > 0) {
        if (permissionsNeeded.size() > 0) {
            // Need Rationale
            String message = "You need to grant access to " + permissionsNeeded.get(0);
            for (int i = 1; i < permissionsNeeded.size(); i++)
                message = message + ", " + permissionsNeeded.get(i);
            showMessageOKCancel(message,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                        }
                    });
            return;
        }
        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
        return;
    }

    insertDummyContact();
}

private boolean addPermission(List<String> permissionsList, String permission) {
    if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
        permissionsList.add(permission);
        // Check for Rationale Option
        if (!shouldShowRequestPermissionRationale(permission))
            return false;
    }
    return true;
}

A: Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
  Manifest.permission.WRITE_CALL_LOG,
  Manifest.permission.READ_CALL_LOG,
  Manifest.permission.READ_CONTACTS,
  Manifest.permission.WRITE_CONTACTS}; // Here i used multiple permission check

Then call it in Oncreate
 if (checkPermissions()) { //  permissions  granted.
    getCallDetails();
 }

Finally, copy the below code
private boolean checkPermissions() {
  int result;
  List<String> listPermissionsNeeded = new ArrayList<>();

   for (String p : permissions) {
     result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
     if (result != PackageManager.PERMISSION_GRANTED) {
       listPermissionsNeeded.add(p);
     }
   }

   if (!listPermissionsNeeded.isEmpty()) {
     ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
     return false;
   }
     return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  switch (requestCode) {
    case MULTIPLE_PERMISSIONS: {
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // permissions granted.
           getCallDetails(); // Now you call here what ever you want :)
        } else {
             String perStr = "";
               for (String per : permissions) {
                   perStr += "\n" + per;
                }   // permissions list of don't granted permission
              }
            return;
          }
       }
    }

A: First initialize permission request code
public  static final int PERMISSIONS_MULTIPLE_REQUEST = 123;

Check android version
 private void checkAndroidVersion() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkPermission();

    } else {
        // write your logic here
    }

}

check multiple permission code
 private void checkPermission() {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
            .checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale
                (getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
                ActivityCompat.shouldShowRequestPermissionRationale
                        (getActivity(), Manifest.permission.CAMERA)) {

      Snackbar.make(getActivity().findViewById(android.R.id.content),
                    "Please Grant Permissions to upload profile photo",
                    Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            requestPermissions(
                                    new String[]{Manifest.permission
                                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                    PERMISSIONS_MULTIPLE_REQUEST);
                        }
                    }).show();
        } else {
            requestPermissions(
                    new String[]{Manifest.permission
                            .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    PERMISSIONS_MULTIPLE_REQUEST);
        }
    } else {
        // write your logic code if permission already granted
    }
}

call back method after grant permission by user
@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_MULTIPLE_REQUEST:
            if (grantResults.length > 0) {
               boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
               boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                if(cameraPermission && readExternalFile)
                {
                    // write your logic here
                } else {
                    Snackbar.make(getActivity().findViewById(android.R.id.content),
                        "Please Grant Permissions to upload profile photo",
                        Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                requestPermissions(
                                        new String[]{Manifest.permission
                                                .READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                        PERMISSIONS_MULTIPLE_REQUEST);
                            }
                        }).show();
                }
           }
           break;
    }
}

A: As said earlier, currently every permission group has own permission dialog which must be called separately.
You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.
Here is a working example link, may be useful for someone.

A: I faced the same problem and below is the workaround I came up with:
public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
        final List<String> permissionsNeeded = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            final String perm = permissions[i];
            if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permissions[i])) {
                    final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
                    dialog.setPositiveButton("OK", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // add the request.
                            permissionsNeeded.add(perm);
                            dialog.dismiss();
                        }
                    });
                    dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
                } else {
                    // add the request.
                    permissionsNeeded.add(perm);
                }
            }
        }

        if (permissionsNeeded.size() > 0) {
            // go ahead and request permissions
            requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
            return false;
        } else {
            // no permission need to be asked so all good...we have them all.
            return true;
        }
    }

And you call the above method like this:
if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
                        // DO YOUR STUFF

                    }

A: check More than one Permission and Request if Not Granted
 public void checkPermissions(){
    if(ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED){
        //Do_SOme_Operation();
    }else{
        requestStoragePermission();
    }
}

public void requestStoragePermission(){
    ActivityCompat.requestPermissions(this
            ,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},1234);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case 1234:if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
  // Do_SOme_Operation();
        }

        default:super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }
}

A:        // **For multiple permission you can use this code :**

       // **First:**
//Write down in onCreate method.

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                    android.Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST);

         }

        //**Second:**
    //Write down in a activity.
     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST:

                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Intent i = new Intent(SplashActivity.this,
                                        HomeActivity.class);
                                startActivity(i);
                                finish();
                            }
                        }, SPLASH_DISPLAY_LENGTH);

                    } else {
                        finish();
                    }
                    return;
            }
        }

A: Based on what i've searched, i think this is the best answers that i've found out Android 6.0 multiple permissions

A: Adding generic code for different types of permissions. Copy-paste with minor changes. Read the "TODO" comments in the code below.
Make the following Activity your Launcher Activity:
public class PermissionReqActivity extends AppCompatActivity {

    private static final int CODE_WRITE_SETTINGS_PERMISSION = 332;
    private static String[] PERMISSIONS_ALL = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //TODO You can Add multiple permissions here.
    private static final int PERMISSION_REQUEST_CODE = 223;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_req);
        context = this;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            boolean allPermissionsGranted = true;
            ArrayList<String> toReqPermissions = new ArrayList<>();

            for (String permission : PERMISSIONS_ALL) {
                if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    toReqPermissions.add(permission);

                    allPermissionsGranted = false;
                }
            }
            if (allPermissionsGranted)
                //TODO Now some permissions are very special and require Settings Activity to launch, as u might have seen in some apps. handleWriteSettingsPermission() is an example for WRITE_SETTINGS permission. If u don't need very special permission(s), replace handleWriteSettingsPermission() with initActivity().
                handleWriteSettingsPermission();
            else
                ActivityCompat.requestPermissions(this,
                        toReqPermissions.toArray(new String[toReqPermissions.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermGranted = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permissions not granted: " + permissions[i], Toast.LENGTH_LONG).show();
                    allPermGranted = false;
                    finish();
                    break;
                }
            }
            if (allPermGranted)
                handleWriteSettingsPermission();//TODO As mentioned above, use initActivity() here if u dont need very special permission WRITE_SETTINGS
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void handleWriteSettingsPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.System.canWrite(context)) {
                initActivity();
            } else {
                Toast.makeText(this, "Please Enable this permission for " +
                        getApplicationInfo().loadLabel(getPackageManager()).toString(), Toast.LENGTH_LONG).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                startActivityForResult(intent, CODE_WRITE_SETTINGS_PERMISSION);
            }
        }
    }

//TODO You don't need the following onActivityResult() function if u dont need very special permissions.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == CODE_WRITE_SETTINGS_PERMISSION) {
            if (Settings.System.canWrite(this))
                initActivity();
            else {
                Toast.makeText(this, "Permissions not granted: " + Manifest.permission.WRITE_SETTINGS, Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    private void initActivity() {
        startActivity(new Intent(this, MainActivity.class));
    }
}

A: Based on vedval i have this solution.
public boolean checkForPermission(final String[] permissions, final int permRequestCode) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    final List<String> permissionsNeeded = new ArrayList<>();
    for (int i = 0; i < permissions.length; i++) {
        final String perm = permissions[i];
        if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(permissions[i])) {
                Snackbar.make(phrase, R.string.permission_location, Snackbar.LENGTH_INDEFINITE)
                        .setAction(android.R.string.ok, new View.OnClickListener() {
                            @Override
                            @TargetApi(Build.VERSION_CODES.M)
                            public void onClick(View v) {
                                permissionsNeeded.add(perm);
                            }
                        });
            } else {
                // add the request.
                permissionsNeeded.add(perm);
            }
        }
    }

    if (permissionsNeeded.size() > 0) {
        // go ahead and request permissions
        requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
        return false;
    } else {
        // no permission need to be asked so all good...we have them all.
        return true;
    }
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_READ_LOCATION) {
        int i = 0;
        for (String permission : permissions ){
            if ( permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                initLocationManager();
            }
            i++;
        }

    }
}

A: I am late, but i want tell the library which i have ended with.
RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
         Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
    if (granted) {
       // All requested permissions are granted
    } else {
       // At least one permission is denied
    }
});

add in your build.gradle
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

A: For Asking Multiple Permission At Once You Can Use this Method link
compile 'com.kishan.askpermission:askpermission:1.0.3'

If you got conflicting in support library then
compile('com.kishan.askpermission:askpermission:1.0.3', {
    exclude group: 'com.android.support'
})

Now ask for Permission
new AskPermission.Builder(this)
    .setPermissions(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    .setCallback(/* PermissionCallback */)
    .setErrorCallback(/* ErrorCallback */)
    .request(/* Request Code */);

permission granted callback
  public void onPermissionsGranted(int requestCode) {
// your code  }

permission denied callback
 public void onPermissionsDenied(int requestCode) {
// your code}

ErrorCallbacks
public void onShowRationalDialog(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
permissionInterface.onDialogShown();

}
public void onShowSettings(PermissionInterface permissionInterface, int requestCode) {
// Alert user by Dialog or any other layout that you want.
// When user press OK you must need to call below method.
// It will open setting screen.
permissionInterface.onSettingsShown();

}

A: you should use the dependency named dexter as given below:
https://github.com/Karumi/Dexter
by this you can get one or many permission easily:
this is the given code
    Dexter.withContext(this).
               withPermissions(Manifest.permission.CAMERA,
          Manifest.permission.WRITE_EXTERNAL_STORAGE)
               .withListener(new MultiplePermissionsListener() {
                  @Override
                    public void onPermissionsChecked(MultiplePermissionsReport
                    multiplePermissionsReport) {
                    displaySong();
                  }

                @Override
                public void    onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
        PermissionToken permissionToken) {

                    permissionToken.continuePermissionRequest();

                }
            }).check();


text:
Q: Tkinter Column Width Trouble So I'm trying to make something that looks like this for a school project:
style I want
But when I tried to put it all together, the textbox stretched my column out way too far:
what I'm stuck with
If I remove the textbox everything else looks great:
without textbox
I just have no clue how to get the textbox to size properly. Any help would be appreciated.
Here's my code that dictates that particular frame
#Line Items
lblLineItems.grid(row= 0, column=0, sticky=tk.W)
txtLine.grid(row=1, column=0, sticky=tk.W)
btnPlaceOrder.grid(row=2, column=0, sticky=tk.W,)
btnCancelOrder.grid(row=2, column=1, sticky=tk.W)
lineFrame.grid(row=1, column=2)

I tried fiddling around with the textbox's "columnspan" but that didn't seem to do anything. I split up the frames a bit more and was able to get the buttons to stick together, but unfortunately no luck on the text box


text:
Q: Paypal send shipping country (use different values lc and country fields) I try to integrate a paypal button payment on my website.
The website accepts users from many countries.
The website's language are english.
My users defines shipping address in my website and I provide it to Paypal with the form.
But, when I sent another country without change lc paramter, Paypal don't pre-fill country with the new.
My Problem is the opposit of this one : Paypal Hosted language bug. Based on 'country' instead of 'lc' for Paypal Express button
Example (my form) :
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

    <input type="hidden" name="amount" value="5">
    <input name="currency_code" type="hidden" value="GBP">
    <input name="shipping" type="hidden" value="0.00">
    <input name="tax" type="hidden" value="0.00">
    <input name="return" type="hidden" value="https://my-shop.com">
    <input name="cancel_return" type="hidden" value="https://my-shop.com">
    <input name="notify_url" type="hidden" value="https://my-shop.com">
    <input name="cmd" type="hidden" value="_xclick">
    <input name="business" type="hidden" value="sales@my-shop.com">
    <input name="no_shipping" type="hidden" value="1">
    <input name="item_name" type="hidden" value="1234">
    <input name="no_note" type="hidden" value="1">
    <input name="bn" type="hidden" value="xxxx">
    <input name="custom" type="hidden" value="the_buyer@gmail.com">
    <input name="invoice" type="hidden" value="1223">

    <input name="address_override" type="hidden" value="1">
    <input name="address1" type="hidden" value="Frani Sramka 20">
    <input name="address2" type="hidden" value="">
    <input name="city" type="hidden" value="Prague 5">
    <input name="zip" type="hidden" value="15000">
    <input name="country" type="hidden" value="CZ">

    <!-- Countries part -->
    <input name="lc" type="hidden" value="GB">

    <input name="address_country" type="hidden" value="CZECH REPUBLIC">
    <input name="address_country_code" type="hidden" value="CZ">
    <input name="residence_country" type="hidden" value="CZ">

    <button type="submit" class="btn btn-primary">Pay by PayPal</button>
</form>

In this case, Paypal set the page language in GB (provided by lc field)
But the Paypal's Country field was pre-fill with United Kingdom, see screenshot :

But I want Paypal take my countries fields (with value CZ) into account.

Set lc field to CZ behavior
If I set lc field to CZ :
<input name="lc" type="hidden" value="CZ">

I get both language in CZ and user country pre-fill in CZ :

Brief question :
Do you know a way to :

*

*Pre-fill user country (CZ)

*Keep the choosen language (GB)

Additional information

*

*Except this language issue, the form works

*I use a custom PHP back-end technology (not a CMS with plugin)

Paypal Documentation
 pre-populate my customer's PayPal sign-up form, contains country and lc description
Countries code

A: I saw China is 'c2' not 'cz' ? am I wrong?

A: You might want to force a location.
<input type="hidden" name="locale.x" value="cz_XC">
<input type="hidden" name="lc" value="GB">


text:
Q: What does 'mothercanuckers' mean? First of all, sorry if it is offensive (I think it somewhat is).
I was going through http://bleacherreport.com/articles/424590-the-funniest-promos-and-moments-in-wwe-history#page/20

The Rock owned everyone by calling the
  Canadians mothercanuckers

I heard him saying this in the video but what does that mean?

A: "Canuck" is a slang word for someone from Canada. It's not usually considered offensive — sometimes it's even affectionate (and Canadians use it themselves in quite a few contexts). It's a regional nickname, like "Yankee" and other terms.
It is likely that "The Rock" simply took the (offensive) word "motherfuckers", and replaced "fuck" with the rhyming "Canuck" (replaced "f" with "can"), to make the word "mothercanuckers".
Thus "mothercanuckers" is a label combining "motherfuckers" and "Canuck" (or, to use Wikipedia's favourite word, it's a portmanteau of the two). It combines an offensive word and a slang nickname.
The humour (if any) comes (I guess) from this combination (of the offensive with the innocuous) — of having used an ordinary nickname to suggest overtones of offensiveness without actually using an offensive word, thus fulfilling the duties of trash-talking presumably expected of the character.


text:
Q: Migrating plsql function to pgplsql (postgresql 9.5) I'm trying to migrate the next function into PostgreSQL:
CREATE OR REPLACE FUNCTION mar.change_const (command text) RETURNS
VOID AS $body$
DECLARE

C_Procedure_Name   CONSTANT   varchar(30) := 'change_constraints';
V_Step                        real := 0;
/* command values: ENABLE | DISABLE */
all_constraints CURSOR(stat text) FOR
       SELECT *
       FROM   all_constraints
       WHERE  status = stat;
cons                          all_constraints%ROWTYPE;
line                          varchar(200);
cons_status                   varchar(10);
BEGIN
RAISE NOTICE 'Start : %, %', C_Procedure_Name, TO_CHAR(clock_timestamp());
V_Step := 1;
IF command IN ('enable', 'ENABLE') THEN
  cons_status := 'DISABLED';
ELSE
  cons_status := 'ENABLED';
END IF;
V_Step := 2;
FOR cons IN all_constraints(cons_status)
LOOP
    V_Step := 2.1;
    line := 'alter table ' || cons.table_name || ' ' || command ||
            ' novalidate constraint ' || CONS.CONSTRAINT_NAME;
    V_Step := 2.2;
    EXECUTE line;
END LOOP;

I know that I can switch all_constraints with information_schema.table_constraints but how can I change the other parts of the code ? I can't disable and enable constraints in PostgreSQL and I don't want to drop them in this part.
I read that I can alter the check constraints (which are the only type of constraint that I have) to novalidate but I didn't find any example in a search engine.

A: you can set NO VALID mark for check constraint only on ADD CONSTRAINT, so you can't do it without dropping old CHECK CONSTRAINT first. Accordingly "ENABLE" here would be ALTER TABLE ...VALIDATE which would lock the table and go over all data (re)validating it.
FK constraints are the only type you can "comfortably" "disable/enable" by ALTER TABLE ... DISABLE TRIGGER ALL and then enabling them back.
But in short the procedure above is so much different from Postgres way of dealing with constraints, that I doubt you will success much here. Probably you have to save definition of all existing constraints, drop them and recreate from saved definitions to "enable"...


text:
Q: Is there a closed form solution for $\frac {d^n}{dx^n} \frac {1}{1-ae^x}$? I am trying to find a closed form solution for $$\frac {d^n}{dx^n} \frac {1}{1-ae^x}$$
I have tried recognizing a pattern by computing specific cases but so far no luck.

I do know that the function is a composition of $x^{-1}$ and $1-ae^x$. The $k$th derivative of the latter is the same for all $k\ge 1$ and there is a closed form of the $k$th derivative of the former. Yet I am still not finding any answer.

However, when computing the derivatives manually I can see that in the numerator there is always a monic polynomial in $ae^x$ with constant term equal to one, all multiplied by $-ae^x$ and the denominator is always raised to the $n+1$ for the $n$th derivative.

I tried arranging the coefficients of the polynomial in the numerator in a triangle like that of Pascal's but I only recognized a pattern for the coefficients of the first and last two terms.

I tried Faa di Bruno's Formula but frankly it is over my head. Is there a clever solution or even a solution at all?

A: By explicitly computing the first few derivatives it looks like the $n$'th derivative of $\frac{1}{1-ae^x}$ is on the form
$$\color{red}{\frac{d^n}{dx^n}\left(\frac{1}{1-ae^x}\right) = \frac{\sum_{k=1}^n f(n,k) a^ke^{kx}}{(1-ae^x)^{n+1}}}$$
where $f(n,k)$ are constants. This functional form can formally be proven by induction. By taking the derivative of the expression above and equating it to the same formula with $n\to n+1$ we get
$$\frac{d}{dx}\left(\frac{\sum_{k=1}^n f(n,k) a^ke^{kx}}{(1-ae^x)^{n+1}}\right) = \frac{\sum_{k=1}^{n+1} f(n+1,k) a^ke^{kx}}{(1-ae^x)^{n+2}} $$
which when expanded gives us a recursion formula for $f(n,k)$:
$$f(n+1,k) = k f(n,k) + (n+2-k) f(n,k-1)~~~\text{for}~~~k=2,3,\ldots,n$$
with $f(n+1,1) = f(n+1,n+1) = 1$. This is the known recursion formula for the (shifted) Eulerian numbers $f(n,k) = A(n,k-1) \equiv \left\langle {n \atop k-1} \right\rangle$.
For more information about the Eulerian numbers see e.g. MathWorld : Euler's number triangle, Wiki : Eulerian Numbers, OEIS  : Eulerian Numbers. The first few values are (each row gives $f(n,k)$ for $k=1,2,\ldots,n$):
$$\matrix{1 & n=1\\1~~~1 & n=2\\1~~~4~~~1 & n=3\\1~~~11~~~11~~~1 & n=4\\1~~~26~~~66~~~26~~~1 & n=5\\1~~~57~~~302~~~302~~~57~~~1 & n=6}$$

A: One can start by applying the identity $\frac{1}{1-y}=1+y+y^2+\ldots$ setting $y=ae^x$. This gives*
$$\frac{1}{1-ae^x}=1+ae^x+a^2e^{2x}+a^3e^{3x}+\ldots.$$
This makes differentiating really easy:
$$\frac{d^n}{dx^n}\frac{1}{1-ae^x}=ae^x+2^na^2e^{2x}+3^na^3e^{3x}+\ldots.$$
Now, it's a reasonably standard fact about generating functions that, for any polynomial $P$ of degree $n$, there is another one $Q$ of degree no more than $n$ such that $$\frac{Q(y)}{(1-y)^{n+1}}=P(0)+P(1)y+P(2)y^2+P(3)y^3+\ldots$$
and we see that we have basically this situation here, where $P(m)=m^n$. How do we find $Q(y)$? Well, we just multiply both sides of the expression through by $(1-y)^{n+1}=\sum_{i=0}^{n+1}(-1)^i{n+1\choose i}y^i$. Then, we collect terms, and find that if $Q(y)=\sum_{i=0}^{n}a_iy^i$ we have
$$a_i=\sum_{j=0}^i(-1)^j{n+1\choose j}P(i-j)=\sum_{j=0}^i(-1)^j{n+1\choose j}(i-j)^n.$$
As is noted in @Winther's answer, these coefficients are Eulerian numbers. That is, $a_i=A(n,i-1)$ in the terminology given on the linked page. Wikipedia notes under the identities section that they are the generating function for the sequence of $n^{th}$ powers, which is exactly why they show up here. If we take this polynomial $Q$, we get that
$$\frac{d^n}{dx^n}\frac{1}{1-ae^{x}}=\frac{Q(ae^x)}{(1-ae^x)^{n+1}}$$
(*Warning: Everything works out okay in the general case, but the logic here only technically applies for $|ae^x|<1$. More or less, we can figure that, since the answer is at least correct on some open set and everything behaves well everywhere (e.g. is holomorphic), things will work out. Some more deep explanation may exist)


text:
Q: star pattern using recursive func in c I am trying to develop a C code that generates * a pattern by given input. First it must print star descending by 2 and after ascending by 2. like:
input
enter number: 8

output
********
******
****
**
****
******
********

here is what i did so far:
#include <stdio.h>

int printpattern(int n){
    if(n==0)return 0;
    printf("*");
    printpattern(n-1);
}

int pattern(int n){
    if(n==0)return 0;
    puts("\n");
    printpattern(n);
    pattern(n-2);
}

int main(){
    int n;
    puts("number: ");
    scanf("%d", &n);
    if(n%2==1){
        puts("must be even");
        main();
    }
    pattern(n);
    return 0;
}

thanks..

A: Calling the function main recursively will result in executing these statements in each invocation of main
puts("number: ");
scanf("%d", &n);

So it is not a good idea to call main recursively.
I would write the function the following way as it is shown in the demonstration program below.
#include <stdio.h>

void print_pattern( unsigned int n )
{
    if ( n )
    {
        putchar( '*' );
        print_pattern( n - 1 );
    }
}

void pattern( unsigned int n )
{
    if ( n )
    {
        print_pattern( n );
        putchar( '\n' );

        if ( n > 2 )
        {
            pattern( n - 2 );
            print_pattern( n );
            putchar( '\n' );
        }
    }
}

int main(void)
{
    while ( 1 )
    {
        printf( "Enter a non-negative number (0 - exit): " );

        unsigned int n;

        if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

        putchar( '\n' );

        pattern( n );

        putchar( '\n' );
    }

    return 0;
}

The program output might look like
Enter a non-negative number (0 - exit): 8

********
******
****
**
****
******
********

Enter a non-negative number (0 - exit): 7

*******
*****
***
*
***
*****
*******

Enter a non-negative number (0 - exit): 6

******
****
**
****
******

Enter a non-negative number (0 - exit): 5

*****
***
*
***
*****

Enter a non-negative number (0 - exit): 4

****
**
****

Enter a non-negative number (0 - exit): 3

***
*
***

Enter a non-negative number (0 - exit): 2

**

Enter a non-negative number (0 - exit): 1

*

Enter a non-negative number (0 - exit): 0

Of course you can call the function only for even numbers though the function is more general and can be called for any non-negative number.
The function itself should not depend on whether an even or odd number was passed to it.

A: I think if the question states you must use recursion, it makes a lot more sense to use recursion this way:
#include <stdio.h>

static void printstars(int n)
{
    for (int i = 0; i < n; i++) {
        printf("*");
    }
    printf("\n");
}

static void printpattern(int n)
{
    printstars(n);
    if (n > 4) {
        printpattern(n - 2);
    } else {
        printstars(2);
    }
    printstars(n);
}

int main(void)
{
    int n;
    puts("number: ");
    scanf("%d", &n);
    if (n & 1) {
        fprintf(stderr, "must be even\n");
        return 1;
    }
    printpattern(n);
    return 0;
}