Thus far the Capital City Crushers have had an exciting and undefeated season! Upcoming events include: Fresh Meat bout: see the Crushers' Fresh Meat players bout against the Little Apple Roller Bombers in Manhattan, KS on May 31st from 7:30 pm - 9:30 pm. 721 Levee Dr, Manhattan, KS 66502.
Page 1 of 2 - B&D crusher rolls - posted in Machinery: I have had it with the steel rolls in our haybine that were supposed to make hay dry quicker than stone rolls.
Throughout the history, people have devised a wide variety of ingeniously hideous methods of torture as a form of punishment for crimes, or simply to extract information.


text:
Sophie Branson debuted at the Tonhalle Zürich
Our young violin student Sophie Branson (class of Liana Tretiakova) performed with the Zurich Symphony Orchestra at two Christmas-Gala concerts at the grand hall of the Tonhalle Zürich on December 21st – for the first time in the school history.
Every young musician in Switzerland dreams about performing at the Tonhalle Zürich – one of the most beautiful concert venues in the world, where such prominent musicians as David Oistrakh, Itzhak Perlman, Maxim Vengerov, Anne-Sophie Mutter, Joshua Bell, Daniel Hope and many-many others have played (the hall was built in 1895 and inaugurated by Johannes Brahms). This Winter Solstice day, on December 21st – which also happened to be the first day of winter – Sophie's dream has come true: she played on the legendary stage for the first time in her life.
It was a truly remarkable performance! She performed 'Mozart Concerto in G-Major' with the Zurich Symphony Orchestra under the baton of Heiko Mathias Förster in the grand hall of the Tonhalle Zürich to the audience of almost 1'500 people twice, and both concerts were sold out. Sophie was at her absolute best and she literally stole the show: despite being the youngest performer, she was given the most of the bravos and was called back to the stage six (!) times after each concert. Bravo to Sophie and bravo to her teacher Liana! The debut was phenomenal!!!
The two Christmas-Gala concerts were dedicated to the greatest composer of all times – the legendary Wolfgang Amadeus Mozart – and his father Leopold Mozart, who was also a prominent composer and an outstanding violinist. Claire Huangci (piano, 32 years old), Polina Tarasenko (trombone, 21 year old) and Sophie Branson (violin, 16 years old) performed four compositions written by the son and two written by the father. The first concert started at 14:00 and the second just four hours later. Sophie's performance was impeccable both times.
Apart from being the debut for Sophie, it was also a debut for the Zakhar Bron School of Music: in the 13-year history of the school, this was the first time when our student was honoured to play at the fine Tonhalle Zürich. We are more than happy about how it went, and from the bottom of our hearts we wish Sophie further achievements in her promising musical career!
Photo credit: Dr. Med. S. Aschkenasy (1) & Evgenia Pronina (2, 3, 4, 5)
Our main sponsor - since 2013

redpajama_set_name: RedPajamaCommonCrawl


It is no secret that law firms hold sensitive client data, including attorney-client privileged information. Moreover, law firms often have weak cyber defenses. For instance, in 2015, Citigroup issued an internal report warning that "digital security at many law firms, despite improvements, generally remains below the standards for other industries." As a result, firms are often among of the most vulnerable targets to cyber-attacks because they are often unguarded treasure troves of valuable electronic data.
Despite this reality, law firms have no regulatory body governing the security of their privileged information. Moreover, many clients are not pushing their law firms to protect their data. For instance, Altman Weil's 2016 Chief Legal Officer Survey found that two-thirds of the general counsels surveyed admitted that they do not require their top 10 firms to comply with specific data security measures. Only 15.9 percent of those general counsels surveyed imposed security measures on all 10 of their most relied upon firms.
However, these trends may change as law firms are attacked more frequently, and reputational fear becomes a real issue. For instance, this year the Panamanian law firm of Mossack Fonseca suffered a cataclysmic data breach. According to current estimates, this breach involved over 11.5 million attorney-client privileged documents of more than 214,488 offshore entities, and this breach incident has even served as the genesis of a dedicated website.
In sum, Section 500.11 requires a bank or financial institution to have a Third-Party Information Security Policy which addresses the identification of all third-party vendors, their cyber security practices, and any related cyber risk posed by these third-party vendors.
Section 500.11 will also require third-party vendor firms, by contract, to have use technical safeguards such as encryption and multi-factor authentication.
Most striking, firms must also guarantee that "the service or product provided to the Covered Entity is free of viruses, trap doors, time bombs and other mechanisms that would impair the security of the Covered Entity's Information Systems or Nonpublic Information." In other words, New York law firms doing work with New banks and financial services could be required to certify in their retainer agreements that their own networks are free of malicious software.
For a while, banking and financial institutions have been industry leaders in cyber security. Now, they may be responsible for compelling the legal industry to get up to speed.
To gain more insights into critical cyber security best practices to protect privileged information, check out our white paper about threats to client confidentiality.


text:
Considering Multiple Futures: Scenario Planning to Address Uncertainty in Natural Resource Conservation
Erika L. Rowland, Holly Hartmann
The publication, Considering Multiple Futures: Scenario Planning to Address Uncertainty in Natural Resource Conservation, presents scenario planning as an approach to help natural resource managers accommodate the uncertainty involved with combined threats to habitats and wildlife, including climate change, habitat fragmentation, land use, and invasive species. The publication presents the core elements of scenario planning, examines how scenario planning differs from other decision-support frameworks, identifies situations in which scenario planning could be used, explores the diversity of implementation options and approaches available to managers, and provides suggestions and additional resources for managers looking to embark on their own scenario planning effort. The report also includes 12 case studies representing a range of climate change-related scenario planning approaches for natural resource and conservation issues across the United States.
Molly Cross U.S. Fish and Wildlife Service (USFWS)
The U.S. Department of the Interior protects and manages the Nation's natural resources and cultural heritage; provides scientific and other information about those resources; and honors its trust responsibilities or special commitments to American Indians, Alaska Natives, and affiliated Island Communities. The Interior heads eight technical bureaus: Bureau of Indian Affairs, Bureau of Land Management, Bureau of Reclamation, Minerals Management Service, National Park Service, Office of Surface Mining, Reclamation and Enforcement, U.S. Fish and Wildlife Service, and U.S.
The Wildlife Conservation Society, founded in 1895, has the clear mission to save wildlife and wild places across the globe. Our story began in the early 1900's when we successfully helped the American bison recover on the Western Plains.
Federal Resource
Conduct scenario planning exercise


Jeth closed his eyes. The pressure around his chest strengthened again, cutting off his ability to breathe. Avalon had been wounded. She was in danger. All of them were.
Jeth looked at her, hoping that some brilliant idea was sprouting in her genius brain.
"Where did you get these charts?" said Milton, voicing the question before Jeth could.
After a moment Jeth nodded, intuitively understanding that she hadn't wanted to tell him. She wanted to explore the data alone for the same reasons he would've wanted to—the desire to experience this hidden piece of their parents' forgotten lives without having to share. No wonder she'd been spending those long hours in her cabin.
But what else was on the crystal? Why had their mother hidden it? With an effort, Jeth forced the questions away. There would be time for that later—he prayed.
"Okay," said Lizzie. "I'll go get the data crystal. Be right back." She turned and left the bridge.
Vince nodded as he scooped up Cora. Then the two of them followed Milton off the bridge.


While Cheryl Cole is axing the celebrity member of her management team, Mariah Carey is bringing one in, with the news that Jermaine Dupri will help advise the singer moving forward. The two are former studio collaborators and long-time friends.
Confirming Dupri would now be part of her management team, Carey told reporters: "We have a bond that surpasses music. I am super excited about our merger because we have so many innovative ideas that I know will come to fruition".
Meanwhile celeb producer and So So Def chief Dupri said: "A multi-talented artist of Mariah's calibre should be doing everything imaginable. I'm sure others have said this but not the way I intend to do it. For me, it's about the execution".


text:
Updated 18 September, 2018 - 13:50 dhwty
Asceticism Across the Faiths: Many People in the Major World Religions Have Done it
Asceticism is a way of life marked by the voluntary abstinence from worldly pleasures. This way of life is most often associated with religion and spirituality, and its practitioners usually aim to achieve certain spiritual goals. Indeed, this lifestyle is observed (to some extent) by the adherents of various major world religions, including Hinduism, Buddhism, Christianity, and Islam. Nevertheless, there are also examples of asceticism being practiced for non-religious purposes, as seen, for instance, in certain philosophical traditions.
Basawan. 'Jain Ascetic Walking Along a Riverbank.' ca.1600. Cleveland Museum of Art. ( Public Domain )
Ascetic Athletes
The roots of the term 'asceticism' is found in the Greek word 'askēsis', which may be translated to mean 'practice', 'training', 'exercise', or more specifically, 'athletic discipline'. This is a reference to the regiment that ancient Greek athletes would follow whilst preparing for physical contests. By abstaining from various physical pleasures, and by subjecting their bodies to difficult physical tests, these athletes were able to achieve the highest possible degree of physical fitness. It may be said that many professional athletes today also follow in the footsteps of their ancient Greek counterparts in this ascetic practice.
Monks, Hermits and Ascetics: The Little-Known History of Women in Desert Asceticism
Siddhartha Gautama: How The Father of Buddhism Walked From Suffering to Enlightenment
Wealth and Religion Tied through Time: Was Ancient Religious Morality Spurred by Affluence?
Discobolus. Marble, Roman copy after a bronze original of the 5th century BC. From the Villa Adriana near Tivoli, Italy. (Valerio Perticon/ CC BY SA 3.0 )
Christian Asceticism
This Greek concept later became a feature of early Christianity , as evident in the New Testament. The idea of asceticism was first used by Paul in his second letter to Timothy (2 Timothy 4:7), in which he famously compares keeping the Christian faith to both a fight and a race, clear references to the ancient Greek association of asceticism with athletics. The concept of asceticism continued to develop as time went by, and it became an important feature in Christian monasticism. Each monastic order observed asceticism to some degree, though some more than others. The Carthusians and Cistercians, for instance, are two Catholic monastic orders notable for their strict adherence of the ascetic way of life.
'St Hugh of Grenoble in the Carthusian Refectory' (1630-1635) by Francisco de Zurbarán. ( Public Domain )
Hindu and Buddhist Ascetics
Asceticism is not a unique Christian practice, as it is found also in various other world religions. For example, in Hinduism, holy men called sadhus are known for their extreme ascetic practices. These practices vary from one sect to another, and even from one sadhu to another. Hindu sadhus not only renounce worldly pleasures, but even subject their bodies to extreme mortification. One ascetic, for example, stared at the Sun until he went blind, whilst another held his hands above his head until they withered. It goes without saying that few are able to achieve such acts of extreme asceticism.
A sadhu by the Ghats on the Ganges, Varanasi. ( CC BY 2.0 )
The Buddha also practiced extreme asceticism prior to achieving enlightenment. He eventually realized that this was not the way to Enlightenment, thus leading to his discovery of the Middle Way, a path that lies between the two extremes of self-denial and self-indulgence. Nevertheless, some level of asceticism was maintained in Buddhism.
A wall painting in a Laotian temple, depicting the Bodhisattva Gautama (Buddha-to-be) undertaking extreme ascetic practices before his enlightenment. A god is overseeing his striving and providing some spiritual protection. The five monks in the background are his future 'five first disciples', after Buddha attained Full Enlightenment. ( Public Domain )
Like the Christian monastic orders, asceticism in Buddhism involved the renunciation of the world. The extent of this asceticism, however, differed between the two main Buddhist sects – the Mahayana and Theravada traditions. One of the beliefs held by the latter is that it is rather unlikely, even impossible, for a layperson to achieve Enlightenment. Therefore, the only way to achieve this goal is to renounce the world by joining a monastery. The Mahayana school, however, disagrees with this view, and therefore has a less ascetic character.
Mahavira: Abandoning Luxury to Revive Jainism
Not for the Faint of Heart: The Aghori and Their Unorthodox Path to Enlightenment
Monk Lives Life of Solitude on This 131-Foot-Tall Rock with a 2,000 Year History
Islamic Asceticism
Asceticism is not limited to those who have taken religious vows. In Islam, for instance, Muslims are required to fast during the month of Ramadhan. They are not allowed to eat, drink, or have sexual relations between sunrise and sunset. Additionally, Muslims are also encouraged to read the entire Quran, and are expected to improve their spiritual lives.
Finally, it may be said that asceticism has been observed for non-religious purposes as well. As mentioned earlier, asceticism was, and still is, practiced by many athletes prior to competitions. In addition, asceticism has been promoted by certain philosophical traditions, such as Stoicism and Cynicism, as this was believed to allow their practitioners to gain mastery over their desires and passions.
'A learned ascetic.' ( Public Domain )
Top image: The Bodhisattva Gautama (Buddha-to-be) undertaking extreme asceticism before his enlightenment. Source: What-Buddha-Said
By Wu Mingren
Campbell, T., 1907. Asceticism. [Online]
Available at: http://www.newadvent.org/cathen/01767c.htm
Chumley, N. J., 2017. The Compelling Spiritual Discipline of Asceticism. [Online]
Available at: https://www.huffingtonpost.com/norris-j-chumley-phd/the-value-of-asceticism-t_b_806700.html?guccounter=1
New World Encyclopedia, 2016. Asceticism. [Online]
Available at: http://www.newworldencyclopedia.org/entry/Asceticism
The Editors of Encyclopaedia Britannica, 2013. Asceticism. [Online]
Available at: https://www.britannica.com/topic/asceticism
www.philosophybasics.com, 2018. Asceticism. [Online]
Available at: https://www.philosophybasics.com/branch_asceticism.html
Carthusians
Cistercians
Wu Mingren ('Dhwty') has a Bachelor of Arts in Ancient History and Archaeology. Although his primary interest is in the ancient civilizations of the Near East, he is also interested in other geographical regions, as well as other time periods.... Read More
22 June, 2021 - 22:56 dhwty
Buried Alive: The Terrifying History of Death by Immurement
Immurement is a practice whereby a person is enclosed within a confined space with no exits. Normally, a person who is immured is left in that space till he/she dies, either of dehydration or...
Read more about Buried Alive: The Terrifying History of Death by Immurement
23 August, 2016 - 16:29 MartiniF
Theodoret of Cyrrhus (423–457) tells us that when little girls played games in forth-century Syria, they played monks and demons. One of the girls, dressed in rags, would reduce her little friends...
Read more about Monks, Hermits and Ascetics: The Little-Known History of Women in Desert Asceticism
29 July, 2016 - 19:00 MartiniF
The Laughing Buddha: The Eccentric Monk, God of Plenty and Patron of Bartenders
Siddhartha Gautama, known as the Buddha, was born in 6 BC, in what is now modern Nepal. He lived the comfortable life of a young prince until one day he ventured out into the world and was confronted...
Read more about The Laughing Buddha: The Eccentric Monk, God of Plenty and Patron of Bartenders


text:
Q: Angular 4 ng build: is --aot automatically executed with --prod? I wonder if there's a difference between
ng build --prod

and
ng build --prod --aot

The file sizes remain the same for me. Is --aot selected automatically if you specify --prod?

A: In the latest Stable version of CLI you need not use the --aot flag the --prod flag enables it by default.
For more info check this LINK

redpajama_set_name: RedPajamaStackExchange


He concluded the report with a brief summary.
They gave a summary of their progress in building the bridge.
In summary [=in conclusion, in sum], we need a better public health-care system.
What made you want to look up summary? Include any comments and questions you have about this word.


text:
Moffat County Sheriff: Fire potential 'no joke anymore'
Posted on June 20, 2012 by Joe Moylan
The Sand Fire is out, Moffat County Sheriff Tim Jantz reported Wednesday.
The wildfire, estimated at 2,000 acres, ignited Tuesday afternoon about 10 miles west of Craig off U.S. Highway 40.
The official report confirming total suppression was issued at 3:30 p.m. Wedneday following more than seven hours of mop-up operations conducted by Moffat County Sheriff's Office and Craig Fire/Rescue firefighters.
Another fire continues to burn in north Moffat County.
Firefighters, including two engines from the Sheriff's Office, have controlled and contained the Willow Fire, which started Tuesday near Baggs, Wyo., and crossed the state line into Slater.
Jantz expected local firefighters to return to Craig around 5 p.m. Thursdsy when the Willow Fire was expected to be moved to monitor status.
Smoke was reported south of Lay shortly after firefighters contained the Sand Fire, but Sheriff's Office deputies coud not locate an active fire.
"We think we have a lot of smoke from other fires settling in the valley near Lay," Jantz said. "I have no problem with residents calling us with those types of reports and I ask everyone to remain on high alert with continued hot weather and dry lightning in this weekend's forecast"
Early Wednesday morning local elected officials participated in an update meeting on the Sand Fire.
Fire investigators believe the wildfire, which started at approximately 5:30 p.m. Tuesday off U.S. Highway 40 near mile marker 79, was ignited by a cigarette.
Jantz said DNA evidence could be collected from the cigarette investigators believe sparked the Sand Fire, but the probability of finding the suspect is unlikely.
More important than acquiring a suspect is Jantz's hope the Sand Fire was enough to convince any remaining skeptics about the serious fire danger in the county.
"This is no joke anymore, we're not joking," Jantz said. "Throwing cigarette butts or hot items from vehicles, which is what appears to have happened, are things we don't do anymore."
Multiple agencies participated in the Wednesday morning update, including BLM officials from the Little Snake Field Office who announced a Stage 2 fire restriction beginning today.
Stage 2 fire restrictions prohibit open fires that could potentially throw an ember, said BLM Fire Management Officer Colt Mortenson. The ban includes, but is not limited to, camp fires, charcoal grills, wood- and coal-burning stoves, and sheep herder stoves.
The ban also prohibits open fires in designated public areas that feature fire rings or grates.
The only exception to the BLM Stage 2 fire ban pertains to liquid or gas-fueled stoves, Mortenson said.
The restriction is limited to federal lands managed by the BLM in the Northwest Colorado Fire Management Unit.
However, Mortenson believes each of the cooperating agencies in the fire management unit would be adopting similar bans this week and that all open fires would likely be prohibited on public lands throughout Northwest Colorado.
Members of the Northwest Colorado Fire Management Unit include the BLM's Little Snake, White River and Kremmling field offices; Medicine Bow and Routt National Forests; Arapahoe and Brown's Park National Wildlife Refuges; the Colorado State Forest Service; Dinosaur National Monument; and Moffat, Routt, Rio Blanco, Jackson, and Grand counties.
Federal lands managed by BLM offices in Larimer, Summit, Eagle, Garfield and Mesa counties are anticipated to raise their respective fire restriction levels to Stage 2 to maintain consistency in the region, Mortenson said.
According to a June 14 executive order by Gov. John Hickenlooper, county sheriffs may continue to issue open fire permits in their respective jurisdictions, Jantz said.
However, should a permitted fire get out of control the state will not allocate Emergency Fire Fund money to assist with firefighting operations.
"The county is now solely responsible," Jantz said. "The decision was made this morning that no open fire permits will be given (in Moffat County).
"I believe the public understands that we have now moved into extreme resource availability and extreme fire conditions, so no open fires, period."
Because the Willow Fire is not officially out, BLM firefighters have not yet been able to GPS the scene of the Sand Fire, Jantz said.
Fire officials therefore continue to estimate the size of the Sand Fire at 2,000 acres.
Click here to have the print version of the Click here to have the print version of the Craig Daily Press delivered to your home.Click here to have the print version of the Craig Daily Press delivered to your home.
Fire restrictions tighten in parts of Colorado
Tourism back in Canyon City after Iron Mountain Fire, Hayman Fire


Lend a charming look and impress your guests with this wide cake stand. Its trendy design and textured finish give it a stunning look and the antique touch makes it more attractive. Made from glass and metal, it is studded and sports a classic styling.


Chicago's filled with stories of long-time eateries buzzing along without getting a ton of media buzz. Pat's Pizza, which opened in 1950, is one of those establishments.
It may not attract the trendiest crowds, but Pat's has been a consistent neighborhood favorite for generations. Originally established at 3114 N. Sheffield Ave. by Nick Pianetto, Sr., the restaurant remains in the family with ownership by Nick Jr.
Pat's appetizer menu is plentiful--and tempting. Customers may choose from classic Italian favorites like fried calamari and mozzarella sticks to more contemporary starters such as a pepperoni pizza dip that's served with garlic toast.
In addition to pizza, there are several notable entrees and pasta dishes. Pork Milanese, chicken Vesuvio and penne pasta topped with grilled salmon in tomato cream sauce are some of the favorites.
Pat's specializes in thin-crust pizza. Guests may customize their pies or choose from a selection of specialty offerings. The vegetarian includes up to four vegetable toppings; meat lovers is topped with sausage, pepperoni, American bacon and ground beef; plus, there's a taco pizza, cheeseburger pizza, pesto chicken pizza and others.


Nuku'alofa – March 22, 2019: 1.15pm (Enviro News): To celebrate World Water Day today – March 22 – the Lands and Survey Ministry distributed posters carrying important information on the need for water.
The world today celebrated the important day.
Tonga, like any other developing country, faces its own challenges as far as having safe and clean drinking water for its people is concerned.
The Tonga Water Authority has the important task of ensuring there is clean and safe water to be used by the people of Tonga.
While the tap water that is supplied from its Matakieua system is now being termed safe to drink and use, most locals turn to bottled water – either locally or imported – for their drinking water supply.
There is also a big reliance on rain water that is harvested from rooftops and stored in water tanks at residences across the Kingdom.
So what can we learn from the 2019 World Water Day?
discrimination, to sufficient, safe, acceptable, physically accessible and affordable water for personal and domestic use; which includes water for drinking, personal sanitation, washing of clothes, food preparation, and personal and household hygiene.


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.security.SecurityUtilTestHelper;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ExecutionType;
import org.apache.hadoop.yarn.api.records.LogAggregationContext;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.api.ContainerType;
import org.apache.hadoop.yarn.server.resourcemanager.MockAM;
import org.apache.hadoop.yarn.server.resourcemanager.MockNM;
import org.apache.hadoop.yarn.server.resourcemanager.MockRM;
import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl;
import org.apache.hadoop.yarn.server.resourcemanager.RMSecretManagerService;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.resource.TestResourceProfiles;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.apache.hadoop.yarn.util.resource.TestResourceUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.MAXIMUM_ALLOCATION_MB;

public class TestContainerAllocation {

  private static final Log LOG = LogFactory
      .getLog(TestContainerAllocation.class);

  private final int GB = 1024;

  private YarnConfiguration conf;

  RMNodeLabelsManager mgr;

  @Before
  public void setUp() throws Exception {
    conf = new YarnConfiguration();
    conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
      ResourceScheduler.class);
    mgr = new NullRMNodeLabelsManager();
    mgr.init(conf);
  }

  @Test(timeout = 60000)
  public void testExcessReservationThanNodeManagerCapacity() throws Exception {
    @SuppressWarnings("resource")
    MockRM rm = new MockRM(conf);
    rm.start();

    // Register node1
    MockNM nm1 = rm.registerNode("127.0.0.1:1234", 2 * GB, 4);
    MockNM nm2 = rm.registerNode("127.0.0.1:2234", 3 * GB, 4);

    nm1.nodeHeartbeat(true);
    nm2.nodeHeartbeat(true);

    // wait..
    int waitCount = 20;
    int size = rm.getRMContext().getRMNodes().size();
    while ((size = rm.getRMContext().getRMNodes().size()) != 2
        && waitCount-- > 0) {
      LOG.info("Waiting for node managers to register : " + size);
      Thread.sleep(100);
    }
    Assert.assertEquals(2, rm.getRMContext().getRMNodes().size());
    // Submit an application
    RMApp app1 = rm.submitApp(128);

    // kick the scheduling
    nm1.nodeHeartbeat(true);
    RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
    MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
    am1.registerAppAttempt();

    LOG.info("sending container requests ");
    am1.addRequests(new String[] {"*"}, 2 * GB, 1, 1);
    AllocateResponse alloc1Response = am1.schedule(); // send the request

    // kick the scheduler
    nm1.nodeHeartbeat(true);
    int waitCounter = 20;
    LOG.info("heartbeating nm1");
    while (alloc1Response.getAllocatedContainers().size() < 1
        && waitCounter-- > 0) {
      LOG.info("Waiting for containers to be created for app 1...");
      Thread.sleep(500);
      alloc1Response = am1.schedule();
    }
    LOG.info("received container : "
        + alloc1Response.getAllocatedContainers().size());

    // No container should be allocated.
    // Internally it should not been reserved.
    Assert.assertTrue(alloc1Response.getAllocatedContainers().size() == 0);

    LOG.info("heartbeating nm2");
    waitCounter = 20;
    nm2.nodeHeartbeat(true);
    while (alloc1Response.getAllocatedContainers().size() < 1
        && waitCounter-- > 0) {
      LOG.info("Waiting for containers to be created for app 1...");
      Thread.sleep(500);
      alloc1Response = am1.schedule();
    }
    LOG.info("received container : "
        + alloc1Response.getAllocatedContainers().size());
    Assert.assertTrue(alloc1Response.getAllocatedContainers().size() == 1);

    rm.stop();
  }

  // This is to test container tokens are generated when the containers are
  // acquired by the AM, not when the containers are allocated
  @Test
  public void testContainerTokenGeneratedOnPullRequest() throws Exception {
    MockRM rm1 = new MockRM(conf);
    rm1.start();
    MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 8000);
    RMApp app1 = rm1.submitApp(200);
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);
    // request a container.
    am1.allocate("127.0.0.1", 1024, 1, new ArrayList<ContainerId>());
    ContainerId containerId2 =
        ContainerId.newContainerId(am1.getApplicationAttemptId(), 2);
    rm1.waitForState(nm1, containerId2, RMContainerState.ALLOCATED);

    RMContainer container =
        rm1.getResourceScheduler().getRMContainer(containerId2);
    // no container token is generated.
    Assert.assertEquals(containerId2, container.getContainerId());
    Assert.assertNull(container.getContainer().getContainerToken());

    // acquire the container.
    List<Container> containers =
        am1.allocate(new ArrayList<ResourceRequest>(),
          new ArrayList<ContainerId>()).getAllocatedContainers();
    Assert.assertEquals(containerId2, containers.get(0).getId());
    // container token is generated.
    Assert.assertNotNull(containers.get(0).getContainerToken());
    rm1.stop();
  }

  @Test
  public void testNormalContainerAllocationWhenDNSUnavailable() throws Exception{
    MockRM rm1 = new MockRM(conf);
    rm1.start();
    MockNM nm1 = rm1.registerNode("unknownhost:1234", 8000);
    RMApp app1 = rm1.submitApp(200);
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // request a container.
    am1.allocate("127.0.0.1", 1024, 1, new ArrayList<ContainerId>());
    ContainerId containerId2 =
        ContainerId.newContainerId(am1.getApplicationAttemptId(), 2);
    rm1.waitForState(nm1, containerId2, RMContainerState.ALLOCATED);

    // acquire the container.
    SecurityUtilTestHelper.setTokenServiceUseIp(true);
    List<Container> containers;
    try {
      containers =
          am1.allocate(new ArrayList<ResourceRequest>(),
              new ArrayList<ContainerId>()).getAllocatedContainers();
      // not able to fetch the container;
      Assert.assertEquals(0, containers.size());
    } finally {
      SecurityUtilTestHelper.setTokenServiceUseIp(false);
    }
    containers =
        am1.allocate(new ArrayList<ResourceRequest>(),
          new ArrayList<ContainerId>()).getAllocatedContainers();
    // should be able to fetch the container;
    Assert.assertEquals(1, containers.size());
  }

  // This is to test whether LogAggregationContext is passed into
  // container tokens correctly
  @Test
  public void testLogAggregationContextPassedIntoContainerToken()
      throws Exception {
    MockRM rm1 = new MockRM(conf);
    rm1.start();
    MockNM nm1 = rm1.registerNode("127.0.0.1:1234", 8000);
    MockNM nm2 = rm1.registerNode("127.0.0.1:2345", 8000);
    // LogAggregationContext is set as null
    Assert
      .assertNull(getLogAggregationContextFromContainerToken(rm1, nm1, null));

    // create a not-null LogAggregationContext
    LogAggregationContext logAggregationContext =
        LogAggregationContext.newInstance(
          "includePattern", "excludePattern",
          "rolledLogsIncludePattern",
          "rolledLogsExcludePattern",
          "policyClass",
          "policyParameters");
    LogAggregationContext returned =
        getLogAggregationContextFromContainerToken(rm1, nm2,
          logAggregationContext);
    Assert.assertEquals("includePattern", returned.getIncludePattern());
    Assert.assertEquals("excludePattern", returned.getExcludePattern());
    Assert.assertEquals("rolledLogsIncludePattern",
        returned.getRolledLogsIncludePattern());
    Assert.assertEquals("rolledLogsExcludePattern",
        returned.getRolledLogsExcludePattern());
    Assert.assertEquals("policyClass",
        returned.getLogAggregationPolicyClassName());
    Assert.assertEquals("policyParameters",
        returned.getLogAggregationPolicyParameters());
    rm1.stop();
  }

  private LogAggregationContext getLogAggregationContextFromContainerToken(
      MockRM rm1, MockNM nm1, LogAggregationContext logAggregationContext)
      throws Exception {
    RMApp app2 = rm1.submitApp(200, logAggregationContext);
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);
    nm1.nodeHeartbeat(true);
    // request a container.
    am2.allocate("127.0.0.1", 512, 1, new ArrayList<ContainerId>());
    ContainerId containerId =
        ContainerId.newContainerId(am2.getApplicationAttemptId(), 2);
    rm1.waitForState(nm1, containerId, RMContainerState.ALLOCATED);

    // acquire the container.
    List<Container> containers =
        am2.allocate(new ArrayList<ResourceRequest>(),
          new ArrayList<ContainerId>()).getAllocatedContainers();
    Assert.assertEquals(containerId, containers.get(0).getId());
    // container token is generated.
    Assert.assertNotNull(containers.get(0).getContainerToken());
    ContainerTokenIdentifier token =
        BuilderUtils.newContainerTokenIdentifier(containers.get(0)
          .getContainerToken());
    return token.getLogAggregationContext();
  }

  private volatile int numRetries = 0;
  private class TestRMSecretManagerService extends RMSecretManagerService {

    public TestRMSecretManagerService(Configuration conf,
        RMContextImpl rmContext) {
      super(conf, rmContext);
    }
    @Override
    protected RMContainerTokenSecretManager createContainerTokenSecretManager(
        Configuration conf) {
      return new RMContainerTokenSecretManager(conf) {

        @Override
        public Token createContainerToken(ContainerId containerId,
            int containerVersion, NodeId nodeId, String appSubmitter,
            Resource capability, Priority priority, long createTime,
            LogAggregationContext logAggregationContext, String nodeLabelExp,
            ContainerType containerType, ExecutionType executionType,
            long allocationRequestId, Set<String> allocationTags) {
          numRetries++;
          return super.createContainerToken(containerId, containerVersion,
              nodeId, appSubmitter, capability, priority, createTime,
              logAggregationContext, nodeLabelExp, containerType,
              executionType, allocationRequestId, allocationTags);
        }
      };
    }
  }

  // This is to test fetching AM container will be retried, if AM container is
  // not fetchable since DNS is unavailable causing container token/NMtoken
  // creation failure.
  @Test(timeout = 30000)
  public void testAMContainerAllocationWhenDNSUnavailable() throws Exception {
    MockRM rm1 = new MockRM(conf) {
      @Override
      protected RMSecretManagerService createRMSecretManagerService() {
        return new TestRMSecretManagerService(conf, rmContext);
      }
    };
    rm1.start();

    MockNM nm1 = rm1.registerNode("unknownhost:1234", 8000);
    RMApp app1;
    try {
      SecurityUtilTestHelper.setTokenServiceUseIp(true);
      app1 = rm1.submitApp(200);
      RMAppAttempt attempt = app1.getCurrentAppAttempt();
      nm1.nodeHeartbeat(true);

      // fetching am container will fail, keep retrying 5 times.
      while (numRetries <= 5) {
        nm1.nodeHeartbeat(true);
        Thread.sleep(1000);
        Assert.assertEquals(RMAppAttemptState.SCHEDULED,
            attempt.getAppAttemptState());
        System.out.println("Waiting for am container to be allocated.");
      }
    } finally {
      SecurityUtilTestHelper.setTokenServiceUseIp(false);
    }
    MockRM.launchAndRegisterAM(app1, rm1, nm1);
  }

  @Test(timeout = 60000)
  public void testExcessReservationWillBeUnreserved() throws Exception {
    /**
     * Test case: Submit two application (app1/app2) to a queue. And there's one
     * node with 8G resource in the cluster. App1 allocates a 6G container, Then
     * app2 asks for a 4G container. App2's request will be reserved on the
     * node.
     *
     * Before next node heartbeat, app2 cancels the reservation, we should found
     * the reserved resource is cancelled as well.
     */
    // inject node label manager
    MockRM rm1 = new MockRM();

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB);

    // launch an app to queue, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch another app to queue, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());
    am2.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    LeafQueue leafQueue = (LeafQueue) cs.getQueue("default");

    // Do node heartbeats 2 times
    // First time will allocate container for app1, second time will reserve
    // container for app2
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // App2 will get preference to be allocated on node1, and node1 will be all
    // used by App2.
    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());

    // Check if a 4G contaienr allocated for app1, and nothing allocated for app2
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp2.getLiveContainers().size());
    Assert.assertTrue(schedulerApp2.getReservedContainers().size() > 0);

    // NM1 has available resource = 2G (8G - 2 * 1G - 4G)
    Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId())
        .getUnallocatedResource().getMemorySize());
    Assert.assertNotNull(cs.getNode(nm1.getNodeId()).getReservedContainer());
    // Usage of queue = 4G + 2 * 1G + 4G (reserved)
    Assert.assertEquals(10 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(4 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(4 * GB, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    // Cancel asks of app2 and re-kick RM
    am2.allocate("*", 4 * GB, 0, new ArrayList<ContainerId>());
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // App2's reservation will be cancelled
    Assert.assertTrue(schedulerApp2.getReservedContainers().size() == 0);
    Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId())
        .getUnallocatedResource().getMemorySize());
    Assert.assertNull(cs.getNode(nm1.getNodeId()).getReservedContainer());
    Assert.assertEquals(6 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(0, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(0, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testAllocationForReservedContainer() throws Exception {
    /**
     * Test case: Submit two application (app1/app2) to a queue. And there's one
     * node with 8G resource in the cluster. App1 allocates a 6G container, Then
     * app2 asks for a 4G container. App2's request will be reserved on the
     * node.
     *
     * Before next node heartbeat, app1 container is completed/killed. So app1
     * container which was reserved will be allocated.
     */
    // inject node label manager
    MockRM rm1 = new MockRM();

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB);

    // launch an app to queue, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch another app to queue, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());
    am2.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    LeafQueue leafQueue = (LeafQueue) cs.getQueue("default");

    // Do node heartbeats 2 times
    // First time will allocate container for app1, second time will reserve
    // container for app2
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // App2 will get preference to be allocated on node1, and node1 will be all
    // used by App2.
    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());

    // Check if a 4G container allocated for app1, and nothing allocated for app2
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp2.getLiveContainers().size());
    Assert.assertTrue(schedulerApp2.getReservedContainers().size() > 0);

    // NM1 has available resource = 2G (8G - 2 * 1G - 4G)
    Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId())
        .getUnallocatedResource().getMemorySize());
    Assert.assertNotNull(cs.getNode(nm1.getNodeId()).getReservedContainer());
    // Usage of queue = 4G + 2 * 1G + 4G (reserved)
    Assert.assertEquals(10 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(4 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(4 * GB, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    // Mark one app1 container as killed/completed and re-kick RM
    for (RMContainer container : schedulerApp1.getLiveContainers()) {
      if (container.isAMContainer()) {
        continue;
      }
      cs.markContainerForKillable(container);
    }
    // Cancel asks of app1 and re-kick RM
    am1.allocate("*", 4 * GB, 0, new ArrayList<ContainerId>());
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // Check 4G container cancelled for app1, and one container allocated for
    // app2
    Assert.assertEquals(1, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(2, schedulerApp2.getLiveContainers().size());
    Assert.assertFalse(schedulerApp2.getReservedContainers().size() > 0);

    // NM1 has available resource = 2G (8G - 2 * 1G - 4G)
    Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId())
        .getUnallocatedResource().getMemorySize());
    Assert.assertNull(cs.getNode(nm1.getNodeId()).getReservedContainer());
    // Usage of queue = 4G + 2 * 1G
    Assert.assertEquals(6 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(0 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(0 * GB, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testReservedContainerMetricsOnDecommisionedNode() throws Exception {
    /**
     * Test case: Submit two application (app1/app2) to a queue. And there's one
     * node with 8G resource in the cluster. App1 allocates a 6G container, Then
     * app2 asks for a 4G container. App2's request will be reserved on the
     * node.
     *
     * Before next node heartbeat, app1 container is completed/killed. So app1
     * container which was reserved will be allocated.
     */
    // inject node label manager
    MockRM rm1 = new MockRM();

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB);

    // launch an app to queue, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch another app to queue, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());
    am2.allocate("*", 4 * GB, 1, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    LeafQueue leafQueue = (LeafQueue) cs.getQueue("default");

    // Do node heartbeats 2 times
    // First time will allocate container for app1, second time will reserve
    // container for app2
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // App2 will get preference to be allocated on node1, and node1 will be all
    // used by App2.
    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());

    // Check if a 4G container allocated for app1, and nothing allocated for app2
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp2.getLiveContainers().size());
    Assert.assertTrue(schedulerApp2.getReservedContainers().size() > 0);

    // NM1 has available resource = 2G (8G - 2 * 1G - 4G)
    Assert.assertEquals(2 * GB, cs.getNode(nm1.getNodeId())
        .getUnallocatedResource().getMemorySize());
    Assert.assertNotNull(cs.getNode(nm1.getNodeId()).getReservedContainer());
    // Usage of queue = 4G + 2 * 1G + 4G (reserved)
    Assert.assertEquals(10 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(4 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(4 * GB, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    // Remove the node
    cs.handle(new NodeRemovedSchedulerEvent(rmNode1));

    // Check all container cancelled for app1 and app2
    Assert.assertEquals(0, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(0, schedulerApp2.getLiveContainers().size());
    Assert.assertFalse(schedulerApp2.getReservedContainers().size() > 0);

    // Usage and Reserved capacity of queue is 0
    Assert.assertEquals(0 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getUsed().getMemorySize());
    Assert.assertEquals(0 * GB, cs.getRootQueue().getQueueResourceUsage()
        .getReserved().getMemorySize());
    Assert.assertEquals(0 * GB, leafQueue.getQueueResourceUsage().getReserved()
        .getMemorySize());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testAssignMultipleOffswitchContainers() throws Exception {
    MockRM rm1 = new MockRM();

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 80 * GB);

    // launch an app to queue, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    am1.allocate("*", 1 * GB, 5, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());

    // Do node heartbeats once
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());

    // App1 will get one container allocated (plus AM container
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());

    // Set assign multiple off-switch containers to 3
    CapacitySchedulerConfiguration newCSConf = new CapacitySchedulerConfiguration();
    newCSConf.setInt(
        CapacitySchedulerConfiguration.OFFSWITCH_PER_HEARTBEAT_LIMIT, 3);

    cs.reinitialize(newCSConf, rm1.getRMContext());

    // Do node heartbeats once
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    // App1 will get 3 new container allocated (plus 2 previously allocated
    // container)
    Assert.assertEquals(5, schedulerApp1.getLiveContainers().size());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testContinuousReservationLookingWhenUsedEqualsMax() throws Exception {
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);
    // Set maximum capacity of A to 10
    newConf.setMaximumCapacity(CapacitySchedulerConfiguration.ROOT + ".a", 10);
    MockRM rm1 = new MockRM(newConf);

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 10 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 90 * GB);

    // launch an app to queue A, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(2 * GB, "app", "user", null, "a");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch 2nd app to queue B, AM container should be launched in nm1
    // Now usage of nm1 is 3G (2G + 1G)
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "b");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 4 * GB, 2, null);

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    RMNode rmNode2 = rm1.getRMContext().getRMNodes().get(nm2.getNodeId());

    // Do node heartbeats twice, we expect one container allocated on nm1 and
    // one container reserved on nm1.
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());

    // App1 will get 2 container allocated (plus AM container)
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp1.getReservedContainers().size());

    // Do node heartbeats on nm2, we expect one container allocated on nm2 and
    // one unreserved on nm1
    cs.handle(new NodeUpdateSchedulerEvent(rmNode2));
    Assert.assertEquals(3, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(0, schedulerApp1.getReservedContainers().size());

    rm1.close();
  }

  @Test
  public void testPendingResourcesConsideringUserLimit() throws Exception {
    // Set maximum capacity of A to 10
    CapacitySchedulerConfiguration newConf = new CapacitySchedulerConfiguration(
        conf);
    newConf.setUserLimitFactor(CapacitySchedulerConfiguration.ROOT + ".default",
        0.5f);
    newConf.setMaximumAMResourcePercentPerPartition(
        CapacitySchedulerConfiguration.ROOT + ".default", "", 1.0f);
    MockRM rm1 = new MockRM(newConf);

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB);

    // launch an app to queue default, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(2 * GB, "app", "u1", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch 2nd app to queue default, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(4 * GB, "app", "u2", null, "default");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    // am1 asks 1 * 3G container
    am1.allocate("*", 3 * GB, 1, null);

    // am2 asks 4 * 5G container
    am2.allocate("*", 5 * GB, 4, null);

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    RMNode rmNode2 = rm1.getRMContext().getRMNodes().get(nm2.getNodeId());

    // Do node heartbeats one, we expect one container allocated reserved on nm1
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));

    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());

    // App1 will get 1 container reserved
    Assert.assertEquals(1, schedulerApp1.getReservedContainers().size());

    /*
     * Note that the behavior of appAttemptResourceUsage is different from queue's
     * For queue, used = actual-used + reserved
     * For app, used = actual-used.
     *
     * TODO (wangda): Need to make behaviors of queue/app's resource usage
     * consistent
     */
    Assert.assertEquals(2 * GB,
        schedulerApp1.getAppAttemptResourceUsage().getUsed().getMemorySize());
    Assert.assertEquals(3 * GB,
        schedulerApp1.getAppAttemptResourceUsage().getReserved()
            .getMemorySize());
    Assert.assertEquals(3 * GB,
        schedulerApp1.getAppAttemptResourceUsage().getPending()
            .getMemorySize());

    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());
    Assert.assertEquals(4 * GB,
        schedulerApp2.getAppAttemptResourceUsage().getUsed().getMemorySize());
    Assert.assertEquals(0 * GB,
        schedulerApp2.getAppAttemptResourceUsage().getReserved()
            .getMemorySize());
    Assert.assertEquals(5 * 4 * GB,
        schedulerApp2.getAppAttemptResourceUsage().getPending()
            .getMemorySize());

    LeafQueue lq = (LeafQueue) cs.getQueue("default");

    // UL = 8GB, so head room of u1 = 8GB - 2GB (AM) - 3GB (Reserved) = 3GB
    //                           u2 = 8GB - 4GB = 4GB
    // When not deduct reserved, total-pending = 3G (u1) + 4G (u2) = 7G
    //          deduct reserved, total-pending = 0G (u1) + 4G = 4G
    Assert.assertEquals(7 * GB, lq.getTotalPendingResourcesConsideringUserLimit(
        Resources.createResource(20 * GB), "", false).getMemorySize());
    Assert.assertEquals(4 * GB, lq.getTotalPendingResourcesConsideringUserLimit(
        Resources.createResource(20 * GB), "", true).getMemorySize());
    rm1.close();
  }

  @Test(timeout = 60000)
  public void testQueuePriorityOrdering() throws Exception {
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);

    // Set ordering policy
    newConf.setQueueOrderingPolicy(CapacitySchedulerConfiguration.ROOT,
        CapacitySchedulerConfiguration.QUEUE_PRIORITY_UTILIZATION_ORDERING_POLICY);

    // Set maximum capacity of A to 20
    newConf.setMaximumCapacity(CapacitySchedulerConfiguration.ROOT + ".a", 20);
    newConf.setQueuePriority(CapacitySchedulerConfiguration.ROOT + ".c", 1);
    newConf.setQueuePriority(CapacitySchedulerConfiguration.ROOT + ".b", 2);
    newConf.setQueuePriority(CapacitySchedulerConfiguration.ROOT + ".a", 3);

    MockRM rm1 = new MockRM(newConf);

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 100 * GB);

    // launch an app to queue A, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(2 * GB, "app", "user", null, "a");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch an app to queue B, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(2 * GB, "app", "user", null, "b");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    // launch an app to queue C, AM container should be launched in nm1
    RMApp app3 = rm1.submitApp(2 * GB, "app", "user", null, "c");
    MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm1);

    // Each application asks 10 * 5GB containers
    am1.allocate("*", 5 * GB, 10, null);
    am2.allocate("*", 5 * GB, 10, null);
    am3.allocate("*", 5 * GB, 10, null);

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());

    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp3 =
        cs.getApplicationAttempt(am3.getApplicationAttemptId());

    // container will be allocated to am1
    // App1 will get 2 container allocated (plus AM container)
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp3.getLiveContainers().size());

    // container will be allocated to am1 again,
    // App1 will get 3 container allocated (plus AM container)
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    Assert.assertEquals(3, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp3.getLiveContainers().size());

    // (Now usages of queues: a=12G (satisfied), b=2G, c=2G)

    // container will be allocated to am2 (since app1 reaches its guaranteed
    // capacity)
    // App2 will get 2 container allocated (plus AM container)
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    Assert.assertEquals(3, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(2, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp3.getLiveContainers().size());

    // Do this 3 times
    // container will be allocated to am2 (since app1 reaches its guaranteed
    // capacity)
    // App2 will get 2 container allocated (plus AM container)
    for (int i = 0; i < 3; i++) {
      cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    }
    Assert.assertEquals(3, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(5, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp3.getLiveContainers().size());

    // (Now usages of queues: a=12G (satisfied), b=22G (satisfied), c=2G))

    // Do this 10 times
    for (int i = 0; i < 10; i++) {
      cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    }
    Assert.assertEquals(3, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(5, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(11, schedulerApp3.getLiveContainers().size());

    // (Now usages of queues: a=12G (satisfied), b=22G (satisfied),
    // c=52G (satisfied and no pending))

    // Do this 20 times, we can only allocate 3 containers, 1 to A and 3 to B
    for (int i = 0; i < 20; i++) {
      cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    }
    Assert.assertEquals(4, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(6, schedulerApp2.getLiveContainers().size());
    Assert.assertEquals(11, schedulerApp3.getLiveContainers().size());

    // (Now usages of queues: a=17G (satisfied), b=27G (satisfied), c=52G))

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testUserLimitAllocationMultipleContainers() throws Exception {
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);
    newConf.setUserLimit("root.c", 50);
    MockRM rm1 = new MockRM(newConf);

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 1000 * GB);

    // launch app from 1st user to queue C, AM container should be launched in nm1
    RMApp app1 = rm1.submitApp(2 * GB, "app", "user1", null, "c");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch app from 2nd user to queue C, AM container should be launched in nm1
    RMApp app2 = rm1.submitApp(2 * GB, "app", "user2", null, "c");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    // Each application asks 1000 * 5GB containers
    am1.allocate("*", 5 * GB, 1000, null);
    am1.allocate("h1", 5 * GB, 1000, null);
    am1.allocate(NetworkTopology.DEFAULT_RACK, 5 * GB, 1000, null);

    // Each application asks 1000 * 5GB containers
    am2.allocate("*", 5 * GB, 1000, null);
    am2.allocate("h1", 5 * GB, 1000, null);
    am2.allocate(NetworkTopology.DEFAULT_RACK, 5 * GB, 1000, null);

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());

    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());

    // container will be allocated to am1
    // App1 will get 2 container allocated (plus AM container)
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    Assert.assertEquals(101, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(100, schedulerApp2.getLiveContainers().size());

    rm1.close();
  }

  @Test
  public void testActiveUsersWithOnlyPendingApps() throws Exception {

    CapacitySchedulerConfiguration newConf =
        new CapacitySchedulerConfiguration(conf);
    newConf.setMaximumAMResourcePercentPerPartition(
        CapacitySchedulerConfiguration.ROOT + ".default", "", 0.2f);
    MockRM rm1 = new MockRM(newConf);

    rm1.getRMContext().setNodeLabelManager(mgr);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);

    RMApp app1 = rm1.submitApp(1 * GB, "app", "u1", null, "default");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    RMApp app2 = rm1.submitApp(1 * GB, "app", "u2", null, "default");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    RMApp app3 = rm1.submitApp(1 * GB, "app", "u3", null, "default");

    RMApp app4 = rm1.submitApp(1 * GB, "app", "u4", null, "default");

    // Each application asks 50 * 1GB containers
    am1.allocate("*", 1 * GB, 50, null);
    am2.allocate("*", 1 * GB, 50, null);

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());

    for (int i = 0; i < 10; i++) {
      cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
      Thread.sleep(1000);
    }
    LeafQueue lq = (LeafQueue) cs.getQueue("default");
    UsersManager um = (UsersManager) lq.getAbstractUsersManager();

    Assert.assertEquals(4, um.getNumActiveUsers());
    Assert.assertEquals(2, um.getNumActiveUsersWithOnlyPendingApps());
    Assert.assertEquals(2, lq.getMetrics().getAppsPending());
    rm1.close();
  }

  @Test(timeout = 60000)
  public void testUnreserveWhenClusterResourceHasEmptyResourceType()
      throws Exception {
    /**
     * Test case:
     * Create a cluster with two nodes whose node resource both are
     * <8GB, 8core, 0>, create queue "a" whose max-resource is <8GB, 8 core, 0>,
     * submit app1 to queue "a" whose am use <1GB, 1 core, 0> and launch on nm1,
     * submit app2 to queue "b" whose am use <1GB, 1 core, 0> and launch on nm1,
     * app1 asks two <7GB, 1core> containers and nm1 do 1 heartbeat,
     * then scheduler reserves one container on nm1.
     *
     * After nm2 do next node heartbeat, scheduler should unreserve the reserved
     * container on nm1 then allocate a container on nm2.
     */
    TestResourceUtils.addNewTypesToResources("resource1");
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);
    newConf.setClass(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS,
        DominantResourceCalculator.class, ResourceCalculator.class);
    newConf
        .setBoolean(TestResourceProfiles.TEST_CONF_RESET_RESOURCE_TYPES, false);
    // Set maximum capacity of queue "a" to 50
    newConf.setMaximumCapacity(CapacitySchedulerConfiguration.ROOT + ".a", 50);
    MockRM rm1 = new MockRM(newConf);

    RMNodeLabelsManager nodeLabelsManager = new NullRMNodeLabelsManager();
    nodeLabelsManager.init(newConf);
    rm1.getRMContext().setNodeLabelManager(nodeLabelsManager);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 8 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 8 * GB);

    // launch an app to queue "a", AM container should be launched on nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "a");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch another app to queue "b", AM container should be launched on nm1
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "b");
    MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 7 * GB, 2, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    RMNode rmNode2 = rm1.getRMContext().getRMNodes().get(nm2.getNodeId());
    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());

    // Do nm1 heartbeats 1 times, will reserve a container on nm1 for app1
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    Assert.assertEquals(1, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(1, schedulerApp1.getReservedContainers().size());

    // Do nm2 heartbeats 1 times, will unreserve a container on nm1
    // and allocate a container on nm2 for app1
    cs.handle(new NodeUpdateSchedulerEvent(rmNode2));
    Assert.assertEquals(2, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(0, schedulerApp1.getReservedContainers().size());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testAllocationCannotBeBlockedWhenFormerQueueReachedItsLimit()
      throws Exception {
    /**
     * Queue structure:
     * <pre>
     *             Root
     *            /  |  \
     *           a   b   c
     *          10   20  70
     *                   |  \
     *                  c1   c2
     *           10(max=10)  90
     * </pre>
     * Test case:
     * Create a cluster with two nodes whose node resource both are
     * <10GB, 10core>, create queues as above, among them max-capacity of "c1"
     * is 10 and others are all 100, so that max-capacity of queue "c1" is
     * <2GB, 2core>,
     * submit app1 to queue "c1" and launch am1(resource=<1GB, 1 core>) on nm1,
     * submit app2 to queue "b" and launch am2(resource=<1GB, 1 core>) on nm1,
     * app1 and app2 both ask one <2GB, 1core> containers
     *
     * Now queue "c" has lower capacity percentage than queue "b", the
     * allocation sequence will be "a" -> "c" -> "b", queue "c1" has reached
     * queue limit so that requests of app1 should be pending
     *
     * After nm1 do 1 heartbeat, scheduler should allocate one container for
     * app2 on nm1.
     */
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);
    newConf.setQueues(CapacitySchedulerConfiguration.ROOT + ".c",
        new String[] { "c1", "c2" });
    newConf.setCapacity(CapacitySchedulerConfiguration.ROOT + ".c.c1", 10);
    newConf
        .setMaximumCapacity(CapacitySchedulerConfiguration.ROOT + ".c.c1", 10);
    newConf.setCapacity(CapacitySchedulerConfiguration.ROOT + ".c.c2", 90);
    newConf.setClass(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS,
        DominantResourceCalculator.class, ResourceCalculator.class);

    MockRM rm1 = new MockRM(newConf);

    RMNodeLabelsManager nodeLabelsManager = new NullRMNodeLabelsManager();
    nodeLabelsManager.init(newConf);
    rm1.getRMContext().setNodeLabelManager(nodeLabelsManager);
    rm1.start();
    MockNM nm1 = rm1.registerNode("h1:1234", 10 * GB);
    MockNM nm2 = rm1.registerNode("h2:1234", 10 * GB);

    // launch an app to queue "c1", AM container should be launched on nm1
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "c1");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);

    // launch another app to queue "b", AM container should be launched on nm1
    RMApp app2 = rm1.submitApp(1 * GB, "app", "user", null, "b");
    MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm1);

    am1.allocate("*", 2 * GB, 1, new ArrayList<ContainerId>());
    am2.allocate("*", 2 * GB, 1, new ArrayList<ContainerId>());

    CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler();
    RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId());
    FiCaSchedulerApp schedulerApp1 =
        cs.getApplicationAttempt(am1.getApplicationAttemptId());
    FiCaSchedulerApp schedulerApp2 =
        cs.getApplicationAttempt(am2.getApplicationAttemptId());

    // Do nm1 heartbeats 1 times, will allocate a container on nm1 for app2
    cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
    rm1.drainEvents();
    Assert.assertEquals(1, schedulerApp1.getLiveContainers().size());
    Assert.assertEquals(2, schedulerApp2.getLiveContainers().size());

    rm1.close();
  }

  @Test(timeout = 60000)
  public void testContainerRejectionWhenAskBeyondDynamicMax()
      throws Exception {
    CapacitySchedulerConfiguration newConf =
        (CapacitySchedulerConfiguration) TestUtils
            .getConfigurationWithMultipleQueues(conf);
    newConf.setClass(CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS,
        DominantResourceCalculator.class, ResourceCalculator.class);
    newConf.set(CapacitySchedulerConfiguration.getQueuePrefix("root.a")
        + MAXIMUM_ALLOCATION_MB, "4096");

    MockRM rm1 = new MockRM(newConf);
    rm1.start();

    // before any node registered or before registration timeout,
    // submit an app beyond queue max leads to failure.
    boolean submitFailed = false;
    MockNM nm1 = rm1.registerNode("h1:1234", 2 * GB, 1);
    RMApp app1 = rm1.submitApp(1 * GB, "app", "user", null, "a");
    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1);
    try {
      am1.allocate("*", 5 * GB, 1, null);
    } catch (InvalidResourceRequestException e) {
      submitFailed = true;
    }
    Assert.assertTrue(submitFailed);

    // Ask 4GB succeeded.
    am1.allocate("*", 4 * GB, 1, null);

    // Add a new node, now the cluster maximum should be refreshed to 3GB.
    CapacityScheduler cs = (CapacityScheduler)rm1.getResourceScheduler();
    cs.getNodeTracker().setForceConfiguredMaxAllocation(false);
    rm1.registerNode("h2:1234", 3 * GB, 1);

    // Now ask 4 GB will fail
    submitFailed = false;
    try {
      am1.allocate("*", 4 * GB, 1, null);
    } catch (InvalidResourceRequestException e) {
      submitFailed = true;
    }
    Assert.assertTrue(submitFailed);

    // But ask 3 GB succeeded.
    am1.allocate("*", 3 * GB, 1, null);

    rm1.close();
  }
}

redpajama_set_name: RedPajamaGithub


text:
Queen of Nigeria
See also: Nigerian traditional rulers
Coat of arms of Nigeria
Queen Elizabeth II (left) in Nigeria 2003;
Saidu Samaila Sambawa (centre)
Her Majesty
Queen Elizabeth on a 1-shilling coin.
From 1960 to 1963, Elizabeth II was Queen of Nigeria: Nigeria was an independent constitutional monarchy. She was also the monarch of the other Commonwealth realms, including the United Kingdom.
The Federation of Nigeria had superseded the Colony and Protectorate of Nigeria within the British Empire on 1 October 1954. The Federation was initially a quasi-federal British colony. It became independent as a dominion within the Commonwealth of Nations on 1 October 1960 under the Parliament of the United Kingdom's Nigeria Independence Act. The Queen was head of state, though her constitutional roles in Nigeria were mostly carried out by the Governor-General of Nigeria.[1]
The monarchy was unpopular with Nigerians and all political parties in Nigeria agreed that the country should be a republic.[1] Nigeria adopted the President of Nigeria as head of state, on 1 October 1963,[1] when the Federation of Nigeria became the Federal Republic of Nigeria, a republic within the Commonwealth.
A stamp of Nigeria overprinted to mark the Queen's visit in 1956
The Queen visited Nigeria twice: 28 January–16 February 1956 and 3–6 December 2003, the latter time to attend the Commonwealth Heads of Government Meeting 2003.[2]
Elizabeth II
(b. 1926) 1 October 1960 – 1 October 1963 The Duke of Edinburgh Charles, Prince of Wales
1 October 1960 – 1 June 1961: By the Grace of God, of the United Kingdom of Great Britain and Northern Ireland and of Her other Realms and Territories Queen, Head of the Commonwealth, Defender of the Faith
1 June 1961 – 1 October 1963: Elizabeth the Second, Queen of Nigeria, and of Her other Realms and Territories, Head of the Commonwealth[3]
Queen In Nigeria (1956)
^ a b c Chika B. Onwuekwe (2003). "Constitutional Development, 1914–1960: British Legacy or Local Exigency?". In Adebayo Oyebade (ed.). The Foundations of Nigeria: Essays in Honor of Toyin Falola. Africa World Press. pp. 172–173. ISBN 1-59221-120-8.
^ "Commonwealth visits since 1952". Official website of the British monarchy. Royal Household. Retrieved 8 November 2015.
^ Royal Styles and Title Act, 1961, quoted in Benjamin Obi Nwabueze (1982). A Constitutional History of Nigeria. C. Hurst & Co. p. 86. ISBN 0-905838-79-3.
Queen Elizabeth II
Current Realms
Antigua and Barbuda
New Zealand
Papua New Guinea
Saint Kitts and Nevis
Saint Lucia
Saint Vincent and the Grenadines
Solomon Islands
Former Realms
Sierra Leone
South Africa
Trinidad and Tobago
Prince Philip, Duke of Edinburgh (husband)
wedding dress
Charles, Prince of Wales (son)
Anne, Princess Royal (daughter)
Prince Andrew, Duke of York (son)
Prince Edward, Earl of Wessex (son)
George VI (father)
Queen Elizabeth The Queen Mother (mother)
Princess Margaret, Countess of Snowdon (sister)
Mountbatten-Windsor family
Accession and
Royal guests
Participants in the procession
Coronation gown
The Queen's Beasts
Treetops Hotel
Proclamation of accession
MacCormick v Lord Advocate
Annus horribilis
Personality and image
Prime ministers
Operation London Bridge
Christopher John Lewis incident
Lithgow Plot
Marcus Sarjeant incident
Michael Fagan incident
Death of Diana, Princess of Wales
Silver Jubilee
Jubilee Gardens
Jubilee line
Jubilee Walkway
Golden Jubilee
Prom at the Palace
Party at the Palace
Jubilee Odyssey
Diamond Jubilee
Armed Forces Parade and Muster
Thames Pageant
Spirit of Chartwell
Gibraltar Flotilla
Other Jubilees
Ruby Jubilee
Sapphire Jubilee
Platinum Jubilee
official openings
Ships used
HMS Vanguard (23)
SS Gothic (1947)
HMY Britannia
State visit to Ireland
Pope Benedict XVI
President Michael D. Higgins
President Xi Jinping
Titles and
Head of the Commonwealth
List of things named after Elizabeth II
Royal Family Order
Elizabeth Cross
Queen's Official Birthday
Depictions
Televised addresses
Royal address to the nation
Royal Christmas Message
Royal Journey (1951)
A Queen Is Crowned (1953)
The Queen in Australia (1954)
The Royal Tour of the Caribbean (1966)
Royal Family (1969)
Elizabeth R: A Year in the Life of the Queen (1992)
Monarchy: The Royal Family at Work (2007)
The Queen (2009 TV serial)
The Diamond Queen (2012)
Elizabeth at 90: A Family Portrait (2016)
The Coronation (2018)
Film and
A Question of Attribution (1992 TV)
Willi und die Windzors (1996)
Her Majesty (2001)
The Queen (2006)
Happy and Glorious (2012)
A Royal Night Out (2015)
The Crown (2016–)
The Queen's Corgi (2019)
A Question of Attribution (1988)
The Audience (2013)
Handbagged
Pietro Annigoni's portraits
Reigning Queens
Her Majesty Queen Elizabeth II – An 80th Birthday Portrait
The Queen
The Coronation Theatre: Portrait of HM Queen Elizabeth II
The Queen and I
The Uncommon Reader
Winnie-the-Pooh Meets the Queen
Queen Camilla
"God Save the Queen"
"Her Majesty"
Machin series (list)
Wilding series
Castle series
Canadian domestic rate stamp
Country definitives
Corgis
Dookie
Carrozza
Height of Fashion
Pall Mall
Jewels of Elizabeth II
Sagana Lodge
Villa Guardamangia
Children's Party at the Palace
The Queen's Birthday Party
Jeannette Charles
Rosa 'Queen Elizabeth'


text:
Villa Mauri, nota anche come Villa Rodolfo Mauri, è una storica residenza della città di Gallarate in Lombardia.

Storia
La villa venne eretta secondo il progetto dell'architetto Carlo Moroni su commissione dell'allora sindaco di Gallarate, Rodolfo Mauri. La mancanza di una puntuale documentazione d'archivio rende impossibile definire con precisione la data di costruzione, collocabile nei primi anni del XX secolo.

Alcune campagne di ristrutturazione hanno parzialmente alterato alcuni dettagli architettonici originali.

Descrizione
La villa presenta uno stile liberty. Si trova in via Solferino 16, sull'ultima propaggine della collina di Crenna in un contesto originariamente rurale, oggi inglobato nell'area urbana di Gallarate.

L'edificio, che si sviluppa su due livelli principali poggiati su un importante basamento, è costituito da volume principale cui sono affiancati alcuni avancorpi, tra i quali spicca la torretta angolare che si erge su tre livelli culminando in una loggia. I prospetti presentano intelaiature angolari intonacati con specchiature in mattone rosso leggermente arretrati. Le aperture, variamente articolate, sono incorniciate da modanature di intonaco più chiaro che tramite la loro articolazione tendono a collegare, in facciata, i due livelli dell'edificio.

Il tratto architettonico distintivo dell'edificio è rappresentato dalle due aperture circolari quali quella del porticato che precede l'ingresso, al centro della quale è posizionato un vaso su piedistallo, e quella del primo piano del prospetto est, affacciata sul giardino. Sono queste, insieme ai parapetti in ferro lavorati a motivo floreale, a collocare chiaramente l'edificio nell'ambito dello stile liberty.

Galleria d'immagini

Note

Voci correlate
 Villa Bossi

Altri progetti

Mauri

redpajama_set_name: RedPajamaWikipedia


text:
Uber to debut service to pay drivers immediately
Posted: 6:39 PM, Mar 17, 2016
By: Alex Hider
Concerned that its drivers are turning to payday lenders and other loan sharks, Uber is set to introduce a system to allow drivers to be paid as soon as their shifts end.
Uber is teaming up with Green Dot, a pre-charge card company to offer a service called GoBank to its drivers. The ride-sharing service will offer the feature for free to its employees, as long as they access their accounts once every six months. Should that not happen, drivers would be charged a monthly fee of $8.95.
"Our drivers should not have to pay for this technology," said Wayne Ting, Uber's general manager for the San Francisco Bay Area.
Uber usually pays its drivers once a week, which can cause a strain on the budgets of its largely low-income workforce. In the past, drivers have turned to payday loans or apps like Clearbanc, which allows drivers to be paid immediately at the cost of $2 per day.
Lyft was the first ride-sharing app to offer immediate payouts when they introduced a similar service recently. However, they require users to deposit at least $50 and charge a fee of 50 cents for each use.
Uber will begin a pilot service for GoBank in select cities, including San Francisco, before expanding nationwide.
Alex Hider is a writer for the E.W. Scripps National Desk. Follow him on Twitter @alexhider.


More details are given in the next section, GCC upgrading explained.Most GCC upgrades are as simple as switching the compiler version (here from 5.4.0 to 6.4.0) and rebuilding Enjoy the new compiler!
Some software problems are inherently difficult to diagnose and yet could be solved by simply rebuilding one or more appropriate packages.
While GCC (or more specifically, libstdc ) goes to great lengths to guarantee stability of the ABI, this guarantee does not extend to all parts of C within libstdc .
Formally, with versions starting from 3.4, GCC/libstdc only guarantees C 98/C 03 ABI stability and not more. GCC only makes C 11 ABI stability guarantees beginning with version 5.1.
GCC upgrading has always been mystified, with suggestions ranging from "users do not need to do anything" to "users will need to rebuild the entire system twice".
Most of this fear, uncertainty and doubt comes from the confusion surrounding ABI incompatibility, something that nowadays rarely happens (and when it does, it will be announced).
(Note that the commands above will cause the packages in the "system" set to be rebuilt twice, which is necessary to be absolutely certain that every package gets built in the same [presumably] "problem-free" environment.
Any problems that remain after doing this are due to either "genuine bugs" that should be reported or poor system configuration.) If dev-libs/boost needs to be rebuilt, one will get the following error message: This means that you are trying to build a package with an older GCC version than that with which some depending libraries were built.
More context to my question: I have been struggling for a while now trying to cross-compile some code, which already works in linux, for Windows.


text:
posted Apr 26, 2016, 1:52 PM by School Websites
Students and staff at St. Peter High School and St. Patrick's High School were recognized for their achievement as exceptional Best Buddies chapters on March 31st. Best Buddies Canada is a national charity that helps to foster friendships between individuals with special needs with student volunteers in over 450 universities, colleges, high schools, and elementary schools across the country.
Through Best Buddies, students with special needs are given the opportunities to enjoy the same experiences many of us take for granted- such as going to the mall, watching a movie, or simply enjoying the company of a friend. Best Buddies Canada has selected St. Peter High School and St. Patrick's High School as two of the Top 20 Best Buddies schools in the country. Selections were based on important factors, such as demonstrating commitment to inclusion and going beyond expectations of running the Best Buddies program.
Principal Norma McDonald, Principal Brid McDonald and the entire Best Buddies Chapter teams at these two schools exceeded these criteria. "I hope our chapters will see how St. Peter High School and St. Patrick's High School have involved Best Buddies into their school" says Steven Pinnock, executive director of Best Buddies Canada. "Out of 450 schools, these two schools fall in the Top 20 in the country. It really shows that students and staff in these chapters are committed to promoting inclusion and friendship."


This level of care provides assessments, individual, family and group therapy. Each client will participate in the development of their individualized treatment plan. Treatment services are provided with Evidence Based Models. Gender specific services are available.
AOD Outpatient Groups utilize evidence based curriculums. Group sessions are available Monday-Friday supported by weekly individual session. Family therapy is integrated as appropriate.
This service Circle for Recovery Offenders (CFRO) is a community based treatment and prevention program designed to assist the returning citizen paroled back into the community and citizens on probation or involved in the legal system. URS provides AOD and life enhancing supportive services that will promote success of the client and their families. Returning citizens are integrated in the URS standard services but also receive curriculum based interventions designed for their special circumstances.
URS Intensive Outpatient AOD treatment is an alternative option for adult male and female clients needing intensive services. Intensive outpatient services are a minimum of three days a week. It is co-ed and is available Mondays – Friday. Gender specific groups are available. Group sessions are held for three hours. Family, Individual sessions and urine screens are built into the program.
The After-Care program is three months long, with the first eight sessions at the rate of two sessions weekly, lasting one hour each. The final two months consist of eight weekly sessions, lasting one hour each session. Overall, After-Care totals 16 sessions with flexibility in the start dates and times.
MAT is used in combination with counseling and behavioral therapy to provide whole patient approach to the treatment of heroin and other opiate based drug use disorders.
A community-based program targeting males and females transitioning from incarceration or community control under the supervision of the Ohio Adult Parole Authority, Probation or other legal entities. The program focuses on relapse prevention and social reintegration services geared towards assisting the community based returning citizen in becoming a productive member of society. U.M.A.D.A.O.P. receives referrals from the Ohio Department of Rehabilitation, Adult Parole Authority, Adult Probation, Ohio Department of Youth Service, Drug Courts, and various community agencies.
The Adolescent Non-Intensive Outpatient is available Monday- Thursdays. All services are developed based on the results of the clients' assessment in conjunction with the guardians' request and referral requirements. Family Bridge sessions, Individual sessions and urine screens are built into the program.
Services for Marijuana and Synthetics use and abuse include education seminars, along with individual and group treatment programs. Dependent on an assessment of individual needs, education and/or treatment consists of two (2) sessions per week for 12 weeks.
URS Intensive Outpatient AOD treatment for adolescent is an alternative option for young people male and female needing a more intensive service. Intensive outpatient services are a minimum of three days a week. It is co-ed and is available Mondays – Thursday. Group sessions are held for three hours. Family, Individual sessions and urine screens are built into the program.


text:
Ryan Reynolds offers $5,000 reward for the safe return of woman's stolen teddy bear
Mon, July 27 by ABC News
Jason Mendez/WireImage
HomeEntertainmentRyan Reynolds offers $5,000 reward for the safe return of woman's stolen teddy bear
(LOS ANGELES) — Ryan Reynolds is doing what he can to help reunite a distraught woman with her lost teddy bear, which carries a special recording of her late mother's voice.
Reynolds, 43, alerted fans that the priceless stuffed animal went missing and offered up a hefty award for its safe return — no questions asked.
"Vancouver: $5,000 to anyone who returns this bear to Mara. Zero questions asked," the Deadpool star tweeted Saturday and linked the call to action. "I think we all need this bear to come home."
The bear in question belongs to Mara Soriano, 28, who says the bag containing her Build-a-Bear, a Nintendo Switch, important documents and an iPad was stolen in the city's west end.
Soriano told CBC that the bear holds a very special message from her late mother, which is a recording of her saying "I love you. I'm proud of you. I'll always be with you."
The 28-year-old says the recording was taken just before her mother, Marilyn Soriano, was placed in hospice care.
Mara says that bear holds the last recording her mother ever made while her voice was still recognizable.
"At hospice her voice was different. Much softer. Not the mom I grew up with," She explained. "That bear is the last memory I have of her speaking in her normal voice."
Marilyn lost her cancer battle in June 2019. She was 53.
"It just makes me feel devastated," Mara told the publication, saying whoever took her bag can keep the items. She only wants the stuffed animal back. "I'm absolutely crushed."
Hopefully, with Ryan Reynolds' intervention, she will be reunited with her bear — and her mother's voice.
By Megan Stone
'Ozark', 'The Crown' lead Netflix-dominated 26th Critics' Choice nominations
"I'd be up for that!" Liam Neeson wants to re-join the 'Star Wars' universe with Disney+'s 'Obi-Wan Kenobi' show
'WandaVision' star Paul Bettany on his father's struggle to come out of the closet
Steve Martin shares hilarious thoughts about getting the COVID-19 vaccine
'The Marksman' dethrones 'Wonder Woman 1984' at the box office with $3.2 million weekend
"Oh, it's fantastic!" Diane Lane loves the fans prompting the release of the 'Justice League' "Snyder Cut"


The analysis and reconstruction of forensically relevant events, such as traffic accidents, criminal assaults and homicides are based on external and internal morphological findings of the injured or deceased person. For this approach high-tech methods are gaining increasing importance in forensic investigations. The non-contact optical 3D digitising system GOM ATOS is applied as a suitable tool for whole body surface and wound documentation and analysis in order to identify injury-causing instruments and to reconstruct the course of event. In addition to the surface documentation, cross-sectional imaging methods deliver medical internal findings of the body. These 3D data are fused into a whole body model of the deceased. Additional to the findings of the bodies, the injury inflicting instruments and incident scene is documented in 3D. The 3D data of the incident scene, generated by 3D laser scanning and photogrammetry, is also included into the reconstruction. Two cases illustrate the methods. In the fist case a man was shot in his bedroom and the main question was, if the offender shot the man intentionally or accidentally, as he declared. In the second case a woman was hit by a car, driving backwards into a garage. It was unclear if the driver drove backwards once or twice, which would indicate that he willingly injured and killed the woman. With this work, we demonstrate how 3D documentation, data merging and animation enable to answer reconstructive questions regarding the dynamic development of patterned injuries, and how this leads to a real data based reconstruction of the course of event.