text:
import { Component, Output, OnInit, EventEmitter, Input, ChangeDetectorRef, OnDestroy } from "@angular/core";
import { IslDataService } from "../services/isl-data.service";
import { DygraphService } from "../services/dygraph.service";
import * as _moment from 'moment';
declare var moment: any;
declare var Dygraph :any;

@Component({
  selector: "app-dygraph",
  templateUrl: "./dygraph.component.html",
  styleUrls: ["./dygraph.component.css"]
})
export class DygraphComponent implements OnInit, OnDestroy {

   @Output() zoomChange = new EventEmitter();
  // @Input() dataObj: any;
  // @Input() graphAPIFlag: boolean = false;
  dataObj: any;
  graphAPIFlag: boolean = false;
  message: {};
  data = [];
  highestYaXis = null;
  labels: any;
  options : any = Object.assign({}, {
    width: "auto",
    chartHeight:"380",
    legend: "onmouseover",
    noDataLabel:"Please wait",
  });

  jsonResponse: any;
  startDate: any;
  endDate: any;
  timezone: any;
  frequency: any;
  numOperator: number;
  count: number = 0;
  objectCount: number = 0;
  optionsObject = {};
  graphDataOptions: any;
  dateMessage:string;

  constructor(
    private islDataService: IslDataService,
    private dygraphService: DygraphService,
    private cdr: ChangeDetectorRef
  ) {

  }

  constructGraphData(data, jsonResponse, startDate, endDate, timezone) {
    this.numOperator = 0;
    var metric1 = "";
    var metric2 = "";
    var direction1 = "";
    var direction2 = "";
    var labels = ["Time", "X", "Y"];
    var graphData = [];
    if (typeof startDate !== "undefined" && startDate != null) {
      var dat = new Date(startDate);
      var startTime = dat.getTime();
      var usedDate = new Date();

       if (typeof timezone !== "undefined" && timezone == "UTC") {
        startTime = startTime - usedDate.getTimezoneOffset() * 60 * 1000;
      }

      var arr = [new Date(startTime), null, null];
      graphData.push(arr);
    }

    if (!jsonResponse) {
      var getValue = typeof data[0] !== "undefined" ? data[0].dps : {};
      var fDps = [];
      var rDps = [];
      metric1 = typeof data[0] !== "undefined" ? data[0].metric : "";
      if (data.length == 2) {
        var getVal = typeof data[1] !== "undefined" ? data[1].dps : {};
        rDps = Object.keys(getVal);
        metric2 = data[1].metric;

        if (data[1].tags.direction) {
          metric2 = data[1].metric + "(" + data[1].tags.direction + ")";
        }
        if (data[0].tags.direction) {
          metric1 = data[0].metric + "(" + data[0].tags.direction + ")";
        }
      }

      fDps = Object.keys(getValue);
      var graphDps = fDps.concat(rDps);
      graphDps.sort();
      graphDps = graphDps.filter((v, i, a) => a.indexOf(v) === i);

      if (graphDps.length <= 0 ) {
        metric1 = "F";
        metric2 = "R";
      } else {

        for(var index=0;index < graphDps.length; index++){
          let i = graphDps[index];
          this.numOperator = parseInt(i);
          if (getValue[i] == null || typeof getValue[i] == 'undefined') {
            getValue[i] = null;
          }else if(getValue[i] < 0){
            getValue[i]=0;
          }

          var temparr = [];
          temparr[0] = new Date(Number(this.numOperator * 1000));
          temparr[1] = getValue[i];
          if (data.length == 2) {
            if (getVal[i] == null || typeof getVal[i] == 'undefined') {
              getVal[i]= null;
            }else if(getVal[i] < 0){
              getVal[i]=0;
            }
            temparr[2] = getVal[i];
          }
          graphData.push(temparr);
          this.numOperator++;
        }
      }
      if (metric1 && metric2) {
        labels = ["Time", metric1, metric2];
      } else if (metric1) {
        labels = ["Time", metric1];
      } else {
        labels = ["Time", metric2];
      }
    } else {
      metric1 = "F";
      metric2 = "R";
      labels = ["Time", metric1, metric2];
    }
    if (typeof endDate !== "undefined" && endDate != null) {
      var dat = new Date(endDate);
      var lastTime = dat.getTime();
      var usedDate =
        graphData && graphData.length
          ? new Date(graphData[graphData.length - 1][0])
          : new Date();
      if (typeof timezone !== "undefined" && timezone == "UTC") {
        lastTime = lastTime - usedDate.getTimezoneOffset() * 60 * 1000;
      }
      var arr = [new Date(lastTime), null, null];
      graphData.push(arr);
      //graphData.shift();
    }

    return { data: graphData, labels: labels };
  }

  ngOnInit() {

    this.islDataService.currentMessage.subscribe(message => {
      this.message = message;
      if (this.count >= 1) {
        this.options = Object.assign({}, {
          width: "auto",
          chartHeight:"380",
          legend: "onmouseover",
          noDataLabel:"Please wait",
        });
        this.drawGraphCall(message);
      }
      this.count++;
    });
    this.islDataService.currentOptionsObject.subscribe(message => {
      this.optionsObject = message;
      this.graphDataOptions = message;
      if (this.objectCount >= 1) {
        this.options = Object.assign({}, {
          width: "auto",
          chartHeight:"380",
          legend: "onmouseover",
          noDataLabel:"Please wait",
        });
        this.drawGraphCall(message);
      }
      this.objectCount++;
    });

    this.islDataService.IslFlowGraph.subscribe(message => {
      this.message = message;
      if (this.count >= 1) {
        this.options = Object.assign({}, {
          width: "auto",
          chartHeight:"380",
          legend: "onmouseover",
          noDataLabel:"Please wait",
        });
        this.plotISLFlowGraph(message);
      }
      this.count++;
    });

    this.islDataService.IslFlowStackedGraph.subscribe(message => {
      this.message = message;
      if (this.count >= 1) {
        this.options = Object.assign({}, {
          width: "auto",
          chartHeight:"380",
          legend: "onmouseover",
          noDataLabel:"Please wait",
        });
        this.plotISLStackedFlowGraph(message);
      }
      this.count++;
    });

    this.dygraphService.flowGraph.subscribe(data => {
      this.options = Object.assign({}, {
        width: "auto",
        chartHeight:"380",
        legend: "onmouseover",
        noDataLabel:"Please wait",
      });
      this.plotFlowGraph(
        data.data,
        data.startDate,
        data.endDate,
        data.timezone
      );
      try {
        this.cdr.detectChanges();
      } catch (err) {}
    });

    this.dygraphService.meterGraph.subscribe(data => {
      this.options = Object.assign({}, {
        width: "auto",
        chartHeight:"380",
        legend: "onmouseover",
        noDataLabel:"Please wait",
      });
      this.plotMeterGraph(
        data.data,
        data.startDate,
        data.endDate,
        data.timezone);
      try {
        this.cdr.detectChanges();
      } catch (err) {}
    })
  }

  drawGraphCall(dataObj) {
   this.timezone = dataObj.timezone;
   this.jsonResponse = undefined;

   let processedResponse = this.dygraphService.constructGraphData(
    dataObj.data,
    this.jsonResponse,
    dataObj.startDate,
    dataObj.endDate,
    dataObj.timezone
  );
   this.data = processedResponse.data;
   this.labels = processedResponse.labels;

  if (this.timezone == "UTC") {
    this.options = Object.assign(this.options, {
    labels: this.labels,
    drawPoints: false,
    animatedZooms: true,
    labelsUTC: true,
    colors: ["#1C227C","#A1CD24"] ,
    legend: "onmouseover",
    valueRange:[0,null],
    connectSeparatedPoints:true,
    legendFormatter:this.dygraphService.legendFormatter,
      zoomCallback: this.zoomCallbackHandler
    });
  }else{

    this.options = Object.assign(this.options, {
      labels: this.labels,
      drawPoints: false,
      animatedZooms: true,
      labelsUTC: false,
      colors: ["#1C227C","#A1CD24"],
      legend: "onmouseover",
      valueRange:[0,null],
      connectSeparatedPoints:true,
      legendFormatter:this.dygraphService.legendFormatter,
      zoomCallback: this.zoomCallbackHandler
    });
  }

  }

  plotISLFlowGraph(dataObj) {
    this.timezone = dataObj.timezone;
    this.jsonResponse = undefined;
    this.labels = dataObj.labels;
    this.data = dataObj.data;
  if(this.timezone == "UTC") {
    this.options = Object.assign(this.options, {
      labels: this.labels,
      drawPoints: false,
      animatedZooms: true,
      labelsUTC: true,
      series: dataObj.series,
      legend: "onmouseover",
      valueRange:[0,null],
      connectSeparatedPoints:true,
      legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler
      });
  }else{
    this.options = Object.assign(this.options, {
      labels: this.labels,
      drawPoints: false,
      animatedZooms: true,
      labelsUTC: false,
      series: dataObj.series,
      legend: "onmouseover",
      valueRange:[0,null],
      connectSeparatedPoints:true,
      legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler
      });
     }
  }

  plotISLStackedFlowGraph(dataObj) {
    this.timezone = dataObj.timezone;
    this.jsonResponse = undefined;
    this.labels = dataObj.labels;
    this.data = dataObj.data;
  if(this.timezone == "UTC") {
    this.options = Object.assign(this.options, {
      labels: this.labels,
      drawPoints: false,
      animatedZooms: true,
      labelsUTC: true,
      series: dataObj.series,
      legend: "onmouseover",
      stackedGraph: true,
      valueRange:[0,null],
      connectSeparatedPoints:true,
      legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler,
        axes: {
          x: {
            drawGrid: false
          }
        }
      });
  }else{
    this.options = Object.assign(this.options, {
      labels: this.labels,
      drawPoints: false,
      animatedZooms: true,
      labelsUTC: false,
      series: dataObj.series,
      legend: "onmouseover",
      stackedGraph: true,
      valueRange:[0,null],
      connectSeparatedPoints:true,
      legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler,
        axes: {
          x: {
            drawGrid: false
          }
        }
      });
     }
  }

  zoomCallbackHandler =  (minX, maxX, yRanges) =>{
    this.zoomChange.emit({ minX:minX, maxX:maxX, yRanges:yRanges});
  }

  /** Start : Flow Graphs */

  plotMeterGraph(data, startDate, endDate, timezone){
    var graph_data = this.dygraphService.computeMeterGraphData(
      data,
      startDate,
      endDate,
      timezone,
    );
    var graphData = graph_data["data"];
    var labels = graph_data["labels"];
    var series = {};
    var colors = graph_data["color"];
    if (labels && labels.length) {
      for (var k = 0; k < labels.length; k++) {
        if (k != 0) {
          series[labels[k]] = { color: colors[k - 1] };
        }
      }
    }

    this.data = graphData;

    if (timezone == "UTC") {
        this.options = Object.assign(this.options,{
          labels: labels,
          labelsUTC: true,
          series: series,
          legend: "onmouseover",
          connectSeparatedPoints:true,
          legendFormatter:this.dygraphService.legendFormatter,
          zoomCallback: this.zoomCallbackHandler
        });

    } else {
       this.options = Object.assign(this.options,{
          labels: labels,
          series: series,
          labelsUTC: false,
          legend: "onmouseover",
          connectSeparatedPoints:true,
          legendFormatter:this.dygraphService.legendFormatter,
          zoomCallback: this.zoomCallbackHandler
        });
    }
  }
  plotFlowGraph(data, startDate, endDate, timezone) {
    let graphData = this.dygraphService.constructGraphData(
      data,
      undefined,
      startDate,
      endDate,
      timezone
    );
    try{
    this.data = graphData["data"];
    this.labels = graphData["labels"];

    if (timezone == "UTC") {
      this.options = Object.assign(this.options,{
        labels: this.labels,
        animatedZooms: true,
        labelsUTC: true,
        colors: ["#1C227C", "#A1CD24"],
        connectSeparatedPoints:true,
        legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler
      });

    } else {
      this.options =  Object.assign(this.options,{
        labels: this.labels,
        animatedZooms: true,
        labelsUTC: false,
        colors: ["#1C227C", "#A1CD24"],
        connectSeparatedPoints:true,
        legendFormatter:this.dygraphService.legendFormatter,
        zoomCallback: this.zoomCallbackHandler
      });
    }
    }catch(err){}
  }
  /** End : Flow Graph Path */

  ngOnDestroy(){
    this.cdr.detach();
  }
}


text:
package org.codelibs.elasticsearch.dynarank.script;

import java.util.Map;

import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.search.SearchHit;

public abstract class DynaRankScript {

    protected final Map<String, Object> params;

    public DynaRankScript(final Map<String, Object> params) {
        this.params = params;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public abstract SearchHit[] execute(final SearchHit[] searchHits);

    public interface Factory {
        DynaRankScript newInstance(final Map<String, Object> params);
    }

    public static final String[] PARAMETERS = {"searchHits"};
    public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("dynarank", Factory.class);
}

redpajama_set_name: RedPajamaGithub


text:
import HomePage from './page-objects/home.page';

describe('Home Page:', () => {
    let page;
    beforeEach(() => {
        page = new HomePage();
        page.load();
    });

    describe('Layout:', () => {
        it('should have correct layout', () => {
            const config = {
                url: '/',
                title: 'Home',
                klass: 'home',
                header: 'prelogin',
                sidebar: false,
                breadcrumb: false
            };
            page.assertCorrectLayout(config);
        });
    });

    describe('Hero section:', () => {
        it('should display correct title and sub title', () => {
            expect(page.ele.mainTitle.getText()).toEqual('Aio Angular App');
            expect(page.ele.subTitle.getText()).toEqual(
                'Awesome web app built on AngularJS & Material Design.');
        });

        it('should go to login page if click get started', () => {
            page.ele.getStartedBtn.click();
            browser._.expectUrlToMatch('login');
        });
    });
});


text:
@interface VCEViewController : UIViewController

@end


text:
#ifndef PTHREADMOCKS_H_
#define PTHREADMOCKS_H_

#include <pthread.h>
#include <string.h>
#include <errno.h>

#include "src/zk_adaptor.h"

#include "Util.h"
#include "MocksBase.h"
#include "LibCSymTable.h"
#include "ThreadingUtil.h"

// an ABC for pthreads
class MockPthreadsBase: public Mock
{
public:
    MockPthreadsBase(){mock_=this;}
    virtual ~MockPthreadsBase(){mock_=0;}

    virtual int pthread_create(pthread_t * t, const pthread_attr_t *a,
            void *(*f)(void *), void *d) =0;
    virtual int pthread_join(pthread_t t, void ** r) =0;
    virtual int pthread_detach(pthread_t t) =0;
    virtual int pthread_cond_broadcast(pthread_cond_t *c) =0;
    virtual int pthread_cond_destroy(pthread_cond_t *c) =0;
    virtual int pthread_cond_init(pthread_cond_t *c, const pthread_condattr_t *a) =0;
    virtual int pthread_cond_signal(pthread_cond_t *c) =0;
    virtual int pthread_cond_timedwait(pthread_cond_t *c,
            pthread_mutex_t *m, const struct timespec *t) =0;
    virtual int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m) =0;
    virtual int pthread_mutex_destroy(pthread_mutex_t *m) =0;
    virtual int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *a) =0;
    virtual int pthread_mutex_lock(pthread_mutex_t *m) =0;
    virtual int pthread_mutex_trylock(pthread_mutex_t *m) =0;
    virtual int pthread_mutex_unlock(pthread_mutex_t *m) =0;

    static MockPthreadsBase* mock_;
};

// all pthread functions simply return an error code
// and increment their invocation counter. No actual threads are spawned.
class MockPthreadsNull: public MockPthreadsBase
{
public:
    MockPthreadsNull():
    pthread_createReturns(0),pthread_createCounter(0),
    pthread_joinReturns(0),pthread_joinCounter(0),pthread_joinResultReturn(0),
    pthread_detachReturns(0),pthread_detachCounter(0),
    pthread_cond_broadcastReturns(0),pthread_cond_broadcastCounter(0),
    pthread_cond_destroyReturns(0),pthread_cond_destroyCounter(0),
    pthread_cond_initReturns(0),pthread_cond_initCounter(0),
    pthread_cond_signalReturns(0),pthread_cond_signalCounter(0),
    pthread_cond_timedwaitReturns(0),pthread_cond_timedwaitCounter(0),
    pthread_cond_waitReturns(0),pthread_cond_waitCounter(0),
    pthread_mutex_destroyReturns(0),pthread_mutex_destroyCounter(0),
    pthread_mutex_initReturns(0),pthread_mutex_initCounter(0),
    pthread_mutex_lockReturns(0),pthread_mutex_lockCounter(0),
    pthread_mutex_trylockReturns(0),pthread_mutex_trylockCounter(0),
    pthread_mutex_unlockReturns(0),pthread_mutex_unlockCounter(0)
    {
        memset(threads,0,sizeof(threads));
    }

    short threads[512];

    int pthread_createReturns;
    int pthread_createCounter;
    virtual int pthread_create(pthread_t * t, const pthread_attr_t *a,
            void *(*f)(void *), void *d){
        char* p=(char*)&threads[pthread_createCounter++];
        p[0]='i'; // mark as created
        *t=(pthread_t)p;
        return pthread_createReturns;
    }
    int pthread_joinReturns;
    int pthread_joinCounter;
    void* pthread_joinResultReturn;
    virtual int pthread_join(pthread_t t, void ** r){
        pthread_joinCounter++;
        if(r!=0)
            *r=pthread_joinResultReturn;
        char* p=(char*)t;
        p[0]='x';p[1]+=1;
        return pthread_joinReturns;
    }
    int pthread_detachReturns;
    int pthread_detachCounter;
    virtual int pthread_detach(pthread_t t){
        pthread_detachCounter++;
        char* p=(char*)t;
        p[0]='x';p[1]+=1;
        return pthread_detachReturns;
    }

    template<class T>
    static bool isInitialized(const T& t){
        return ((char*)t)[0]=='i';
    }
    template<class T>
    static bool isDestroyed(const T& t){
        return ((char*)t)[0]=='x';
    }
    template<class T>
    static int getDestroyCounter(const T& t){
        return ((char*)t)[1];
    }
    template<class T>
    static int getInvalidAccessCounter(const T& t){
        return ((char*)t)[2];
    }
    int pthread_cond_broadcastReturns;
    int pthread_cond_broadcastCounter;
    virtual int pthread_cond_broadcast(pthread_cond_t *c){
        pthread_cond_broadcastCounter++;
        if(isDestroyed(c))((char*)c)[2]++;
        return pthread_cond_broadcastReturns;
    }
    int pthread_cond_destroyReturns;
    int pthread_cond_destroyCounter;
    virtual int pthread_cond_destroy(pthread_cond_t *c){
        pthread_cond_destroyCounter++;
        char* p=(char*)c;
        p[0]='x';p[1]+=1;
        return pthread_cond_destroyReturns;
    }
    int pthread_cond_initReturns;
    int pthread_cond_initCounter;
    virtual int pthread_cond_init(pthread_cond_t *c, const pthread_condattr_t *a){
        pthread_cond_initCounter++;
        char* p=(char*)c;
        p[0]='i'; // mark as created
        p[1]=0;   // destruction counter
        p[2]=0;   // access after destruction counter
        return pthread_cond_initReturns;
    }
    int pthread_cond_signalReturns;
    int pthread_cond_signalCounter;
    virtual int pthread_cond_signal(pthread_cond_t *c){
        pthread_cond_signalCounter++;
        if(isDestroyed(c))((char*)c)[2]++;
        return pthread_cond_signalReturns;
    }
    int pthread_cond_timedwaitReturns;
    int pthread_cond_timedwaitCounter;
    virtual int pthread_cond_timedwait(pthread_cond_t *c,
            pthread_mutex_t *m, const struct timespec *t){
        pthread_cond_timedwaitCounter++;
        if(isDestroyed(c))((char*)c)[2]++;
        return pthread_cond_timedwaitReturns;
    }
    int pthread_cond_waitReturns;
    int pthread_cond_waitCounter;
    virtual int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m){
        pthread_cond_waitCounter++;
        if(isDestroyed(c))((char*)c)[2]++;
        return pthread_cond_waitReturns;
    }
    int pthread_mutex_destroyReturns;
    int pthread_mutex_destroyCounter;
    virtual int pthread_mutex_destroy(pthread_mutex_t *m){
        pthread_mutex_destroyCounter++;
        char* p=(char*)m;
        p[0]='x';p[1]+=1;
        return pthread_mutex_destroyReturns;
    }
    int pthread_mutex_initReturns;
    int pthread_mutex_initCounter;
    virtual int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *a){
        pthread_mutex_initCounter++;
        char* p=(char*)m;
        p[0]='i'; // mark as created
        p[1]=0;   // destruction counter
        p[2]=0;   // access after destruction counter
        return pthread_mutex_initReturns;
    }
    int pthread_mutex_lockReturns;
    int pthread_mutex_lockCounter;
    virtual int pthread_mutex_lock(pthread_mutex_t *m){
        pthread_mutex_lockCounter++;
        if(isDestroyed(m))((char*)m)[2]++;
        return pthread_mutex_lockReturns;
    }
    int pthread_mutex_trylockReturns;
    int pthread_mutex_trylockCounter;
    virtual int pthread_mutex_trylock(pthread_mutex_t *m){
        pthread_mutex_trylockCounter++;
        if(isDestroyed(m))((char*)m)[2]++;
        return pthread_mutex_trylockReturns;
    }
    int pthread_mutex_unlockReturns;
    int pthread_mutex_unlockCounter;
    virtual int pthread_mutex_unlock(pthread_mutex_t *m){
        pthread_mutex_unlockCounter++;
        if(isDestroyed(m))((char*)m)[2]++;
        return pthread_mutex_unlockReturns;
    }
};

// simulates the way zookeeper threads make use of api_prolog/epilog and
//
class MockPthreadZKNull: public MockPthreadsNull
{
    typedef std::map<pthread_t,zhandle_t*> Map;
    Map map_;
public:
    virtual int pthread_create(pthread_t * t, const pthread_attr_t *a,
            void *(*f)(void *), void *d){
        int ret=MockPthreadsNull::pthread_create(t,a,f,d);
        zhandle_t* zh=(zhandle_t*)d;
        adaptor_threads* ad=(adaptor_threads*)zh->adaptor_priv;
        api_prolog(zh);
        ad->threadsToWait--;
        putValue(map_,*t,zh);
        return ret;
    }
    virtual int pthread_join(pthread_t t, void ** r){
        zhandle_t* zh=0;
        if(getValue(map_,t,zh))
            api_epilog(zh,0);
        return MockPthreadsNull::pthread_join(t,r);
    }
};

struct ThreadInfo{
    typedef enum {RUNNING,TERMINATED} ThreadState;

    ThreadInfo():
        destructionCounter_(0),invalidAccessCounter_(0),state_(RUNNING)
    {
    }

    ThreadInfo& incDestroyed() {
        destructionCounter_++;
        return *this;
    }
    ThreadInfo& incInvalidAccess(){
        invalidAccessCounter_++;
        return *this;
    }
    ThreadInfo& setTerminated(){
        state_=TERMINATED;
        return *this;
    }
    int destructionCounter_;
    int invalidAccessCounter_;
    ThreadState state_;
};

class CheckedPthread: public MockPthreadsBase
{
    // first => destruction counter
    // second => invalid access counter
    //typedef std::pair<int,int> Entry;
    typedef ThreadInfo Entry;
    typedef std::map<pthread_t,Entry> ThreadMap;
    static ThreadMap tmap_;
    static ThreadMap& getMap(const TypeOp<pthread_t>::BareT&){return tmap_;}
    typedef std::map<pthread_mutex_t*,Entry> MutexMap;
    static MutexMap mmap_;
    static MutexMap& getMap(const TypeOp<pthread_mutex_t>::BareT&){return mmap_;}
    typedef std::map<pthread_cond_t*,Entry> CVMap;
    static CVMap cvmap_;
    static CVMap& getMap(const TypeOp<pthread_cond_t>::BareT&){return cvmap_;}

    static Mutex mx;

    template<class T>
    static void markDestroyed(T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        if(getValue(getMap(Type()),t,e)){
            putValue(getMap(Type()),t,Entry(e).incDestroyed());
        }else{
            putValue(getMap(Type()),t,Entry().incDestroyed());
        }
    }
    template<class T>
    static void markCreated(T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        if(!getValue(getMap(Type()),t,e))
            putValue(getMap(Type()),t,Entry());
    }
    template<class T>
    static void checkAccessed(T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        if(getValue(getMap(Type()),t,e) && e.destructionCounter_>0)
            putValue(getMap(Type()),t,Entry(e).incInvalidAccess());
    }
    static void setTerminated(pthread_t t){
        Entry e;
        synchronized(mx);
        if(getValue(tmap_,t,e))
            putValue(tmap_,t,Entry(e).setTerminated());
    }
public:
    bool verbose;
    CheckedPthread():verbose(false){
        tmap_.clear();
        mmap_.clear();
        cvmap_.clear();
        mx.release();
    }
    template <class T>
    static bool isInitialized(const T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        return getValue(getMap(Type()),t,e) && e.destructionCounter_==0;
    }
    template <class T>
    static bool isDestroyed(const T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        return getValue(getMap(Type()),t,e) && e.destructionCounter_>0;
    }
    static bool isTerminated(pthread_t t){
        Entry e;
        synchronized(mx);
        return getValue(tmap_,t,e) && e.state_==ThreadInfo::TERMINATED;
    }
    template <class T>
    static int getDestroyCounter(const T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        return getValue(getMap(Type()),t,e)?e.destructionCounter_:-1;
    }
    template<class T>
    static int getInvalidAccessCounter(const T& t){
        typedef typename TypeOp<T>::BareT Type;
        Entry e;
        synchronized(mx);
        return getValue(getMap(Type()),t,e)?e.invalidAccessCounter_:-1;
    }

    struct ThreadContext{
        typedef void *(*ThreadFunc)(void *);

        ThreadContext(ThreadFunc func,void* param):func_(func),param_(param){}
        ThreadFunc func_;
        void* param_;
    };
    static void* threadFuncWrapper(void* v){
        ThreadContext* ctx=(ThreadContext*)v;
        pthread_t t=pthread_self();
        markCreated(t);
        void* res=ctx->func_(ctx->param_);
        setTerminated(pthread_self());
        delete ctx;
        return res;
    }
    virtual int pthread_create(pthread_t * t, const pthread_attr_t *a,
            void *(*f)(void *), void *d)
    {
        int ret=LIBC_SYMBOLS.pthread_create(t,a,threadFuncWrapper,
                new ThreadContext(f,d));
        if(verbose)
            TEST_TRACE(("thread created %p",*t));
        return ret;
    }
    virtual int pthread_join(pthread_t t, void ** r){
        if(verbose) TEST_TRACE(("thread joined %p",t));
        int ret=LIBC_SYMBOLS.pthread_join(t,r);
        if(ret==0)
            markDestroyed(t);
        return ret;
    }
    virtual int pthread_detach(pthread_t t){
        if(verbose) TEST_TRACE(("thread detached %p",t));
        int ret=LIBC_SYMBOLS.pthread_detach(t);
        if(ret==0)
            markDestroyed(t);
        return ret;
    }
    virtual int pthread_cond_broadcast(pthread_cond_t *c){
        checkAccessed(c);
        return LIBC_SYMBOLS.pthread_cond_broadcast(c);
    }
    virtual int pthread_cond_destroy(pthread_cond_t *c){
        markDestroyed(c);
        return LIBC_SYMBOLS.pthread_cond_destroy(c);
    }
    virtual int pthread_cond_init(pthread_cond_t *c, const pthread_condattr_t *a){
        markCreated(c);
        return LIBC_SYMBOLS.pthread_cond_init(c,a);
    }
    virtual int pthread_cond_signal(pthread_cond_t *c){
        checkAccessed(c);
        return LIBC_SYMBOLS.pthread_cond_signal(c);
    }
    virtual int pthread_cond_timedwait(pthread_cond_t *c,
            pthread_mutex_t *m, const struct timespec *t){
        checkAccessed(c);
        return LIBC_SYMBOLS.pthread_cond_timedwait(c,m,t);
    }
    virtual int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m){
        checkAccessed(c);
        return LIBC_SYMBOLS.pthread_cond_wait(c,m);
    }
    virtual int pthread_mutex_destroy(pthread_mutex_t *m){
        markDestroyed(m);
        return LIBC_SYMBOLS.pthread_mutex_destroy(m);
    }
    virtual int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *a){
        markCreated(m);
        return LIBC_SYMBOLS.pthread_mutex_init(m,a);
    }
    virtual int pthread_mutex_lock(pthread_mutex_t *m){
        checkAccessed(m);
        return LIBC_SYMBOLS.pthread_mutex_lock(m);
    }
    virtual int pthread_mutex_trylock(pthread_mutex_t *m){
        checkAccessed(m);
        return LIBC_SYMBOLS.pthread_mutex_trylock(m);
    }
    virtual int pthread_mutex_unlock(pthread_mutex_t *m){
        checkAccessed(m);
        return LIBC_SYMBOLS.pthread_mutex_unlock(m);
    }
};

#endif /*PTHREADMOCKS_H_*/


text:
package toru.io.my.bviper.interactor;

/**
 * Created by toruchoi on 08/10/2017.
 */

public interface BViperInteractorOut<T> {
    void onResponseSuccess(T result);
    void onResponseFailed(Throwable throwable);
}


text:
package com.toscaruntime.util;

import java.util.concurrent.TimeUnit;

public class SynchronizationUtil {

    public interface Predicate {

        boolean isSatisfied();
    }

    public static boolean waitUntilPredicateIsSatisfied(Predicate predicate, int times, long coolDown, TimeUnit timeUnit) {
        int currentTimes = 0;
        while (true) {
            if (predicate.isSatisfied()) {
                return true;
            } else {
                if (currentTimes++ > times) {
                    return false;
                }
                try {
                    Thread.sleep(timeUnit.toMillis(coolDown));
                } catch (InterruptedException e) {
                    return false;
                }
            }
        }
    }
}


text:
layout: blog
title: 'Empower to protect: Recalls & safety alerts in Canada'
description: >-
  We interviewed Eric Chouinard for our 'People behind the service' series. Read about his experiences (as Project Manager) re-designing and launching the 'Recall and safety alerts' subscription service at Health Canada.
author: 'Eric Chouinard, Health Canada'
date: '2022-07-05T14:30:00.000Z'
image: https://de2an9clyit2x.cloudfront.net/A_EN_Blog_Post_image_jpg_bdb43ff50e.jpg
image-alt: Photograph of Eric Chouinard, RSA Project Manager at Health Canada. They're being featured in CDS's "people behind the service" series.
thumb: https://de2an9clyit2x.cloudfront.net/small_A_EN_Blog_Post_image_jpg_bdb43ff50e.jpg
translationKey: blog-pbs-series-eric
---
Did you hear about the [recent berries recall](https://recalls-rappels.canada.ca/en/alert-recall/below-zero-brand-whole-raspberries-iqf-recalled-due-norovirus)  or the [Kinder one in April](https://recalls-rappels.canada.ca/en/alert-recall/certain-kinder-brand-chocolate-products-recalled-due-possible-salmonella-0)?

They have been issued by the [Recalls and Safety Alerts (RSA)](https://recalls-rappels.canada.ca/en) team!

A team dedicated to bringing you some peace of mind when it comes to the 'safety' of products you (and millions of people in Canada) consume daily.

One of the key ways the Government of Canada works to protect your health and safety is by regulating the products you use and consume daily. Everything from food, health products, medical equipment, consumer products, vehicles, and cannabis.

If these products become unsafe (for any reason), regulatory groups at various departments play a vital role in notifying the public. Together, they help keep people in Canada updated and safe by posting the information online, via the RSA website.

It's clear that public services can help many people better inform themselves on the products they consume. Improving this service improves people's ability to protect themselves, as Eric Chouinard on the RSA team shares in his  interview below!

---

## **How GC Notify improved Health Canada's RSA service**
Back in November of 2021, Health Canada launched a new [Recalls and Safety Alerts (RSA) website](https://recalls-rappels.canada.ca/en) that completely overhauled the previous site, improving it to have many new features.

A helpful new feature for the public is the [RSA subscription service](https://recalls-rappels.canada.ca/en/subscribe). It uses [GC Notify](https://notification.canada.ca/home), a notification tool designed by CDS for GC public servants, that enables the public to sign up to receive email notifications when a recall or safety alert is posted online.

### **People can also customize their notifications by:**
- Setting their language preference; English or French.
- Choosing how often to receive notifications; once a day or in real time.
- Selecting which products to receive notifications for.

---

## **Interviewing Eric Chouinard, Project Manager on the RSA team**
To learn more about how our [GC Notify](https://notification.canada.ca/home) tool empowered the RSA team to set up a subscription notification service to better protect the public, we sat down with Eric Chouinard, Project Manager for the [RSA Service](https://recalls-rappels.canada.ca/en) at Health Canada.

![Photo of Eric Chouinard, Project Manager on the RSA team, Health Canada](https://de2an9clyit2x.cloudfront.net/eric_chouinard_headshot_19bf0ca15e.jpg)
*Photo of Eric Chouinard, Project Manager on the RSA team, Health Canada*

### **Q1: What are the benefits of RSA's new subscription feature?**

#### **Enabling product selection for notifications**
The subscription feature allows you to receive direct notifications about any type of consumer, food, medical, or health products that are the subject of a [recall, safety alert](https://recalls-rappels.canada.ca/en/subscribe), and/or advisory.

This is a huge improvement as it allows visitors to sign up to one tool and get notifications about multiple types of products regulated by different departments and agencies. You can specify the product type(s) that you are interested in or simply receive all notices. This is especially useful if you have food allergies or if you're a parent who wants to make sure the food and consumer products that you purchase for your family are safe. I'm a parent myself and appreciate that extra bit of protection.

A recent example is the [public advisory](https://recalls-rappels.canada.ca/en/alert-recall/shortage-infant-formulas-babies-food-allergies-what-you-should-know-and-do) RSA sent out for infant formula shortages, that Health Canada [tweeted](https://twitter.com/GovCanHealth/status/1534218921192132610) guidance for. Together, regulatory groups at various departments are helping keep people in Canada safe by providing updates online.

#### **Providing frequency options for notifications**
Subscribers have the option to receive immediate notifications (once they're posted to the website) or a single, daily notification, depending on subscription preferences. This enables subscribers to get relevant notifications, tailored to their needs, right to their email inbox.

#### **RSAs are reaching many and growing!**
The RSA notification system uses the GC Notify tool to send out emails to subscribers. As of June 2022, there are more than 40 000 subscribers receiving notifications from the RSA system.
To date, the system has generated a click-through rate (CTR) of over 15%, more than triple the government average for email links. So it's clear people are wanting this recall and safety information!

![Screenshot of the email subscription page for RSA. It shows the language preference and frequency options and lists selections for product alerts.](https://de2an9clyit2x.cloudfront.net/en_eric_chouinard_rsa_graph_591e8666eb.jpeg)
*Screenshot of the email subscription page for RSA. It shows the language preference and frequency options and lists selections for product alerts.*

### **Q2: How has GC Notify improved the way your team serves the public?**

#### **Getting time-sensitive alerts out quicker**
GC Notify made it easy for our project team to use an off-the-shelf Government of Canada system to send timely, accessible, and bilingual notifications to the public.

In the past, posting recalls to our website and issuing a recall notification could take 1 to 2 hours, and only some programs had notification tools. Now, it can take as little as 15-25 minutes to create a notification and activating the subscription notification is as easy as checking off a box.

Not only can we send notifications about new recalls, safety alerts, and advisories, but we can also send notifications about updated recalls and alerts!

#### **Improved user experiences**
This was my first experience using and creating an account for GC Notify. I found it to be very user friendly and secure. It includes a two-factor authentication function, which is necessary for this type of system.
Our vendor made the [Drupal module](https://www.drupal.org/project/message_gcnotify) we used to integrate GC Notify publicly available, so any government department can use it!

#### **Increasing the reach of notifications**
The more channels that we can use to communicate with people, and the easier it is to send out notifications, the better.

When Health Canada and our partners post a recall, safety alert, or advisory, they will typically send the information out via official social media channels. These messages aren't tailored to people's needs and not all people who need the info are on socials/following those accounts. The email subscription service empowers people with an additional channel to get this info. Now, people without socials can get tailored updates.

**Performance statistics:** Since the RSA service launched in November 2021, there have been 3.5 million visitors to our website, creating over 6.5 million page views!

![Screenshot of RSA's 'Messages sent' dashboard for GC Notify. From 2021 to 2022, they've sent over a million emails, significantly increasing in April, 2022.](https://de2an9clyit2x.cloudfront.net/en_eric_chouinard_email_graph_6dbd2ecf8a.jpg)
*Screenshot of RSA's 'Messages sent' dashboard for GC Notify. From 2021 to 2022, they've sent over a million emails, significantly increasing in April, 2022.*

### **Q3: Can you tell us a little bit about how and when you ended up working on this project?**
I was looking for an opportunity to work on an agile IT project that would provide me with the chance to work with a dedicated team of professionals on something that has a *meaningful impact* for people in Canada.

#### **RSA service timeline**
My predecessors initially began this project in 2018, with many talented colleagues and partners setting the foundation for the work my team has carried on. When I began work on the project in 2020, we were on the cusp of finalizing our contract with our IT vendor, in order to begin the development work. My supervisor, David Gotlieb, had been instrumental in the project's later stages, as well as contracting for the vendor.

We began the development of the new CMS and website in January 2021 and hit the ground running. By November 2021, we launched the new CMS and new website. Since then, we've been improving, refining, and adding new features that continue to enhance the end-user experience (both on the CMS and public-facing website), including the notifications subscription service powered by GC Notify.

As the project enters its next development phases, the project team, our executive team, and our partners are looking forward to continuing to build on our successes and plan for the future of the RSA service CMS and website.

#### **Giving credit where it's due**
We worked and collaborated with our colleagues at the Canadian Food Inspection Agency (CFIA), Environment and Climate Change Canada (ECCC), and Transport Canada (TC) to align our information management systems. It has been a great experience.

Their collaboration has helped us develop a recalls and safety alerts CMS tool that enables partners to:

- Maximize efficiency;
- Reduce processing times; and
- Send information out to people in Canada as efficiently and quickly as possible.

Also, our information technology vendor on the project, OpenPlus, has been instrumental in helping us achieve our technical goals. Using an agile methodology, we've been able to accomplish a significant amount of work in a short period of time.

Huge credit also goes to our executive team, led by Renée Couturier and Patrycja Arkuszewski, our Health Canada colleagues, and Government of Canada partners. It's because of your support that we've been able to make this project a success!

## **Conclusion**
Are you interested in receiving recall and safety alert notifications?
Be sure to **check out the [RSA Website](https://recalls-rappels.canada.ca/en/subscribe) and subscribe!**

Or are you a public servant interested in sending notifications faster and more securely?

**[Contact our GC Notify team](https://notification.canada.ca/contact) for a demo to learn more information!**