text:
Q: Change body background color in an iframe using one css file Using a iframe where I call a site from my webspace, Using one css file with body {background-color: #222}.
The iframe src also use this CSS file. The Problem is that the body in the iframe need another background-colour.
tried
iframe>body { background-color: #other }

Any idea or suggestions?

A: I assume the iframe takes up a smaller portion of your site. In that case I would advice you to simply use a div with the same size of the iframe is loaded, and giving this div the proper background-color.
OR: include a style property in the source of the iframe page:
<head>
    <style>body {background-color:#COLOR}</style>
</head>

A: This question is similar to How to apply css to iframe content?. Basically you can use jQuery to change the CSS properties in the iframe
$('#yourIframe').contents().find('body').css({
    background-color: '#333333'
});

Edit:
You may need to add that when the iframe loads:
$('#yourIframe').load(function(){
    $(this).contents().find('body').css({
        background-color: '#333333'
    });
});

A: Remember that a Javascript can modify only properties of iframe with the same origin of the site, otherwise you'll get a Security Error.
Protocols, domains and ports must match.

A: ive used this and it works for me. (and its sooooo easy!)
in your CSS file put:
iframe { background-color:orange; }
Just change the "orange" to whatever color you need.
Thats it!
Enjoy!

A: In the page that the iframe contains, link another stylesheet and then change all the CSS styles that you wish to.

A: using Javascript We can add Background Color to Iframe
 var x = document.getElementById("myframe");
    var y = (x.contentWindow || x.contentDocument);
    if (y.document)y = y.document;
    y.body.style.backgroundColor = "red";

Reference w3schools


text:
Q: Non specific JS for selecting DOM elements I GET a HTML response from AJAX over cors and the response is a table. Each category has its title and sub elements. The title names vary quite a bit and are likely to change in the future. The sub elements in each title change almost on a daily basis, but the DOM structure doesn't.
Is there a way I could get rid of this if statement and replace it with code that isn't element specific? Some way of selecting DOM elements I'm not aware of?
Relevat JS
    classifiedFilter: function( response ) {
            var Classified = {
                ClaAdministrative: [],
                Paraeducator: [],
                Clerical: [],
                Custodial: [],
                NonRep: [],
                Maintenance: [],
                ClaSubstitute: [],
                Coaching: []
            },
                response = $(response).find("table tbody tr td").html();
            $(response).find("#isHeadType").remove();
            $(response).find("font:contains(Open to all)").parent().parent().remove();

            //Filter each span title and classify sub items
            $(response).find("span").parents("tr").each( function() {

                //Find categories and separate by class
                var rowtext = $(this).find("span").text(),
                    position = "";

                position = rowtext.replace(/-/gi, "").replace(/\s/g, "");

                $(this).nextAll("tr").addClass(position);

                //Push content into Classified
                ((position === "Administrative") ? $(this).nextUntil(".Paraeducator").each( function() {
                    Classified.ClaAdministrative.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Paraeducator") ? $(this).nextUntil(".Clerical").each( function() {
                    Classified.Paraeducator.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Clerical") ? $(this).nextUntil(".Custodial").each( function() {
                    Classified.Clerical.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Custodial") ? $(this).nextUntil(".NonRep").each( function() {
                    Classified.Custodial.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "NonRep") ? $(this).nextUntil(".Maintenance").each( function() {
                    Classified.NonRep.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Maintenance") ? $(this).nextUntil(".Substitute").each( function() {
                    Classified.Maintenance.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Substitute") ? $(this).nextUntil(".Coaching").each( function() {
                    Classified.ClaSubstitute.push( $.trim( "
" + $(this).html() + "
" ) );
                }) :
                ((position === "Coaching") ? $(this).nextAll().each( function() {
                    Classified.Coaching.push( $.trim( "
" + $(this).html() + "
" ) );
                }) : [] ) ) ) ) ) ) ) );
            });

            //remove title from array
            Certificated.Elementary.shift();
            Certificated.MiddleSchool.shift();
            Certificated.HighSchool.shift();
            Certificated.K12.shift();
            Certificated.Substitute.shift();
    }

Summarized HTML GET response (added spaces for visual aid)

            External Positions: Open to all applicants.

                Administrative

                          Administrative Assistant I, Health Tech-Leave Replacement-2 hours  -   ME1214

                Paraeducator

                          Paraeducator, SpEd IP/ELL-6.5hours -   MC1223

                          Special Ed Paraeducator, School Adjustment Program (SA-)-6.5 hours -   MK1215

                Clerical

                          Admin Assistant IV-8 hours -   IT1209

                Non-Rep

                          Licensed Practical Nurse (Pool position)   -   2012LPNPool

                          Certified Occupational/Physical Therapist Assistant- POOL  -   COTA2012Pool

                Substitute

                          Substitute Food Service Helpers  -   FSSub

                          Substitute Custodians    -   MTSub

A: This seems equivalent to the core of your current code:
$(this).each( function() {
    Classified[position].push( $.trim( "
" + $(this).html() + "
" ) );
});

[Edit] I don't see where you declare your arrays, you might actually need this:
$(this).each( function() {
    Classified[position]=Classified[position]||[];
    Classified[position].push( $.trim( "
" + $(this).html() + "
" ) );
});

[Update] Based on the comments, this loop updates position whenever it hits a span:
var position = "";
$(response).find("tr").each( function() {
    var currentTR=$(this);
    // catch span if any
    var rowtext = currentTR.find("span").text().replace(/-/gi, "").replace(/\s/g, "");
    if (rowtext) {
        position = rowtext;
        Classified[position]=[];
    }
    // Collect rows
    Classified[position].push( "
" + $.trim($(this).html()) + "
" );
});

A: I think, you can use CSS class names in find function instead of tag names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When value is negative, subtract result from previous value I have a dataset that logically shouldn't have any negative values, but because of revisions to the data, it sometimes does. To adjust for this, I want to distribute negative values to the previous day's data.
For example, I'd like the values to change like so:

Old
New

18
18

12
10

1
0

0
0

0
0

-3
0

1
1

0
0

0
0

I'm trying to do this programmatically in R, but haven't been able to make it work.
Here's my latest attempt, which kinda works, but only partially and feels unstable:
library(tidyverse)
library(lubridate)

# Data
nums <- as_tibble(list(
  value = c(18, 12, 1, 0, 0, -3, 1, 0, 0 ),
  date = c("2022-01-01","2022-01-02","2022-01-03",
           "2022-01-04","2022-01-05","2022-01-06",
           "2022-01-07","2022-01-08","2022-01-09"))) |>
  mutate(date = ymd(date)) %>%
  select(date,value)

# Remove negatives
no_negs <- nums |>
  arrange(desc(date)) |>
  mutate(neww = if_else(lag(value,1) < 0, value + lag(value,1),value)) |>
  arrange(date) |>
  mutate(neww = ifelse(is.na(neww), 0, neww))

Any thoughts on whether this is possible, and if so, how?
Thanks!
Edit: new example data

A: Edits: reduction of code, fix for consecutive zeroes, use second data set, general improvement.

We can Reduce it:
nums1 %>%
  mutate(
    add = Reduce(function(prev, this) min(this+prev, 0),
                 value, init = 0, accumulate = TRUE, right = TRUE)[-1],
    value2 = pmax(value + add, 0)
  ) %>%
  select(-add)
# # A tibble: 6 x 3
#   date       value value2
#   <date>     <dbl>  <dbl>
# 1 2022-01-01    18     18
# 2 2022-01-02    12      5
# 3 2022-01-03    -3      0
# 4 2022-01-04    -4      0
# 5 2022-01-05     5      3
# 6 2022-01-06    -2      0

and the second dataset with more consecutive zeroes:
nums2 %>%
  mutate(
    add = Reduce(function(prev, this) min(this+prev, 0),
                 value, init = 0, accumulate = TRUE, right = TRUE)[-1],
    value2 = pmax(value + add, 0)
  ) %>%
  select(-add)
# # A tibble: 9 x 3
#   date       value value2
#   <date>     <dbl>  <dbl>
# 1 2022-01-01    18     18
# 2 2022-01-02    12     10
# 3 2022-01-03     1      0
# 4 2022-01-04     0      0
# 5 2022-01-05     0      0
# 6 2022-01-06    -3      0
# 7 2022-01-07     1      1
# 8 2022-01-08     0      0
# 9 2022-01-09     0      0

Data
nums1 <- structure(list(date = structure(c(18993, 18994, 18995, 18996, 18997, 18998), class = "Date"), value = c(18, 12, -3, -4, 5, -2)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
nums2 <- structure(list(date = structure(c(18993, 18994, 18995, 18996, 18997, 18998, 18999, 19000, 19001), class = "Date"), value = c(18, 12, 1, 0, 0, -3, 1, 0, 0)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))


text:
Q: How to pass only year from url to view I have my django app and I want to pass from url to view years in format, for example: 2017-18.
Below I got an error that my date have to be in date format - YYYY-MM-DD.
Here is my url:
url(r'^(?P<branch_slug>/production/(?P<year1>[0-9]{4})-(?P<year2>[0-9]{2})$', Events.as_view()),

Here is my view:
def get_queryset(self):
    season = Events.objects.get(start=self.kwargs['year1'], end=self.kwargs['year2'])
    filter_['start__gte'] = season.start
    filter_['start__lte'] = season.end
    return self.model.objects.filter(**filter_)

A: The start and end attributes of your Event object are probably datetime.date instances (if you are using a DateField). So you need to convert the year1 and year2 variables from your url to a date before using them in your view.
some_date = datetime.date(YYYY, 1, 1)

A: Your original question, and others' answers here, match a season that begins on 1 January of year1 and ends on 31 December of year2. I suspect that this is not what you want, and that instead you want a season which starts sometime in year1 and ends some time in year2, and then you want to look up events between those dates.
Django has a special lookup for matching only the year part of a date, using __year=. See https://docs.djangoproject.com/en/1.10/ref/models/querysets/#year for more on this. You don't need to convert the input values to dates to use this; it works with integers.
def get_queryset(self):
    # Get a season starting any time in year1 and ending in year2
    season = Events.objects.get(
        start__year=int(self.kwargs['year1']),
        end__year=int(self.kwargs['year2']),
    )

As with others have commented you should change the URL regex to match 4-digit years to avoid ambiguity.
url(r'^(?P<branch_slug>/production/(?P<year1>[0-9]{4})-(?P<year2>[0-9]{4})$', Events.as_view()),

A: As @dentemm pointed out, to do filtering on datetime fields, strings representing date must be converted to datetime objects. My suggestion is to use datetime field. Pass year string as you are already doing and then in the views convert date string to a datetime object to do filtering
import datetime
def get_queryset(self):
    start=datetime.strptime('1-1-'+self.kwargs['year1'], '%m-%d-%Y')
    end=datetime.strptime('12-31-'+self.kwargs['year2'], '%m-%d-%Y')
    season = Events.objects.get(start=start, end=end)
    filter_['start__gte'] = season.start
    filter_['start__lte'] = season.end
    return self.model.objects.filter(**filter_)

datetime.strptime('1-1-'+self.kwargs['year1'], '%m-%d-%Y') will create datetime object for start date with date as 1st of january for given start date string and datetime.strptime('12-31-'+self.kwargs['year2'], '%m-%d-%Y') will create datetime object for end date with date as 31st of december for given end date string. To make sure all objects created within end date is returned by query you may do something like
`end_date = datetime.strptime('31-12-'+self.kwargs['year1']+'T23:59:59.999999', '%m-%d-%YT%H:%M:%S.%f')`

As @Alasdair mnetioned in one of the comments change (?P<year2>[0-9]{2}) to (?P<year2>[0-9]{4}) to accept 4 digit year string from url

A: If you have a datetime/date field in your model, use the year lookup from Django:
https://docs.djangoproject.com/en/1.10/ref/models/querysets/#year
As it says:
Entry.objects.filter(pub_date__year=2005)
is equal in sql to:
SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';


text:
Q: Internet very slow on Ubuntu 16.04 and 18.04 but fast on 19.04 I have an OVH server.
When I install Ubuntu 16.04 or 18.04 or 18.10 on it, the internet speed is 70Mbps download and 4.16Mbps upload.
But when I upgrade to Ubuntu 19.04, the internet speed becomes 400Mbps download and 400Mbps upload (which is the full speed of the server)
I've searched a lot to fix that on 16.04, 18.04, and 18.10 but I failed.
I tried Very slow internet connection on ubuntu 16.04 and https://unix.stackexchange.com/questions/366220/ubuntu-16-04-minimal-extremely-slow-internet-connection but without luck :/
I don't want to use Ubuntu 19.04 because it is pretty new and not everything is supported on it yet.
Thanks!

A: I fixed it! This is how:
I followed https://www.itzgeek.com/how-tos/linux/debian/how-to-disable-ipv6-on-debian-9-ubuntu-16-04.html (Method 1) to disable IPv6 on my server.
Then I removed the DNS servers from the /etc/resolv.conf file by removing the nameserver lines.
Then I installed network-manager by using: apt -y install network-manager
Then I disabled other DNS services by fully opting-out from the NetworkManager by typing:
echo -e "[main]\ndns=none" > /etc/NetworkManager/conf.d/no-dns.conf
systemctl restart NetworkManager.service
rm /etc/resolv.conf
Then I disabled and removed systemd-resolved by typing the following:
sudo systemctl disable systemd-resolved.service
sudo systemctl stop systemd-resolved

Then I have put the following line in the [main] section of my /etc/NetworkManager/NetworkManager.conf file:
dns=default

Then I removed /etc/resolv.conf by typing: rm /etc/resolv.conf
Then I finally restarted network-manager by typing: sudo service network-manager restart
Now my internet speed is the normal one :)
This also works on Debian.
For CentOS: All what you have to do is to disable IPv6, and remove the nameserver lines from /etc/resolv.conf only.

A: Uninstalling networkmanager does the trick too and configuration /etc/network/interfaces. Especially for wired desktops, I found this the fastest and most reliable as it is not depending on systemd.
sudo systemctl disable network-manager

sudo systemctl stop network-manager

If you want to remove network-manager totally:
sudo apt-get purge network-manager

sudo apt autoremove

Look up your network card(s)
ifconfig -a

sudo gedit /etc/network/interfaces

Example based on 2 network cards cards:
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
# Internet
auto enp5s0 (replace with your network card)
iface enp5s0 inet dhcp (replce with your network card)
netmask 255.255.255.0
gateway 192.168.xxx.xxx
# Server connection
auto enp4s0 (replace with your network card)
iface enp4s0 inet static (replace with your network card)
address 192.168.xxx.xxx
netmask 255.255.xxx.xxx
mtu 9000 (correct to server speed/ network cards and abillity of jumbo frames)

Reboot or bring network cards up with:
ifup <your network card>


text:
Q: Where can one learn about dispersion relations for S-matrices? Most textbooks on quantum field theory never mention dispersion relations at all. Where can one learn about dispersion relations for S-matrices?

A: Bjorken  & Drell's QFT book. It is old but therefore strong on this point.


text:
Q: What are the differences between function generator and oscillator? (Specific design) I design the attached circuit:
75 MHz Sine wave that connected to R and C in parallel:

In the output, the amplitude of the sine wave is changing according to the C, more capacitance smaller amplitude of the sine wave.
When I tried that in the lab I got 2 results:

*1. When I connected the function generator as the source I got the same results - higher C lower amplitude (of the sine wave in the output)

*2. When I connected it to oscillator (http://www.farnell.com/datasheets/75480.pdf) I'm getting different results: the output is a sine wave, but if I make C higher the amplitude becomes lower until the sine wave (in the output) is "flipping" (kind of changing phase) and, if I keep raising the C higher, the sine wave in the output starts getting higher.
What are the differences between the two?
How can I make the oscillator work like the function generator in this case?

A: I'm going to assume that you used something like a breadboard to mount your components, and standard breadboard jumpers several inches long. And there lies your problem.
75 MHz is just too high a frequency to get reliable results on a standard breadboard unless you use great care. The biggest problem is the ground connection of your scope, which needs to be as short as possible, and connected to the circuit as close as possible to the ground pin of your oscillator. Just as an experiment, try looking at your oscillator output on the scope and try moving the probe around (changing the angle of your hand and probe).
Another way to look at this is to consider that your physical setup is almost certainly not exactly what your schematic indicates. Long wires will have parasitic inductances which become important at 75 MHz.
Second, especially with the oscillator, is making sure you have properly decoupled it. Use a 0.1 uF ceramic cap connected as close to the power and ground pins as is humanly possible, with the cap leads as short as possible.
Comparing your oscillator and an external function generator is fraught with possible difficulties. As a start, the FG is probably putting out fairly good sine wave. Your oscillator, on the other hand, is doing its best to put out a square wave - notice the 3 nsec rise and fall times. This will produce large signal components at multiples of 75 MHz. Granted, the large load capacitances you use will tend to filter these harmonics out, but with varying effects.
And finally (although perhaps I should have listed it as first), as asdex has pointed out, your oscillator is completely unsuited for the circuit you are investigating.

A: First, Thanks for the answers. I post another answer to attach the photos.
I know that 75MHz is a problem with a breadboard and because of that I soldered it on protoboard. This is the photo of the oscillator on the board:

And this is the output signal (with just 15pF from the output to the GND, @Spehro Pefhany, @asdfex - does it look like "an elephant-shaped"?):

I know that I'm doing something wrong and because of that I post it here. I search a little more and understood that I need to add a buffer. What do you say?


text:
Q: Can't figure out why I'm getting the typeError 'unsupported operand type(s) for -: 'int' and 'str' ' I posted 15 mins ago about this problem but was told there wasn't enough code to tell what the problem was so I've included the whole thing this time.
The problem is in the self.__r_miles += (new_odo - self.__odometer) line in the process_rental function. I know that based off the error and the specific line, self.__odometer is a string. But for the life of me I cannot figure out why. I'm assuming it's something obvious but I've just been staring at it for too long to notice.
I believe I've put everything in as an int whenever I need to but obviously I messed up somewhere.
 class Fleet(object):
    fleetcount = 0
    car_desc = "DMC DeLorean"
    daily_rate = 100
    maxfleet = 10

    def get_vin(self):
        return self.__vin
    def get_year(self):
        return self.__year
    def get_odometer(self):
        return self.__odometer
    def set_odometer(self, miles):
        if miles>self.__odometer:
            self.__odometer = miles
    def get_r_miles(self):
        return self.__r_miles
    def get_r_days(self):
        return self.__r_days
    def get_rentals(self):
        return self.__rentals

    def __init__(self, vin, typ, year, color, odometer, r_miles = 0, r_days = 0, rentals = 0 ):
        self.__vin = vin
        self.__type = typ
        self.__year = year
        self.color = color
        self.__odometer = odometer
        self.__r_miles = r_miles
        self.__r_days = r_days
        self.__rentals = rentals
        Fleet.fleetcount += 1

    def process_rental(self, new_odo, days):
        self.__rentals += 1
        self.__r_days += days
        self.__r_miles += (new_odo - self.__odometer)
        self.set_odometer(new_odo)

    def calc_bill(self,new_odo, days):
        return days * Fleet.daily_rate

    def calc_age(self, curr_yr):
        age = curr_yr - self.__year
        return age

    def sell_car(self,curr_yr):
        if self.calc_age(curr_yr)>3 or self.__odometer>50000:
            return True
        else:
            return False

    def print_summary(self):
        print("VIN:", self.__vin, "Make:",Fleet.car_desc, "Year:", self.__year, "Color:", self.color, "Odometer:", self.__odometer, "\n")

    def print_metrics(self, curr_yr):
        age = curr_yr - self.__year
        rmpy = self.__r_miles/age
        rdpy = self.__r_days/age
        rpy = self.__rentals/age
        mpr = self.__r_miles/self.__rentals
        dpr = self.__r_days/self.__rentals
        print("METRICS FOR CAR WITH VIN", self.__vin, "ARE AS FOLLOWS")
        print("Average rental miles per year:", rmpy)
        print("Average rental days per year:", rdpy)
        print("Average times rented per year:", rpy)
        print("Average miles per rental:", mpr)
        print("Average days per rental:", dpr, "\n")

    def fleet_left(self):
        remaining = Fleet.maxfleet - Fleet.fleetcount
        if remaining>0:
            return remaining
        else:
            return 0

    def __str__(self):
        return self.__vin + "," + self.__type + "," + self.__year + "," + self.__odometer + "," + self.color + "," + self.__r_miles + "," + self.__r_days + "," + self.__rentals

class Truck(Fleet):
    daily_rate = 85
    mile_rate = .5
    def calc_bill(self, new_odo, days):
        miles = new_odo - self.__odometer
        return (miles * Truck.mile_rate) + (days * Truck.daily_rate)

with open("fleet.txt", "r") as myfile:
    next(myfile)
    fleet = {}
    for line in myfile:
         v, ty, y, o, c, rm, rd, r = line.strip().split(",")
         if ty == "C":
            fleet[v] = Fleet(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
         else:
            fleet[v] = Truck(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))

totalrev = 0
with open("transaction.txt", "r") as myfile:
    for line in myfile:
        trans = line.strip().split(",")
        if trans[1] == "R":
            totalrev += fleet[trans[0]].calc_bill(int(trans[2]), int(trans[3]))
            fleet[trans[0]].process_rental(int(trans[2]), int(trans[3]))
        elif trans[1] == "S":
            fleet[trans[0]].set_odometer(int(trans[2]))
        elif trans[1] == "P":
            fleet[trans[0]].color = trans[2]

yr = int(input("What is the current year? "))
sell_list = []
for obj in fleet:
    if obj.sell_car(yr) == True:
        sell_list.append(obj.get_vin())

rem = Fleet.fleet_left()

print("Total Revenue:", totalrev)
print("VINs of vehicles that should be sold:", sell_list)
print("Additional number of vehicles that can be acquired:", rem)

with open("updated_fleet.txt", "w") as myfile:
    for obj in fleet:
        outline = obj.__str__()
        myfile.write(outline)
    myfile.close()

A: This is what you're saying produces an error
self.__r_miles += (new_odo - self.__odometer)

Specifically
new_odo - self.__odometer

And the error is:
unsupported operand type(s) for -: 'int' and 'str'

This means that self.__odometer is a string. So you have either:

*

*Initialized it to a string value

*Changed its value to a string somewhere

Check the parts of your code that sets self.__odometer and make sure that the assigned value is always int. You might not have casted something to int e.g. something like self.__odometer = trans[0] instead of self.__odometer = int(trans[0]).
This is the source of the error.
v, ty, y, o, c, rm, rd, r = line.strip().split(",")
if ty == "C":
    fleet[v] = Fleet(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
else:
    fleet[v] = Truck(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
#                                           ^ You didn't cast the 5th argument, which is for odometer

The line.strip().split(",") produces strings. Then, you just directly used it to initialize odometer which is the 5th argument:
class Fleet:
    def __init__(self, vin, typ, year, color, odometer, r_miles = 0, r_days = 0, rentals = 0 ):
        #                                     ^ 5th argument

You only passed the string c. Instead, cast it to int first int(c).


text:
Q: How to make page take whole browser window? I only recently started looking into bootstrap. I have created a very simple page, and I want it to take all of the window instead of just wrapping to content size. I am focusing on webkit browsers. I want the content to take 100% of the page height-wise and width-wise. Width is already done but I have trobules with taking 100% of height.
I tried the following solution from a similar question on Stack Overflow:
  html{
    min-height: 100%; /* real browsers */
    height: auto !important; /* real browsers */
    height: 100%; /* IE6: treated as min-height*/
  }
  body {
    background-color: #FFF;
    margin: 0;
    padding: 0;
    min-height: 100%; /* real browsers */
    height: auto !important; /* real browsers */
    height: 100%; /* IE6: treated as min-height*/
  }

But it has no effect.
This:
  html{
    height: 100%;
  }
  body {
    background-color: #FFF;
    height: 100%;
  }

Takes up too much space - it gets too tall and scrollbar appears.
What should I do to achieve my goal?
Full code is here: https://gist.github.com/LucasSeveryn/d1590bcafbf6e23b1239

A: The key to 100% height is that you need a wrapper div around all of your content that is also set to min-height: 100%. Here is your code with the extra wrapper added in (I gave it a red background for demo purposes):
<!DOCTYPE html>

  <title>ActRecognitionWeb</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

        ActRecognition

Summary

Challenges

Routes

Settings

Log Out

There's a great nuts and bolts tutorial on this here:
http://www.sitepoint.com/forums/showthread.php?171943-CSS-FAQ-Tips-etc-Please-read-before-posting!&p=1243541#post1243541
with a simpler solution if you are just targeting IE8 and above.

A: I think the solution is use height: 100% with overflow: scroll property.

A: You can also use jQuery
$(document).ready( function() {
    var windowHeight = $(window).height();
    $('body').height(windowHeight);
});


text:
Q: requesting user permissions not working facebook graph api hi i am using facebook graph api PHP SDK . here i am trying to get the logged in user's facebook details , currently i am getting only the basic details which are not required any permissions .
Array
(
    [id] => xxxxxxxxx
    [name] => Kanishka Bandara Panamaldeniya
    [first_name] => Kanishka
    [middle_name] => Bandara
    [last_name] => Panamaldeniya
    [link] => http://www.facebook.com/kanishka.panamaldeniya
    [username] => kanishka.panamaldeniya
    [hometown] => Array
        (
            [id] => 108014839219027
            [name] => Kandy
        )

    [location] => Array
        (
            [id] => 108602292505393
            [name] => Colombo, Sri Lanka
        )

    [quotes] => every action has a reaction....
    [work] => Array
        (
            [0] => Array
                (
                    [employer] => Array
                        (
                            [id] => 234117399957729
                            [name] => Cyber LMJ
                        )

                    [location] => Array
                        (
                            [id] => 108602292505393
                            [name] => Colombo, Sri Lanka
                        )

                    [position] => Array
                        (
                            [id] => 109542932398298
                            [name] => Software Engineer
                        )

                    [start_date] => 2011-08
                )

            [1] => Array
                (
                    [employer] => Array
                        (
                            [id] => 235852306375
                            [name] => eMarketingEye
                        )

                    [position] => Array
                        (
                            [id] => 109542932398298
                            [name] => Software Engineer
                        )

                    [start_date] => 2010-09
                    [end_date] => 2011-08
                )

        )

    [sports] => Array
        (
            [0] => Array
                (
                    [id] => 103992339636529
                    [name] => Cricket
                )

        )

    [favorite_teams] => Array
        (
            [0] => Array
                (
                    [id] => 191485640872790
                    [name] => Sri Lanka Cricket Team
                )

        )

    [favorite_athletes] => Array
        (
            [0] => Array
                (
                    [id] => 185101794860886
                    [name] => Kumara Sangakkara
                )

            [1] => Array
                (
                    [id] => 119473804782315
                    [name] => Angelo Mathews
                )

            [2] => Array
                (
                    [id] => 164574093575397
                    [name] => Kumar Sangakkara
                )

            [3] => Array
                (
                    [id] => 169411436417102
                    [name] => Virat Kohli
                )

            [4] => Array
                (
                    [id] => 166273026737204
                    [name] => Lahiru Thirimanne
                )

            [5] => Array
                (
                    [id] => 101237886616765
                    [name] => Dinesh Chandimal
                )

        )

    [education] => Array
        (
            [0] => Array
                (
                    [school] => Array
                        (
                            [id] => 34663330581
                            [name] => Dharmaraja College-Kandy
                        )

                    [year] => Array
                        (
                            [id] => 138383069535219
                            [name] => 2005
                        )

                    [type] => High School
                )

            [1] => Array
                (
                    [school] => Array
                        (
                            [id] => 112872282058324
                            [name] => University of Colombo School of Computing
                        )

                    [year] => Array
                        (
                            [id] => 140617569303679
                            [name] => 2007
                        )

                    [type] => College
                )

            [2] => Array
                (
                    [school] => Array
                        (
                            [id] => 107577089271805
                            [name] => University of Colombo
                        )

                    [type] => Graduate School
                    [with] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 705760115
                                    [name] => Lasitha Benaragama
                                )

                        )

                )

        )

    [gender] => male
    [timezone] => 5.5
    [locale] => en_US
    [languages] => Array
        (
            [0] => Array
                (
                    [id] => 104023029632921
                    [name] => Sinhala
                )

            [1] => Array
                (
                    [id] => 106059522759137
                    [name] => English
                )

        )

    [verified] => 1
    [updated_time] => 2012-07-29T16:34:22+0000
)

now i want to get fields
*email
*birth day

and some other permission requesting fields .
so i am doing
    $this->co_config_items = $this->ci->config->item('connections_config');
    $fbconfig = array(
    'appId' => $this->co_config_items['fb_appid'],
    'secret' => $this->co_config_items['fb_secret'],
    'cookie' => true,
    'domain' => $this->ci->config->item('domain')
    );

    $this->ci->load->library('3rd/connectors/facebook', $fbconfig);

    $facebook = new Facebook($fbconfig);
    Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
    Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

    $session = $facebook->getSession();

    $url = $facebook->getLoginUrl(array(
                   'canvas' => 1,
                   'fbconnect' => 0,
                   'scope' => 'read_stream,friends_likes,user_birthday'
    ));

    if(!$session){
        $url = $facebook->getLoginUrl(array(
                   'canvas' => 1,
                   'fbconnect' => 0,
                   'scope' => 'read_stream,friends_likes,user_birthday'

                  ));

        echo "<script type='text/javascript'>window.location = '$url';</script>";
    }
    else{
        //echo "<script type='text/javascript'>window.opener.location.href='" . base_url() . "home/auth/get_user_facebook_details_list" . "'; self.close();
        //</script>";
        try {

            $me = $facebook->api('/me');

            $this->ci->session->set_flashdata ( 'user_details',$me);
            $url=base_url()."home/auth/user_contact_information";
            echo "<script type='text/javascript'>window.opener.location.href = '$url';self.close();</script>";

        } catch (FacebookApiException $e) {
            $this->ci->message->set_error(array('An errror occured , please try again'));
        }
    }

i am trying to ask permissions by
        $url = $facebook->getLoginUrl(array(
                       'canvas' => 1,
                       'fbconnect' => 0,
                       'scope' => 'read_stream,friends_likes,user_birthday'
)):

but it is not asking for any permission , the default array is always printing . why is that . please help . thanks in advance

A: Try doing this instead:
$url = $facebook->getLoginUrl(array('scope' => 'read_stream,friends_likes,user_birthday'));

A: i was using the version 2 of PHP sdk , now i am using version 3 , now it is working , thank you very much . i saw some changes in two versions in this function
version 2
  public function getLoginUrl($params=array()) {
        $currentUrl = $this->getCurrentUrl();
        return $this->getUrl(
                'www',
                'login.php',
                array_merge(array(
                    'api_key' => $this->getAppId(),
                    'cancel_url' => $currentUrl,
                    'display' => 'page',
                    'fbconnect' => 1,
                    'next' => $currentUrl,
                    'return_session' => 1,
                    'session_version' => 3,
                    'v' => '1.0',
                        ), $params)
        );
    }

version 3
 public function getLoginUrl($params=array()) {
    $this->establishCSRFTokenState();
    $currentUrl = $this->getCurrentUrl();

    // if 'scope' is passed as an array, convert to comma separated list
    $scopeParams = isset($params['scope']) ? $params['scope'] : null;
    if ($scopeParams && is_array($scopeParams)) {
      $params['scope'] = implode(',', $scopeParams);
    }

    return $this->getUrl(
      'www',
      'dialog/oauth',
      array_merge(array(
                    'client_id' => $this->getAppId(),
                    'redirect_uri' => $currentUrl, // possibly overwritten
                    'state' => $this->state),
                  $params));
  }

in version 3 this i can see this additional code
// if 'scope' is passed as an array, convert to comma separated list
    $scopeParams = isset($params['scope']) ? $params['scope'] : null;
    if ($scopeParams && is_array($scopeParams)) {
      $params['scope'] = implode(',', $scopeParams);
    }

in version 2 , there is nothing called scope .and also
in version 2
return $this->getUrl(
                    'www',
                    'login.php',

in version 3
return $this->getUrl(
          'www',
          'dialog/oauth',


text:
Q: A strange error of 'let' in bash I wonder if the code below has wrong syntax ?
#!/bin/bash
set -e
let "time_used = 1 - 1"
echo $time_used

When I run it, nothing print. The script died on let "time_used = 1 - 1".
If I remove set -e in second line, I get the correct result 0.
Why it happened?

A: let is a bash built-in for shell arithmentic
let "time_used = 1 - 1"

is equivalent to
(( time_used = 1 - 1 ))

however 0 in shell arithmetic means false and gives error exit status to avoid to exit with -e || true can be added after command
(( 0 )) || true
let "time_used = 1 - 1" || true

|| true allows to "bypass" -e option for commands returning an error exit status however we can't distinguish a command that failed from a command that returns a false exit status. Other option can be to use arithmetic to return always a truthy value.
(( (time_used = 1 - 1) || 1))

A: Because let returns 1 if it's result is equal 0.
In other case, it returns 0.

$ help let | tail -n2
      Exit Status:
      If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.


text:
Q: Why method overloading is not able to resolve by return type in java Method overloading is based on the method signature. But when we make it clear by the return type that which method needs to be called, why Java is not able to figure this out? The sample code is below.
public class TestClass {
    public static void main(String[] args) {
        int i = new TestClass().getI(5);       //line 3

        String t = new TestClass().getI(3);    //line 5
    }

    public int getI(int i){  //Line 8
        return 1;
    }

    public String getI(int i){  //Line 12
        return "ss";
    }
}

Here we can see that in line 3 we are expecting a return type as integer. So it is evident that we want to call the method at line 8. In line 5, it is evident that we want to invoke method at line 12. But Java is not able to handle it and on execution gives Error. I needed to understand why Java is not able to figure out this simple scenario?


text:
Q: Distribution (group) comparison based on PCA I am looking for a way to compare the first the k principal components belonging to two separate groups of two-dimensional data, in order to see how similar the two groups are. I do not know which method to use to do this properly.
Googe showed me several, including Between-Group Comparison and Discriminant Analysis of Principal Components. Since I'm very new to PCA, I am looking for advice on which method should be employed for this kind of problem.
Particulars of my data are following: 46 data clusters, each a bi-variate distribution formed by two variables measuring different things (so, the units are different). The total number of observations of variables varies between the clusters. One might have dimensions of 150x2, another of 75x2, and yet another 12x2. The clusters are not necessarily Gaussian (that is, the constituting variables have mostly normal distribution, but their joint distribution which is a cluster is often not normal).
Because the variables generating the clusters are of different units, for PCA performed on individual data clusters I first standardize the data. Once I obtain principal components and loadings for each of the 46 data clusters, I need to find a method to compare those results. I have already tried various other distribution comparison methods (like KLD, something based on Mahalonobis distance, etc.), with mixed results.
I work with Matlab and Python, and have no knowledge of R or programs like SPSS.


text:
Q: Syntax highlight operators such as *,-> I'm using the spf-13 vim distribution on OS X (this problem is not specific to this distribution). I tried a few different color schemes (solarized, default, desert) and none of them highlight C specific operators such as *,->, etc. Further reading showed that this depends on the regex defined to identify these operators. I'm not versed enough in vim script/regex to try this modification yet on a color scheme.
Is it possible to modify solarized or any other scheme to highlight these operators in C? It would be ideal if there is a color scheme that already supports this.

A: Colorschemes only define colors for syntax/highlight groups defined in syntax files (and default groups).
Since the default C syntax file doesn't appear to define anything for these operators (or any other, actually) there's nothing you can do to your colorscheme to make them stand out. It's the syntax file that should be mofified… or extended.
This syntax file extends the default syntax file with, among other things, operators.


text:
Q: Selecting specific rows in Excel and perform calculations using VBA I have this spreadsheet:

For each of the sectors (IT, Consumer Discretionary, Financials, etc), I want to add % invested and return the result summed values. For example, IT should return 7%(1+2+4) and Health Care should return 24%(7+8+9).
This is what I have so far:
Dim sector_array As Variant
Dim sector As Variant
Dim ocell As Range
Dim rng As Range
sector_array = Array("Information Technology", "Financials", "Consumer
Discretionary", "Energy", "Materials", "Consumer Staples", "Health Care",
"Industrials", "Utilities", "Telecommunication Services", "Real Estate")

For Each sector In sector_array
For Each ocell In Range("C:C")
    If ocell.Value = sector Then
        If rng Is Nothing Then
            Set rng = ocell.EntireRow
        Else
            Set rng = Union(rng, ocell.EntireRow)
        End If
    End If
Next ocell
If Not rng Is Nothing Then
    rng.Select

End If
Next sector

How would I achieve this please?

A: I would do an SUMIF formula specifying each category in the column F.

A: Use a dictionary. The keys are the sector and values the percentages. If a key exists then add the percentage to the existing value.
Option Explicit
Public Sub test()
    Dim lastRow As Long, dict As Object, i As Long, key As Variant

    With ActiveSheet
        Dim dataArr()
        dataArr = .Range("C2:E" & .Cells(.Rows.Count, "C").End(xlUp).Row).Value
    End With

    Set dict = CreateObject("Scripting.Dictionary")

    For i = LBound(dataArr, 1) To UBound(dataArr, 1)
        If Not dict.exists(dataArr(i, 1)) Then
            dict.Add dataArr(i, 1), dataArr(i, 3)
        Else
            dict(dataArr(i, 1)) = dict(dataArr(i, 1)) + dataArr(i, 3)
        End If
    Next i

   For Each key In dict.keys
       Debug.Print key & " : " & dict(key)
   Next key

End Sub

Result in immediate window (Ctrl + G)


text:
Q: Wordpress Post HTML after Posting I am writing a plugin for WordPress, one of the tasks I need to-do is send the HTML content of a new post to an e-mail address at the time of posting, I know I can use certain hooks to fire after the post has been saved, but is there a way to get the full HTML content of the new page/post with the theme applied?
I have custom fields within the post so ideally I would like to get the whole post from the URL rather then reconstructing all the fields to then send in HTML.
Any help would be appreciated!
Thanks

A: add_action('publish_post', 'email_post');
function email_post($postID)
{
    $post = get_post($postID);
    $content = $post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]>', $content);
    $mailto = 'youremail';
    $subject = 'New Post';
    if(mail($mailto, $subject, $content))
        return true;
    else
        return false;
}

Be sure to set your headers or anything else you might need to populate your email correctly. This is untested, but it should help get you started.


text:
Q: How to merge two CSV documents together using pandas and plot a bar graph? Data1: shanghaiData.csv
Data2: timesData.csv
I'm just learning to use data from CSV and visualization. I am trying to merge two CSV sheets and then plot both world rankings on a bar graph for a specific university.
My code is:
import pandas as pd
import matplotlib
times_df = pd.read_csv("timesData.csv")
shanghai_df = pd.read_csv("shanghaiData.csv")
combined = times_df.merge(shanghai_df, on='university_name', how='left')
combined = combined.loc[combined['university_name']=='Harvard University']
combined.plot(
    kind = 'bar',
    x = 'year_y',
    y = ['world_rank_x', 'world_rank_y']
)

TypeError                                 Traceback (most recent call last)
<ipython-input-1-e360afadaed4> in <module>
      3 combined.loc[combined['university_name']=='Harvard University']
      4 combined = combined.loc[combined['university_name']=='Harvard University']
----> 5 combined.plot(
      6     kind = 'bar',
      7     x = 'year_y',

/usr/lib/python3.9/site-packages/pandas/plotting/_core.py in __call__(self, *args, **kwargs)
    970                     data.columns = label_name
    971
--> 972         return plot_backend.plot(data, kind=kind, **kwargs)
    973
    974     __call__.__doc__ = __doc__

/usr/lib/python3.9/site-packages/pandas/plotting/_matplotlib/__init__.py in plot(data, kind, **kwargs)
     69             kwargs["ax"] = getattr(ax, "left_ax", ax)
     70     plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 71     plot_obj.generate()
     72     plot_obj.draw()
     73     return plot_obj.result

/usr/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py in generate(self)
    284     def generate(self):
    285         self._args_adjust()
--> 286         self._compute_plot_data()
    287         self._setup_subplots()
    288         self._make_plot()

/usr/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py in _compute_plot_data(self)
    451         # no non-numeric frames or series allowed
    452         if is_empty:
--> 453             raise TypeError("no numeric data to plot")
    454
    455         self.data = numeric_data.apply(self._convert_to_ndarray)

TypeError: no numeric data to plot

If I try to cast year as and integer I still get an error.
combined['year_y'] = combined['year_y'].astype(int)

A: I'm not sure about your output and why draw bar plot, but I change your code and correct it.
change this line of code:
import matplotlib.pyplot as plt

plt.bar(combined['year_y'], combined['world_rank_x'])

finally:
import pandas as pd
import matplotlib.pyplot as plt

times_df = pd.read_csv("timesData.csv")
shanghai_df = pd.read_csv("shanghaiData.csv")

combined = times_df.merge(shanghai_df, on='university_name', how='left')
combined = combined.loc[combined['university_name']=='Harvard University']

plt.bar(combined['year_y'], combined['world_rank_x'])

and if you want two bar plot in one plot, you can use this code:
import numpy as np
import matplotlib.pyplot as plt

barWidth = 0.25
fig = plt.subplots(figsize =(12, 8))

world_rank_x = [2, 2, 2, 2, 2]
world_rank_y = [6, 6, 6, 6, 6]

br1 = np.arange(len(world_rank_x))
br2 = [x + barWidth for x in br1]

plt.bar(br1, world_rank_x, color ='r', width = barWidth,
        edgecolor ='grey', label ='world_rank_x')
plt.bar(br2, world_rank_y, color ='g', width = barWidth,
        edgecolor ='grey', label ='world_rank_y')

plt.xlabel('Year', fontweight ='bold', fontsize = 15)
plt.ylabel('world rank', fontweight ='bold', fontsize = 15)
plt.xticks([r+(barWidth)/2 for r in range(len(world_rank_x))],
        ['2015', '2016', '2017', '2018', '2019'])

plt.legend()
plt.show()

output:


text:
Q: How to bring Tkinter window in front of other windows? I'm working with some Tkinter Python code (Python 3.4), and I've come across a problem. When I create my Tkinter window it doesn't show up in front. I do it currently with the following code:
from tkinter import *
win = Tk()
win.minsize(width=1440, height=828)
win.maxsize(width=1440, height=828)

The minsize() and maxsize() make the window cover my entire screen, but the original python running window (The one that wouldprint("Hello, World!")) ends up on top. Is there a way to fix this? I'm running OS X 10.10.1.

A: Set it as the topmost (but it will always stay in front of the others):
win.attributes('-topmost', True) # note - before topmost

To not make it always in front of the others, insert this code before the mainloop:
win.lift()
win.attributes('-topmost', True)
win.attributes('-topmost', False)

Don't forget win.mainloop() at the end of your code (even if in some cases it's not explicitly required)
Other discussions on the same problem:

*

*How to put a Tkinter window on top of the others

*How to make a Tkinter window jump to the front?


text:
Q: Error in jelastic php 7.3 regarding zip.so When redeploying or newly deploying a Node with PHP 7.3 (nginx 1.14.2) i get the following error when trying to create a zip-archive in php using zip.so

php: symbol lookup error: /usr/lib64/php/modules/zip.so: undefined symbol: zip_file_add

(this is from calling the $zip->addFile() function.
This is a problem across jelastic hosting-providers (tested on two different hosting-providers)


text:
Q: Orphan lines with memoir I have read that for memoir in order to set separation between paragraphs you use
\abnormalparskip{6pt}

However I have a question: Does it fix to 6pt or does it allow a little variation between minus and max setting \parskip. If the behaviour is differnt how can I set it to give a min an a max. I have some orphan lines which I want to remove, but using clubpenaty and widowpenalty makes the document look ugly.
\setlength{\parskip}{6pt plus 0.2 \baselineskip minus 0.2 \baselineskip}

I don't know how can I write a mwe for this issue. Sorry for that.
Edit: MWE
\documentclass[11pt, twoside, a4paper]{memoir}

\usepackage[utf8]{inputenc}
\usepackage[spanish, es-noquoting, es-tabla]{babel}
\usepackage[spanish]{translator}
\usepackage[T1]{fontenc}

\usepackage[a4paper,
            hmargin = 2.5cm,
            vmargin = 2.5cm,
            twoside,
            includefoot,
            includehead,
            bindingoffset = 0.1cm
             ]
             {geometry}

\setlength{\parindent}{1em}
\setsecnumdepth{subsubsection} %Numeracion hasta subsection
\setcounter{tocdepth}{3}
%\setlength{\parskip}{6pt plus4mm minus3mm}
\abnormalparskip{6pt} % este es el que hay que usar en memoir 12

%Headers
\openright

\pagestyle{ruled}%

%\clubpenalty=10000
%\widowpenalty=10000

\begin{document}
\vspace*{55em}

xx xxxx xx xx xxxxxxxx xx xxxxxxxxxxx xx xxxxxxx xxx xxxxxxxxxxxx xx xxx xxxxxxxxxxxxx xxxxxxxxxxx, xxxxxxxxxx xx xx xxxxxx xxx xxx xxxxxxxx xxxxxxx xxx xxx xxxxxxx xxxxxxxxxxxxx, xx xxxxxx xx xx xx, xxx xxxxxxxx xx xxxxxxxxxxxxxxx x xxx xxxxx xx xxxxxxx xxxxxxx xx xxxxxxxxxxxxxxx xx xxx xxxxxxx xx xxxxxxxxxxxx xxxxxxx x xxx, xxxx xx xxx xxxxxxxxxxxxxx, xxxxxxxx xxxxxx xx xxxxxxxxxxxxx xx xxx xxxxxxxxxx xx xxxxxxxxx xxxxxx xx xx xx x xx xxxxxxxxxxx xxxxx xx.
\end{document}


text:
Q: Reversing values in a column My data is something like this. I want to reverse the values of column B.
df <- data.frame(A = c(  "Not at all"  ,"Several days" ,  "More than half the days",  "Nearly every day "),
                 B = c(1, 2, 3, 4))

So, I want to have it like this.

df <- data.frame(A = c(  "Not at all"  ,"Several days" ,  "More than half the days",  "Nearly every day "),
                 B = c(4, 3, 2, 1))

rev is not working with my data and the structure of the data is :
'data.frame':   511 obs. of  6 variables:
 $ id...1          : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Q3.2_1...2      : num  1 3 2 2 2 2 2 2 3 2 ...
 $ id...3          : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Q3.2_1...4      : chr  "Several days" "Not at all" "Not at all" "Nearly every day" ...
 $ newcolumn.id    : int  1 2 3 4 5 6 7 8 9 10 ...
 $ newcolumn.Q3.2_1: chr  "Several days" "Not at all" "Not at all" "Nearly every day"

I want to reverse Q3.2_1 num.

A: Try this:
#Code
df$B <- rev(df$B)

Output:
df
                        A B
1              Not at all 4
2            Several days 3
3 More than half the days 2
4       Nearly every day  1

Or with dplyr:
library(dplyr)
#Code
df <- df %>% mutate(B=rev(B))


text:
Q: How to integrate swagger with Azure Active Directory OAuth I'm trying to setup Swagger in my AspNetCore 2.1 application using Azure Active Directory V2 but I cannot seem to get it right. I am able to configure the setup so that swagger prompts, redirects and successfully authenticates my client/user but when passing the bearer token to the server results in the error Bearer error="invalid_token", error_description="The signature is invalid". I have created a GitHub repository with the project I am trying to get work with all its configuration (https://github.com/alucard112/auth-problem)
I have managed to get the V1 endpoint working, by setting the resource to the Client Id of the AAD app, which results in the JWT token having the 'aud' set to the app client Id. In the V2 endpoint the 'aud' is being set to what I think is the Graph API resource '00000003-0000-0000-c000-000000000000'. I believe this is my problem at the moment, although am not 100 % sure. The V2 endpoints don't seem to have a way to define the audience like the V1 did unless of course there is some oversight from my side.
My Startup file is structured as follows:
The authentication is setup as the following:
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

            services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
            {
                options.Authority = $"https://login.microsoftonline.com/{tenantId}";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // In multi-tenant apps you should disable issuer validation:
                    ValidateIssuer = false,
                    // In case you want to allow only specific tenants,
                    // you can set the ValidIssuers property to a list of valid issuer ids
                    // or specify a delegate for the IssuerValidator property, e.g.
                    // IssuerValidator = (issuer, token, parameters) => {}
                    // the validator should return the issuer string
                    // if it is valid and throw an exception if not
                };
            });

And the swagger is setup as follows:
 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "Protected Api",
                });

                c.OperationFilter<SecurityRequirementsOperationFilter>();

                //IMATE - StevensW
                // Define the OAuth2.0 scheme that's in use (i.e. Implicit Flow)
                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize",
                    TokenUrl = $"https://login.microsoftonline.com/common/{tenantId}/v2.0/token",
                    Scopes = new Dictionary<string, string>
                   {
                       { "openid", "Unsure" },
                       { "profile", "Also Unsure" }
                   }
                });
            });

 app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.OAuthClientId(Configuration.GetValue<string>("AzureAd:ClientId"));
                c.OAuthAppName("Protected API");

                // c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
                // NEVER set the client secret here. It will ve exposed in the html of the swagger page if you "view source" and its not needed for OpenID Auth
                // c.OAuthClientSecret(Configuration.GetValue<string>("AzureAd:ClientId"));
            });

I am hoping to configure the swagger UI to use AAD's V2 endpoint and allow for a multi-tenant login that allows successfully authenticated API calls to be executed. Any help or direction would be greatly appreciated.

A: I ended up fixing the problem I was having. Working through this post helped me understand my mistakes.
The first mistake was my actual AAD app registration. I had not set a scope for the application under "Expose an API". Because they deprecated the resource property in V2, the way you would set the resource was to create a scope with the format api"//{application ID}/{scope_name}. After I made this change my AAD application was now correctly configured.
After that, I needed to add an additional section to my startup file:
return services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
             {
                 // This is an Azure AD v2.0 Web API
                 options.Authority += "/v2.0";

                 // The valid audiences are both the Client ID (options.Audience) and api://{ClientID}
                 options.TokenValidationParameters.ValidAudiences = new string[] { options.Audience, $"api://{options.Audience}" };

                 options.TokenValidationParameters.ValidateIssuer = false;
             });

Note: the link above provided an alternative solution to turning off the validation of the issuer if anyone is interested.
My AppSettings file was also simplified by only needing to define the Instance, TenantId, and ClientId.
Then from a swagger perspective, I just needed to add an additional scope to the security definition matching the one I created in my AAD application.
          c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
                    TokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    Scopes = new Dictionary<string, string>
                   {
                       { "openid", "Sign In Permissions" },
                       { "profile", "User Profile Permissions" },
                       { $"api://{clientId}/access_as_user", "Application API Permissions" }
                   }
                });

After these changes my application is now working as expected.

A: for v2 endpoint, update the accessTokenAcceptedVersion in Manifest of AAD from null to 2. It will work.


text:
Q: ¿Forma óptima de llamar un método No-estático de una activity desde una clase AsyncTask? No sé si mi pregunta sea adecuada pero tengo la siguiente duda:
Tengo una clase que extiende de AsyncTask y ejecuta operaciones con base de datos, en PostExecute() necesito ejecutar un método de una Activity, pero dicho método NO es estático, y no puedo acceder a el desde el contexto estático de mi AsyncTask.
Creo que hay 2 posibles soluciones:

*

*Convertir mi método a estático en la Activity.
ó

*Pasar la Activity como argumento al ejecutar la clase AsyncTask.
¿Cuál es la forma más óptima de hacerlo y por qué?


text:
Q: Laravel error . Request does not exit .why? This is the controller page. The error says

The request does not exist

I am unable to find why.
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function insert( Request $req)
    {
            $name=$req->input('task_name');

            $detail=$req->input('task_detail');

            $data=array('task_name'=>$name,'task_detail'=>$detail);

            DB::table('tasks')->insert($data);
            echo "success";
    }
}

A: Add the namespace
use App\Http\Requests\Request;


text:
Q: Why do two Ubuntu systems in the same network behave differently in DNS resolution? I have two systems, both running Ubuntu 12.04, which are within the same network (connected by hubs without routing logic). Both systems are configured quite similar, but not identical. In particular, the command route gives the identical results on both system.
Within the network a windows server is operating by a name winshared. One Linux system work resolving the IP:
> nslookup winshared
Server:     127.0.0.1
Address:    127.0.0.1#53

Name:   winshared.somepc.xx
Address: 172.16.0.110

while the other Linux system fails with
> nslookup winshared
;; connection timed out; no servers could be reached

Why do I see the difference in DNS resolution on both systems? And how to fix it?
Additional remarks:

*

*The content of /etc/resolv.conf is identical on both systems with the content:
nameserver 127.0.0.1

A: The answer to this problem is starting from the entries in /etc/resolv.conf. The content is identical, and the given IP address 127.0.0.1 refers to the system itself.
The next hint comes from the output of nslookup: It shows, the address of winshared is being resolved by a process listening on port 53. Using sudo netstat -nlp on the working  system reveals one process dnsmasq listening on this port. The other system, however, has a second process, named, listening on this port. named is a DNS server and thus probably responsible for the mess of not able to resolve a name.
As explained this service can be stopped by uninstalling bind9, after which the DNS service is stopped on the faulty system, and both systems only have a process dnsmasq running on port 53, which is a leightweight forwarding service for DNS requests.
Afterwards, the name winshared can be resolved on both systems.

A: Typically servers behave differently because they're configured differently ;)
DNS servers are either set by DHCP or configured manually in the /etc/resolv.conf file.
Static entries for certain hostnames/ip-addresses may exist in /etc/hosts.
The /etc/nsswitch.conf may instruct the resolvers to give different precendence to sources such as local files / NIS / LDAP or DNS

A: I suppose the file /etc/resolv.conf is generated by the packet resolvconf.
Are you using static or Dynamic network configuration?
Have a look at the differents files in /etc/resolvconf/
and /etc/networks/interfaces.
Or if installed, use network-manager.


text: Q: Swipedown on sidebar menu not working on iPhone using jQuery I am facing a strange problem, I am unable to swipedown the sidebar menu on my website, but if I swipe the other content of the page then it works fine, even I am able to swipeup the menu, but it does not work for swipedown.


text:
Q: Does the gamblers fallacy not apply to Bayesian probability? Bayesian probability is an alternative probability theory that uses data from past outcomes to predict future outcomes. Do they have some work-around for the gamblers fallacy or do they just ignore it?
Or is Bayesian probability literally just the gamblers fallacy by another name?

A: The predictive power of Bayesian inference only applies when the probability of an event is unknown, such as testing fairness of a possibly biased coin. It does not allow bypassing the gambler's fallacy when the probability is known or can be calculated, as is the case with most casino games.

A: In fact, a Bayesian approach is the exact opposite of the gambler's fallacy.
The gambler's fallacy supposes that if a certain event has happened more often than expected in a series of independent trials¹ - for example, a roulette wheel has been observed to mostly pick red numbers over the last day - it is likely to happen less often in the future, until it has evened out. A fallacious gambler will therefore bet on black in this instance, because a black is "due".
The Bayesian approach is that, supposing there was some initial uncertainty about the exact probability of the event, the fact that it has happened more often provides some evidence for what the actual probability is, and it will tend to revise our estimate for the probability upwards. So a Bayesian gambler will therefore bet on red, reasoning that the wheel may be slightly biased in favour of red.
This method of identifying small biases from observations of roulette tables was famously used to "break the bank" at Monte Carlo in the 19th century by Joseph Jagger.

¹ If the trials are not independent, e.g. cards dealt in blackjack, this may not be fallacious.


text:
Q: Missing Detail in Construction of Étale Fundamental Group $\DeclareMathOperator\Aut{Aut}$I am currently trying to consolidate my understanding of the étale fundamental group, and there is a small detail in the construction that I do not understand in general. While I can see why this occurs for most particular examples, my arguments are quite ad hoc and do not give me insight into the wider problem.
Given a pro-representing system $\tilde X = (X_i)_{i \in I}$ for the functor which takes lifts of a geometric point, I do not understand why we get induced maps $\Aut_X(X_j) \to \Aut_X(X_i)$. This is quite important because one possible definition of the étale fundamental group is $\pi_1(X, \overline{x}) \mathrel{:=} \varprojlim \Aut_X(X_i)$. My topological intuition tells me that there is probably some sort of Lifting Criterion-style argument here, but I cannot fill in the gaps.


text:
Q: For N-day moving average, how is N parameter called? I'm looking for a good name for the variable. Average window length? Sounds like a term for a glass cutter.

A: "Window length" is used without comment on the Wikipedia page for moving averages and it's been there for quite a while without being edited out (despite the page getting other edits), so I think that suggests that "window length" is a fine way to refer to this idea.


text:
Q: Ignore indent of itemize for figures, lstlistings etc I have a list of items where some of the items contain figures, listings, etc. How can I make these environments ignore the additional indent in an itemize environment?
My code looks like this:
\begin{itemize}
    \item
     Bla bla
     \begin{figure}
        % indent should be ignored here!
        ...
     \end{figure}
    \item
     More bla bla
     \begin{lstlisting}
        // indent should be ignored here!
        ...
     \end{lstlisting}
\end{itemize}

A: Two options:

*

*Interrupt the itemize for the image and the listing.

*Use an \hbox for the image and the listing (this requires previously boxing the listing):
The code showing both options:
\documentclass{article}
\usepackage{listings}
\usepackage{graphicx}

\newsavebox\mybox

\begin{document}

\begin{lrbox}{\mybox}
\begin{lstlisting}
// indent is ignored here!
code test text
\end{lstlisting}
\end{lrbox}

Some test text for the example and some more words test text for the example and some more words test text for the example and some more words test text for the example and some more words test text for the example and some more words
\begin{itemize}
    \item
     Bla bla
\end{itemize}
\includegraphics[width=\textwidth,height=2cm]{example-image-a}
\begin{itemize}
    \item
     More bla bla
\end{itemize}
\begin{lstlisting}
// indent is ignored here!
code test text
\end{lstlisting}
Some test text for the example and some more words test text for the example and some more words test text for the example and some more words test text for the example and some more words test text for the example and some more words
\begin{itemize}
    \item
     Bla bla\par\medskip

    \hbox{\includegraphics[width=\textwidth,height=2cm]{example-image-a}}
    \item
     More bla bla\par\medskip

     \hbox{\usebox\mybox}
\end{itemize}

\end{document}

Of course, it's best not to use the float figure for your image, otherwise the figure might float away from where you want it to appear (inside the itemize at a precise location). In case you need some caption for the figure, use \captionof from the capt-of or caption packages.


text:
Q: Dispatch from action to reducer I'm having a bit of struggle to get a few things with Redux. I got the following code and what I'm trying to do is to push things to the reducer, can I dispatch here and how do I do that? Im used to Vue and Vuex and there I can use commit() (as seen in the example below)
export function subscribeToResponsiveEvents() {
  _.forOwn(breakpoints, (mediaQuery, key) => {
    const mql = window.matchMedia(mediaQuery)

    const callback = ({ matches }) => {
      // how I do it in Vue
      // commit('set_responsive_data', { path: ['breakpoints', key], value: matches })

      // I would like to dispatch this to the reducer
    }

    mql.addListener(callback)
    callback(mql)
  })

  window.addEventListener('orientationchange', e => {
    // how I do it in Vue
    // commit('set_responsive_data', { path: 'screenOrientation', value: window.innerHeight > window.innerWidth ? 'landscape' : 'portrait' })

    // I would like to dispatch this to the reducer
  })
}

I know I can do like this, but as I got a loop here and don't want to return, just call the reducer to change the state I'm a bit confused on how.
export function somefunction() {
  return { type: SET_RESPONSIVE_DATA, payload }
}


text:
Q: How to share a variable among main and subclass in python? (Not a profi programmer here, mine is probably a dumb question)
I've a database stored in several ascii files (one file per table) within the same directory.
I'm used to read all files and load each of them in Pandas DataFrame. Eventually I bundle all the dataframes in a single dict variable.
Reading the files from disk takes about 1s.
The DB has several sections describing different groups of objects, each one with their configuration parameters:
DB
|
+-TC
|  +-PAR
+-TM
|  +-PAR
+-SEQ
   +-PAR

I want to define a module having classes and methods to load, browse and manipulate the data and I'm wondering which is the best approach with the constrain to read the db from disc only once.
Option 1 [preferred]: have a class/subclass structure mimic the DB organisation.
The desired usage would be something like:
db = DB()
dbdata= db.load(dir)
print( db.version())
tcName = DB.TC('tcName')
print(tcName.description)
tcName.PAR('param1').setvalue(value1)

module:
class DB:
   def __init__(self):

   def load(self, dbDir):
      self.db = read_all_db_files_from_dbDir
      return self.db

   def version(self):

   class TC:
      def __init__(self, tcName):
         self.tcName = tcName
      def description(self)
      def parametes(self)

      class PAR:
         def __init__(self, tcParName):
            self.parName = tcParName
         def description(self)
         def setvalue(self, value)
[...]
   class SEQ:
      [...definitions similar to TC...]

      class PAR
         def __init__(self, seqParName):
            self.parName = seqParName
         def description(self)
         def setvalue(self, value)

Option 2: flat class structure.
class DB:
   def load(self, dbDir):
      self.db = read_all_db_files_from_dbDir
      return self.db

   def version(self):

class TC:
   def __init__(self, tcName, dbData):
      self.tcName = tcName
      self.dbData = dbData

   def description(self)
   def parametes(self)

class TCPAR:
   def __init__(self, tcParName, dbData):
      self.tcParName = tcParName
      self.dbData = dbData

   def description(self)
   def setvalue(self, value)

[... and so on also for the SEQ and SEQPAR classes]

In this case I suppose I need to pass the db variable when calling each method:
db = DB()
dbData = db.load(dir)
tcName = TC('tcName',dbData)
print(tcName.description)
param1 = TCPAR('param1',dbData)
param1.setvalue(value1)

Option 1 question: how can I pass the variable self.db to the subclasses without reloading the db every time I use a subclass/method?
Option 2 question: any other way to share the variable dbData among the classes?

A: You coud make the variables global with the global tag:
global var_global
var_global = 'test'

It would look something like this in a class with subclasses:
class test:
    def __init__(self, var):
        global var_global
        var_global = var

    class sub:
        def __init__(self):
            print('Output:', var_global)

tst = test('test')
tst.sub()

Output:
Output: test

Process finished with exit code 0

I think there are much better solutions than this one but i think it fits your idea. :)


text:
Q: make: Nothing to be done for first.pdf I'm a newbie to linux and make, I've written a makefile to automatically compile the .tex file to .pdf. But when i call make, it said "Nothing to be done for 'first.pdf'", here's my makefile:
    TEXFILE= first.tex
    PDF= $(TEXFILE:.tex=.pdf)

    .tex.pdf:
            pdflatex $<
    $(PDF):$(TEXFILE)
    view:
            evince $(PDF)
    clean:
            @rm -f \
            $(TEXFILE:.tex=.log) \
            $(TEXFILE:.tex=.aux) \
            $(TEXFILE:.tex=.toc)

could any one tell me what's wrong with it?

A: Probably, one of the suffixes is not known.
You can add a .SUFFIXES directive:
TEXFILE=first.tex
PDF=$(TEXFILE:.tex=.pdf)

.SUFFIXES: .tex .pdf
# etc.

However, better than using outdated suffix rules, you should use pattern rules:
%.pdf : %.tex
        pdflatex $<

A: This issue exists if one splits writing into multiple .tex files.
make can be successful, but unless you modify the first.tex you will be getting:

"Nothing to be done for 'first.pdf'

Makefile for multiple inputs changes
# ...

# include all text files from current directory
SOURCES := $(shell find . -name '*.tex')
# include files figs directory ...
SOURCES += $(shell find ./figs)

# ...

# add sources here will cause recompilation when something is modified
$(PDF):$(TEXFILE) $(SOURCES)

# some phony targets
.PHONY: all pdf view clean


text:
Q: При слиянии ветки не обязательно указывать no-ff если оно нужно? Во всяких интернетах (в т.ч. на английском SO) пестрят картинки, что  если мы хотим сохранить историю коммитов ветки, которую вливаем и не переводить указатель чисто вперёд, то нужно ставить --no-ff.
Типичные картинки

Однако тут говорится о том, что если в ветке уже были коммиты, то --no-ff в любом случае будет происходить

Теперь изменения бранча testbranch идут в отдельной ветке даже без указания no fast-forward.

Вопрос вполне логичный и простой:
В итоге, если я нахожусь в какой-то ветке и нужно слить другую и чтобы коммиты сделанные в другой ветке согласно истории принадлежали именно второй, то если я уже делал коммиты в первой, то указывать --no-ff не обязательно?
А если я нахожусь на ветке test1 сливаю себе dev, чтобы обновить данные, делаю ещё небольшую правку, коммит, пуш, а потом перехожу на dev и вливаю себе эту ветку test1 то тоже уже не надо указывать флаг --no-ff?
Мне важна история всегда. Важно чтобы коммиты отображались именно на тех ветках, где были сделаны, а не шли в одной ветке, как прямая дорога.

A: К сожалению ваша ссылка «тут» недоступна из моего региона, а ваше цитат не полная.
git может проводить слияние тремя способами:

*

*--ff — (по умолчанию) попытаться выполнить перемотку (fast forward), если не удалось, то создать коммит слияния.

*--no-ff — всегда создавать коммит слияния.

*--ff-only — попытаться выполнить перемотку, если не удалось, завершить ошибкой.

Подробности: https://git-scm.com/docs/git-merge#Documentation/git-merge.txt---ff
Перемотка может быть выполнена только если ветка, в которую идёт слияние стоит на том коммите, который есть во вливаемой ветке (как правило это точка ветвления, но не обязательно).
Если после точки ветвления в обеих ветках есть свои коммиты (отсутствующие во второй), то будет создан коммит слияния. В этом случае совершенно не обязательно указывать параметр --no-ff. Но и мешать он не будет.

А если я нахожусь на ветке test1 сливаю себе dev, чтобы обновить данные, делаю ещё небольшую правку, коммит, пуш, а потом перехожу на dev и вливаю себе эту ветку test1 то тоже уже не надо указывать флаг --no-ff?

Если после вливание dev в test1 в ветке dev не было новых коммитов, то без указания --no-ff будет выполнена перемотка. Потому что коммит ветки dev находится в ветке test1, вы его сами влили. А так как вы ранее вливали dev в test1, то в истории коммиты из test1 будут отображаться как будто они были сделаны в основной ветке, а коммиты из dev — как из ветки разработки. Тут настоятельно рекомендуется делать --no-ff.
Для того, чтоб не задумываться ставить --no-ff или нет, лучше всегда ставить. А чтоб не забывать, можно указать в настройках git, что по умолчанию нужно использовать --no-ff, а не --ff. Делается это командой git config --add merge.ff false
Подробности: https://git-scm.com/docs/git-config#Documentation/git-config.txt-mergeff


text:
Q: Assign children to object in casperjs I am trying to assign to nested object (in casperjs):
    var yearz = [];
    var yearz2 = $('#form_model optgroup');
    yearz2.each(function() {
        var theyear = $(this).attr('label');
        var theobj = {
            Year: theyear,
            Thing: [{}]
        };

        for (var i = 0; i < $(this).children().length; i++){
            theobj["Thing"].push({Name: $(this).children()[i].attr("value")});
        }

        yearz.push(theobj);
    });

this.echo(yearz) returnsnull
Can you see the problem?
Best Regards
EDIT
var yearz = [];
var yearz2 = $('#form_model optgroup');
yearz2.each(function() {
    var theyear = $(this).attr('label');
    var lengthch = $(this).children().length;
    var thisch = $(this).children();
    var theobj = [];
    var alls = [];

    for (var i = 0; i < lengthch; i++){
        alls.push(thisch.attr("value"));
    }

    theobj = {
        Year: theyear.trim(),
        Thing: alls
    };

    yearz.push(theobj);
});

This pushes same element in alls array. But there are two of them. How can i push both of them, not the same twice?
This does not work:
for (var i = 0; i < lengthch; i++){
    alls.push(thisch[i].attr("value")); //Note [i] here.
}

A: alls.push(thisch[i].attr("value")); //Note [i] here.

That does not work because [] returns a DOM, not a jQuery object and DOM does not have .attr()
so it should be
thisch.eq(i).val()

or
thisch[i].value

You can also just use each() or map() instead of the for loop.
var values = thisch.map( function() { return this.value; } ).get();

A: A shot in the dark, because context is unknown, but try:
var yearz = [];
var yearz2 = $('#form_model optgroup');
yearz2.each(function(i, item) {
    var theyear = $(item).attr('label');
    var theobj = {
        Year: theyear,
        Thing: [{}]
    };

    for (var i = 0; i < $(item).children().length; i++){
        theobj["Thing"].push({Name: $(item).children()[i].attr("value")});
    }

    yearz.push(theobj);
});


text:
Q: Android Studio com problema na MainActivity Eu comecei a utilizar o Android Studio hoje, e ao criar o Projeto do Aplicativo me deparei com um problema: Eu consigo criar, porém a classe MainActivity fica cheia de erros sendo que eu não mudei nada do aplicativo.

É isso, por acaso vocês já se depararam com esse problema ?
Antes do Android Studio eu usava o Eclipse.
Obrigado!

A: Para resolver isto, faça:

*

*Clean project localizado em Build

*Rebuild project localizado em Build, após o término do Clean Project.

Lembre-se que a classe R é criada automaticamente após o Build do seu projeto, ou seja, se algum Build seu terminou com erro, essa classe não existirá mais e você terá que dar um Build nele novamente.


text:
Q: Drupal function to return content types associated with a term I am looking for a function which will list out the content types which a specific term (tid) can be applied to.
There doesn't seem to be a direct way to do it from http://api.drupal.org/api/search/6/taxonomy.
Any ideas?

A: No, there doesn't seem to be one. You should be able to use this query, though.
$c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);

Source: http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_form_alter/6
Or a simplified version of that, if you for example only need the vid.


text:
Q: In which file Tomcat Java Memory options are saved I want to change memory configuration of Tomcat. I know it can be done at
Start > Apache Tomcat > Configure Tomcat > Java Tab] as can be seen below

and specifying options like
-Xms512m
-Xmx1024m
-XX:MaxPermSize=512m
-XX:MaxHeapFreeRatio=70

there.
However this program group is created if I install Tomcat from an executable. I have installed Tomcat by simply extracting the zip which does not create Program group. So now where can I specify this information

A: With regards to the question of where Tomcat's memory options are saved when using the service version, on my machine at least they can be found in the Windows Registry at:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Apache Software Foundation\Procrun 2.0\Tomcat-6\Parameters\Java

Initial memory and Maximum memory are recorded against the JvmMs and JvmMx values, while the options text is recorded against the Options value.
The Tomcat-6 portion of the address on mine is, I believe, based on the identifier I gave to the service (i.e. within the service manager Tomcat is named "Apache Tomcat 6.0 Tomcat-6"), and you may not need to go through Wow6432Node depending on whether you're using 32-bit or 64-bit Tomcat.
I'm assuming here that they haven't made any dramatic changes in where this information is stored in versions of Tomcat more recent than Tomcat 6.

A: Ohkay while digging inside Tomcat I found some information in one of its txt files (point 3.4) and online:
Apart from CATALINA_HOME (which is set to apache-tomcat-x.x.x directory, for e.g. C:\Program Files\Apache Software Foundation\apache-tomcat-7.0.41) and CATALINA_BASE (optional, defaults to CATALINA_HOME), all environment variables can
be specified in the setenv script. The script is placed either into
CATALINA_BASE/bin or into CATALINA_HOME/bin directory and is named
setenv.bat (on Windows) or setenv.sh (on *nix). The file has to be
readable.
By default the setenv script file is absent. If the script file is present
both in CATALINA_BASE and in CATALINA_HOME, the one in CATALINA_BASE is
preferred.
For example, to configure the JRE_HOME and CATALINA_PID variables you can
create the following script file:
On Windows, %CATALINA_BASE%\bin\setenv.bat:
set "JRE_HOME=%ProgramFiles%\Java\jre6"
exit /b 0

On *nix, $CATALINA_BASE/bin/setenv.sh:
JRE_HOME=/usr/java/latest
CATALINA_PID="$CATALINA_BASE/tomcat.pid"

To set Java options for memory allocation for web app, add something like following (as per memory requirements of your application) to the same file
set JAVA_OPTS="-Xms256m -Xmx512m"

The CATALINA_HOME and CATALINA_BASE variables cannot be configured in the
setenv script, because they are used to locate that file.
All the environment variables described here and the setenv script are
used only if you use the standard scripts to launch Tomcat. For example, if
you have installed Tomcat as a service on Windows, the service wrapper
launches Java directly and does not use the script files.


text:
Q: Receive SMS not working (java android) I do not understand, when I receive an sms nothing appears.
public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    private static final String RECEIVE_MSG = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(RECEIVE_MSG)){
            Bundle extra = intent.getExtras();
            if(extra!= null){
                Object[] pdus = (Object[])extra.get("pdus");
                final SmsMessage[] messages = new SmsMessage[pdus.length];
                for(int i = 0; i<pdus.length; i++){
                    messages[i]= SmsMessage.createFromPdu((byte[])pdus[i]);
                }
                if (messages.length>-1) {
                    for (int i = 0; i<messages.length; i++) {
                        final String messageBody = messages[i].getMessageBody();
                        final String phoneNumber = messages[i].getDisplayOriginatingAddress();
                        Toast.makeText(context,"Expéditeur:" + phoneNumber, Toast.LENGTH_LONG).show();
                        Toast.makeText(context,"Message : " + messageBody, Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

    }
}

A: Are you registered the reicever in manifest or Activity?
<receiver android:name=".broadcast.SmsBroadcastReceiver" >
        <intent-filter android:priority="5000">
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>

</receiver>

or
 IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
 filter.setPriority(9999);
 registerReceiver(new SmsBroadcastReceiver(),filter);


text:
Q: web app on mobile, pages have different dimensions There is a behaviour I don't understand on my web app on Chrome for mobile, on my Nexus 4.
Let's say I want to open a an html ad, contained in the page view.html. The ad is 250px * 250px.
1 - If I open directly view.html in the browser: window.innerWidth = 284 and window.innerHeight = 511. The dimension of the ad looks good.
2 - Index.html is the page that opens view.html in an iframe. If I open index.html, window.innerWidth = 980 and window.innerHeight = 1305.
The iframe loads view.html but in this situation, the iframe looks too small.
I don't understand why the two pages have different dimensions ?
Thank you for your help !

A: As @jcubic said in comment, all I needed was to add:
<meta name="viewport" content="width=device-width" />

in the head of index.html
Thank you


text:
Q: Python expand user doesn't work over su on Solaris and AIX My script needs to execute as root, and for some tasks as someuser, I also need to get someuser $HOME path, and thats where comes the problem.
For that job (find user home) I'm using os.path.expanduser.
As mentioned the script needs to change his user with su and run the code to get user home:
test_home.py
from os.path import expanduser

def user_home():
    home = expanduser("~")
    return home

print user_home()

The main script calls the test_home.py with su:
# su someuser -c /tmp/test_home.py
/home/someuser

Perfectly fine. But for AIX and Solaris the script doesn't get someuser $HOME, instead, it gets the root $HOME.
AIX: Executing as root
su someuser -c /tmp/test_home.py
/

Solaris:
 Executing as root
su someuser -c /tmp/test_home.py
shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
/root

I've tested this code on several distros:

*

*RedHat

*SLES

*HP-UX

*AIX

*Solaris

*Debian

The problem it's only on AIX and Solaris. Does anyone knows why?
UPDATE
Using login with with - or -l works, but I can't use su - on my script.  Any thoughts on how to overcome this?
I was trying to not use a shell approach like the above but I'm getting out of options
cat /etc/passwd | grep someuser | cut -d: -f 6

A: I faced same issue, after using sudo or su , It was giving root home directory, I fixed with below way:
akjha-mn2:~ akjha$ python test1
/Users/akjha
akjha-mn2:~ akjha$ sudo python test1
Password:
/Users/akjha
akjha-mn2:~ akjha$ cat test1
#!/bin/env python
import os
user1=os.getlogin()
home=os.path.expanduser("~{0}".format(user1))
print home
akjha-mn2:~ akjha$

A: import socket
import os
import time
import sys
import pwd

###############################################################################
# Set uid and gid
###############################################################################

def set_uid_gid( uid, gid ):
    os.setgid(gid)
    os.setuid(uid)
###############################################################################
# Set effective uid and gid
###############################################################################
def set_effective_uid_gid( uid, gid ):
    os.setegid(gid)
    os.seteuid(uid)

###############################################################################
# Get uid and gid
###############################################################################

def get_uid_gid():
    uid = os.getuid()
    gid = os.getgid()
    return( uid, gid )
###############################################################################
def get_euid_egid():
    uid = os.geteuid()
    gid = os.getegid()
    return( uid, gid )

###############################################################################
def get_uid_gid_for_user( username):
    pwd_obj = pwd.getpwnam(username)
    uid = pwd_obj.pw_uid
    gid = pwd_obj.pw_gid
    return( uid, gid)

#Switch to <SOMEUSER>
def switch_user():
    (original_uid , original_gid) = get_uid_gid()
    (analyst_uid , analyst_gid) = get_uid_gid_for_user("<SOMEUSER>")
    set_effective_uid_gid(analyst_uid ,analyst_gid)
    os.system('python run_this_script,py')
    #Switch back to root/original
    set_uid_gid(original_uid , original_gid)


text:
Q: Downloading Google CLient Library in Mac Using Terminal?     **//Ya I got it..**

The following steps i follow to get Google APi Objective CLient Library
Step1- Install Command Line Tools for Xcode and we can get it from Xcode / Behaviors / Edit behaviors... / Downloads / Command Line Tools / Install
Step2- In Terminal type... svn checkout http://google-api-objectivec-client.googlecode.com/svn/trunk/ google-api-objectivec-client-read-only

A: Click on magnifying glass on top-right of Mac (or command-space for shortcut). Type "terminal". Change your directory to where you want to download the app using command cd. Type this command svn checkout http://google-api-objectivec-client.googlecode.com/svn/trunk/ google-api-objectivec-client-read-only


text:
Q: Image ratio using in image drawing react-native I have an app, where I take a pic and draw it to the pdf file.
I have been trying to get them in right ratio. If I take all picture horizontal, it would be fine. If I take all pictures vertical, it would be fine. Problem is, when I take both vertical and horizontal, last picture's ratio applied to all pictures.
I save image ratio to AsyncStorage, where I get it in other component.
Questions is: How can I keep original ratios when I take pictures both ways?
Camera component -> takePicture function:
takePicture = async() => {

    if (this.camera) {
        const options = { quality: 0.5, base64: true , fixOrientation: true};
        const data = await this.camera.takePictureAsync(options);
        console.log(data.uri);

        Image.getSize(data.uri, (width, height) => { // Get image height and width
            let imageWidth = width;
            let imageHeight = height;

            let stringImageWidth = '' + imageWidth; // Convert to string for AsyncStorage saving
            let stringImageHeight = '' + imageHeight;

            const horizontalRatioCalc = () => { // return ratio for own variable
                return (imageWidth/imageHeight);
              };

            const verticalRatioCalc = () => {
                return (imageWidth/imageHeight);
            };

            horizontalImageRatio = horizontalRatioCalc();
            verticalImageRatio = verticalRatioCalc();

            stringHorizontalImageRatio = '' + horizontalImageRatio;
            stringVerticalImageRatio = '' + verticalImageRatio;

            console.log(`Size of the picture ${imageWidth}x${imageHeight}`);

            horizontalRatio = async () => {
                if (imageHeight>imageWidth) {

                    verticalRatioCalc();

                    try {
                        AsyncStorage.setItem("imageVerticalRatio", stringVerticalImageRatio),
                        AsyncStorage.setItem("asyncimageWidth", stringImageWidth),
                        AsyncStorage.setItem("asyncimageHeight", stringImageHeight),

                        console.log(`Vertical ratio saved! It's ${stringVerticalImageRatio}`),
                        console.log(`Image Width saved! It's ${stringImageWidth}`),
                        console.log(`Image height saved! It's ${stringImageHeight}`)

                    }   catch (e) {
                        console.log(`AsyncStorage saving of image vertical ratio cannot be done.`)
                    }
                }if (imageHeight<imageWidth) {

                    horizontalRatioCalc();

                    try {
                        AsyncStorage.setItem("imageHorizontalRatio", stringHorizontalImageRatio),
                        AsyncStorage.setItem("asyncimageWidth", stringImageWidth),
                        AsyncStorage.setItem("asyncimageHeight", stringImageHeight),

                        console.log(`Horizontal ratio saved! It's ${stringHorizontalImageRatio}`),
                        console.log(`Image Width saved! It's ${stringImageWidth}`),
                        console.log(`Image height saved! It's ${stringImageHeight}`)

                    }   catch (e) {
                        console.log(`AsyncStorage saving of image vertical ratio cannot be done.`)
                    }
                }
            }
            horizontalRatio();

            }, (error) => {
            console.error(`Cannot size of the image: ${error.message}`);

        });
        back(data.uri)
        //CameraRoll.saveToCameraRoll(data.uri).then((data) => {
        //    console.log(data)
            //back(data);

        //}).catch((error) => {
            //console.log(error)
      //})
    }

CreatePdf component -> PDF drawing function:
readData = async () => {
        try {
          kuvakorkeus = await AsyncStorage.getItem('asyncimageHeight')
          kuvaleveys = await AsyncStorage.getItem('asyncimageWidth')

          vertikaaliratio = await AsyncStorage.getItem('imageVerticalRatio')
          horisontaaliratio = await AsyncStorage.getItem('imageHorizontalRatio')

          if (kuvakorkeus !== null) {
            return kuvakorkeus;
            return kuvaleveys;
            return vertikaaliratio;
            return horisontaaliratio;
          }
        } catch (e) {
          alert('Failed to fetch the data from storage')
        }
      }
      readData ();

      kuvanpiirto = () => {

                    pdfKuvaKorkeus = 100;

                    if(kuvakorkeus>kuvaleveys) { // VERTICAL / PYSTYKUVA
                        page.drawImage(arr[i].path.substring(7),'jpg',{
                            x: imgX,
                            y: imgY,
                            width: pdfKuvaKorkeus*vertikaaliratio,
                            height: pdfKuvaKorkeus,
                        })
                    }
                    if(kuvakorkeus<kuvaleveys) { // Horizontal / Vaakakuva
                        page.drawImage(arr[i].path.substring(7),'jpg',{
                            x: imgX,
                            y: imgY,
                            width: pdfKuvaKorkeus*horisontaaliratio,
                            height: pdfKuvaKorkeus,
                        })
                    }
                }
                kuvanpiirto();


text:
Q: global algebraic functions $\Gamma(T^{*}M)$ on the cotangent bundle of moduli space Let $X\colon$ smooth projective curve,
$\mathcal{M}\colon $ moduli space of semistable higgs bundle of rank $r$ and with fixed determinat $\xi$, and
$H\colon \mathcal{M}\rightarrow W=\oplus_{i=2}^{r} H^{0}(X,K_{X}^{\otimes i})$ be the Hitchin map.
$T^{*}M\subseteq \mathcal{M}$ cotangent bundle of stable vector bundle as an open subscheme.
$h$ denotes the restriction of $H$ to $T^{*}M$.
I'm reaing the paper of Indranil Biswas, Tomas L. Gomez, V. Munoz and want to show the following Lemma,

the natural map $\Gamma(W)\rightarrow \Gamma(T^{*}M)$ induced by $h$ is an isomorphism.

I already know that $\Gamma(W)\rightarrow \Gamma(\mathcal{M})$ is an isomorphism.
Let $\eta\in W$ be the generic point. Then, $H^{-1}(\eta)$ is smooth, and
$\operatorname{codim}(h^{-1}(\eta),H^{-1}(\eta))\geq 2$.
From this, the paper concludes that the Lemma holds.
But I don't know how to deduce and complete the proof. I'm stuck.
Thanks in advance.