text:
Q: Is it a good way to remove 1 element from an array without using a temporary array and without declaring an allocatable variable? I want to know if the following implementation is a good way to remove an element from an array without moving by a temporary array and without considering array as an allocatable variable:
subroutine delete_elements(array, index,size)
    type(tcb),dimension(size),intent(inout)::array
    integer::size,index,i

    do i=index,size-1
       array(i)=array(i+1)
    end do
    size=size-1
 end subroutine delete_elements

I use this subroutine as following:
call delete_elements(tasks_ready_master,1,size(tasks_ready_master))

My array is called tasks_ready_master. I want to retire the first element. size(tasks_ready_master) should be the size of the array used. I'm not sure about the last argument.

A: There are multiple problems here to address: data structure and change of constant argument.

Data structure
You are using an operation (erase) on a data structure (array) which is inherently bad at it.
Why is that?
For removing one element you need to move all following elements in the array.
Here is the wikipedia article talking about comparison of efficiencies of array to other data structures.

Change of constant argument
In your code is a problem:
you supply the constant total size of the array size(tasks_ready_master) but within the procedure you actually change that argument size=size-1.
A quick fix would look something along the lines of
integer :: n
real :: a(5) = [1.0, 2.0, 3.0, 4.0, 5.0]

n = 5
call erase(2, n, a)  ! result: n = 4, a(1:n) = [1.0, 3.0, 4.0, 5.0]
call erase(3, n, a)  ! result: n = 3, a(1:n) = [1.0, 3.0, 5.0]
call erase(1, n, a)  ! result: n = 2, a(1:n) = [3.0, 5.0]

Here I rewrote your procedure to reflect the arguments intent and using vectorization.
subroutine erase(i, n, array)
  !! removes the i-th element within the array.
  !! the array has the total length size(array) but currently only uses n elements.
  integer, intent(in)    :: i
    !! i-th element to erase
  integer, intent(inout) :: n
    !! current length
  real,    intent(inout) :: array

  array(i:n-1) = array(i+1:n)
  n = n-1
end subroutine

Mask
For many operations you can define masks such that you do not need to change the actual array but rather mark the item to delete in another logical array.
You must think of it like turning off specific elements within the array.
There is the downside of the extra memory you need to allocate for the mask but the performance boost from not needing to shift lots of elements outweighs it in most cases.
The following example hopefully explains that in more detail
program main
  integer, parameter :: n = 5
  logical :: m(n) = .true.
  real    :: a(n) = [1.0, 2.0, 3.0, 4.0, 5.0]

  print *, sum(a) ! output: 15

  ! "erase" 2nd element:  a = [1.0, XXX, 3.0, 4.0, 5.0]
  m(2) = .false.
  print *, sum(a, mask=m) ! output: 13

  ! "erase" 3rd element (wrt original array): a = [1.0, XXX, XXX, 4.0, 5.0]
  m(3) = .false.
  print *, sum(a, mask=m) ! output: 10
end program

A: Yes, whenever you will remove an element using your method delete_elements() it will allocate less memory than memory required in creating temporary array.


text:
Q: How can I ggplot a merged data frame composed of factors with an alphabetical sorted x-axis? I have two data frames of nations A and B, some are matching. With rbind() and dplyr::summarise() I generate a new data frame with the counts of each country. In order to ggplot() with alphabetically sorted x-axis I sort the data frame by country with order() and even drop the rownames. Why are in the resulting plot some of the merged countries still appearing at the end of the x-axis and not in the desired alphabetic sorting I've made? (BTW isn't the order of a data frame alphabetic by default, even when it is merged?) Thanks for your help.
# Group A
ctry <- factor(c("ALB", "ALB", "ALB", "ALB", "BEL", "BIH", "CHE", "CHE", "CHE", "CHE", "CHE", "CHE", "CHE",
                 "DEU", "DEU", "ITA", "KOS", "KOS", "KOS", "SVK", "TUR", "TUR"))
df01 <- data.frame(ctry)

rm(ctry)

# Group B
ctry <- factor(c("ECU", "GHA", "CHE", "JAM", "ITA", "KOS", "TUR", "DOM"))
df02 <- data.frame(ctry)

# Group joined
df <- rbind(df01, df02)

# Countries Counts

library(dplyr)

df.sum <- df %>%
  group_by(ctry) %>%
  summarise(num=n()) %>%
  as.data.frame()

# alphabetic sorting

df.sum  <- df.sum [order(df.sum [1]),]
rownames(df.sum ) <- NULL

df.sum

# ctry num                         # Here it's alphabetically sorted...
# 1   ALB   4
# 2   BEL   1
# 3   BIH   1
# 4   CHE   8
# 5   DEU   2
# 6   DOM   1
# 7   ECU   1
# 8   GHA   1
# 9   ITA   2
# 10  JAM   1
# 11  KOS   4
# 12  SVK   1
# 13  TUR   3

# ggplot                         # ...but not in the ggplot. -->

library(ggplot2)

ggplot(df.sum , aes(ctry)) + geom_bar(aes(weight = num, fill = ctry)) +
  scale_fill_discrete(name="Countries")

A: Factors are just numbers with labels, so they may not combine like you think they should.  With rbind and c you get df01 countries first and then anything new in df02.
unclass(ctry)
[1] 3 4 1 6 5 7 8 2
attr(,"levels")
[1] "CHE" "DOM" "ECU" "GHA" "ITA" "JAM" "KOS" "TUR"

I would use dplyr::bind_rows instead of rbind and that will tell you one problem and try to correct it.
df2 <- bind_rows(df01, df02)
 Warning message:
 In bind_rows_(x, .id) : Unequal factor levels: coercing to character

Then ctry is just a character string and will sort like you want
  df.sum <- df2 %>%
  group_by(ctry) %>%
  summarise(num=n())

  ggplot...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can one stop the execution of a foreign method in Java? Is it possible to, and if so how can I, stop the execution of a method that exists in a foreign dependency with Java perhaps by using something such as AoP i.e, AspectJ?
Take this scenario for example:
Foreign code:
class SomeForeignClass {
  private Entity entity;

  public void anApiMethod(String aString) {
    entity.doSomethingWith(aString);
  }
}

If anApiMethod were called, I would want my application to be able to know about its invocation through some sort of listener (this is where I thought AoP might come in handy) and based on some condition either allow it to continue executing or take over control (perhaps for example, save aString for later execution.)
It is currently my understanding that to get close to something like this I would need to fork the existing dependency, make my own changes, and then depend on my own fork. Is this true?

A: That is not necessarily true.  It depends on who creates instances of SomeForeignClass.   If you create them, or you can reinject replacements for them, then you could extend the class and get this new class to act as a wrapper.
SomeForeignClass sfc = getXX();
Wrapper w = new Wrapper(sfc);
setXX(w);

Where Wrapper is
class Wrapper extends SomeForeignClass {
    final SomeForeignClass sfc;

    Wrapper(SomeForeignClass _sfc) {
         sfc = _sfc;
    }

    @Override
    void anApiMethod(String aString) {
        if ( condition() )
             sfc.anApiMethod(aString);
        else
             anAlternateMethod(aString);
    }

    /* ... etc ... */
}

If entity can be retrieved somehow, it could be a little simpler, as you wouldn't need to override every public member, only the ones of interest.
class Wrapper extends SomeForeignClass {

    Wrapper(SomeForeignClass _sfc) {
        super(_sfc.getEntity() );
    }

    @Override
    void anApiMethod(String aString) {
        if ( condition() )
             super.anApiMethod(aString);
        else
             anAlternateMethod(aString);
    }
}

But just because it might be possible to do it this way doesn't mean you should; it may be simpler to depend on your own fork, at least until the change can be pushed upstream.


text:
Q: Integrate product of polynomials I am trying to compute the integral $\int_0^1 p^x(1-p)^{n-x+1} dp$ using integration by parts, however, I am stuck in a loop where I keep computing integrals of products of polynomials (of higher order than the originals).
Is there a general method to compute such integrals?

A: Assuming the exponents are integers the integration by parts should terminate.  The standard convention for the exponents in the integral ("Eulerian Integral of the First Kind") would be $\int _0^1 {x^{m-1}(1-x)^{n-1}dx}$.  Letting $u=x^{m-1}$ and $dv=(1-x)^{n-1}dx$ for an integration by parts gives $$\int _0^1 {x^{m-1}(1-x)^{n-1}dx}= \frac{m-1}{n} \int _0 ^1 {x^{m-2}(1-x)^{n}dx}$$  Proceeding inductively after (m-1) intgegration by parts $$\int _0^1 {x^{m-1}(1-x)^{n-1}dx}= \frac{(m-1)(m-2)\cdot\cdot\cdot2\cdot1}{n(n+1)(n+2)\cdot\cdot\cdot(n+m-2)} \int _0 ^1 {(1-x)^{n+m-2}dx}$$  After evaluating the last integral $$\int _0^1 {x^{m-1}(1-x)^{n-1}dx}= \frac{(m-1)(m-2)\cdot\cdot\cdot2\cdot1}{n(n+1)(n+2)\cdot\cdot\cdot(n+m-1)}=\frac{(m-1)!\space (n-1)!}{(n+m-1)!}$$  The latter expression defines the Beta function $B (m,n)$.


text:
Q: SQL - exact decimal value from averaging a range I tried reading up on previously asked questions, and trying different solutions but I cannot seem to figure it out. I am still learning so any tips and guidance is greatly appreciated.
Here is my query
select  AVG(DATEDIFF(DAY, xx, yy)) AS DayDiff

FROM database1.dbo.table1

where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
       and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
       and ApprovalRequiredFrom = 'GRM'

Result sql gives me is 9, but when I average it in excel it is 9.18. I need sql to give me 2 decimal places. I tried using 'cast' but I cant figure out the correct syntax.
Thanks

A: SQL Server does decimal division, even for averages.  I just multiply by 1.0 as a quick fix:
select  AVG(1.0 * DATEDIFF(DAY, xx, yy)) AS DayDiff

A: DATEDIFF function returns integer (INT) values. Average (AVG) returns the same data type as the expression that holds inside. Operations between integer values (in SQL Server) return integer values. However, operations between integer and other numeric values (like float or decimal) return the last one.
So if you convert the DATEDIFF to return decimal, the result will be decimal.
SELECT AVG(CONVERT(DECIMAL(8,2), DATEDIFF(DAY, xx, yy))) AS DayDiff

Following the same rule, a hard-coded value of 1.0 represents a decimal, so multiplying any integer value with 1.0 yields the same value but with decimal data type.
SELECT  AVG(DATEDIFF(DAY, xx, yy) * 1.0) AS DayDiff

As Jeroen mentioned, converting the argument will yield a decimal average, but with more than 2 decimals. You will have to convert the average result at the end.
SELECT
    CONVERT(DECIMAL(8,2),
        AVG(DATEDIFF(DAY, xx, yy) * 1.0)) AS DayDiff


text:
Q: How can I set the max value of the progress bar dynamically I'm working on a site help student to type fast
the text that student should write  is a quote from api.quotable.io
my question is how can I set the max value of progress bar to suit the text length and increase the value when the student type the character right and decrease it when wrong.
I added comment in javascript file where my problems is .

const RANDOM_QUOTE_API_URL = "http://api.quotable.io/random";
const quoteDisplayElement = document.getElementById("quoteDisplay");
const quoteInputElement = document.getElementById("quoteInput");
const timerElement = document.getElementById("timer");

quoteInputElement.addEventListener("input", () => {
  const arrayQuote = quoteDisplayElement.querySelectorAll("span");
  const arrvalue = quoteInputElement.value.split("");
  // Get the progress bar and set the max value
  document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuemax', arrayQuote.length);
  let correct = true;
  let progress = 0;
  arrayQuote.forEach((characterSpan, index) => {
    const character = arrvalue[index];
    if (character == null) {
      characterSpan.classList.remove("correct");
      characterSpan.classList.remove("incorrect");
      correct = false;
    } else if (character == characterSpan.innerText) {
      characterSpan.classList.add("correct");
      characterSpan.classList.remove("incorrect");
      // increase the value for the progress bar if the char is correct
      progress = index;
      document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow', progress);
      document.getElementsByClassName('progress-bar').item(0).setAttribute('style', 'width:' + progress + '%');
    } else {
      characterSpan.classList.add("incorrect");
      characterSpan.classList.remove("correct");
      correct = false;
      // Decrease the value for the progress bar if the char is correct
      progress -= 1;
      document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow', progress);
      document.getElementsByClassName('progress-bar').item(0).setAttribute('style', 'width:' + progress + '%');
    }
  });
  if (correct) renderNewQuote();
});

function getRandomQuote() {
  return fetch(RANDOM_QUOTE_API_URL)
    .then((response) => response.json())
    .then((data) => data.content);
}

async function renderNewQuote() {
  const quote = await getRandomQuote();
  quoteDisplayElement.innerHTML = "";
  quote.split("").forEach((character) => {
    const characterSpan = document.createElement("span");
    characterSpan.innerText = character;
    quoteDisplayElement.appendChild(characterSpan);
  });
  document.getElementsByClassName('progress-bar').item(0).setAttribute('style', 'width:' + Number(0) + '%');
  quoteInputElement.value = null;
  startTimer();
}
let startTime;

function startTimer() {
  timerElement.innerText = 0;
  startTime = new Date();
  setInterval(() => {
    timerElement.innerText = getTimerTime();
  }, 1000);
}

function getTimerTime() {
  return Math.floor((new Date() - startTime) / 1000);
}
renderNewQuote();
#login-dp {
  min-width: 250px;
  padding: 14px 14px 0;
  overflow: hidden;
  background-color: rgba(255, 255, 255, .8);
}

#login-dp .help-block {
  font-size: 12px
}

#login-dp .bottom {
  background-color: rgba(255, 255, 255, .8);
  border-top: 1px solid #ddd;
  clear: both;
  padding: 14px;
}

#login-dp .social-buttons {
  margin: 12px 0
}

#login-dp .social-buttons a {
  width: 49%;
}

#login-dp .form-group {
  margin-bottom: 10px;
}

.btn-fb {
  color: #fff;
  background-color: #3b5998;
}

.btn-fb:hover {
  color: #fff;
  background-color: #496ebc
}

.btn-tw {
  color: #fff;
  background-color: #55acee;
}

.btn-tw:hover {
  color: #fff;
  background-color: #59b5fa;
}

@media(max-width:768px) {
  #login-dp {
    background-color: inherit;
    color: #fff;
  }
  #login-dp .bottom {
    background-color: inherit;
    border-top: 0 none;
  }
}

.container {
  background-color: black;
  padding: 1rem;
  border-radius: .5rem;
  color: green;
}

.quote-display {
  margin-bottom: 1rem;
  margin-left: calc(1rem+2px);
  margin-right: calc(1rem+2px);
  font-family: Arial, Helvetica, sans-serif;
  font-size: x-large;
  height: 20rem;
}

.quote-input {
  background-color: transparent;
  border: 2px solid #A1922E;
  outline: none;
  width: 100%;
  height: 10rem;
  margin: auto;
  resize: none;
  /* padding: .3rem 1rem; */
  font-size: x-large;
  border-radius: .5rem;
}

.quote-input:focus {
  border-color: black;
}

.correct {
  color: rgb(20, 204, 20);
}

.incorrect {
  color: red;
}
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Bootstrap Navbar with Login Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="css/style.css" />

  <link rel="stylesheet" href="css/demo.css" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

          </button>

Hannibla Typing Club

Link

            Levels

Level 1

Level 2

Level 3

Level 4

Level 5

Already have an account?

            Login

                    <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">

                        Email address
                          <input
                            type="email"
                            class="form-control"
                            id="exampleInputEmail2"
                            placeholder="Email address"
                            required
                          />

                          Password
                          <input
                            type="password"
                            class="form-control"
                            id="exampleInputPassword2"
                            placeholder="Password"
                            required
                          />

                            Forget the password ?

                          <button
                            type="submit"
                            class="btn btn-primary btn-block"
                          >
                            Sign in
                          </button>

                            <input type="checkbox" /> keep me logged-in

                    </form>

                    New here ? Join Us

    <textarea id="quoteInput" class="quote-input" autofocus></textarea>

    Author: Stefano - Distributed By:
    Write Code


text:
Q: Outlets cannot be connected to repeating content iOS I have just created an app and have started hooking up @IBOutlet's to the storyboard. I am connecting some of them to labels in a UITableViewCell Prototype Cell with a Basic Style. When I connect it though I get this error in the Storyboard:

The detailText Outlet from the TableViewController to the UILabel is invalid. Outlets cannot be connected to repeating content.

Can someone help me out? I have set it up the way I always do successfully but this time it has chucked me this error.

A: There are two types of table views cells provided to you through the storyboard, they are Dynamic Prototypes and Static Cells

1. Dynamic Prototypes
From the name, this type of cell is generated dynamically. They are controlled through your code, not the storyboard. With help of table view's delegate and data source, you can specify the number of cells, heights of cells, prototype of cells programmatically.
When you drag a cell to your table view, you are declaring a prototype of cells. You can then create any amount of cells base on this prototype and add them to the table view through cellForRow method, programmatically. The advantage of this is that you only need to define 1 prototype instead of creating each and every cell with all views added to them by yourself (See static cell).
So in this case, you cannot connect UI elements on cell prototype to your view controller. You will have only one view controller object initiated, but you may have many cell objects initiated and added to your table view. It doesn't make sense to connect cell prototype to view controller because you cannot control multiple cells with one view controller connection. And you will get an error if you do so.

To fix this problem, you need to connect your prototype label to a UITableViewCell object. A UITableViewCell is also a prototype of cells and you can initiate as many cell objects as you want, each of them is then connected to a view that is generated from your storyboard table cell prototype.

Finally, in your cellForRow method, create the custom cell from the UITableViewCell class, and do fun stuff with the label
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! YourCell

    cell.label.text = "it works!"

    return cell
}

2. Static Cells
On the other hand, static cells are indeed configured though storyboard. You have to drag UI elements to each and every cell to create them. You will be controlling cell numbers, heights, etc from the storyboard. In this case, you will see a table view that is exactly the same from your phone compared with what you created from the storyboard. Static cells are more often used for setting page, which the cells do not change a lot.
To control UI elements for a static cell, you will indeed need to connect them directly to your view controller, and set them up.

A: Or you don't have to use IBOutlet to refer to the object in the view. You can give the Label in the tableViewCell a Tag value, for example set the Tag to 123 (this can be done by the attributes inspector). Then you can access the label by
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "someID", for: indexPath)

    let label = cell.viewWithTag(123) as! UILabel //refer the label by Tag

    switch indexPath.row {
    case 0:
        label.text = "Hello World!"
    default:
        label.text = "Default"
    }
    return cell
}

A: If you're using a table view to display Settings and other options (like the built-in Settings app does), then you can set your Table View Content to Static Cells under the Attributes Inspector.  Also, to do this, you must embedded your Table View in a UITableViewController instance.

A: Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.

A: With me I have a UIViewcontroller, and into it I have a tableview with a custom cell on it. I map my outlet of UILabel into UItableviewcell to the UIViewController then got the error.

A: As most people have pointed out that subclassing UITableViewCell solves this issue.
But the reason this not allowed because the prototype cell(UITableViewCell) is defined by Apple and you cannot add any of your own outlets to it.

A: Sometimes Xcode could not control over correctly cell outlet connection.
Somehow my current cell's label/button has connected another cell
I just remove those and error goes away.

A: For collectionView :
solution:

From viewcontroller, kindly remove the IBoutlet of colllectionviewcell

. the issue mentions the invalid of your IBOutlet. so remove all subclass which has multi-outlet(invalids) and reconnect it.
The answer is already mentioned in another question for collectionviewcell

A: Click on simulator ,
Navigate to Window and enable Device Bezels


text:
Q: MJML- is there a way to get text under two columns? I am currently trying to get text to display under two columns in a section in the MJML email framework.  The issue I am having is that I can put the text under 1 column or under the other. But I want to center this text under both columns in question.  This needs to be done without breaking the mobile responsiveness.  I have tried grouping them but the text disappears on mobile.  I have also built a whole separate section to get it underneath but then is falls out of line when on mobile and it goes under the social icons instead of staying under the appstore and googleplay icons like I want it too.
This is what I want:

This is what I am getting. I am able to put text under each image but not under both centered like I want.
This is what I have

Does anyone know how to successfully do this.  Like I said adding sections or grouping the items ends up destroying the responsiveness for mobile.
This is what I want it to look like stacked up on mobile.
What I want it to look like on mobile

This is the code:
<mj-raw>

</mj-raw>
<mj-section padding="0px 0px 0px 0px">
  <mj-column width="80px" padding="0px 0px">
    <mj-text font-family="'Open Sans',Helvetica,Arial,sans-serif" padding="0px"
       align="center" font-size="10px" font-weight="700" line-height="20px"
       color="#00bced">get to
know us!
    </mj-text>
  </mj-column>
  <mj-column width="110px">
    <mj-image padding="5px 7px" href="https://www.petsmart.com/"
       src="/assets/appstore.png" width="96px" height="29px" />
    <mj-text align="center" line-height="20px" color="#002d3f" padding="0px" font-
        size="10px">
        download the FREE PetSmart app
    </mj-text>
  </mj-column>
  <mj-column width="110px">
    <mj-image padding="5px 7px" href="https://www.petsmart.com/"
       src="/assets/playstore.png" width="96px" height="29px" />
    <mj-text align="center" line-height="20px" color="#002d3f" padding="0px" font-
      size="10px">
      download the FREE PetSmart app
    </mj-text>
  </mj-column>
  <mj-group width="300px">
    <mj-column>
      <mj-image padding="0" href="https://www.petsmart.com/"
         src="/assets/treats_loyalty.png" width="51.33px" height="33px" />
      <mj-text font-family="'Open Sans',Helvetica,Arial,sans-serif" align="center" font-
         size="10px" line-height="0px" color="#002d3f">
        loyalty
      </mj-text>
    </mj-column>
    <mj-column>
      <mj-image padding="0" href="https://www.petsmart.com/" src="/assets/instagram.png"
         width="33px" height="33px" />
      <mj-text font-family="'Open Sans',Helvetica,Arial,sans-serif" align="center" font-
         size="10px" line-height="0px" color="#002d3f">
        social
      </mj-text>
    </mj-column>
    <mj-column>
      <mj-image padding="0" href="https://www.petsmart.com/" src="/assets/location.png"
         width="25px" height="33px" />
      <mj-text font-family="'Open Sans',Helvetica,Arial,sans-serif" align="center" font-
          size="10px" line-height="0px" color="#002d3f">
        location
      </mj-text>
    </mj-column>
  </mj-group>
</mj-section>
<mj-section padding="0px 0px 30px 0px" border-bottom="1px solid #c9c9c9">
</mj-section>

A: So firstly you need to combine the two buttons into one column, because their layout will stay the same on desktop and mobile. That will prevent them separately stacking.
Secondly, for the two buttons side by side, it looks like what you want is the mj-group component. That will not stack (https://documentation.mjml.io/#mj-group) Wrap the images in mj-columns, and then wrap all of that in a mj-group, with the text separate (underneath).
That's all we need to change.
  <mj-column width="220px">
    <mj-group  width="100%">
      <mj-column>
        <mj-image padding="5px 5px" href="https://www.petsmart.com/"
       src="https://via.placeholder.com/96x29" width="96px" height="29px" />
        </mj-column>
      <mj-column>
        <mj-image padding="5px 5px" href="https://www.petsmart.com/"
       src="https://via.placeholder.com/96x29" width="96px" height="29px" />
        </mj-column>
      </mj-group>

    <mj-text align="center" line-height="20px" color="#002d3f" padding="0px" font-size="10px">
        download the FREE PetSmart app
    </mj-text>
  </mj-column>

Ref: https://mjml.io/try-it-live/QiFDHwx-Y


text:
Q: DevOps : AWS Lambda .zip with Terraform I have written Terraform to create a Lambda function in AWS.
This includes specifying  my python code zipped.
Running from Command Line into my tech box, all goes well.
The terraform apply action sees my zip moved into AWS and used to create the lambda.
Key section of code :
resource "aws_lambda_function" "meta_lambda" {
              filename = "get_resources.zip"
              source_code_hash = filebase64sha256("get_resources.zip")
              .....

Now, to get this into other environments, I have to push my Terraform via Azure DevOps.
However, when I try to build in DevOps, I get the following :

Error: Error in function call   on main.tf line 140, in resource
  "aws_lambda_function" "meta_lambda": 140:   source_code_hash =
  filebase64sha256("get_resources.zip") Call to function
  "filebase64sha256" failed: no file exists at get_resources.zip.

I have a feeling that I am missing a key concept here as I can see the .zip in the repo - so do not understand how it is not found by the build?
Any hints/clues as to what I am doing wrong, gratefully welcome.

A: Chaps, I'm afraid that I may have just been over my head here - new to terraform & DevOps !
I had a word with our (more) tech folks and they have sorted this.

The reason I think yours if  failing is becuase the Tar Terraform step
  needs to use a different command line so it gets the zip file included
  into the artifacts.   tar -cvpf terraform.tar .terraform .tf tfplan
      tar --recursion -cvpf terraform.tar --exclude='/.git' --exclude='.gitignore' .

.. it that means anything to you !
Whatever they did, it works !
As there is a bounty on this, I still going to assign it as I am grateful for the input !
Sorry if this was a it of a newbie error.

A: You can try building your package with terraform AWS lambda build module. As it has been very useful for the processTerraform Lambda build module

A: According to the document example, in the source_code_hash argument, filebase64sha256 ("get_resources.zip") needs to be enclosed in double quotes.

You can refer to this document for details.


text:
Q: How to properly setup googleTest on OS X aside from XCode How do I setup gTest, so that I can link aganist the library? I will code in vim, so I just want to install the libraries, unlike the XCode setup. Goal is to be able to link a project against the library by setting -lgtest as linker flag and optionally, if I did not write my own test mainroutine, the explicit -lgtest_main flag.

A: It's adviced that you link statically. There's no secret. Being a bit offtopic, I use CMake in my projects, which I recommend, and here (https://github.com/oblitum/operations) I have setup a very basic skeleton project that links to gmock and gtest (it's also adviced by google that you use the same gtest from gmock, when you use gmock). In the external folder reside the external CMake files that actually import gtest and gmock through ExternalProject_Add. In the sample, I'm setting the URL as a file path in my system where gmock and gtest are downloaded, but, if you check CMake ExternalProject_Add docs you can see that download urls, online repository urls are also available, which can allow your build to download gtest and gmock, and cache it, automatically.

A: Before you start make sure your have read and understood
this note from Google! This tutorial makes using gtest easy, but may introduce nasty bugs.
1. Get the googletest framework
$ wget https://github.com/google/googletest/archive/release-1.8.0.zip

Or get it by hand. I guess I won't manitain this little How-to, so if you stumbled upon it and the links are outdated, feel free to edit it.
2. Unzip and build google test
$ unzip gtest-1.8.0.zip
$ cd gtest-1.8.0
$ ./configure
$ make

3. "Install" the headers and libs on your system.
$ sudo cp -a include/gtest /usr/include
$ sudo cp -a lib/.libs/* /usr/lib/

gTestframework is now ready to use. Just don't forget to link your project against the library by setting -lgtest as linker flag and optionally, if you did not write your own test mainroutine, the explicit -lgtest_main flag.
From here on you might want to go to Googles documentation about the framework to learn how it works. Happy coding!

A: I think cmake is an easy way to setup and use gtest on OSX. It works  without manually copying files. Unzip gooletest-release-1.8.0, then
cd googletest-release-1.8.0

# create a build directory
mkdir build
cd build

# build configuration
cmake .. -DBUILD_GTEST=ON -DBUILD_SHARED_LIBS=ON

# build it
make

# installation
sudo make install

Afterwards, you can easily incorporate gtest in your project with the cmake commands
# sets GTEST_INCLUDE_DIRS and GTEST_LIBRARIES
find_package( GTest REQUIRED )

# adds the gtest include directory
include_directories( ${GTEST_INCLUDE_DIRS} )

# links gtest
target_link_libraries( yourTestApp ${GTEST_LIBRARIES} )


text:
Q: How can I get a guarantee that when a memory is freed, the OS will reclaim that memory for it's use? I noticed that this program:
#include <stdio.h>

int main() {
  const size_t alloc_size = 1*1024*1024;
  for (size_t i = 0; i < 3; i++) {
    printf("1\n");
    usleep(1000*1000);
    void *p[3];
    for (size_t j = 3; j--; )
      memset(p[j] = malloc(alloc_size),0,alloc_size); // memset for de-virtualize the memory
    usleep(1000*1000);
    printf("2\n");
    free(p[i]);
    p[i] = NULL;
    usleep(1000*1000*4);
    printf("3\n");
    for (size_t j = 3; j--; )
      free(p[j]);
  }
}

which allocates 3 memories, 3 times and each time frees different memory, frees the memory according to watch free -m, which means that the OS reclaimed the memory for every free regardless of the memory's position inside the program's address space. Can I somehow get a guarantee for this effect? Or is there already anything like that (like a rule of >64KB allocations)?

A: The short answer is: In general, you cannot guarantee that the OS will reclaim the freed memory, but there may be an OS specific way to do it or a better way to ensure such behavior.
The long answer:

*

*Your code has undefined behavior: there is an extra free(p[i]); after the printf("2\n"); which accesses beyond the end of the p array.

*You allocate large blocks (1 MB) for which your library makes individual system calls (for example mmap in linux systems), and free releases these blocks to the OS, hence the observed behavior.

*Various OSes are likely to implement such behavior for a system specific threshold (typically 128KB), but the C standard gives guarantee about this, so relying on such behavior is system specific.

*Read the manual page for malloc() on your system to see if this behavior can be controlled. For example, the C library on Linux uses an environment variable MMAP_THRESHOLD to override the default setting for this threshold.

*If you program to a Posix target, you might want to use mmap() directly instead of malloc to guarantee that the memory is returned to the system once deallocated with munmap(). Note that the block returned by mmap() will have been initialized to all bits zero before the first access, so you may avoid such explicit initialization to take advantage of on demand paging, on perform explicit initialization to ensure the memory is mapped to try and minimize latency in later operations.

A: On the OSes I know, and especially on linux:
no, you cannot guarantee reuse. Why would you want that? Reuse only happens when someone needs more memory pages, and Linux will then have to pick pages that aren't currently mapped to a process; if these run out, you'll get into swapping. And: you can't make your OS do something that is none of your processes' business. How it internally manages memory allocations is none of the freeing process' business. In fact, that's security-wise a good thing.
What you can do is not only freeing the memory (which might leave it allocated to your process, handled by your libc, for later mallocs), but actually giving it back (man sbrk, man munmap, have fun). That's not something you'd usually do.
Also: this is yet another instantiation of "help, linux ate my RAM"... you misinterpret what free tells you.

A: For glibc malloc(), read the man 3 malloc man page.
In short, smaller allocations use memory provided by sbrk() to extend the data segment; this is not returned to the OS. Larger allocations (typically 132 KiB or more; you can use MMAP_THRESHOLD on glibc to change the limit) use mmap() to allocate anonymous memory pages (but also include memory allocation bookkeeping on those pages), and when freed, these are usually immediately returned to the OS.
The only case when you should worry about the process returning memory to the OS in a timely manner, is if you have a long-running process, that temporarily does a very large allocation, running on an embedded or otherwise memory-constrained device. Why? Because this stuff has been done in C successfully for decades, and the C library and the OS kernel do handle these cases just fine. It just isn't a practical problem in normal circumstances. You only need to worry about it, if you know it is a practical problem; and it won't be a practical problem except on very specific circumstances.

I personally do routinely use mmap(2) in Linux to map pages for huge data sets. Here, "huge" means "too large to fit in RAM and swap".
Most common case is when I have a truly huge binary data set. Then, I create a (sparse) backing file of suitable size, and memory-map that file. Years ago, in another forum, I showed an example of how to do this with a terabyte data set -- yes, 1,099,511,627,776 bytes -- of which only 250 megabytes or so was actually manipulated in that example, to keep the data file small. The key here in this approach is to use MAP_SHARED | MAP_NORESERVE to ensure the kernel does not use swap memory for this dataset (because it would be insufficient, and fail), but use the file backing directly. We can use madvise() to inform the kernel of our probable access patterns as an optimization, but in most cases it does not have that big of an effect (as the kernel heuristics do a pretty good job of it anyway). We can also use msync() to ensure certain parts are written to storage. (There are certain effects that has wrt. other processes that read the file backing the mapping, especially depending on whether they read it normally, or use options like O_DIRECT; and if shared over NFS or similar, wrt. processes reading the file remotely. It all goes quite complicated very quickly.)
If you do decide to use mmap() to acquire anonymous memory pages, do note that you need to keep track of both the pointer and the length (length being a multiple of page size, sysconf(_SC_PAGESIZE)), so that you can release the mapping later using munmap(). Obviously, this is then completely separate from normal memory allocation (malloc(), calloc(), free()); but unless you try to use specific addresses, the two will not interfere with each other.

A: If you want memory to be reclaimed by the operating system you need to use operating system services to allocate the memory (which be allocated in pages). Deallocate the memory, you need to call the operating system services that remove pages from your process.
Unless you write your own malloc/free that does this, you are never going to be able to accomplish your goal with off-the-shelf library functions.


text:
Q: how to run commands (external) in gvim I am getting ready to write lot of small experimental java programs as I am studying for java certification. Since I want to avoid using an IDE I'm giving gvim a try.
I have a HelloWorld.java file open. How can I run javac and then java and then be able to see the output all in one window?
I do not want to alt tab to a dos prompt window. compile/run the program there and then come back to my editor.

A: Try this in command mode:
:!javac HelloWorld.java && java HelloWorld

Edit: I believe that in windows do concatenate multiple commands you use && and not ; as I posted previously. But I'm not sure if this applies to gvim.

A: You can run external programs from vim by prefixing the command you want to run with "!". For example you could run javac straight from gvim by typing ":!javac filename"


text:
Q: Number of distinct UK bingo pages An UK bingo ticket contains 27 spaces, arranged in nine columns by three rows. Each row contains five numbers and four blank spaces. Each column contains up to three numbers, which are arranged as follows:

*

*The first column contains numbers from 1 to 9,

*The second column numbers from 10 to 19,

*The third column number from 20 to 29 so on up until the last column, which contains numbers from 80 to 90.

Tickets are created as strips of 6, in such a way that every number from 1 to 90 appears exactly once. This is also called a bingo page. (Wikipedia page)
Example of a valid bingo page:
$$
  \begin{array}{ | c |}
    \hline
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
    3 & 12 &    & 33 &    &    &    & 70 & 83 \\ \hline
    6 & 16 & 20 &    &    &    & 61 & 75 &    \\ \hline
      &    & 29 &    & 43 & 56 & 65 & 78 &    \\ \hline
    \hline
  \end{array}
  \\
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
      & 11 & 26 & 30 & 40 &    & 60 &    &    \\ \hline
    7 & 17 &    &    & 46 & 58 &    &    & 88 \\ \hline
      &    &    & 32 & 49 &    & 69 & 77 & 89 \\ \hline
    \hline
  \end{array}
  \\
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
      & 10 & 23 & 34 &    & 54 &    &    & 90 \\ \hline
    1 &    & 25 &    &    & 57 & 66 & 73 &    \\ \hline
      & 19 &    & 38 & 48 & 59 & 68 &    &    \\ \hline
    \hline
  \end{array}
  \\
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
      & 13 & 28 &    &    & 50 & 62 & 74 &    \\ \hline
    4 &    &    & 37 & 45 & 55 &    &    & 80 \\ \hline
    5 &    &    & 39 &    &    & 64 & 79 & 84 \\ \hline
    \hline
  \end{array}
  \\
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
      & 15 & 21 &    & 44 & 52 &    &    & 81 \\ \hline
    2 &    & 22 & 35 &    &    & 67 &    & 82 \\ \hline
    9 &    &    & 36 &    & 53 &    & 71 & 86 \\ \hline
    \hline
  \end{array}
  \\
  \begin{array}{ | c | c | c | c | c | c | c | c | c | }
    \hline
      & 14 & 24 & 31 & 41 &    &    & 72 &    \\ \hline
    8 &    & 27 &    & 42 &    &    & 76 & 85 \\ \hline
      & 18 &    &    & 47 & 51 & 63 &    & 87 \\ \hline
    \hline
  \end{array}
  \end{array}
$$
How can one calculate how many different bingo pages can be created?


text:
Q: Apple Remote for iPhone won't discover iTunes library without network gateway to internet enabled This may be a networking question as much as an Apple-specific question; however it's directly related to configuration / behaviour of Apple Remote, so hoping to find an answer here.
My goal: Build a USB-powered music server to be used in my car. Control it via the iTunes remote app on my iPhone. Enable direct wireless connection between iPhone and music server without any additional network infrastructure.
My setup:

*

*Apple Remote (latest version from App Store) running on iOS 7.1.1.

*Raspberry Pi running forked-daapd, an iTunes-compatible media server with support for Apple Remote. It's also running Shairport which is an Airplay-compatible receiver.

*Edimax EW-7811UN USB wireless adapter attached to the Raspberry Pi.

The Pi is configured to act as a wireless access point and assign IP addresses via DHCP to any devices that connect to it. It has no other network interfaces, so has no internet connectivity.
My iPhone is connected directly to the wireless network broadcast by the Pi. I can successfully stream music to the Airplay receiver on the Pi, and have also paired the Remote app on my iPhone with the forked-daapd server on the Pi and can control the library from my iPhone.
The problem is connecting to the Pi's wireless network prevents the iPhone from accessing the mobile data network, as it tries to route internet traffic over the wireless network, and the Pi has no internet connection.
This is easily resolved - configure the Pi's wireless access point not to assign a router/dns server. So only an IP address and subnet is provided to DHCP clients. In the case of the iPhone, this means it will continue to route internet traffic over the mobile data connection, and send local traffic for addresses on the wireless network to the Pi.
With this configuration, I can still successfully stream audio via Airplay to the Pi, whilst simultaneously accessing the internet over the iPhone's mobile data connection. However, it prevents the Remote app from finding the library on the Pi. Even with "Stay Connected" enabled in the Remote app settings, as soon as I remove the router/dns settings from the Pi's wireless access point DHCP config and renew the DHCP lease on the iPhone, Remote can no longer connect to the library.
I'm assuming that mDNS is working correctly, as the Airplay receiver is still discoverable by the iPhone. Does anyone know what could be causing Remote to fail to see the library, and how I might go about resolving this issue?


text:
Q: Python script (subprocess) exits with status 1 I am running a Python script that calls another program that takes in input files and converts it to another format.
I have
subprocess.check_output("/usr/local/bin/program -c convert -f {0} -o {1}".format(full_input_path, full_output_path),shell=True).split("\n")[0:-1]

I get the error Command '/usr/local/bin/program -c convert -f /full/path/to/input/file -o /full/path/to/output/folder' returned non-zero exit status 1
However, if I copy and paste the exact command in the error message and run it on its own, there is no error. Even when I run the script with the error message, the input file is still correctly converted and stored in the output folder. It all seems like there is nothing wrong with the command.
I'm suspect that the program code simply exits with status 1 even where there is no error, but I can't check because I don't have the source code.
Is there a way to not display the error message?


text:
Q: Display a webcam stream in PyQt4 using OpenCV Camera Capture I am using this Python script to display my webcam:
from opencv.cv import *
from opencv.highgui import *

import sys

cvNamedWindow("w1", CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cvCreateCameraCapture(camera_index)

def repeat():
    global capture #declare as globals since we are assigning to them now
    global camera_index
    frame = cvQueryFrame(capture)
    cvShowImage("w1", frame)
    c = cvWaitKey(10)

    if c == "q":
        sys.exit(0)

if __name__ == "__main__":
    while True:
        repeat()

It is working quite well, but I would like to set this display inside my Qt application.
How can I use the IplImage OpenCV image into a Qt VideoWidget?

A: It looks like we need to bind this C++ code in Python :
QImage& cvxCopyIplImage(const IplImage *pIplImage, QImage &qImage)
{
        if(!CV_IS_IMAGE(pIplImage)) return qImage;

        int w = pIplImage->width;
        int h = pIplImage->height;

        if(qImage.width() != w || qImage.height() != h)
        {
                qImage = QImage(w, h, QImage::Format_RGB32);
        }

        int x, y;
        for(x = 0; x < pIplImage->width; ++x)
        {
                for(y = 0; y < pIplImage->height; ++y)
                {
                        CvScalar color = cvGet2D(pIplImage, y, x);

                        if(pIplImage->nChannels == 1)
                        {
                                int v = color.val[0];

                                qImage.setPixel(x, y, qRgb(v,v,v));
                        }
                        else
                        {
                                int r = color.val[2];
                                int g = color.val[1];
                                int b = color.val[0];

                                qImage.setPixel(x, y, qRgb(r,g,b));
                        }
                }
        }

        if(pIplImage->origin != IPL_ORIGIN_TL)
        {
                qImage = qImage.mirrored(false, true);
        }

        return qImage;
}

A: I used the code bellow to covert a Iplimage objet to a QImage. It took me some time to get the right formats. Iplimage is a 3-channel format with BGR channel order while QImage uses RGB channel order.
camcapture = cv.CaptureFromCAM(0)
cv.SetCaptureProperty(camcapture,cv.CV_CAP_PROP_FRAME_WIDTH, 1280)
cv.SetCaptureProperty(camcapture,cv.CV_CAP_PROP_FRAME_HEIGHT, 720);

frame = cv.QueryFrame(camcapture)
image = QImage(frame.tostring(), frame.width, frame.height, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(image)

A: This one worked for me. I work on Linux with Python 2.6.5:
import base64
import Image
import time
import urllib2
import cv

# Basic HTTP Authentication...
url = 'http://192.168.0.11:82/Videostream.cgi'
ww = 'Username:Password'
encodedstring = base64.encodestring(ww)[:-1]
auth = "Basic %s" % encodedstring
req = urllib2.Request(url,None, {"Authorization": auth })
handle = urllib2.urlopen(req)

def read_stream():
    buf = ''
    b = handle.readlines(45)
    for a in b:
        if a.startswith('Content-Length'):
            readlen = str(a).split()[1]
    b1 = handle.read(int(readlen)+4)
    return b1

def test():
    pass

def write_stream():
    imgc = read_stream()
    cv_img = cv.CreateImageHeader((640,480), cv.IPL_DEPTH_8U, 3)
    buf = Image.fromstring('RGB',(640,480),imgc[2:], 'jpeg', 'RGB', None)
    cv.SetData(cv_img, buf.tostring(), (640*3))
    return cv_img

fps = 10.0

if __name__ == "__main__":
    while True:
        frame = write_stream()
        cv.ShowImage('Camera', frame)
        k = cv.WaitKey(10)
        time.sleep(int(1.0/fps))
        if k == 0x10001b: # ESC
            cv.DestroyWindow("Camera")
            print 'ESC pressed. Exiting ...'
            break


text:
Q: Pandas: Replace a string with 'other' if it is not present in a list of strings I have the following data frame, df, with column 'Class'
    Class
0   Individual
1   Group
2   A
3   B
4   C
5   D
6   Group

I would like to replace everything apart from Group and Individual with 'Other', so the final data frame is
    Class
0   Individual
1   Group
2   Other
3   Other
4   Other
5   Other
6   Group

The dataframe is huge, with over 600 K rows. What is the best way to optimally look for values other than 'Group' and 'Individual' and replace them with 'Other'?
I have seen examples for replace, such as:
df['Class'] = df['Class'].replace({'A':'Other', 'B':'Other'})

but since the sheer amount of unique values i have are too many i cannot individually do this. I want to rather just use the exclude subset of 'Group' and 'Individual'.

A: Another approach could be:
df.loc[~df['Class'].isin(['Individual', 'Group']), 'Class'] = 'Other'

A: I think you need:
df['Class'] = np.where(df['Class'].isin(['Individual','Group']), df['Class'], 'Other')
print (df)
        Class
0  Individual
1       Group
2       Other
3       Other
4       Other
5       Other
6       Group

Another solution (slower):
m = (df['Class'] == 'Individual') | (df['Class'] == 'Group')
df['Class'] = np.where(m, df['Class'], 'Other')

Another solution:
df['Class'] = df['Class'].map({'Individual':'Individual', 'Group':'Group'}).fillna('Other')

Performance (in real data depends of number of replacements):
#[700000 rows x 1 columns]
df = pd.concat([df] * 100000, ignore_index=True)
#print (df)

In [208]: %timeit df['Class1'] = np.where(df['Class'].isin(['Individual','Group']), df['Class'], 'Other')
25.9 ms ± 485 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [209]: %timeit df['Class2'] = np.where((df['Class'] == 'Individual') | (df['Class'] == 'Group'), df['Class'], 'Other')
120 ms ± 6.63 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [210]: %timeit df['Class3'] = df['Class'].map({'Individual':'Individual', 'Group':'Group'}).fillna('Other')
95.7 ms ± 3.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [211]: %timeit df.loc[~df['Class'].isin(['Individual', 'Group']), 'Class'] = 'Other'
97.8 ms ± 6.78 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: You can do it this way for example

*

*get list of unique items list = df['Class'].unique()

*remove your known class list.remove('Individual')....

*then list all Other rows df[df.class is in list]

*replace class values df[df.class is in list].class = 'Other'
Sorry for this pseudo-pseudo code, but principle is same.

A: You can use pd.Series.where:
df['Class'].where(df['Class'].isin(['Individual', 'Group']), 'Other', inplace=True)

print(df)

        Class
0  Individual
1       Group
2       Other
3       Other
4       Other
5       Other
6       Group

This should be efficient versus map + fillna:
df = pd.concat([df] * 100000, ignore_index=True)

%timeit df['Class'].where(df['Class'].isin(['Individual', 'Group']), 'Other')
# 60.3 ms per loop

%timeit df['Class'].map({'Individual':'Individual', 'Group':'Group'}).fillna('Other')
# 133 ms per loop

A: Another way using apply :
df['Class'] = df['Class'].apply(lambda cl : cl if cl in ["Individual","Group"] else "Other"]


text:
Q: How to handle an empty param in Kotlin? In java we can do following
class A{
  int id;
  String name;

  public A(){}
  public A(int id, String name){
    this.id = id;
    this.name = name;
  }
  // getter/ setter
}

then I can create a new Object and get json as following
A a= new A()
a.setName("test")

System.out.println(new Gson().toJson(a))

which gives me the result
{"name":"test"}

In kotlin how can i achive this?
The problem I am facing is kotlin saying primitive type has to be initialized. So in json I am getting both id and name; which i don't want
So how to do this???

A: Kotlint treats null safety seriously thus you have to be explicit about the initialization values. Your example can be translated to:
class A(var id: Int? = null, var name: String? = null)

Notice that the above has both default arguments and a parameterless constructor on the JVM. This let's you write:
val a = A()

As well as:
val a = gson.fromJson(json, A::class.java)

A: How about lateinit?
/* ***************************************************************************/
class A() {
  lateinit var id : Integer // Integer instead of Int due to lateinit's no-primitives requirement
  lateinit var name : String

  constructor(id : Integer, name : String) : this() {
    this.id = id
    this.name = name
  }
}
/* ***************************************************************************/

/* ***************************************************************************/
fun main(args: Array<String>) {
  val a = A()

  a.name = "test"

  assert(Gson().toJson(a) == """{"name":"test"}""")

  val aFromJson = Gson().fromJson("""{"name":"test"}""", A::class.java)

  assert(a.name == "test")
}
/* ***************************************************************************/

The advantage of using lateinit is the lack of nullable properties inside the class thus, you avoid dealing with a bunch of null checking and ?. derefering.


text:
Q: R question: How to mimic this graph to show the percent change of cells in health and disease? I am interested in showing how the proportions of cells change from health to disease. I wanted to show a 'flow' from health to disease rather than just have two separate stacked bar charts, but I'm unsure if this type of visualization has a name and I have not been able to find many examples online. I would like to do this in R. It's almost a mix between a sankey diagram and a chord diagram.
I was hoping some of you would have some ideas on which packages I could use to achieve this in R.

A: As Ian Campbell points out in the comments, this is called an alluvial plot, and you can probably get quite close with the ggalluvial package. However, it is possible to get a near-identical recreation of your plot using just geom_ribbon and geom_text from ggplot2:

However, it's a bit tricky to do. First we need a way of producing those nice smooth curves that go from one side to the other. The following function takes the starting and ending levels (as numbers between 0 and 1). It also allows an optional increasing or decreasing the width of the columns on either side:
ribbon_line <- function(p1, p2, width = 10, len = 100)
{
  if (width > 50) width <- 50
  if (width < 0) width <- 0
  if (p1 < 0) p1 <- 0
  if (p1 > 1) p1 <- 1
  if (p2 < 0) p2 <- 0
  if (p2 > 1) p2 <- 1

  yvals <- c(p1, p1, pnorm(seq(-2.5, 2.5, length.out = len)) * (p2 - p1) + p1, p2, p2)
  xvals <- c(0, seq(width, 100 - width, length.out = len + 2), 100)
  list(x = xvals, y = yvals)
}

Now we need a way of combining two lines into a data frame with co-ordinates we can plot:
ribbon_df <- function(uppers, lowers, group, width = 10)
{
  data.frame(x    = ribbon_line(uppers[1], uppers[2], width)$x,
             ymax = ribbon_line(uppers[1], uppers[2], width)$y,
             ymin = ribbon_line(lowers[1], lowers[2], width)$y,
             group = group, stringsAsFactors = FALSE)
}

Next, we need a method of taking a simple input and turning it into a group of these ribbons, plus left and right columns, plus text labels:
multi_ribbons <- function(left_bottom, right_bottom, left_top, right_top,
                          groups, width = 10)
{
  if (length(left_bottom) != length(right_bottom) |
      length(left_bottom) != length(left_top)     |
      length(left_top)    != length(right_top))
    stop("Left and right columns different length")
  if (length(groups) != length(left_bottom))
    stop("Group length has to be same length as columns")

  d <- lapply(seq_along(groups), function(i) {
    ribbon_df(c(left_top[i], right_top[i]),
              c(left_bottom[i], right_bottom[i]),
              groups[i], width)})

  left_cols <- lapply(d, function(x) x[1:2,])
  right_cols <- lapply(d, function(x) x[nrow(x) - 1:0,])

  res <- list( left = do.call(rbind, left_cols),
               right = do.call(rbind, right_cols),
               bands = do.call(rbind, d))

  text_y <- c((res$left$ymax + res$left$ymin)/2,
             (res$right$ymax + res$right$ymin)/2)
  text_x <- c(rep(width / 2, length(res$left$x)),
              rep(100 - width/2, length(res$left$x)))
  text_labels <- paste0(round(c(res$left$ymax - res$left$ymin,
                         res$right$ymax - res$right$ymin), 3) * 100, "%")
  res$text <- data.frame(x = text_x, y = text_y, labels = text_labels)
  res
}

Finally, we want a way of taking our data as a simple pair of factor vectors and using the above functions to plot them:
alluvial <- function(yvar, xvar, width = 20)
{
  tab <- table(yvar, xvar)
  x_labs <- rownames(tab)
  y_labs <- colnames(tab)
  left <- tab[1,]/sum(tab[1,])
  left <- cumsum(sort(left))
  right <- tab[2,]/sum(tab[2,])
  right <- cumsum(sort(right))
  left_lower <- c(0, left[-length(left)])
  names(left_lower) <- names(left)
  right_lower <- c(0, right[-length(right)])
  names(right_lower) <- names(right)
  right <- right[match(names(left), names(right))]
  right_lower <- right_lower[match(names(left), names(right_lower))]
  df_list <- multi_ribbons(left_lower, right_lower, left, right,
                           names(left), width = 20)
  ggplot(df_list$bands, aes(x = x, ymin = ymin, ymax = ymax, fill = group)) +
    geom_ribbon(alpha = 0.5) +
    geom_ribbon(alpha = 1, data = df_list$left) +
    geom_ribbon(alpha = 1, data = df_list$right) +
    geom_text(data = df_list$text, inherit.aes = FALSE, colour = "white",
              aes(x = x, y = y, label = labels), size = 8) +
    geom_text(data = data.frame(x = c(width / 2, 100 - width /2), y = c(1.05, 1.05),
                         labels = factor(x_labs, levels = x_labs)),
              inherit.aes = FALSE,
              mapping = aes(x = x, y = y, label = labels), size = 12) +
    geom_text(data = data.frame(x = rep(-5, length(y_labs)),
                                y = unique(df_list$text$y[1:(nrow(df_list$text)/2)]),
                                labs = unique(df_list$bands$group)),
              mapping = aes(x = x, y = y, colour = labs, label = labs),
              inherit.aes = FALSE, size = 8, hjust = 1) +
    scale_fill_manual(values = c("#e64b35", "#806249", "#00a087", "#3c5488")) +
    scale_colour_manual(values = c("#e64b35", "#806249", "#00a087", "#3c5488")) +
    coord_cartesian(xlim = c(-15, 101)) +
    theme_void() + theme(legend.position = "none")
}

So, if we you data frame is in a format like this:
head(df, 20)
#>     condition    variable
#> 110   Disease      Immune
#> 149   Disease  Fibroblast
#> 133   Disease      Immune
#> 184   Disease Endothelial
#> 137   Disease      Immune
#> 200   Disease Endothelial
#> 30     Health      Immune
#> 11     Health      Immune
#> 63     Health  Fibroblast
#> 88     Health Endothelial
#> 42     Health  Fibroblast
#> 38     Health  Fibroblast
#> 106   Disease      Immune
#> 139   Disease      Immune
#> 6      Health  Epithelial
#> 21     Health      Immune
#> 27     Health      Immune
#> 181   Disease Endothelial
#> 95     Health Endothelial
#> 108   Disease      Immune

You can just do:
alluvial(df$condition, df$variable)

To get the above plot, or, for something more random:
set.seed(69)
alluvial(sample(c(TRUE, FALSE), 200, replace = TRUE),
         sample(LETTERS[1:4], 200, replace = TRUE))

If you want more than four colour or fill levels, you can remove or adjust the scale_colour_manual and scale_fill_manual calls, to get, for example:
set.seed(69)
alluvial(sample(c(TRUE, FALSE), 200, replace = TRUE),
         sample(LETTERS[1:20], 200, replace = TRUE))


text:
Q: htaccess RewriteRule - Multiple optional parameters in no particular order I need friendly urls on my webpage and I'm using the htaccess file for that purpose.
Actually it's pretty easy, but there are some pages where the url can have multiple optional parameters in no particular order and I can't image how the rewrite rule shpuld look like for those pages.
For example, a page to display a huge list of movies from the database. You can filter by medium (dvd, blu-ray), age, genre. You can sort the results by alphabet, rating, etc. and you can switch pages. All of this works with url paremeters.
index.php?movies

Shows all movies, no filters, no sorting. The rewritten url should lie this:
/movie

No problem so far. But it can also look like this:
index.php?movies&medium=1&genre=3&age=17&sort=alphabet&page=15

This would return page 15 of all R-rated horror movies on dvd, ordered by name.
The parameters have no particular order and are all optional. If my RewriteRule would loo like this
RewriteRule ^movies/([0-9]+)/([0-9]+)/?$

how do you know if the first parameter is medium or page or whatever?
Is there a way to identify the parameters?
/movies/genre-3/page-15

Thank you very much!

A: You can use a rule like this:
RewriteEngine On
RewriteBase /

# reucrsion based rule to convert /n1/v1/n2/v2 to /?n2=v2&n1=v1
RewriteRule "([^/]+)/([^/]*)(/.*)?$" $3?$1=$2 [L,QSA]

This rewrites a URI like /movies/medium/1/genre/3&age/17/sort/alphabet/page/15 to:/?page=15&sort=alphabet&3&age=17&1=genre&movies=medium


text:
Q: Performance problems when adding columns to NSOutlineView programmatically In my application I would like to use an outline view to display attributes of different kinds of objects. Since the attributes are retrieved from an external database, they are not known at compile time; therefore, I need to add the columns dynamically.
I have set up Cocoa bindings to display the values, but I have run into some pretty serious performance issues. When I define the columns with bindings in Interface Builder, the performance is great. But when I add columns and bind to the same values programmatically, the application hangs for seconds when scrolling, using 100% of the CPU.
The data model is the following:

Each dynamicAttributes attribute contains an NSDictionary with the following structure:

I use the following code to add the columns:
for (NSString *key in instDynAttsDict) {

    NSTableColumn *column = [[NSTableColumn alloc] initWithIdentifier:key];
    column.title = key;
    [self.instancesOutlineView addTableColumn:column];

    NSString *keyPath = [NSString stringWithFormat:@"arrangedObjects.dynamicAttributes.%@.value", key];
    [column bind:NSValueBinding toObject:self.instancesTreeController withKeyPath:keyPath options:nil];

}

I posted a test project here, with some sample data: https://drive.google.com/open?id=0B5lGn_3atgSeNWVUX3l6cmVxUUE
You will need to copy the database OSXCoreDataObjC.storedata into the Application Support directory. (The specific path is logged out on app launch.)


text:
Q: What are high memory and low memory on Linux? I'm interested in the difference between Highmem and Lowmem:

*

*Why is there such a differentiation?

*What do we gain by doing so?

*What features does each have?

A: On a 32-bit architecture, the address space range for addressing RAM is:
0x00000000 - 0xffffffff

or 4'294'967'295 (4 GB).
The linux kernel splits that up 3/1 (could also be 2/2, or 1/3 1) into user space (high memory) and kernel space (low memory) respectively.
The user space range:
0x00000000 - 0xbfffffff

Every newly spawned user process gets an address (range) inside this area. User processes are generally untrusted and therefore are forbidden to access the kernel space. Further, they are considered non-urgent, as a general rule, the kernel tries to defer the allocation of memory to those processes.
The kernel space range:
0xc0000000 - 0xffffffff

A kernel processes gets its address (range) here. The kernel can directly access this 1 GB of addresses (well, not the full 1 GB, there are 128 MB reserved for high memory access).
Processes spawned in kernel space are trusted, urgent and assumed error-free, the memory request gets processed instantaneously.
Every kernel process can also access the user space range if it wishes to. And to achieve this, the kernel maps an address from the user space (the high memory) to its kernel space (the low memory), the 128 MB mentioned above are especially reserved for this.

1 Whether the split is 3/1, 2/2, or 1/3 is controlled by the CONFIG_VMSPLIT_... option; you can probably check under /boot/config* to see which option was selected for your kernel.

A: HIGHMEM is a range of kernel's memory space, but it is NOT memory you access but it's a place where you put what you want to access.
A typical 32bit Linux virtual memory map is like:

*

*0x00000000-0xbfffffff: user process (3GB)

*0xc0000000-0xffffffff: kernel space (1GB)
(CPU-specific vector and whatsoever are ignored here).
Linux splits the 1GB kernel space into 2 pieces, LOWMEM and HIGHMEM. The split varies from installation to installation.
If an installation chooses, say, 512MB-512MB for LOW and HIGH mems, the 512MB LOWMEM (0xc0000000-0xdfffffff) is statically mapped at the kernel boot time; usually the first so many bytes of the physical memory is used for this so that virtual and physical addresses in this range have a constant offset of, say, 0xc0000000.
On the other hand, the latter 512MB (HIGHMEM) has no static mapping (although you could leave pages semi-permanently mapped there, but you must do so explicitly in your driver code). Instead, pages are temporarily mapped and unmapped here so that virtual and physical addresses in this range have no consistent mapping. Typical uses of HIGHMEM include single-time data buffers.

A: For the people looking for an explanation in the context of Linux kernel memory space, beware that there are two conflicting definitions of the high/low memory split (unfortunately there is no standard, one has to interpret that in context):

*

*"High memory" defined as the totality of kernel space in VIRTUAL memory. This is a region that only the kernel can access and comprises all virtual addresses greater or equal than PAGE_OFFSET. "Low memory" refers therefore to the region of the remaining addresses, which correspond to the user-space memory accessible from each user process.
For example: on 32-bit x86 with a default PAGE_OFFSET, this means that high memory is any address ADDR with ADDR ≥ 0xC0000000 = PAGE_OFFSET (i.e. higher 1 GB).
This is the reason why in Linux 32-bit processes are typically limited to 3 GB.
Note that PAGE_OFFSET cannot be configured directly, it depends on the configurable VMSPLIT_x options (source).
To summarize: in 32-bit archs, virtual memory is by default split into lower 3 GB (user space) and higher 1 GB (kernel space).
For 64 bit, PAGE_OFFSET is not configurable and depends on architectural details that are sometimes detected at runtime during kernel load.
On x86_64, PAGE_OFFSET is 0xffff888000000000 for 4-level paging (typical) and 0xff11000000000000 for 5-level paging (source). For ARM64 this is usually 0x8000000000000000. Note though, if KASLR is enabled, this value is intentionally unpredictable.

*

*"High memory" defined as the portion of PHYSICAL memory that cannot be mapped contiguously with the rest of the kernel virtual memory. A portion of the kernel virtual address space can be mapped as a single contiguous chunk into the so-called physical "low memory". To fully understand what this means, a deeper knowledge of the Linux virtual memory space is required. I would recommend going through these slides.
From the slides:

This kind of "high/low memory" split is only applicable to 32-bit architectures where the installed physical RAM size is relatively high (more than ~1 GB). Otherwise, i.e. when the physical address space is small (<1 GB) or when the virtual memory space is large (64 bits), the whole physical space can be accessed from the kernel virtual memory space. In that case, all physical memory is considered "low memory".
It is preferable that high memory does not exist at all because the whole physical space can be accessed directly from the kernel, which makes memory management a lot simpler and efficient. This is especially important when dealing with DMAs (which typically require physically contiguous memory).
See also the answer by @gilles

A: As far as I remember, "High Memory" is used for application space and "Low Memory" for the kernel.
Advantage is that (user-space) applications can't access kernel-space memory.

A: The first reference to turn to is Linux Device Drivers (available both online and in book form), particularly chapter 15 which has a section on the topic.
In an ideal world, every system component would be able to map all the memory it ever needs to access. And this is the case for processes on Linux and most operating systems: a 32-bit process can only access a little less than 2^32 bytes of virtual memory (in fact about 3GB on a typical Linux 32-bit architecture). It gets difficult for the kernel, which needs to be able to map the full memory of the process whose system call it's executing, plus the whole physical memory, plus any other memory-mapped hardware device.
So when a 32-bit kernel needs to map more than 4GB of memory, it must be compiled with high memory support. High memory is memory which is not permanently mapped in the kernel's address space. (Low memory is the opposite: it is always mapped, so you can access it in the kernel simply by dereferencing a pointer.)
When you access high memory from kernel code, you need to call kmap first, to obtain a pointer from a page data structure (struct page). Calling kmap works whether the page is in high or low memory. There is also kmap_atomic which has added constraints but is more efficient on multiprocessor machines because it uses finer-grained locking. The pointer obtained through kmap is a resource: it uses up address space. Once you've finished with it, you must call kunmap (or kunmap_atomic) to free that resource; then the pointer is no longer valid, and the contents of the page can't be accessed until you call kmap again.

A: This is relevant to the Linux kernel; I'm not sure how any Unix kernel handles this.
The High Memory is the segment of memory that user-space programs can address. It cannot touch Low Memory.
Low Memory is the segment of memory that the Linux kernel can address directly. If the kernel must access High Memory, it has to map it into its own address space first.
There was a patch introduced recently that lets you control where the segment is. The tradeoff is that you can take addressable memory away from user space so that the kernel can have more memory that it does not have to map before using.
Additional resources:

*

*http://tldp.org/HOWTO/KernelAnalysis-HOWTO-7.html

*http://linux-mm.org/HighMemory

A: Many people have said that the low memory is for the operating system. This is usually true but does not have to be. High memory and low memory are just two parts of the memory space, but in Linux system low memory is only for kernel and high memory for user processes.
According to the "Dinosaur book (operating system concepts)", we can place the operating system in either low memory or high memory. The major factor affecting this decision is the location of the interrupt vector. Since the interrupt vector is often in low memory, programmers usually place the operating system in low memory as well.


text:
Q: How to get a list of friends that uses the same app and can be tagged in one Graph API request only? Our mobile app wants to offer the functionality of allowing a user to post an invite with friends mentions in the message, but we only want to display a list of the friend users that currently have the app installed too. The user will be able to type their preferred message and then select the users to mention.
The Graph Api offers the endpoint for getting a list of friends that have the app installed /me/friends?fields=installed and with /{user-id}/taggable_friends you get a list of all your friends that allows tagging/mentioning.
Is there a way to obtain the list of all the taggable friends that have authorized our app?
We are developing our app using Titanium Studio and their Facebook module, we're using Titanium SDK 3.2.0.GA and deploying for Android and iOS.


text:
Q: Is there a simple way in swiftui to create a 3 tier master-context-detail application like Mail? I'm building my first app in swiftui and I've got an iPhone version working nicely using a stackNavigationViewStyle navigation view. However when used in landscape mode on large screens or on an iPad it gets distorted and a better use of that screen real estate would be to show the navigation.
I have tried a DoubleColumnNavigationViewStyle and that gets me two columns but the second tier of navigation is still very wide and is replaced by the content when you choose something.
Ideally there would be a default "unselected" view displayed underneath everything and then the navigation on large devices would remain, showing the content in a thinner column on the right. On smaller screens the nav would replace each other on the left and on smallest screens it would be nav or content, one at a time.
I'm just wondering if this or any similar behaviour with 3 tier apps is possible in swiftui or if I'm going to have to jump in with both feet to full fat swift to get this behaviour going. I've done quite a bit of searching and I can't find much, maybe because I'm using the wrong terms.
Thanks!
Edit: Here's the code
ChooseBoatView.swift
struct ChooseBoatView: View {
    var body: some View {
        NavigationView {
            ZStack {
                BoatList(boats: BoatData())
                    .navigationBarTitle("Choose vessel")
            }
        }
        .navigationViewStyle(DoubleColumnNavigationViewStyle())
    }
}

struct Boat: Decodable, Identifiable {
    var id  = UUID()
    var name: String
    var listIcon: String
    var headerImage: String
    var topics: [Topic]

    enum CodingKeys: String, CodingKey {
        case name = "name"
        case listIcon = "listIcon"
        case headerImage = "headerImage"
        case topics = "topics"
    }
}

struct BoatRow: View {
    var boat: Boat

    var body: some View {
        NavigationLink(destination: ChooseTopicView(boat: boat)) {
            HStack {
                Image(decorative: boat.listIcon).resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(minWidth: 0,
                           maxWidth: .infinity,
                           minHeight: 0,
                           maxHeight: .infinity)
                Text(boat.name)
                    .frame(minWidth: 0,
                           maxWidth: .infinity,
                           minHeight: 0,
                           maxHeight: .infinity,
                           alignment: .trailing)
            }
        }
    }
}

struct BoatList: View {
    var boats: [Boat]

    var body: some View {
        return List(boats, rowContent: BoatRow.init)
    }
}

ChooseTopicView.swift
struct ChooseTopicView: View {
    var boat: Boat
    var body: some View {
        if #available(iOS 14.0, *) {
            TopicList(topics: boat.topics)
                .navigationBarTitle(boat.name, displayMode: .inline)
        } else {
            TopicList(topics: boat.topics)
                .navigationBarTitle(boat.name)
        }
    }
}

struct Topic: Decodable, Identifiable {
    var id  = UUID()
    var name: String
    var image: String
    var boatName: String
    var policyLink: String
    var policyLinkDescription: String
    var videoLink: String

    enum CodingKeys: String, CodingKey {
        case name = "name"
        case image = "image"
        case boatName = "boatName"
        case policyLink = "policyLink"
        case policyLinkDescription = "policyLinkDescription"
        case videoLink = "videoLink"
    }
}

struct TopicRow: View {
    var topic: Topic
    var body: some View {
        NavigationLink(destination: TopicView(topic: topic)) {
                Image(decorative: topic.image)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(minWidth: 0,
                           maxWidth: .infinity,
                           minHeight: 0,
                           maxHeight: .infinity)
                    .background(Color(.white))
                    .clipped()
                Text(topic.name)
                    .frame(minWidth: 0,
                           maxWidth: .infinity,
                           minHeight: 0,
                           maxHeight: .infinity,
                           alignment: .trailing)
                    .multilineTextAlignment(.trailing)
        }.frame(maxHeight: 100.0)
    }
}

struct TopicList: View {
    var topics: [Topic]

    var body: some View {
        if(topics.count > 0) {
            List(topics, rowContent: TopicRow.init)
        } else {
            Text("No topics available yet for this vessel")
        }
    }
}

Topic itself can be any view.
I think it would be enough either to make the secondary nav replace the primary instead of appearing as the detail, but if there's a way to make all 3 columns appear that would be ideal.

A: A three-tier view is possible in iPadOS, but you have to give your NavigationView three subviews to initialize it, otherwise it will fall back to the two-pane version. For example:
NavigationView {
  SidebarView()
  Text("List placeholder")
  Text("Detail placeholder")
}

Any NavigationLink destination links will populate the column where "List placeholder" will appear in the example above. And if that is a list with its own NavigationLinks, they will appear in place of the detail placeholder.
Note that in this configuration on iPad, the sidebar will typically be off-screen by default, but can be brought onscreen by hitting the back button above the list or swiping from the left edge. Although iOS 15 brings some minor improvements to three-pane handling on iPad, there's still a way to go to bring it up to a level with a native UIKit implementation.
Note that you probably won't want to use exactly the same navigation on smaller devices - either iPhone screens, or a split-screen or SlideOver iPad view. So you might want a higher level view that looks at our window size classes, and only implements a three-tier navigation view for iPad views that have the width to support them.


text:
Q: Django: Tweaking @login_required decorator I want to begin a private Beta for my website.  I have a splash page where a user can enter a code to then access the rest of the site. Currently, all the other site pages (except the splash page) consist of a series of redirects set up by requiring user login (via @login_required decorator).
I want both logged in users and people who enter the Beta Tester code to be able to access the rest of the site.  That means that I can't just use the decorator for all my views.
Should I alter the @login_required decorator itself?  I'm more tempted to just do the following (I added a session variable if user enters correct code on splash page).
def view_name(request):
    user=request.user
    if not user.id or not request.session.get('code_success'):
           return HttpResponseRedirect('/splash/')

Does this seem reasonable?  I'd hate to have to repeat it for all my views
Brendan

A: I would recommend using a middleware instead. That will make it easier to drop once you move out of your private beta. There are a couple examples of login required middlewares on djangonsippets:
http://djangosnippets.org/snippets/1220/
http://djangosnippets.org/snippets/136/
I would recommend taking one of those and tweaking it to include you beta code logic.

A: Write your own decorator - it's fairly straight forward.  In fact, if you look at the Django source for login_required, you should be able to fiddle around with a copy for your own purposes.
def my_login_required(function):
    def wrapper(request, *args, **kw):
        user=request.user
        if not (user.id and request.session.get('code_success')):
            return HttpResponseRedirect('/splash/')
        else:
            return function(request, *args, **kw)
    return wrapper

A: HOW to re-use (tweak) internal Django login_required
For example, you need to allow access to page for only users who passed login_required checks and also are Coaches - and (save) pass coach instance to you view for further processing

decorators.py

from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

from profiles.models import CoachProfile

def coach_required(function):
    def wrapper(request, *args, **kwargs):
        decorated_view_func = login_required(request)
        if not decorated_view_func.user.is_authenticated():
            return decorated_view_func(request)  # return redirect to signin

        coach = CoachProfile.get_by_email(request.user.email)
        if not coach:  # if not coach redirect to home page
            return HttpResponseRedirect(reverse('home', args=(), kwargs={}))
        else:
            return function(request, *args, coach=coach, **kwargs)

    wrapper.__doc__ = function.__doc__
    wrapper.__name__ = function.__name__
    return wrapper

views.py

@coach_required
def view_master_schedule(request, coach):
    """coach param is passed from decorator"""
    context = {'schedule': coach.schedule()}
    return render(request, 'template.html', context)

A: I would create a guest account and login people that enter the Beta Tester code to that account. Something along these lines:
def beta_code_accepted(request):
    guest_user = User.objects.get(username='beta_guest')
    login(request, guest_user)

Once your beta is complete, just disable the splash view.


text:
Q: Why is my bootstrap not working? Please help me! Why is bootstrap not loading the classes?
Here's my code which is just a table and a simple button, yet no classes are applied
<!DOCTYPE html>

    <title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    </title>

            Order ID
            TX ID CxPay
            TX ID IY
            Amount
            Class
            Date

            1asas
            1asas
            1asas
            1asas
            1asas
            1asas

<button class="btn btn-success">asasa</button>

Neither bootstrap nor datatables is working. What am I missing here?
Any help is appreciated!

A: You are importing the script inside <title> that's not correct. In <title> only text is allowed describing your page's title. Place your

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


text:
Q: Java Concurrent Hashmap initTable() Why the try/finally block? I have been looking at the following code (sourced from here)'
/**
 * Initializes table, using the size recorded in sizeCtl.
 */
private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    while ((tab = table) == null || tab.length == 0) {
        if ((sc = sizeCtl) < 0)
            Thread.yield(); // lost initialization race; just spin
        else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
            try {
                if ((tab = table) == null || tab.length == 0) {
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    table = tab = nt;
                    sc = n - (n >>> 2);
                }
            } finally {
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

Can someone explain why there is a need for the try block?

A: unchecked exceptions and errors exist as a concept. If you call .put() on a ConcurrentHashMap, and you're real tight on memory, that map may try to make an array, and that call may fail with an OutOfMemoryError. Code will still continue (at the catch block that catches this, perhaps), and the references to that map still exist. It would be a bit shite if, after that happens, the map crashes and is completely invalidated because sizeCtl has a broken value.
The point is that finally block, which restores the sizeCtl value. This is used for various things, notable including managing which thread gets access. If it didn't, any other put calls would spin forever.
The relevance of this (as in, how often does a throwable occur here, vs. removing the 'try' and the 'finally' and just ending with sizeCtl = sc; without the additional overhead of try/finally) is low, but if it is relevant, it is quite relevant.

A: It's a kind of mutex - and a double-check lock.
Firstly
if ((sc = sizeCtl) < 0)
    Thread.yield(); // lost initialization race; just spin

checks the sizeCtl mutex.  If it's less than zero, someone else has grabbed it, so we just wait for a bit.
If it's zero (or more), chances are we'd obtain the lock.  So a Compare-And-Swap is performed:
if (U.compareAndSetInt(this, SIZECTL, sc, -1)

This is an atomic operation - if another thread grabbed it between the first and second check, the if would not be taken.
If the CAS is successful, then the method becomes reponsible for releasing the mutex.  Therefore, a try-finally is used to ensure that the mutex is released (sizeCtl reset to its original value) irrespective of whether an exception occurs (e.g. out of memory assigning the new Node - or if there is a unique restriction applicable to the map) or not.


text:
Q: how to build a inputConnection between edit text that inside the input method service and the service I am writing an IME (InputMethodService) and I have an edit text that in the IME itself, but when I want type text into the edit text , the edit text can't get focused and what I type just go to another edit text outside the IME. how can I make the edit text inside the IME work like normal edit text

A: The way I solved this was by keeping two input connections, one to the original textfield that the user WAS editing, and another to the textfield inside the keyboard. More on the second one later. The first one you should already have, it's where the keyboard sends all of its commands. In my case it was called mIC. So I created another InputConnection variable called mOtherIC on my class that had the InputConnection, and introduced a new method called getIC() which just returned the appropriate one of those two InputConnections to be using at the time (controlled by a boolean in my case, true meant use the textfield in the keyboard, false meant use the textfield that originally presented the keyboard). Every time I had previously accessed mIC, I replaced it with getIC() so it would seamlessly be able to send input to the correct input connection.
The InputConnection for the textfield in the keyboard is the interesting one here, I essentially had to copy the internal Android EditableInputConnection into my own CustomInputConnection class:
public class CustomInputConnection extends BaseInputConnection {
    private static final boolean DEBUG = false;
    private static final String TAG = "CustomInputConnection";

    private final TextView mTextView;

    // Keeps track of nested begin/end batch edit to ensure this connection always has a
    // balanced impact on its associated TextView.
    // A negative value means that this connection has been finished by the InputMethodManager.
    private int mBatchEditNesting;

    public CustomInputConnection(TextView textview) {
        super(textview, true);
        mTextView = textview;
    }

    @Override
    public Editable getEditable() {
        TextView tv = mTextView;
        if (tv != null) {
            return tv.getEditableText();
        }
        return null;
    }

    @Override
    public boolean beginBatchEdit() {
        synchronized(this) {
            if (mBatchEditNesting >= 0) {
                mTextView.beginBatchEdit();
                mBatchEditNesting++;
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean endBatchEdit() {
        synchronized(this) {
            if (mBatchEditNesting > 0) {
                // When the connection is reset by the InputMethodManager and reportFinish
                // is called, some endBatchEdit calls may still be asynchronously received from the
                // IME. Do not take these into account, thus ensuring that this IC's final
                // contribution to mTextView's nested batch edit count is zero.
                mTextView.endBatchEdit();
                mBatchEditNesting--;
                return true;
            }
        }
        return false;
    }

//    @Override
//    protected void reportFinish() {
//        super.reportFinish();
//
//        synchronized(this) {
//            while (mBatchEditNesting > 0) {
//                endBatchEdit();
//            }
//            // Will prevent any further calls to begin or endBatchEdit
//            mBatchEditNesting = -1;
//        }
//    }

    @Override
    public boolean clearMetaKeyStates(int states) {
        final Editable content = getEditable();
        if (content == null) return false;
        KeyListener kl = mTextView.getKeyListener();
        if (kl != null) {
            try {
                kl.clearMetaKeyState(mTextView, content, states);
            } catch (AbstractMethodError e) {
                // This is an old listener that doesn't implement the
                // new method.
            }
        }
        return true;
    }

    @Override
    public boolean commitCompletion(CompletionInfo text) {
        if (DEBUG) Log.v(TAG, "commitCompletion " + text);
        mTextView.beginBatchEdit();
        mTextView.onCommitCompletion(text);
        mTextView.endBatchEdit();
        return true;
    }

    /**
     * Calls the {@link TextView#onCommitCorrection} method of the associated TextView.
     */
    @Override
    public boolean commitCorrection(CorrectionInfo correctionInfo) {
        if (DEBUG) Log.v(TAG, "commitCorrection" + correctionInfo);
        mTextView.beginBatchEdit();
        mTextView.onCommitCorrection(correctionInfo);
        mTextView.endBatchEdit();
        return true;
    }

    @Override
    public boolean performEditorAction(int actionCode) {
        if (DEBUG) Log.v(TAG, "performEditorAction " + actionCode);
        mTextView.onEditorAction(actionCode);
        return true;
    }

    @Override
    public boolean performContextMenuAction(int id) {
        if (DEBUG) Log.v(TAG, "performContextMenuAction " + id);
        mTextView.beginBatchEdit();
        mTextView.onTextContextMenuItem(id);
        mTextView.endBatchEdit();
        return true;
    }

    @Override
    public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) {
        if (mTextView != null) {
            ExtractedText et = new ExtractedText();
            if (mTextView.extractText(request, et)) {
                if ((flags&GET_EXTRACTED_TEXT_MONITOR) != 0) {
//                    mTextView.setExtracting(request);
                }
                return et;
            }
        }
        return null;
    }

    @Override
    public boolean performPrivateCommand(String action, Bundle data) {
        mTextView.onPrivateIMECommand(action, data);
        return true;
    }

    @Override
    public boolean commitText(CharSequence text, int newCursorPosition) {
        if (mTextView == null) {
            return super.commitText(text, newCursorPosition);
        }
        if (text instanceof Spanned) {
            Spanned spanned = ((Spanned) text);
            SuggestionSpan[] spans = spanned.getSpans(0, text.length(), SuggestionSpan.class);
//            mIMM.registerSuggestionSpansForNotification(spans);
        }

//        mTextView.resetErrorChangedFlag();
        boolean success = super.commitText(text, newCursorPosition);
//        mTextView.hideErrorIfUnchanged();

        return success;
    }

    @Override
    public boolean requestCursorUpdates(int cursorUpdateMode) {
        if (DEBUG) Log.v(TAG, "requestUpdateCursorAnchorInfo " + cursorUpdateMode);

        // It is possible that any other bit is used as a valid flag in a future release.
        // We should reject the entire request in such a case.
        final int KNOWN_FLAGS_MASK = InputConnection.CURSOR_UPDATE_IMMEDIATE |
                InputConnection.CURSOR_UPDATE_MONITOR;
        final int unknownFlags = cursorUpdateMode & ~KNOWN_FLAGS_MASK;
        if (unknownFlags != 0) {
            if (DEBUG) {
                Log.d(TAG, "Rejecting requestUpdateCursorAnchorInfo due to unknown flags." +
                        " cursorUpdateMode=" + cursorUpdateMode +
                        " unknownFlags=" + unknownFlags);
            }
            return false;
        }

        return false;

//        if (mIMM == null) {
//            // In this case, TYPE_CURSOR_ANCHOR_INFO is not handled.
//            // TODO: Return some notification code rather than false to indicate method that
//            // CursorAnchorInfo is temporarily unavailable.
//            return false;
//        }
//        mIMM.setUpdateCursorAnchorInfoMode(cursorUpdateMode);
//        if ((cursorUpdateMode & InputConnection.CURSOR_UPDATE_IMMEDIATE) != 0) {
//            if (mTextView == null) {
//                // In this case, FLAG_CURSOR_ANCHOR_INFO_IMMEDIATE is silently ignored.
//                // TODO: Return some notification code for the input method that indicates
//                // FLAG_CURSOR_ANCHOR_INFO_IMMEDIATE is ignored.
//            } else if (mTextView.isInLayout()) {
//                // In this case, the view hierarchy is currently undergoing a layout pass.
//                // IMM#updateCursorAnchorInfo is supposed to be called soon after the layout
//                // pass is finished.
//            } else {
//                // This will schedule a layout pass of the view tree, and the layout event
//                // eventually triggers IMM#updateCursorAnchorInfo.
//                mTextView.requestLayout();
//            }
//        }
//        return true;
    }
}

The class looks pretty bad because I commented out code that wouldn't build, presumably because it accesses internal Android APIs. That said, with a few caveats (cursor probably needs to be set manually when you switch to this input method, capitalization kind of carries-over between the two InputConnections), it works. All you have to do now is at some point set mOtherIC from my first paragraph to a new CustomInputConnection(yourTextfield) where yourTextfield is the textfield inside the keyboard.


text:
Q: Activemq web console in Spring I am creating an embedded ActiveMQ broker in Spring application like this:
@EnableJms
@Configuration
public class MqConfig {
    @Bean
    public BrokerService broker() throws Exception {
        BrokerService broker = new BrokerService();
        broker.setBrokerName("ETL");
        broker.addConnector("tcp://localhost:61616");
        broker.start();
        return broker;
    }
}

How can I embed the ActiveMQ Admin Web console also in the same spring application? Searched the net for 2-3 hours, but found no useful answer. The only thing that ActiveMQ site mentions is this http://activemq.apache.org/web-console.html, however is not useful with Spring


text:
Q: Чтение xls с удаленного сервера через PHPExel есть вот такой код:
     $file_path_excel = "http://site.ua/system/PHPExcel/my.xls";
function readExelFile($filepath){
    require_once "Classes/PHPExcel.php"; //подключаем наш фреймворк
    $ar=array(); // инициализируем массив
$inputFileType = PHPExcel_IOFactory::identify($filepath);  // узнаем тип файла, excel может хранить файлы в разных форматах, xls, xlsx и другие
$objReader = PHPExcel_IOFactory::createReader($inputFileType); // создаем объект для чтения файла
$objPHPExcel = $objReader->load($filepath); // загружаем данные файла в объект
$ar = $objPHPExcel->getActiveSheet()->toArray(); // выгружаем данные из объекта в массив
return $ar; //возвращаем массив
}

$ar=readExelFile($file_path_excel);
foreach($ar as $ar_colls){

делаем что то....

По пути который я вставляю файл скачивается , если перейти через браузер.
а phpexel открыть его не может.
код ошибки
<b>Fatal error</b>:  Uncaught exception 'PHPExcel_Reader_Exception' with message 'Could not open http://.....ua/system/PHPExcel/my.xls for reading! File does not exist.' in ....www/system/PHPExcel/Classes/PHPExcel/Reader/Excel5.php:433

Подскажите, как мне получить файл с удаленного сервера?
Спасибо

A: $filename = basename($file_path_excel);

$content = file_get_contents($file_path_excel);
if (file_put_contents($filename, $content)) {
    readExelFile($filename);
    unlink($filename);
} else
    die("Something went wrong");

Вы должны сначало сохранить файл в своей системе локально, потом его открывать.

A:
Подскажите, как мне получить файл с удаленного сервера?

Попробуйте так
$filecontent = file_get_contents("http://site.ua/system/PHPExcel/my.xls");
if (!$filecontent){
    throw new Exception("Can't read remote file");
}
file_put_contents(PATH_TMP."/my.xls", $filecontent);

$ar=readExelFile(PATH_TMP."/my.xls");
...