text:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A New Website.">
<meta name="author" content="Ravi Saxena">
<link rel="icon" href="icon.png" type="image/png" sizes="32x32">

<TITLE>World . Ecosystems</TITLE>

<link rel="stylesheet" type="text/css" href="style3.css">

<link rel="stylesheet" type="text/CSS" href="mystyle.css">

Search The Content

<button id="home">HOME</button>  <button id="id1">MENU</button>  <button id="id2">ARCHIVE</button>  <button id="id3">My Artworks</button>

<z class="blink_text">World Ecosystems</z>

Region-(Australia & Oceania)-Reef

Hello World!! this is php

Great Barrier Reef

<textarea maxlength="50" rows="7" cols="50" style="position:relative;max-width:100%;color:red;background-color:#28CAA3;font-family:cooper;font-weight:bold;box-shadow: 0 0 10px 10px pink; ">
Great Barrier Reef

The Great Barrier Reef is a site of remarkable variety and beauty on the north-east coast of Australia. It contains the world's largest collection of coral reefs, with 400 types of coral, 1,500 species of fish and 4,000 types of mollusc. It also holds great scientific interest as the habitat of species such as the dugong ('sea cow') and the large green turtle, which are threatened with extinction.

UNESCO Article as List

Brief synthesis
As the world's most extensive coral reef ecosystem, the Great Barrier Reef is a globally outstanding and significant entity. Practically the entire ecosystem was inscribed as World Heritage in 1981, covering an area of 348,000 square kilometres and extending across a contiguous latitudinal range of 14o (10oS to 24oS). The Great Barrier Reef (hereafter referred to as GBR) includes extensive cross-shelf diversity, stretching from the low water mark along the mainland coast up to 250 kilometres offshore. This wide depth range includes vast shallow inshore areas, mid-shelf and outer reefs, and beyond the continental shelf to oceanic waters over 2,000 metres deep.
Within the GBR there are some 2,500 individual reefs of varying sizes and shapes, and over 900 islands, ranging from small sandy cays and larger vegetated cays, to large rugged continental islands rising, in one instance, over 1,100 metres above sea level. Collectively these landscapes and seascapes provide some of the most spectacular maritime scenery in the world.
The latitudinal and cross-shelf diversity, combined with diversity through the depths of the water column, encompasses a globally unique array of ecological communities, habitats and species. This diversity of species and habitats, and their interconnectivity, make the GBR one of the richest and most complex natural ecosystems on earth. There are over 1,500 species of fish, about 400 species of coral, 4,000 species of mollusk, and some 240 species of birds, plus a great diversity of sponges, anemones, marine worms, crustaceans, and other species. No other World Heritage property contains such biodiversity. This diversity, especially the endemic species, means the GBR is of enormous scientific and intrinsic importance, and it also contains a significant number of threatened species. Attime of inscription, the IUCN evaluation stated "… if only one coral reef site in the world were to be chosen for the World Heritage List, the Great Barrier Reef is the site to be chosen".
Criterion (vii): The GBR is of superlative natural beauty above and below the water, and provides some of the most spectacular scenery on earth. It is one of a few living structures visible from space, appearing as a complex string of reefal structures along Australia's northeast coast.
From the air, the vast mosaic patterns of reefs, islands and coral cays produce an unparalleled aerial panorama of seascapes comprising diverse shapes and sizes. The Whitsunday Islands provide a magnificent vista of green vegetated islands and spectacular sandy beaches spread over azure waters. This contrasts with the vast mangrove forests in Hinchinbrook Channel, and the rugged vegetated mountains and lush rainforest gullies that are periodically cloud-covered on Hinchinbrook Island.
On many of the cays there are spectacular and globally important breeding colonies of seabirds and marine turtles, and Raine Island is the world's largest green turtle breeding area. On some continental islands, large aggregations of over-wintering butterflies periodically occur.
Beneath the ocean surface, there is an abundance and diversity of shapes, sizes and colours; for example, spectacular coral assemblages of hard and soft corals, and thousands of species of reef fish provide a myriad of brilliant colours, shapes and sizes. The internationally renowned Cod Hole near Lizard Island is one of many significant tourist attractions. Other superlative natural phenomena include the annual coral spawning, migrating whales, nesting turtles, and significant spawning aggregations of many fish species.
Criterion (viii): The GBR, extending 2,000 kilometres along Queensland's coast, is a globally outstanding example of an ecosystem that has evolved over millennia. The area has been exposed and flooded by at least four glacial and interglacial cycles, and over the past 15,000 years reefs have grown on the continental shelf.
During glacial periods, sea levels dropped, exposing the reefs as flat-topped hills of eroded limestone. Large rivers meandered between these hills and the coastline extended further east. During interglacial periods, rising sea levels caused the formation of continental islands, coral cays and new phases of coral growth. This environmental history can be seen in cores of old massive corals.
Today the GBR forms the world's largest coral reef ecosystem, ranging from inshore fringing reefs to mid-shelf reefs, and exposed outer reefs, including examples of all stages of reef development. The processes of geological and geomorphological evolution are well represented, linking continental islands, coral cays and reefs. The varied seascapes and landscapes that occur today have been moulded by changing climates and sea levels, and the erosive power of wind and water, over long time periods.
One-third of the GBR lies beyond the seaward edge of the shallower reefs; this area comprises continental slope and deep oceanic waters and abyssal plains.
Criterion (ix): The globally significant diversity of reef and island morphologies reflects ongoing geomorphic, oceanographic and environmental processes. The complex cross-shelf, longshore and vertical connectivity is influenced by dynamic oceanic currents and ongoing ecological processes such as upwellings, larval dispersal and migration.
Ongoing erosion and accretion of coral reefs, sand banks and coral cays combine with similar processes along the coast and around continental islands. Extensive beds of Halimeda algae represent active calcification and accretion over thousands of years.
Biologically the unique diversity of the GBR reflects the maturity of an ecosystem that has evolved over millennia; evidence exists for the evolution of hard corals and other fauna. Globally significant marine faunal groups include over 4,000 species of molluscs, over 1,500 species of fish, plus a great diversity of sponges, anemones, marine worms, crustaceans, and many others. The establishment of vegetation on the cays and continental islands exemplifies the important role of birds, such as the Pied Imperial Pigeon, in processes such as seed dispersal and plant colonisation.
Human interaction with the natural environment is illustrated by strong ongoing links between Aboriginal and Torres Strait Islanders and their sea-country, and includes numerous shell deposits (middens) and fish traps, plus the application of story places and marine totems.
Criterion (x): The enormous size and diversity of the GBR means it is one of the richest and most complex natural ecosystems on earth, and one of the most significant for biodiversity conservation. The amazing diversity supports tens of thousands of marine and terrestrial species, many of which are of global conservation significance.
As the world's most complex expanse of coral reefs, the reefs contain some 400 species of corals in 60 genera. There are also large ecologically important inter-reefal areas. The shallower marine areas support half the world's diversity of mangroves and many seagrass species. The waters also provide major feeding grounds for one of the world's largest populations of the threatened dugong. At least 30 species of whales and dolphins occur here, and it is a significant area for humpback whale calving.
Six of the world's seven species of marine turtle occur in the GBR. As well as the world's largest green turtle breeding site at Raine Island, the GBR also includes many regionally important marine turtle rookeries.
Some 242 species of birds have been recorded in the GBR. Twenty-two seabird species breed on cays and some continental islands, and some of these breeding sites are globally significant; other seabird species also utilize the area. The continental islands support thousands of plant species, while the coral cays also have their own distinct flora and fauna.
Integrity
The ecological integrity of the GBR is enhanced by the unparalleled size and current good state of conservation across the property. At the time of inscription it was felt that to include virtually the entire Great Barrier Reef within the property was the only way to ensure the integrity of the coral reef ecosystems in all their diversity.
A number of natural pressures occur, including cyclones, crown-of-thorns starfish outbreaks, and sudden large influxes of freshwater from extreme weather events. As well there is a range of human uses such as tourism, shipping and coastal developments including ports. There are also some disturbances facing the GBR that are legacies of past actions prior to the inscription of the property on the World Heritage list.
At the scale of the GBR ecosystem, most habitats or species groups have the capacity to recover from disturbance or withstand ongoing pressures. The property is largely intact and includes the fullest possible representation of marine ecological, physical and chemical processes from the coast to the deep abyssal waters enabling the key interdependent elements to exist in their natural relationships.
Some of the key ecological, physical and chemical processes that are essential for the long-term conservation of the marine and island ecosystems and their associated biodiversity occur outside the boundaries of the property and thus effective conservation programs are essential across the adjoining catchments, marine and coastal zones.
Protection and management requirements
The GBR covers approximately 348,000 square kilometres.  Most of the property lies within the GBR Marine Park: at 344,400 square kilometres, this Federal Marine Park comprises approximately 99% of the property. The GBR Marine Park's legal jurisdiction ends at low water mark along the mainland (with the exception of port areas) and around islands (with the exception of 70 Commonwealth managed islands which are part of the Marine Park).  In addition the GBR also includes over 900 islands within the jurisdiction of Queensland, about half of which are declared as 'national parks', and the internal waters of Queensland that occur within the World Heritage boundary (including a number of long-established port areas).
The World Heritage property is and has always been managed as a multiple-use area.  Uses include a range of commercial and recreational activities. The management of such a large and iconic world heritage property is made more complex due to the overlapping State and Federal jurisdictions. The Great Barrier Reef Marine Park Authority, an independent Australian Government agency, is responsible for protection and management of the GBR Marine Park.  The Great Barrier Reef Marine Park Act 1975 was amended in 2007 and 2008, and now provides for "the long term protection and conservation ... of the Great Barrier Reef Region" with specific mention of meeting "... Australia's responsibilities under the World Heritage Convention".
Queensland is responsible for management of the Great Barrier Reef Coast Marine Park, established under the Marine Parks Act 2004 (Qld). This is contiguous with the GBR Marine Park and covers the area between low and high water marks and many of the waters within the jurisdictional limits of Queensland. Queensland is also responsible for management of most of the islands.
The overlapping jurisdictional arrangements mean that the importance of complementary legislation and complementary management of islands and the surrounding waters is well recognised by both governments. Strong cooperative partnerships and formal agreements exist between the Australian Government and the Queensland Government. In addition, strong relationships have been built between governments and commercial and recreational industries, research institutions and universities. Collectively this provides a comprehensive management influence over a much wider context than just the marine areas and islands.
Development and land use activities in coastal and water catchments adjacent to the property also have a fundamental and critical influence on the values within the property.  The Queensland Government is responsible for natural resource management and land use planning for the islands, coast and hinterland adjacent to the GBR. Other Queensland and Federal legislation also protects the property's Outstanding Universal Value addressing such matters as water quality, shipping management, sea dumping, fisheries management and environmental protection.
The Federal Environment Protection and Biodiversity Conservation Act 1999 (EPBC Act) provides an overarching mechanism for protecting the World Heritage values from inappropriate development, including actions taken inside or outside which could impact on its heritage values. This requires any development proposals to undergo rigorous environmental impact assessment processes, often including public consultation, after which the Federal Minister may decide, to approve, reject or approve under conditions designed to mitigate any significant impacts. A recent amendment to the EPBC Act makes the GBR Marine Park an additional 'trigger' for a matter of National Environmental Significance which provides additional protection for the values within the GBR.
The GBR Marine Park and the adjoining GBR Coast Marine Park are zoned to allow for a wide range of reasonable uses while ensuring overall protection, with conservation being the primary aim. The zoning spectrum provides for increasing levels of protection for the 'core conservation areas' which comprise the 115,000 square kilometres of 'no-take' and 'no-entry' zones within the GBR.
While the Zoning Plan is the 'cornerstone' of management and provides a spatial basis for determining where many activities can occur, zoning is only one of many spatial management tools and policies applied to collectively protect the GBR. Some activities are better managed using other spatial and temporal management tools like Plans of Management, Special Management Areas, Agreements with Traditional Owners and permits (often tied to specific zones or smaller areas within zones, but providing a detailed level of management not possible by zoning alone). These statutory instruments also protect the Outstanding Universal Value of the property.
Many Aboriginal and Torres Strait Island peoples undertake traditional use of marine resource activities to provide traditional food, practice their living maritime culture, and to educate younger generations about traditional and cultural rules and protocols.  In the GBR these activities are managed under both Federal and Queensland legislation and policies including Traditional Use of Marine Resource Agreements (TUMRAs) and Indigenous Land Use Agreements (ILUAs).  These currently cover some 30 per cent of the GBR inshore area, and support Traditional Owners to maintain cultural connections with their sea country.
Similarly non-statutory tools like site management and Industry Codes of Practice contribute to the protection of World Heritage values. Some spatial management tools are not permanently in place nor appear as part of the zoning, yet achieve effective protection for elements of biodiversity (e.g. the temporal closures that are legislated across the GBR prohibit all reef fishing during specific moon phases when reef fish are spawning).
Other key initiatives providing increased protection for the GBR include thecomprehensive Great Barrier Reef Outlook Report (and its resulting 5-yearly reporting process); the Reef Water Quality Protection Plan; the GBR Climate Change Action Plan; and the Reef Guardians Stewardship Programs which involve building relationships and working closely with those who use and rely on the GBR or its catchment for their recreation or their business.
The 2009 Outlook Report identified the long-term challenges facing the GBR; these are dominated by climate change over the next few decades. The extent and persistence of damage to the GBR ecosystem will depend to a large degree on the amount of change in the world's climate and on the resilience of the GBR ecosystem to such change. This report also identified continued declining water quality from land-based sources, loss of coastal habitats from coastal development, and some impacts from fishing, illegal fishing and poaching as the other priority issues requiring management attention for the long-term protection of the GBR.
Emerging issues since the 2009 Outlook Report include proposed port expansions, increases in shipping activity, coastal development and intensification and changes in land use within the GBR catchment; population growth; the impacts from marine debris; illegal activities; and extreme weather events including floods and cyclones.
Further building the resilience of the GBR by improving water quality, reducing the loss of coastal habitats and increasing knowledge about fishing and its effects and encouraging modified practices, will give the GBR its best chance of adapting to and recovering from the threats ahead, including the impacts of a changing climate.
</textarea>

T=7s

Slide the Bottom-Right-Square to read info in the Text Box        &copy R.S.

Go To Wikipedia Page For More ...

<button id="id4">CONTACT</button>

Dated 9/12/16.


text:
SELECT b.id,
       b.kind,
       concurrency,
       duration,
       b.created_at,
       b.updated_at,
       SUM(CASE
             WHEN success THEN 1
             ELSE 0
           END)     AS success,
       SUM(retries) AS retry,
       SUM(CASE
             WHEN success THEN 0
             ELSE 1
           END)     AS fail,
       SUM(CASE
             WHEN service = 'Msw' THEN retries
             ELSE 0
           END)     AS msw_retry,
       SUM(CASE
             WHEN success = FALSE
                  AND service = 'Msw' THEN 1
             ELSE 0
           END)     AS msw_fail,
       SUM(CASE
             WHEN service IN ( 'SurflineLola', 'SurflineNearshore' ) THEN
             retries
             ELSE 0
           END)     AS surfline_v1_retry,
       SUM(CASE
             WHEN success = FALSE
                  AND service IN ( 'SurflineLola', 'SurflineNearshore' ) THEN 1
             ELSE 0
           END)     AS surfline_v1_fail,
       SUM(CASE
             WHEN service = 'SurflineV2' THEN retries
             ELSE 0
           END)     AS surfline_v2_retry,
       SUM(CASE
             WHEN success = FALSE
                  AND service = 'SurflineV2' THEN 1
             ELSE 0
           END)     AS surfline_v2_fail,
       SUM(CASE
             WHEN service = 'SpitcastV1' THEN retries
             ELSE 0
           END)     AS spitcast_v1_retry,
       SUM(CASE
             WHEN success = FALSE
                  AND service = 'SpitcastV1' THEN 1
             ELSE 0
           END)     AS spitcast_v1_fail,
       SUM(CASE
             WHEN service = 'SpitcastV2' THEN retries
             ELSE 0
           END)     AS spitcast_v2_retry,
       SUM(CASE
             WHEN success = FALSE
                  AND service = 'SpitcastV2' THEN 1
             ELSE 0
           END)     AS spitcast_v2_fail
FROM   api_requests r
       join update_batches b
         ON r.batch_id = b.id
GROUP  BY b.id,
          b.kind,
          b.created_at,
          b.updated_at,
          concurrency,
          duration

redpajama_set_name: RedPajamaGithub


text:
package jetbrains.buildServer.nuget.server;

import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.serverSide.RunType;
import jetbrains.buildServer.serverSide.RunTypeRegistry;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created Eugene Petrenko (eugene.petrenko@gmail.com)
 * date: 28.04.11
 */
public class NuGetPublishRunType extends RunType {
  private final PluginDescriptor myPluginDescriptor;

  public NuGetPublishRunType(@NotNull final PluginDescriptor pluginDescriptor,
                             @NotNull final RunTypeRegistry registry) {
    myPluginDescriptor = pluginDescriptor;
    registry.registerRunType(this);
  }

  @Override
  public String getEditRunnerParamsJspFilePath() {
    return myPluginDescriptor.getPluginResourcesPath("editNuGet.jsp");
  }

  @Override
  public String getViewRunnerParamsJspFilePath() {
    return null;
  }

  @NotNull
  @Override
  public String getType() {
    return "NuGet";
  }

  @NotNull
  @Override
  public String getDisplayName() {
    return "NuGet Package";
  }

  @NotNull
  @Override
  public String getDescription() {
    return "Generates NuGet package from a given package specification (.nuspec) file";
  }

  @Override
  public PropertiesProcessor getRunnerPropertiesProcessor() {
    return null;
  }

  @Override
  public Map<String, String> getDefaultRunnerProperties() {
    return null;
  }

  @NotNull
  public Set<String> getTags() {
    return new HashSet<>(Arrays.asList(".NET", "NuGet"));
  }

  @Nullable
  @Override
  public String getIconUrl() {
    return myPluginDescriptor.getPluginResourcesPath("nuget-runner.svg");
  }
}


text:
package master.flame.danmaku.danmaku.model.android;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.Danmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;

public class Danmakus implements IDanmakus {

    public Collection<BaseDanmaku> items;

    private Danmakus subItems;

    private BaseDanmaku startItem, endItem;

    private BaseDanmaku endSubItem;

    private BaseDanmaku startSubItem;

    private volatile AtomicInteger mSize = new AtomicInteger(0);

    private int mSortType = ST_BY_TIME;

    private BaseComparator mComparator;

    private boolean mDuplicateMergingEnabled;
    private Object mLockObject = new Object();

    public Danmakus() {
        this(ST_BY_TIME, false);
    }

    public Danmakus(int sortType) {
        this(sortType, false);
    }

    public Danmakus(int sortType, boolean duplicateMergingEnabled) {
        this(sortType, duplicateMergingEnabled, null);
    }

    public Danmakus(int sortType, boolean duplicateMergingEnabled, BaseComparator baseComparator) {
        BaseComparator comparator = null;
        if (sortType == ST_BY_TIME) {
            comparator = baseComparator == null ? new TimeComparator(duplicateMergingEnabled) : baseComparator;
        } else if (sortType == ST_BY_YPOS) {
            comparator = new YPosComparator(duplicateMergingEnabled);
        } else if (sortType == ST_BY_YPOS_DESC) {
            comparator = new YPosDescComparator(duplicateMergingEnabled);
        }
        if (sortType == ST_BY_LIST) {
            items = new LinkedList<>();
        } else {
            mDuplicateMergingEnabled = duplicateMergingEnabled;
            comparator.setDuplicateMergingEnabled(duplicateMergingEnabled);
            items = new TreeSet<>(comparator);
            mComparator = comparator;
        }
        mSortType = sortType;
        mSize.set(0);
    }

    public Danmakus(Collection<BaseDanmaku> items) {
        setItems(items);
    }

    public Danmakus(boolean duplicateMergingEnabled) {
        this(ST_BY_TIME, duplicateMergingEnabled);
    }

    public void setItems(Collection<BaseDanmaku> items) {
        if (mDuplicateMergingEnabled && mSortType != ST_BY_LIST) {
            synchronized (this.mLockObject) {
                this.items.clear();
                this.items.addAll(items);
                items = this.items;
            }
        } else {
            this.items = items;
        }
        if (items instanceof List) {
            mSortType = ST_BY_LIST;
        }
        mSize.set(items == null ? 0 : items.size());
    }

    @Override
    public boolean addItem(BaseDanmaku item) {
        synchronized (this.mLockObject) {
            if (items != null) {
                try {
                    if (items.add(item)) {
                        mSize.incrementAndGet();
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public boolean removeItem(BaseDanmaku item) {
        if (item == null) {
            return false;
        }
        if (item.isOutside()) {
            item.setVisibility(false);
        }
        synchronized (this.mLockObject) {
            if (items.remove(item)) {
                mSize.decrementAndGet();
                return true;
            }
        }
        return false;
    }

    private Collection<BaseDanmaku> subset(long startTime, long endTime) {
        if (mSortType == ST_BY_LIST || items == null || items.size() == 0) {
            return null;
        }
        if (subItems == null) {
            subItems = new Danmakus(mDuplicateMergingEnabled);
            subItems.mLockObject = this.mLockObject;
        }
        if (startSubItem == null) {
            startSubItem = createItem("start");
        }
        if (endSubItem == null) {
            endSubItem = createItem("end");
        }

        startSubItem.setTime(startTime);
        endSubItem.setTime(endTime);
        return ((SortedSet<BaseDanmaku>) items).subSet(startSubItem, endSubItem);
    }

    @Override
    public IDanmakus subnew(long startTime, long endTime) {
        Collection<BaseDanmaku> subset = subset(startTime, endTime);
        if (subset == null || subset.isEmpty()) {
            return null;
        }
        LinkedList<BaseDanmaku> newSet = new LinkedList<BaseDanmaku>(subset);
        return new Danmakus(newSet);
    }

    @Override
    public IDanmakus sub(long startTime, long endTime) {
        if (items == null || items.size() == 0) {
            return null;
        }
        if (subItems == null) {
            if(mSortType == ST_BY_LIST) {
                subItems = new Danmakus(Danmakus.ST_BY_LIST);
                subItems.mLockObject = this.mLockObject;
                synchronized (this.mLockObject) {
                    subItems.setItems(items);
                }
            } else {
                subItems = new Danmakus(mDuplicateMergingEnabled);
                subItems.mLockObject = this.mLockObject;
            }
        }
        if (mSortType == ST_BY_LIST) {
            return subItems;
        }
        if (startItem == null) {
            startItem = createItem("start");
        }
        if (endItem == null) {
            endItem = createItem("end");
        }

        if (subItems != null) {
            long dtime = startTime - startItem.getActualTime();
            if (dtime >= 0 && endTime <= endItem.getActualTime()) {
                return subItems;
            }
        }

        startItem.setTime(startTime);
        endItem.setTime(endTime);
        synchronized (this.mLockObject) {
            subItems.setItems(((SortedSet<BaseDanmaku>) items).subSet(startItem, endItem));
        }
        return subItems;
    }

    private BaseDanmaku createItem(String text) {
        return new Danmaku(text);
    }

    public int size() {
        return mSize.get();
    }

    @Override
    public void clear() {
        synchronized (this.mLockObject) {
            if (items != null) {
                items.clear();
                mSize.set(0);
            }
        }
        if (subItems != null) {
            subItems = null;
            startItem = createItem("start");
            endItem = createItem("end");
        }
    }

    @Override
    public BaseDanmaku first() {
        if (items != null && !items.isEmpty()) {
            if (mSortType == ST_BY_LIST) {
                return ((LinkedList<BaseDanmaku>) items).peek();
            }
            return ((SortedSet<BaseDanmaku>) items).first();
        }
        return null;
    }

    @Override
    public BaseDanmaku last() {
        if (items != null && !items.isEmpty()) {
            if (mSortType == ST_BY_LIST) {
                return ((LinkedList<BaseDanmaku>) items).peekLast();
            }
            return ((SortedSet<BaseDanmaku>) items).last();
        }
        return null;
    }

    @Override
    public boolean contains(BaseDanmaku item) {
        return this.items != null && this.items.contains(item);
    }

    @Override
    public boolean isEmpty() {
        return this.items == null || this.items.isEmpty();
    }

    private void setDuplicateMergingEnabled(boolean enable) {
        mComparator.setDuplicateMergingEnabled(enable);
        mDuplicateMergingEnabled = enable;
    }

    @Override
    public void setSubItemsDuplicateMergingEnabled(boolean enable) {
        mDuplicateMergingEnabled = enable;
        startItem = endItem = null;
        if (subItems == null) {
            subItems = new Danmakus(enable);
            subItems.mLockObject = this.mLockObject;
        }
        subItems.setDuplicateMergingEnabled(enable);
    }

    @Override
    public Collection<BaseDanmaku> getCollection() {
        return this.items;
    }

    @Override
    public void forEachSync(Consumer<? super BaseDanmaku, ?> consumer) {
        synchronized (this.mLockObject) {
            forEach(consumer);
        }
    }

    @Override
    public void forEach(Consumer<? super BaseDanmaku, ?> consumer) {
        consumer.before();
        Iterator<BaseDanmaku> it = items.iterator();
        while (it.hasNext()) {
            BaseDanmaku next = it.next();
            if (next == null) {
                continue;
            }
            int action = consumer.accept(next);
            if (action == DefaultConsumer.ACTION_BREAK) {
                break;
            } else if (action == DefaultConsumer.ACTION_REMOVE) {
                it.remove();
                mSize.decrementAndGet();
            } else if (action == DefaultConsumer.ACTION_REMOVE_AND_BREAK) {
                it.remove();
                mSize.decrementAndGet();
                break;
            }
        }
        consumer.after();
    }

    @Override
    public Object obtainSynchronizer() {
        return mLockObject;
    }

}


text:
package com.lidroid.xutils.view.annotation.event;

import android.widget.AdapterView;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Author: wyouflf
 * Date: 13-8-16
 * Time: 下午2:32
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(
        listenerType = AdapterView.OnItemClickListener.class,
        listenerSetter = "setOnItemClickListener",
        methodName = "onItemClick")
public @interface OnItemClick {
    int[] value();

    int[] parentId() default 0;
}


text:
"""Helpers for automation integration."""
from homeassistant.components.blueprint import DomainBlueprints
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.singleton import singleton

from .const import DOMAIN, LOGGER

DATA_BLUEPRINTS = "script_blueprints"

def _blueprint_in_use(hass: HomeAssistant, blueprint_path: str) -> bool:
    """Return True if any script references the blueprint."""
    from . import scripts_with_blueprint  # pylint: disable=import-outside-toplevel

    return len(scripts_with_blueprint(hass, blueprint_path)) > 0

@singleton(DATA_BLUEPRINTS)
@callback
def async_get_blueprints(hass: HomeAssistant) -> DomainBlueprints:
    """Get script blueprints."""
    return DomainBlueprints(hass, DOMAIN, LOGGER, _blueprint_in_use)


text:
import { race as raceObs } from 'rxjs'
import { filter as filterObs, mapTo } from 'rxjs/operators'
import { fromVueEvent as obsFromVueEvent, fromVueWatcher as obsFromVueWatcher } from '../rx-ext'
import { hasAncestorVm, hasProp, stubTrue, waitFor } from '../utils'
import olCmp, { CanceledError, isCreateError, OlObjectEvent } from './ol-cmp'

export default {
  methods: {
    async beforeInit () {
      try {
        await waitFor(
          () => this.$mapVm != null,
          raceObs(
            this.$olObjectEvents.pipe(
              filterObs(({ name, args }) => {
                return name === OlObjectEvent.ERROR &&
                  args[0] instanceof CanceledError
              }),
            ),
            obsFromVueEvent(this.$eventBus, OlObjectEvent.ERROR).pipe(
              filterObs(([err, vm]) => {
                return isCreateError(err) &&
                  hasProp(vm, '$map') &&
                  hasAncestorVm(this, vm)
              }),
            ),
          ).pipe(
            mapTo(stubTrue()),
          ),
        )
        if (this.$mapVm.resolvedViewProjection !== this.viewProjection) {
          this.viewProjection = this.$mapVm.resolvedViewProjection
        }
        if (this.$mapVm.resolvedDataProjection !== this.dataProjection) {
          this.dataProjection = this.$mapVm.resolvedDataProjection
        }
        this.subscribeTo(
          obsFromVueWatcher(this, () => this.$mapVm.resolvedViewProjection),
          ({ value }) => {
            if (value !== this.viewProjection) {
              this.viewProjection = value
            }
          },
        )
        this.subscribeTo(
          obsFromVueWatcher(this, () => this.$mapVm.resolvedDataProjection),
          ({ value }) => {
            if (value !== this.dataProjection) {
              this.dataProjection = value
            }
          },
        )
        await this.$nextTickPromise()

        return this::olCmp.methods.beforeInit()
      } catch (err) {
        err.message = `${this.vmName} wait for $mapVm injection: ${err.message}`
        throw err
      }
    },
  },
}


text:
import {
  permissionLookup,
  makePermissionsBlob,
  getRoleForPermissions,
} from 'lib/permissions/thread-permissions';
import { relationshipBlockedInEitherDirection } from 'lib/shared/relationship-utils';
import {
  threadFrozenDueToBlock,
  permissionsDisabledByBlock,
} from 'lib/shared/thread-utils';
import { userRelationshipStatus } from 'lib/types/relationship-types';
import type {
  ThreadType,
  ThreadPermission,
  ThreadPermissionsBlob,
  ThreadRolePermissionsBlob,
} from 'lib/types/thread-types';

import { dbQuery, SQL } from '../database/database';
import type { Viewer } from '../session/viewer';
import { fetchThreadInfos } from './thread-fetchers';
import { fetchKnownUserInfos } from './user-fetchers';

// Note that it's risky to verify permissions by inspecting the blob directly.
// There are other factors that can override permissions in the permissions
// blob, such as when one user blocks another. It's always better to go through
// checkThreads and friends, or by looking at the ThreadInfo through
// threadHasPermission.
async function fetchThreadPermissionsBlob(
  viewer: Viewer,
  threadID: string,
): Promise<?ThreadPermissionsBlob> {
  const viewerID = viewer.id;
  const query = SQL`
    SELECT permissions
    FROM memberships
    WHERE thread = ${threadID} AND user = ${viewerID}
  `;
  const [result] = await dbQuery(query);

  if (result.length === 0) {
    return null;
  }
  const row = result[0];
  return row.permissions;
}

function checkThreadPermission(
  viewer: Viewer,
  threadID: string,
  permission: ThreadPermission,
): Promise<boolean> {
  return checkThread(viewer, threadID, [{ check: 'permission', permission }]);
}

function viewerIsMember(viewer: Viewer, threadID: string): Promise<boolean> {
  return checkThread(viewer, threadID, [{ check: 'is_member' }]);
}

type Check =
  | { +check: 'is_member' }
  | { +check: 'permission', +permission: ThreadPermission };

function isThreadValid(
  permissions: ?ThreadPermissionsBlob,
  role: number,
  checks: $ReadOnlyArray<Check>,
): boolean {
  for (const check of checks) {
    if (check.check === 'is_member') {
      if (role <= 0) {
        return false;
      }
    } else if (check.check === 'permission') {
      if (!permissionLookup(permissions, check.permission)) {
        return false;
      }
    }
  }
  return true;
}

async function checkThreads(
  viewer: Viewer,
  threadIDs: $ReadOnlyArray<string>,
  checks: $ReadOnlyArray<Check>,
): Promise<Set<string>> {
  if (viewer.isScriptViewer) {
    // script viewers are all-powerful
    return new Set(threadIDs);
  }

  const threadRows = await getValidThreads(viewer, threadIDs, checks);
  return new Set(threadRows.map(row => row.threadID));
}

type PartialMembershipRow = {
  +threadID: string,
  +role: number,
  +permissions: ThreadPermissionsBlob,
};
async function getValidThreads(
  viewer: Viewer,
  threadIDs: $ReadOnlyArray<string>,
  checks: $ReadOnlyArray<Check>,
): Promise<PartialMembershipRow[]> {
  const query = SQL`
    SELECT thread AS threadID, permissions, role
    FROM memberships
    WHERE thread IN (${threadIDs}) AND user = ${viewer.userID}
  `;

  const permissionsToCheck = [];
  for (const check of checks) {
    if (check.check === 'permission') {
      permissionsToCheck.push(check.permission);
    }
  }

  const [[result], disabledThreadIDs] = await Promise.all([
    dbQuery(query),
    checkThreadsFrozen(viewer, permissionsToCheck, threadIDs),
  ]);

  return result
    .map(row => ({ ...row, threadID: row.threadID.toString() }))
    .filter(
      row =>
        isThreadValid(row.permissions, row.role, checks) &&
        !disabledThreadIDs.has(row.threadID),
    );
}

async function checkThreadsFrozen(
  viewer: Viewer,
  permissionsToCheck: $ReadOnlyArray<ThreadPermission>,
  threadIDs: $ReadOnlyArray<string>,
) {
  const threadIDsWithDisabledPermissions = new Set();

  const permissionMightBeDisabled = permissionsToCheck.some(permission =>
    permissionsDisabledByBlock.has(permission),
  );
  if (!permissionMightBeDisabled) {
    return threadIDsWithDisabledPermissions;
  }

  const [{ threadInfos }, userInfos] = await Promise.all([
    fetchThreadInfos(viewer, SQL`t.id IN (${[...threadIDs]})`),
    fetchKnownUserInfos(viewer),
  ]);

  for (const threadID in threadInfos) {
    const blockedThread = threadFrozenDueToBlock(
      threadInfos[threadID],
      viewer.id,
      userInfos,
    );
    if (blockedThread) {
      threadIDsWithDisabledPermissions.add(threadID);
    }
  }
  return threadIDsWithDisabledPermissions;
}

async function checkIfThreadIsBlocked(
  viewer: Viewer,
  threadID: string,
  permission: ThreadPermission,
): Promise<boolean> {
  const disabledThreadIDs = await checkThreadsFrozen(
    viewer,
    [permission],
    [threadID],
  );

  return disabledThreadIDs.has(threadID);
}

async function checkThread(
  viewer: Viewer,
  threadID: string,
  checks: $ReadOnlyArray<Check>,
): Promise<boolean> {
  const validThreads = await checkThreads(viewer, [threadID], checks);
  return validThreads.has(threadID);
}

// We pass this into getRoleForPermissions in order to check if a hypothetical
// permissions blob would block membership by returning a non-positive result.
// It doesn't matter what value we pass in, as long as it's positive.
const arbitraryPositiveRole = '1';

type CandidateMembers = {
  +[key: string]: ?$ReadOnlyArray<string>,
  ...
};
type ValidateCandidateMembersParams = {
  +threadType: ThreadType,
  +parentThreadID: ?string,
  +containingThreadID: ?string,
  +defaultRolePermissions: ThreadRolePermissionsBlob,
};
type ValidateCandidateMembersOptions = { +requireRelationship?: boolean };
async function validateCandidateMembers(
  viewer: Viewer,
  candidates: CandidateMembers,
  params: ValidateCandidateMembersParams,
  options?: ValidateCandidateMembersOptions,
): Promise<CandidateMembers> {
  const requireRelationship = options?.requireRelationship ?? true;

  const allCandidatesSet = new Set();
  for (const key in candidates) {
    const candidateGroup = candidates[key];
    if (!candidateGroup) {
      continue;
    }
    for (const candidate of candidateGroup) {
      allCandidatesSet.add(candidate);
    }
  }
  const allCandidates = [...allCandidatesSet];

  const fetchMembersPromise = fetchKnownUserInfos(viewer, allCandidates);

  const parentPermissionsPromise = (async () => {
    const parentPermissions = {};
    if (!params.parentThreadID || allCandidates.length === 0) {
      return parentPermissions;
    }
    const parentPermissionsQuery = SQL`
      SELECT user, permissions
      FROM memberships
      WHERE thread = ${params.parentThreadID} AND user IN (${allCandidates})
    `;
    const [result] = await dbQuery(parentPermissionsQuery);
    for (const row of result) {
      parentPermissions[row.user.toString()] = row.permissions;
    }
    return parentPermissions;
  })();

  const memberOfContainingThreadPromise = (async () => {
    const results = {};
    if (allCandidates.length === 0) {
      return results;
    }
    if (!params.containingThreadID) {
      for (const userID of allCandidates) {
        results[userID] = true;
      }
      return results;
    }
    const memberOfContainingThreadQuery = SQL`
      SELECT user, role AS containing_role
      FROM memberships
      WHERE thread = ${params.containingThreadID} AND user IN (${allCandidates})
    `;
    const [result] = await dbQuery(memberOfContainingThreadQuery);
    for (const row of result) {
      results[row.user.toString()] = row.containing_role > 0;
    }
    return results;
  })();

  const [
    fetchedMembers,
    parentPermissions,
    memberOfContainingThread,
  ] = await Promise.all([
    fetchMembersPromise,
    parentPermissionsPromise,
    memberOfContainingThreadPromise,
  ]);

  const ignoreMembers = new Set();
  for (const memberID of allCandidates) {
    const member = fetchedMembers[memberID];
    if (!member && requireRelationship) {
      ignoreMembers.add(memberID);
      continue;
    }
    const relationshipStatus = member?.relationshipStatus;
    const memberRelationshipHasBlock = !!(
      relationshipStatus &&
      relationshipBlockedInEitherDirection(relationshipStatus)
    );
    if (memberRelationshipHasBlock) {
      ignoreMembers.add(memberID);
      continue;
    }
    const permissionsFromParent = parentPermissions[memberID];
    if (
      relationshipStatus !== userRelationshipStatus.FRIEND &&
      !permissionsFromParent &&
      requireRelationship
    ) {
      ignoreMembers.add(memberID);
      continue;
    }
    if (!memberOfContainingThread[memberID]) {
      ignoreMembers.add(memberID);
      continue;
    }
    const permissions = makePermissionsBlob(
      params.defaultRolePermissions,
      permissionsFromParent,
      '-1',
      params.threadType,
    );
    if (!permissions) {
      ignoreMembers.add(memberID);
      continue;
    }
    const targetRole = getRoleForPermissions(
      arbitraryPositiveRole,
      permissions,
    );
    if (Number(targetRole) <= 0) {
      ignoreMembers.add(memberID);
      continue;
    }
  }
  if (ignoreMembers.size === 0) {
    return candidates;
  }

  const result = {};
  for (const key in candidates) {
    const candidateGroup = candidates[key];
    if (!candidateGroup) {
      result[key] = candidates[key];
      continue;
    }
    result[key] = [];
    for (const candidate of candidateGroup) {
      if (!ignoreMembers.has(candidate)) {
        result[key].push(candidate);
      }
    }
  }
  return result;
}

export {
  fetchThreadPermissionsBlob,
  checkThreadPermission,
  viewerIsMember,
  checkThreads,
  getValidThreads,
  checkThread,
  checkIfThreadIsBlocked,
  validateCandidateMembers,
};


text:
package org.apache.shardingsphere.example.shadow.raw.jdbc.factory;

import org.apache.shardingsphere.example.shadow.raw.jdbc.config.ShadowConfiguration;
import org.apache.shardingsphere.example.shadow.raw.jdbc.config.ShadowDefaultAlgorithmConfiguration;
import org.apache.shardingsphere.example.shadow.raw.jdbc.config.ShadowEncryptConfiguration;
import org.apache.shardingsphere.example.type.ShardingType;

import javax.sql.DataSource;
import java.sql.SQLException;

public final class DataSourceFactory {

    public static DataSource newInstance(final ShardingType shardingType) throws SQLException {
        switch (shardingType) {
            case SHADOW:
                return new ShadowConfiguration().getDataSource();
            case SHADOW_DEFAULT_ALGORITHM:
                return new ShadowDefaultAlgorithmConfiguration().getDataSource();
            case ENCRYPT_SHADOW:
                return new ShadowEncryptConfiguration().getDataSource();
            default:
                throw new UnsupportedOperationException(shardingType.name());
        }
    }
}


text:
.. _extending_device:

Extending device model
======================

Allows you to store additional data in the device model (e.g. foreign key to the user)

Device model
------------

In your application, you need to create your own `Device` model. This model has to inherit from `fcm.models.AbstractDevice`.

.. code-block:: python

    # import the AbstractDevice class to inherit from
    from fcm.models import AbstractDevice

    class MyDevice(AbstractDevice):
        pass

Use your model
--------------

In the end, you have to inform `django-fcm` where it can find your model.

Add appropriate path to the ``settings.py`` file:

.. code-block:: python

    FCM_DEVICE_MODEL = 'your_app.MyDevice'


text:
// Package main ...
package main

import (
	"syscall"

	pb "github.com/golanghr/platform-examples/hello/protos"
	"github.com/golanghr/platform/handlers"
	"github.com/golanghr/platform/logging"
	"github.com/golanghr/platform/managers"
	"github.com/golanghr/platform/options"
	"github.com/golanghr/platform/servers"
	"github.com/golanghr/platform/services"
	"google.golang.org/grpc"
)

// Service - tbd ...
type Service struct {

	// Options - Is a global service options
	options.Options

	// Servicer - Is a Servicer interface
	services.Servicer

	// Grpc - Here GRPC server is located.
	Grpc servers.Serverer

	// HTTP - Here HTTP server is located.
	HTTP servers.Serverer

	// Managerer - Service runtime manager. Manager actually contains start, stop
	// and all of the runtime related management handlers.
	managers.Managerer

	// Logging -
	*logging.Entry
}

// GrpcServer - Will return back actual grpc.Server
// I understand that this looks like a hack but I'd rather have it require to satisfy interface
// than having it require to satisfy nil.
func (s *Service) GrpcServer() *grpc.Server {
	return s.Grpc.Interface().(*servers.Grpc).Server
}

// Terminate - Will send SIGTERM towards service interrupt signal resulting entire
// service to go down
func (s *Service) Terminate() {
	s.GetInterruptChan() <- syscall.SIGTERM
}

// NewService -
func NewService(opts options.Options, logger *logging.Entry) (*Service, error) {

	serv, err := services.New(opts)

	if err != nil {
		return nil, err
	}

	grpcServer, err := servers.NewGrpcServer(serv, opts, logger)

	if err != nil {
		return nil, err
	}

	httpServer, err := servers.NewHTTPServer(serv, opts, logger)

	if err != nil {
		return nil, err
	}

	serviceManager, err := managers.New(serv, opts, logger)

	if err != nil {
		return nil, err
	}

	// We are about to attach GRPC service now ...
	if err := serviceManager.Attach("grpc", grpcServer); err != nil {
		return nil, err
	}

	// We are about to attach HTTP service now ...
	if err := serviceManager.Attach("http", httpServer); err != nil {
		return nil, err
	}

	sc := &Service{
		Options:   opts,
		Servicer:  serv,
		Grpc:      grpcServer,
		HTTP:      httpServer,
		Entry:     logger,
		Managerer: serviceManager,
	}

	pb.RegisterHelloServer(sc.GrpcServer(), sc)

	hander, err := handlers.NewHttpGrpcHandler(serv, logger, pb.RegisterHelloHandler)

	if err != nil {
		return nil, err
	}

	httpServer.Interface().(*servers.HTTP).Handler = hander
	return sc, nil
}


text:
package org.jbpm.services.task;

import static org.junit.Assert.*;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.jbpm.services.task.impl.factories.TaskFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.internal.task.api.InternalTaskService;
import org.kie.internal.task.api.model.InternalTask;
import org.kie.internal.utils.ChainedProperties;
import org.kie.internal.utils.ClassLoaderUtil;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;

import bitronix.tm.resource.jdbc.PoolingDataSource;

public class TaskReminderTest extends HumanTaskServicesBaseTest {

    private PoolingDataSource pds;
    private EntityManagerFactory emf;
    private Wiser wiser;

    @Before
    public void setup() {
        final ChainedProperties props =
                new ChainedProperties("email.conf", ClassLoaderUtil.getClassLoader(null, getClass(), false));

        wiser = new Wiser();
        wiser.setHostname(props.getProperty("mail.smtp.host", "localhost"));
        wiser.setPort(Integer.parseInt(props.getProperty("mail.smtp.port", "2345")));
        wiser.start();
        try {
            Thread.sleep(1000);
        } catch (Throwable t) {
            // Do nothing
        }

        pds = setupPoolingDataSource();
        emf = Persistence.createEntityManagerFactory("org.jbpm.services.task");
        this.taskService = (InternalTaskService) HumanTaskServiceFactory.newTaskServiceConfigurator()
                .entityManagerFactory(emf)
                .getTaskService();
    }

    @After
    public void clean() {
        if (wiser != null) {
            wiser.stop();
            try {
                Thread.sleep(1000);
            } catch (Throwable t) {
                // Do nothing
            }
        }
        super.tearDown();
        if (emf != null) {
            emf.close();
        }
        if (pds != null) {
            pds.close();
        }
    }

    @Test
    public void testTaskReminderWithoutNotification() throws Exception {
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("now", new Date());

        Reader reader = new InputStreamReader(getClass().getResourceAsStream(MvelFilePath.ReminderWithoutNotification));
        InternalTask task = (InternalTask) TaskFactory.evalTask(reader, vars);
        System.out.println("testTaskReminderWithoutNotification " + task.getTaskData().getStatus());

        assertNull(task.getDeadlines());

        long taskId = taskService.addTask(task, new HashMap<String, Object>());

        taskService.executeReminderForTask(taskId, "Luke Cage");
        Thread.sleep(1000);
        assertEquals(1, wiser.getMessages().size());

        String receiver = wiser.getMessages().get(0).getEnvelopeReceiver();
        assertEquals("tony@domain.com", receiver);
        MimeMessage msg = ((WiserMessage) wiser.getMessages().get(0)).getMimeMessage();
        assertEquals("You have a task ( Simple Test Task ) of process ( taskReminder )",
                msg.getSubject());

    }

    @Test
    public void testTaskReminderWithNotificationByTaskNostarted() throws Exception {
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("now", new Date());

        Reader reader = new InputStreamReader(getClass().getResourceAsStream(MvelFilePath
                .ReminderWithNotificationReserved));
        InternalTask task = (InternalTask) TaskFactory.evalTask(reader, vars);
        System.out.println("testTaskReminderWithNotificationByTaskNostarted " + task.getTaskData().getStatus());

        assertEquals(1, task.getDeadlines().getEndDeadlines().size());
        assertEquals(1, task.getDeadlines().getStartDeadlines().size());

        long taskId = taskService.addTask(task, new HashMap<String, Object>());
        taskService.executeReminderForTask(taskId, "Luke Cage");

        long time = 0;
        while (wiser.getMessages().size() < 2 && time < 5000) {
            Thread.sleep(50);
            time += 50;
        }
        assertEquals(2, wiser.getMessages().size());

        final List<String> list = new ArrayList<String>(2);
        list.add(wiser.getMessages().get(0).getEnvelopeReceiver());
        list.add(wiser.getMessages().get(1).getEnvelopeReceiver());

        assertTrue(list.contains("tony@domain.com"));
        assertTrue(list.contains("darth@domain.com"));

        MimeMessage msg = ((WiserMessage) wiser.getMessages().get(0)).getMimeMessage();
        assertEquals("ReminderWithNotificationReserved:you have new task to be started", msg.getSubject());
        assertEquals("task is not started", msg.getContent());

        msg = ((WiserMessage) wiser.getMessages().get(1)).getMimeMessage();
        assertEquals("ReminderWithNotificationReserved:you have new task to be started", msg.getSubject());
        assertEquals("task is not started", msg.getContent());
    }

    @Test
    public void testTaskReminderWithNotificationByTaskNoCompleted() throws Exception {
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("now", new Date());

        Reader reader = new InputStreamReader(getClass().getResourceAsStream(MvelFilePath
                .ReminderWithNotificationInProgress));
        InternalTask task = (InternalTask) TaskFactory.evalTask(reader, vars);
        System.out.println("testTaskReminderWithNotificationByTaskNoCompleted " + task.getTaskData().getStatus());

        assertEquals(1, task.getDeadlines().getEndDeadlines().size());
        assertEquals(1, task.getDeadlines().getStartDeadlines().size());
        long taskId = taskService.addTask(task, new HashMap<String, Object>());
        taskService.executeReminderForTask(taskId, "Luke Cage");

        long time = 0;
        while (wiser.getMessages().size() < 2 && time < 5000) {
            Thread.sleep(50);
            time += 50;
        }
        assertEquals(2, wiser.getMessages().size());

        List<String> list = new ArrayList<String>(2);
        list.add(wiser.getMessages().get(0).getEnvelopeReceiver());
        list.add(wiser.getMessages().get(1).getEnvelopeReceiver());

        assertTrue(list.contains("tony@domain.com"));
        assertTrue(list.contains("darth@domain.com"));

        MimeMessage msg = ((WiserMessage) wiser.getMessages().get(0)).getMimeMessage();
        assertEquals("ReminderWithNotificationInProgress:you have new task to be completed",
                msg.getSubject());
        assertEquals("task is not completed", msg.getContent());

        msg = ((WiserMessage) wiser.getMessages().get(1)).getMimeMessage();
        assertEquals("ReminderWithNotificationInProgress:you have new task to be completed",
                msg.getSubject());
        assertEquals("task is not completed", msg.getContent());
    }
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202208;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Contains third party auto-pixeling settings for cross-sell Partners.
 *
 *
 *
Java class for ThirdPartyMeasurementSettings complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ThirdPartyMeasurementSettings">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="viewabilityPartner" type="{https://www.google.com/apis/ads/publisher/v202208}ThirdPartyViewabilityIntegrationPartner" minOccurs="0"/>
 *         <element name="viewabilityClientId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="viewabilityReportingId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="publisherViewabilityPartner" type="{https://www.google.com/apis/ads/publisher/v202208}ThirdPartyViewabilityIntegrationPartner" minOccurs="0"/>
 *         <element name="publisherViewabilityClientId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="publisherViewabilityReportingId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="brandLiftPartner" type="{https://www.google.com/apis/ads/publisher/v202208}ThirdPartyBrandLiftIntegrationPartner" minOccurs="0"/>
 *         <element name="brandLiftClientId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="brandLiftReportingId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="reachPartner" type="{https://www.google.com/apis/ads/publisher/v202208}ThirdPartyReachIntegrationPartner" minOccurs="0"/>
 *         <element name="reachClientId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="reachReportingId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="publisherReachPartner" type="{https://www.google.com/apis/ads/publisher/v202208}ThirdPartyReachIntegrationPartner" minOccurs="0"/>
 *         <element name="publisherReachClientId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="publisherReachReportingId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ThirdPartyMeasurementSettings", propOrder = {
    "viewabilityPartner",
    "viewabilityClientId",
    "viewabilityReportingId",
    "publisherViewabilityPartner",
    "publisherViewabilityClientId",
    "publisherViewabilityReportingId",
    "brandLiftPartner",
    "brandLiftClientId",
    "brandLiftReportingId",
    "reachPartner",
    "reachClientId",
    "reachReportingId",
    "publisherReachPartner",
    "publisherReachClientId",
    "publisherReachReportingId"
})
public class ThirdPartyMeasurementSettings {

    @XmlSchemaType(name = "string")
    protected ThirdPartyViewabilityIntegrationPartner viewabilityPartner;
    protected String viewabilityClientId;
    protected String viewabilityReportingId;
    @XmlSchemaType(name = "string")
    protected ThirdPartyViewabilityIntegrationPartner publisherViewabilityPartner;
    protected String publisherViewabilityClientId;
    protected String publisherViewabilityReportingId;
    @XmlSchemaType(name = "string")
    protected ThirdPartyBrandLiftIntegrationPartner brandLiftPartner;
    protected String brandLiftClientId;
    protected String brandLiftReportingId;
    @XmlSchemaType(name = "string")
    protected ThirdPartyReachIntegrationPartner reachPartner;
    protected String reachClientId;
    protected String reachReportingId;
    @XmlSchemaType(name = "string")
    protected ThirdPartyReachIntegrationPartner publisherReachPartner;
    protected String publisherReachClientId;
    protected String publisherReachReportingId;

    /**
     * Gets the value of the viewabilityPartner property.
     *
     * @return
     *     possible object is
     *     {@link ThirdPartyViewabilityIntegrationPartner }
     *
     */
    public ThirdPartyViewabilityIntegrationPartner getViewabilityPartner() {
        return viewabilityPartner;
    }

    /**
     * Sets the value of the viewabilityPartner property.
     *
     * @param value
     *     allowed object is
     *     {@link ThirdPartyViewabilityIntegrationPartner }
     *
     */
    public void setViewabilityPartner(ThirdPartyViewabilityIntegrationPartner value) {
        this.viewabilityPartner = value;
    }

    /**
     * Gets the value of the viewabilityClientId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getViewabilityClientId() {
        return viewabilityClientId;
    }

    /**
     * Sets the value of the viewabilityClientId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setViewabilityClientId(String value) {
        this.viewabilityClientId = value;
    }

    /**
     * Gets the value of the viewabilityReportingId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getViewabilityReportingId() {
        return viewabilityReportingId;
    }

    /**
     * Sets the value of the viewabilityReportingId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setViewabilityReportingId(String value) {
        this.viewabilityReportingId = value;
    }

    /**
     * Gets the value of the publisherViewabilityPartner property.
     *
     * @return
     *     possible object is
     *     {@link ThirdPartyViewabilityIntegrationPartner }
     *
     */
    public ThirdPartyViewabilityIntegrationPartner getPublisherViewabilityPartner() {
        return publisherViewabilityPartner;
    }

    /**
     * Sets the value of the publisherViewabilityPartner property.
     *
     * @param value
     *     allowed object is
     *     {@link ThirdPartyViewabilityIntegrationPartner }
     *
     */
    public void setPublisherViewabilityPartner(ThirdPartyViewabilityIntegrationPartner value) {
        this.publisherViewabilityPartner = value;
    }

    /**
     * Gets the value of the publisherViewabilityClientId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPublisherViewabilityClientId() {
        return publisherViewabilityClientId;
    }

    /**
     * Sets the value of the publisherViewabilityClientId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPublisherViewabilityClientId(String value) {
        this.publisherViewabilityClientId = value;
    }

    /**
     * Gets the value of the publisherViewabilityReportingId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPublisherViewabilityReportingId() {
        return publisherViewabilityReportingId;
    }

    /**
     * Sets the value of the publisherViewabilityReportingId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPublisherViewabilityReportingId(String value) {
        this.publisherViewabilityReportingId = value;
    }

    /**
     * Gets the value of the brandLiftPartner property.
     *
     * @return
     *     possible object is
     *     {@link ThirdPartyBrandLiftIntegrationPartner }
     *
     */
    public ThirdPartyBrandLiftIntegrationPartner getBrandLiftPartner() {
        return brandLiftPartner;
    }

    /**
     * Sets the value of the brandLiftPartner property.
     *
     * @param value
     *     allowed object is
     *     {@link ThirdPartyBrandLiftIntegrationPartner }
     *
     */
    public void setBrandLiftPartner(ThirdPartyBrandLiftIntegrationPartner value) {
        this.brandLiftPartner = value;
    }

    /**
     * Gets the value of the brandLiftClientId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBrandLiftClientId() {
        return brandLiftClientId;
    }

    /**
     * Sets the value of the brandLiftClientId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBrandLiftClientId(String value) {
        this.brandLiftClientId = value;
    }

    /**
     * Gets the value of the brandLiftReportingId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBrandLiftReportingId() {
        return brandLiftReportingId;
    }

    /**
     * Sets the value of the brandLiftReportingId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBrandLiftReportingId(String value) {
        this.brandLiftReportingId = value;
    }

    /**
     * Gets the value of the reachPartner property.
     *
     * @return
     *     possible object is
     *     {@link ThirdPartyReachIntegrationPartner }
     *
     */
    public ThirdPartyReachIntegrationPartner getReachPartner() {
        return reachPartner;
    }

    /**
     * Sets the value of the reachPartner property.
     *
     * @param value
     *     allowed object is
     *     {@link ThirdPartyReachIntegrationPartner }
     *
     */
    public void setReachPartner(ThirdPartyReachIntegrationPartner value) {
        this.reachPartner = value;
    }

    /**
     * Gets the value of the reachClientId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReachClientId() {
        return reachClientId;
    }

    /**
     * Sets the value of the reachClientId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReachClientId(String value) {
        this.reachClientId = value;
    }

    /**
     * Gets the value of the reachReportingId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReachReportingId() {
        return reachReportingId;
    }

    /**
     * Sets the value of the reachReportingId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReachReportingId(String value) {
        this.reachReportingId = value;
    }

    /**
     * Gets the value of the publisherReachPartner property.
     *
     * @return
     *     possible object is
     *     {@link ThirdPartyReachIntegrationPartner }
     *
     */
    public ThirdPartyReachIntegrationPartner getPublisherReachPartner() {
        return publisherReachPartner;
    }

    /**
     * Sets the value of the publisherReachPartner property.
     *
     * @param value
     *     allowed object is
     *     {@link ThirdPartyReachIntegrationPartner }
     *
     */
    public void setPublisherReachPartner(ThirdPartyReachIntegrationPartner value) {
        this.publisherReachPartner = value;
    }

    /**
     * Gets the value of the publisherReachClientId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPublisherReachClientId() {
        return publisherReachClientId;
    }

    /**
     * Sets the value of the publisherReachClientId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPublisherReachClientId(String value) {
        this.publisherReachClientId = value;
    }

    /**
     * Gets the value of the publisherReachReportingId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPublisherReachReportingId() {
        return publisherReachReportingId;
    }

    /**
     * Sets the value of the publisherReachReportingId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPublisherReachReportingId(String value) {
        this.publisherReachReportingId = value;
    }

}


text:
<?php

namespace TestSubject\Http\Serializers;

use Kahire\Serializers\Fields\StringField;
use Kahire\Serializers\ModelSerializer;
use TestSubject\Author;

class AuthorSerializer extends ModelSerializer
{
    protected $model = Author::class;

    protected $useTimeStamps = false;

    public function generateFields()
    {
        return [
            'name' => StringField::generate(),
        ];
    }
}


text:
package chapter14

import (
	"github.com/petar/GoLLRB/llrb"
	"sort"
)

type LineSegment struct {
	l, r, c, h int
}

func (p *LineSegment) Less(than llrb.Item) bool {
	return p.h < than.(*LineSegment).h
}

type endpoint struct {
	x      int
	seg    *LineSegment
	isLeft bool
}

type endpointList []endpoint

func (lst endpointList) Len() int           { return len(lst) }
func (lst endpointList) Less(i, j int) bool { return lst[i].x < lst[j].x }
func (lst endpointList) Swap(i, j int)      { lst[i], lst[j] = lst[j], lst[i] }

func ViewFromAbove(seq []LineSegment) []LineSegment {
	allEndpoints := make(endpointList, 0, len(seq)*2)

	for i := range seq {
		allEndpoints = append(allEndpoints, endpoint{seq[i].l, &seq[i], true}, endpoint{seq[i].r, &seq[i], false})
	}

	sort.Sort(allEndpoints)

	active := llrb.New()

	result := make([]LineSegment, 0)

	var curr, prevMax *LineSegment

	for _, p := range allEndpoints {
		if p.isLeft {
			active.ReplaceOrInsert(p.seg)
		} else {
			active.Delete(p.seg)
		}

		var max *LineSegment
		if active.Len() > 0 {
			max = active.Max().(*LineSegment)
		}

		if curr == nil {
			curr = &LineSegment{l: p.x, c: max.c, h: max.h}
		} else if max != prevMax {
			curr.r = p.x
			if curr.r != curr.l {
				result = append(result, *curr)
			}
			if max == nil {
				curr = nil
			} else {
				curr = &LineSegment{l: p.x, c: max.c, h: max.h}
			}
		}

		prevMax = max
	}

	return result
}


text:
package org.jetbrains.plugins.javaFX.fxml.refs;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.position.FilterPattern;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;

import static com.intellij.patterns.PsiJavaPatterns.literalExpression;
import static com.intellij.patterns.PsiJavaPatterns.psiMethod;

public class JavaFxReferencesContributor extends PsiReferenceContributor {
  public static final PsiJavaElementPattern.Capture<PsiLiteralExpression> STYLESHEET_PATTERN =
      literalExpression().methodCallParameter(psiMethod()).and(new FilterPattern(new ElementFilter() {
        public boolean isAcceptable(Object element, PsiElement context) {
          final PsiExpression psiExpression = getParentElement((PsiLiteralExpression)context);
          if (psiExpression != null) {
            final PsiType psiType = psiExpression.getType();
            return psiType != null && psiType.equalsToText(JavaFxCommonNames.JAVA_FX_PARENT);
          }
          return false;
        }

        public boolean isClassAcceptable(Class hintClass) {
          return true;
        }
      }));

  public static PsiExpression getParentElement(PsiLiteralExpression context) {
    PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(context, PsiMethodCallExpression.class);
    final Object value = context.getValue();
    if (value instanceof String && ((String)value).endsWith(".bss")) {
      final PsiExpressionList addArgumentsList = PsiTreeUtil.getParentOfType(methodCallExpression, PsiExpressionList.class);
      methodCallExpression = PsiTreeUtil.getParentOfType(addArgumentsList, PsiMethodCallExpression.class);
    }
    if (methodCallExpression != null) {
      PsiMethod psiMethod = methodCallExpression.resolveMethod();
      if (psiMethod != null) {
        if ("getResource".equals(psiMethod.getName())) {
          final PsiExpressionList addArgumentsList = PsiTreeUtil.getParentOfType(methodCallExpression, PsiExpressionList.class);
          methodCallExpression = PsiTreeUtil.getParentOfType(addArgumentsList, PsiMethodCallExpression.class);
          psiMethod = methodCallExpression != null ? methodCallExpression.resolveMethod() : null;
          if (psiMethod == null) return null;
        }
        if ("add".equals(psiMethod.getName())) {
          final PsiClass containingClass = psiMethod.getContainingClass();
          if (containingClass != null ) {
            final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
            if (qualifierExpression instanceof PsiMethodCallExpression) {
              final PsiReferenceExpression getStylesheetsMethodExpression = ((PsiMethodCallExpression)qualifierExpression).getMethodExpression();
              if ("getStylesheets".equals(getStylesheetsMethodExpression.getReferenceName())) {
                return getStylesheetsMethodExpression.getQualifierExpression();
              }
            }
          }
        }
      }
    }
    return null;
  }

  public static final PsiJavaElementPattern.Capture<PsiLiteralExpression> FXML_PATTERN =
    literalExpression().methodCallParameter(psiMethod().withName("getResource")).and(new FilterPattern(new ElementFilter() {
      public boolean isAcceptable(Object element, PsiElement context) {
        final PsiLiteralExpression literalExpression = (PsiLiteralExpression)context;
        PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(literalExpression, PsiMethodCallExpression.class);
        final PsiCallExpression superCall = PsiTreeUtil.getParentOfType(callExpression, PsiCallExpression.class, true);
        if (superCall instanceof PsiMethodCallExpression) {
          final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)superCall).getMethodExpression();
          if ("load".equals(methodExpression.getReferenceName())) {
            final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
            PsiClass psiClass = null;
            if (qualifierExpression instanceof PsiReferenceExpression) {
              final PsiElement resolve = ((PsiReferenceExpression)qualifierExpression).resolve();
              if (resolve instanceof PsiClass) {
                psiClass = (PsiClass)resolve;
              }
            } else if (qualifierExpression != null) {
              psiClass = PsiUtil.resolveClassInType(qualifierExpression.getType());
            }
            if (psiClass != null && JavaFxCommonNames.JAVAFX_FXML_FXMLLOADER.equals(psiClass.getQualifiedName())) {
              return true;
            }
          }
        } else if (superCall instanceof PsiNewExpression) {
          final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)superCall).getClassOrAnonymousClassReference();
          if (reference != null) {
            final PsiElement resolve = reference.resolve();
            if (resolve instanceof PsiClass && JavaFxCommonNames.JAVAFX_FXML_FXMLLOADER.equals(((PsiClass)resolve).getQualifiedName())) {
              return true;
            }
          }
        }
        return false;
      }

      public boolean isClassAcceptable(Class hintClass) {
        return true;
      }
    }));

  @Override
  public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(FXML_PATTERN, new JavaFxFileReferenceProvider(JavaFxFileTypeFactory.FXML_EXTENSION));
    registrar.registerReferenceProvider(STYLESHEET_PATTERN, new JavaFxFileReferenceProvider("css") {
      @Override
      protected String preprocessValue(String value) {
        if (value.endsWith(".bss")) {
          return StringUtil.trimEnd(value, ".bss") + ".css";
        }
        return value;
      }
    });
  }
}


text:
[![Build Status](http://img.shields.io/travis/pikesley/HbA1c.svg)](https://travis-ci.org/pikesley/HbA1c)
[![Dependency Status](http://img.shields.io/gemnasium/pikesley/HbA1c.svg)](https://gemnasium.com/pikesley/HbA1c)
[![Coverage Status](http://img.shields.io/coveralls/pikesley/HbA1c.svg)](https://coveralls.io/r/pikesley/HbA1c)
[![Code Climate](http://img.shields.io/codeclimate/github/pikesley/HbA1c.svg)](https://codeclimate.com/github/pikesley/HbA1c)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://pikesley.mit-license.org)
[![Badges](http://img.shields.io/:badges-6/6-ff6799.svg)](https://github.com/pikesley/badger)

# HbA1c

## Just because my pancreas is broken, doesn't mean it can't have a RESTful API

_v0.0.1_

I've [broken](http://uncleclive.herokuapp.com/) the [chain](https://pokrovsky.herokuapp.com/) and built something that _might actually be useful_. So:

I collect blood-glucose and medication data with [this](http://www.medivo.com/ontrack/). It can export XML and push it straight into Dropbox. Let's make an API! Let's make a dashboard! _Let's have badges!_

## The ODI's metrics-api

We built [this thing](https://metrics.theodi.org/) at the [Open Data Institute](http://theodi.org), which already does quite a lot of what I want. I forked it and spent the recent [Real Food Hack](http://lanyrd.com/2014/real-food-hack/) weekend bending it to my will.

## API

###Fetching data

All requests should include `Accept: application/json`, and provide basic auth credentials, e.g.

    curl -X GET -H 'Accept: application/json' --basic -u user:password https://pancreas-api.herokuapp.com/metrics/glucose

#### `GET /metrics`

Fetches list of available metrics

#### `GET /metrics/:metric_name`

Fetches latest value for specified metric

#### `GET /metrics/:metric_name/:time`

Fetch the most recent value of the metric at the specified time, where time is an [ISO8601 date/time](http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations)

#### `GET /metrics/:metric_name/:from/:to`

Fetch all values of the metric between the specified times. _:from_ and _:to_ can be either:

* An ISO8601 date/time
* An ISO8601 [duration](http://en.wikipedia.org/wiki/ISO_8601#Durations)
* *, meaning unspecified

### Adding data

#### `/metrics/:metric-name`

All requests should include `Content-type: application/json`, and provide basic auth credentials, with a JSON payload like:

    {
      "datetime": "{iso8601-date-time}",
      "category": "{category}"
      "value": "{value}"
    }

where

* `category` is one of
  * `Breakfast`
  * `After breakfast`
  * etc
* `value` is a Float, with
  * medication metrics assumed to have units of [Insulin Units](http://en.wikipedia.org/wiki/Insulin_therapy#The_dosage_units)
  * glucose metrics assumed to have units of _mmol/L_
  * HbA1c assumed to be a percentage

## Setting it up

You need Ruby 2.1.0 installed. Now:

    git clone https://github.com/pikesley/HbA1c
    cd HbA1c
    bundle

### Heroku FTW

You'll need a working Heroku configuration, which [is pretty damned easy](https://devcenter.heroku.com/articles/quickstart) these days.

Now create a Heroku app (called something other than _pancreas-api_, I already claimed that):

    ➔ heroku apps:create pancreas-api --region eu
    Creating pancreas-api... done, region is eu
    http://pancreas-api.herokuapp.com/ | git@heroku.com:pancreas-api.git
    Git remote heroku added

Heroku have at least 2 MongoDB add-on services. MongoHQ is _really_ slick, but it's not currently available in the EU region, so let's use Mongolab instead (UPDATE: this seems to be no longer true):

    ➔ heroku addons:add mongolab
    Adding mongolab on pancreas-api... done, v3 (free)
    Welcome to MongoLab.  Your new subscription is being created and will be available shortly.  Please consult the MongoLab Add-on Admin UI to check on its progress.
    Use `heroku addons:docs mongolab` to view documentation

Now there's some manual fiddling to set up a DB user, so do

    heroku addons:open mongolab

There you should see your new database; create a user and password on it. Then bring those creds back to your shell:

    ➔ MONGOLAB_USER=hba1c
    ➔ MONGOLAB_PASS=i_r_secure_password
    ➔ heroku config:set MONGOLAB_URI="mongodb://${MONGOLAB_USER}:${MONGOLAB_PASS}@ds063158.mongolab.com:63158/heroku_app21605738"
    Setting config vars and restarting pancreas-api... done, v4
    MONGOLAB_URI: mongodb://hba1c:i_r_secure_password@ds063158.mongolab.com:63158/heroku_app21605738

If you look at _mongoid.yml_, you'll see this:

    production:
      sessions:
        default:
          uri: <%= ENV['MONGOLAB_URI'] %>

So because this stuff is all made of magic, this will now work.

### Dropbox integration

For the Dropbox bit, you need a Dropbox API key and secret from [here](https://www.dropbox.com/developers/apps), then the [dropbox-api](https://github.com/futuresimple/dropbox-api) gem comes with a splendid Rake task

    rake dropbox:authorize

to do the Oauth manoeuvres and get the token and secret for you. Put these in _.env_ like this (and while you're at it, choose a login and password for the API, which you'll use to GET and POST data):

    DROPBOX_APP_KEY: ive_got_the_key
    DROPBOX_APP_SECRET: ive_got_the_secret
    DROPBOX_TOKEN: i_also_have_a_token
    DROPBOX_SECRET: and_another_secret
    METRICS_API_USERNAME: hba1c
    METRICS_API_PASSWORD: ifyouusethispasswordbadthingswillhappen

Now you need to set these in the Heroku environment as well. Here's an ugly hack to do just that thing:

    for line in `cat .env` ; do heroku config:set `echo ${line} | sed "s/: /=/"` ; done

Time to push the code to Heroku:

    git push heroku master

And see if it worked:

    heroku open

 You should now be looking at, erm, this README

### Import some data

We'll use the Heroku scheduler to run the data import job, but let's test that first. Do a data export from OnTrack:

* Yes, you want to 'email' it
* Into a Dropbox directory called _ontrack_
* As XML

Now

    heroku run RACK_ENV=production bundle exec rake export:jsonify

(Yes, that's a shittily-named task. Also that job currently has _no tests_~~, and I know of at least one bug in the importer~~. And it's shelling out to cURL. This is not my best work).

Anyway, you _should_ see a load of curl lines whizzing past, and when it's finished, some data should have been imported. You can test it with something like:

    curl -X GET -H 'Accept: application/json' --basic -u user:password https://pancreas-api.herokuapp.com/metrics/glucose

which should return some JSON for the latest blood-glucose event.

### Heroku scheduler

This task would obviously be better handled by a robot:

    heroku addons:add scheduler
    heroku addons:open scheduler

Add a new task, `bundle exec rake export:jsonify`, to run once a day.

And that's that.

## Dashboard

The obvious next step is to put a [beautiful Dashing dashboard](https://github.com/pikesley/diabetes-dashboard) on the front of this.


text:
listInsert() with bin is of type an array

--DESCRIPTION--
This testcase will test for bin is of type an array.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("ListInsert", "edge_002");
--EXPECT--
ERR_PARAM


text:
<?php
/**
 * @file
 * Contains \Drupal\language\Form\LanguageListController.
 */

namespace Drupal\language;

use Drupal\Core\Config\Entity\DraggableListController;
use Drupal\Core\Entity\EntityInterface;

/**
 * User interface for the language overview screen.
 */
class LanguageListController extends DraggableListController {

  /**
   * {@inheritdoc}
   */
  protected $entitiesKey = 'languages';

  /**
   * {@inheritdoc}
   */
  public function load() {
    $entities = $this->storage->loadByProperties(array('locked' => '0'));
    uasort($entities, array($this->entityInfo['class'], 'sort'));
    return $entities;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'language_admin_overview_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getOperations(EntityInterface $entity) {
    $operations = parent::getOperations($entity);
    $default = language_default();

    // Edit and delete path for Languages entities have a different pattern
    // than other config entities.
    $path = 'admin/config/regional/language';
    if (isset($operations['edit'])) {
      $operations['edit']['href'] = $path . '/edit/' . $entity->id();
    }
    if (isset($operations['delete'])) {
      $operations['delete']['href'] = $path . '/delete/' . $entity->id();
    }

    // Deleting the site default language is not allowed.
    if ($entity->id() == $default->id) {
      unset($operations['delete']);
    }

    return $operations;
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = t('Name');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $this->getLabel($entity);
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    $form = parent::buildForm($form, $form_state);
    $form[$this->entitiesKey]['#languages'] = $this->entities;
    $form['actions']['submit']['#value'] = t('Save configuration');
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    parent::submitForm($form, $form_state);

    // Kill the static cache in language_list().
    drupal_static_reset('language_list');

    // Update weight of locked system languages.
    language_update_locked_weights();

    drupal_set_message(t('Configuration saved.'));
  }

}


text:
import { ResourceWindow, Buckets, Template, ResourceComboResult,
ResourceType, ResourceValidationResult } from './interfaces';
export function groupByRole(workWindows: ResourceWindow[]) {
  let buckets: Buckets = {
    technicians: [],
    advisors: [],
    managers: [],
    valets: []
  };

  if (workWindows && workWindows.length) {
    workWindows.forEach((workWindow) => {
      let roles = ['technician', 'advisor', 'valet', 'manager'];
      roles.forEach((role) => {
        if (workWindow && workWindow.roles
          && workWindow.roles.indexOf(ResourceType[role]) > -1) {
          buckets[`${role}s`].push(workWindow);
        }
      });
    });
  }

  return buckets;
}

export function sortByStart(workWindows: ResourceWindow[]) {
  if (workWindows && workWindows.length) {
    return workWindows.sort((prev, next) => prev.start > next.start ? 1 : -1);
  } else {
    return workWindows;
  }
}

export function findResources(template: Template, buckets: Buckets,
  roundId: number = 1): ResourceComboResult {
  console.log(`Finding resources ... Resource level ${roundId}`);
  if (template && template.resources && template.resources.length) {
    if (buckets) {
      // process the first resource
      let resourceNeeded = template.resources[0];

      // find the right bucket by resource type
      let roleBucket = <ResourceWindow[]>buckets[`${ResourceType[resourceNeeded.role]}s`];

      // loop through the windows in the bucket
      if (roleBucket && roleBucket.length) {
        for (let i = 0; i < roleBucket.length; i++) {
          let currentResource = roleBucket[i];
          let validationResult: ResourceValidationResult
              = validateWindow(currentResource, template.start, template.end, resourceNeeded.duration);

          if (validationResult && validationResult.isValid && (currentResource.roundId || 0) < roundId) {
            currentResource.roundId = roundId;

            // block the current resource
            currentResource.blocked = true;

            console.log('Matched resource: ', currentResource);

            let remainingResources = template.resources.slice(1);
            if (remainingResources.length) {
              let isSequential = resourceNeeded.sequence !== remainingResources[0].sequence;
              let result: ResourceComboResult;
              if (isSequential) {
                let newTemplate: Template = {
                  start: validationResult.endOfWork,
                  end: template.end,
                  resources: remainingResources
                };

                result = findResources(newTemplate, buckets, roundId + 1);
              } else {
                let newTemplate: Template = {
                  start: template.start,
                  end: template.end,
                  resources: remainingResources
                };

                result = findResources(newTemplate, buckets, roundId + 1);
              }
              let comboResult: ResourceComboResult;
              if (result) {
                comboResult = {
                  resources: [currentResource].concat(result.resources),
                  requirementsMet: result.requirementsMet
                };
              } else {
                comboResult = {
                  resources: [currentResource],
                  requirementsMet: false
                };
              }
              if (comboResult.requirementsMet) {
                return comboResult;
              } else {
                // unblock the blocked resource
                currentResource.blocked = false;

                // look for another resource
                return findResources(template, buckets, roundId);
              }
            } else {
              return {
                resources: [currentResource],
                requirementsMet: true
              };
            }
          } else {
            return {
              resources: null,
              requirementsMet: false
            };
          }
        }
      } else {
        return {
          resources: null,
          requirementsMet: false
        };
      }
    } else {
      return {
        resources: null,
        requirementsMet: false
      };
    }
  }

  return {
    resources: null,
    requirementsMet: true
  };
}

export function validateWindow(openWindow: ResourceWindow, start: number,
  end: number, duration: number): ResourceValidationResult {
    if (openWindow && !openWindow.blocked) {
      // window must be within timeframe
      if (openWindow.start >= start) {
        let workEndsAt = openWindow.start + (duration * 60);
        if (workEndsAt <= end && workEndsAt <= openWindow.end) {
          // mark this window as "blocked"
          openWindow.blocked = true;
          return {
            isValid: true,
            endOfWork: workEndsAt
          };
        }
      }
    }

    return {
      isValid: false,
      endOfWork: null
    }
}

export function findResource(roundId: number, start: number, end: number,
  duration: number, role: ResourceType, buckets: Buckets) {
  if (buckets) {
    let roleBucket = <ResourceWindow[]>buckets[`${ResourceType[role]}s`];
    if (roleBucket && roleBucket.length) {
      for (let i = 0; i < roleBucket.length; i++) {
        let openWindow = roleBucket[i];
        if (openWindow && !openWindow.blocked && (openWindow.roundId || 0) !== roundId) {
          // mark this window as "visited"
          openWindow.roundId = roundId;

          // window must be within timeframe
          if (openWindow.start >= start) {
            let workEndsAt = openWindow.start + (duration * 60);
            if (workEndsAt <= end && workEndsAt <= openWindow.end) {
              // mark this window as "blocked"
              openWindow.blocked = true;
              return {
                resource: openWindow,
                endOfWork: workEndsAt
              };
            }
          }
        }
      }
    }
  }

  return null;
}


text:
@protocol SearchFilterLoaded;

@interface SearchFilter : NSObject {
    id <SearchFilterLoaded> delegate;
}

-(void)loadSearchFilters;

@property (retain, nonatomic) id <SearchFilterLoaded> delegate;

@end

@protocol SearchFilterLoaded <NSObject>;

-(void) availableFilters:(NSMutableArray *)filters;

@end


text:
from chatterbot import ChatBot
from django.test import TransactionTestCase
from tests_django import test_settings

class ChatterBotTestCase(TransactionTestCase):

    def setUp(self):
        super().setUp()
        self.chatbot = ChatBot(**test_settings.CHATTERBOT)


text:
package org.camunda.bpm.model.dmn.impl.instance;

import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.DMN11_NS;
import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.DMN_ATTRIBUTE_IMPORT_TYPE;
import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.DMN_ATTRIBUTE_LOCATION_URI;
import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.DMN_ATTRIBUTE_NAMESPACE;
import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.DMN_ELEMENT_IMPORT;

import org.camunda.bpm.model.dmn.instance.Import;
import org.camunda.bpm.model.xml.ModelBuilder;
import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder.ModelTypeInstanceProvider;
import org.camunda.bpm.model.xml.type.attribute.Attribute;

public class ImportImpl extends DmnModelElementInstanceImpl implements Import {

  protected static Attribute<String> namespaceAttribute;
  protected static Attribute<String> locationUriAttribute;
  protected static Attribute<String> importTypeAttribute;

  public ImportImpl(ModelTypeInstanceContext instanceContext) {
    super(instanceContext);
  }

  public String getNamespace() {
    return namespaceAttribute.getValue(this);
  }

  public void setNamespace(String namespace) {
    namespaceAttribute.setValue(this, namespace);
  }

  public String getLocationUri() {
    return locationUriAttribute.getValue(this);
  }

  public void setLocationUri(String locationUri) {
    locationUriAttribute.setValue(this, locationUri);
  }

  public String getImportType() {
    return importTypeAttribute.getValue(this);
  }

  public void setImportType(String importType) {
    importTypeAttribute.setValue(this, importType);
  }

  public static void registerType(ModelBuilder modelBuilder) {
    ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Import.class, DMN_ELEMENT_IMPORT)
      .namespaceUri(DMN11_NS)
      .instanceProvider(new ModelTypeInstanceProvider<Import>() {
        public Import newInstance(ModelTypeInstanceContext instanceContext) {
          return new ImportImpl(instanceContext);
        }
      });

    namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE)
      .required()
      .build();

    locationUriAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LOCATION_URI)
      .build();

    importTypeAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_IMPORT_TYPE)
      .required()
      .build();

    typeBuilder.build();
  }

}


text:
<?php

namespace Lowgain\Uploady\Storage;

use \Lowgain\Uploady\Storage;

/**
* Uploady Storage driver that works with an FTP connection.
*
* @package Uploady
* @author Lowgain <logan@bnotions.com>
*/
class FTP implements Storage {

	protected $ftp_host;

	protected $ftp_username;

	protected $ftp_password;

	protected $root_path;

	protected $ftp_connection;

	/**
	 * Creates a new \Lowgain\Uploady\Storage\FTP instance.
	 *
	 * @param string $ftp_host The address of the FTP host
	 * @return void
	 */
	public function __construct($ftp_host, $ftp_username, $ftp_password, $root_path = '/')
	{
		$this->ftp_host = $ftp_host;
		$this->ftp_username = $ftp_username;
		$this->ftp_password = $ftp_password;
		$this->root_path = $root_path;
		$this->ftp_connection = ftp_connect($ftp_host);

		if ($this->ftp_connection === FALSE)
			throw new \Exception('FTP Connection Failed!');

		if (ftp_login($this->ftp_connection, $ftp_username, $ftp_password) === FALSE)
			throw new \Exception('FTP Login Failed!');
	}

	public function __destruct()
	{
		if ($this->ftp_connection)
		{
			ftp_close($this->ftp_connection);
		}
	}

	public function put_file($file_name, $file_contents)
	{
		// I believe we need to make a temporary file first
		$fh = fopen(tempnam(sys_get_temp_dir(), 'ftpfile'));

		if ($fh === FALSE)
			return FALSE;

		if (fwrite($fh, $file_contents) === FALSE)
			return FALSE;

		return ftp_put($this->ftp_connection, $this->build_path($file_name), $fh, FTP_BINARY);
	}

	public function get_file($file_name)
	{
		// Again, this saves to a temporary path
		$temp_file = tempnam(sys_get_temp_dir(), 'ftpfile');

		if (ftp_get($this->ftp_connection, $temp_file, $this->build_path($file_name), FTP_BINARY) === FALSE)
			return FALSE;

		return file_get_contents($tmp_file);
	}

	public function file_exists($file_name)
	{
		return ftp_size($this->ftp_connection, $this->build_path($file_name)) !== -1;
	}

	public function delete_file($file_name)
	{
		return ftp_delete($this->ftp_connection, $this->build_path($file_name));
	}

	protected function build_path($file_name)
	{
		return preg_replace("/[\/\\\]/", DIRECTORY_SEPARATOR, "{$this->root_path}/{$file_name}");
	}

}


text:
define(["backbone", "jquery"], function(B, $) {
    return B.Model.extend({
        getFeatures: function() {
            // Returns a Deferred feature collection once the data
            // becomes available.
            var f = this.get("features");

            if (f) {
                return $.Deferred().resolve(f);
            }

            this.set("_loading", true);

            var self = this;
            return $.getJSON(this.get("source"))
                .then(function(json) {
                    self.set({features: json, _loading: false});
                    return json;
                }, function(response) {
                    self.set({_loading: false, _errorResponse: response});
                    return _;
                });
        }
    });
});


text:
title: Ministers
is_name: false

---

Ministers Accounts