text:
window.voicesearch = {};
voicesearch.hotwords = [
  "ok google",
  "okay google",
  "ok papyrus",
  "okay papyrus",
  "hi papyrus",
  "hey papyrus"
];
voicesearch.hotwordsCustom = JSON.parse(localStorage.getItem("voicesearch:hotwords") || "[]") || [];
voicesearch.alwaysListening = (localStorage.getItem("voicesearch:alwaysListening") || "false") == "true";
voicesearch.alwaysListeningTimeoutTime = 1000;
voicesearch.alwaysListeningPhase = -1;
voicesearch.speechTimeoutTime = 250;

voicesearch.handlers = [
  {id: "google", handler: function(query) {
    handleSearch(query);
    location.href = "https://www.google.com/search?gs_ivs=1&q="+encodeURIComponent(query).replace(new RegExp("%20", "g"), " ");
    return true;
  }}
];

if (localize) {
  console.log("voicesearch.js found localize.js; adding listeners...");
  localize.listeners.get.push(function(lang, data) {
    if (data.hotwords) {
      voicesearch.hotwords = voicesearch.hotwords.concat(data.hotwords);
    }
  });
}

voicesearch.recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition || window.oSpeechRecognition)();
voicesearch.active = false;
voicesearch.ignore = "";
voicesearch.ignoreRegexp = null;

voicesearch.override = {
  onerror: function() {
    voicesearch.active = false;
    if (voicesearch.alwaysListening && voicesearch.alwaysListeningPhase == -1) {
      voicesearch.alwaysListeningPhase = 1;
      setTimeout(function() {voicesearch.recognition.start();}, voicesearch.alwaysListeningTimeoutTime);
    } else if (voicesearch.context.onerror) {voicesearch.context.onerror.apply(this, arguments)};
  },
  onstart: function() {
    voicesearch.active = true;
    if (voicesearch.context.onstart && voicesearch.alwaysListeningPhase > -1) {voicesearch.context.onstart.apply(this, arguments)};
    voicesearch.alwaysListeningPhase = -1;
  },
  onend: function() {
    voicesearch.active = false;
    if (voicesearch.alwaysListening && voicesearch.alwaysListeningPhase == -1) {
      voicesearch.alwaysListeningPhase = 1;
      setTimeout(function() {voicesearch.recognition.start();}, voicesearch.alwaysListeningTimeoutTime);
    } else if (voicesearch.context.onend) {voicesearch.context.onend.apply(this, arguments)};
  }
};
voicesearch.speech = {
  name: "speech",
  continuous: true,
  interimResults: true,
  onresult: function(event) {
    if (typeof(event.results) == "undefined") {
      voicesearch.stopListening(true);
      return;
    }
    var final = "";
    var approx = "";
    var isFinal = true;
    var backdrop = $("#button-g-backdrop");
    backdrop.css("transition-duration", "");
    backdrop.css("transition-property", "");
    backdrop.css("transition-timing-function", "");
    var convidenceSum = 0;
    for (var i = event.resultIndex; i < event.results.length; i++) {
      convidenceSum += event.results[i][0].confidence;
      var transcript = event.results[i][0].transcript;
      if (transcript.toLowerCase().indexOf(voicesearch.ignore) >= 0) {
        transcript = transcript.substr(transcript.toLowerCase().indexOf(voicesearch.ignore) + voicesearch.ignore.length);
      } else if (i > event.resultIndex) {
        var transcriptTmp = transcript + event.results[i-1][0].transcript;
        if (transcriptTmp.toLowerCase().indexOf(voicesearch.ignore) >= 0) {
          transcriptTmp = transcriptTmp.substr(transcriptTmp.toLowerCase().indexOf(voicesearch.ignore) + voicesearch.ignore.length);
        }
        if (transcriptTmp.length <= 1) {
          isFinal = false;
          continue;
        }
      } else if (i < event.results.length-1) {
        var transcriptTmp = transcript + event.results[i+1][0].transcript;
        if (transcriptTmp.toLowerCase().indexOf(voicesearch.ignore) >= 0) {
          transcriptTmp = transcriptTmp.substr(transcriptTmp.toLowerCase().indexOf(voicesearch.ignore) + voicesearch.ignore.length);
        }
        if (transcriptTmp.length <= 1) {
          isFinal = false;
          continue;
        }
      }
      backdrop.css("transform", "scale("+(1.0 + (1.0 - (convidenceSum / (event.results.length - event.resultIndex))) + Math.sin(new Date().getTime() / 300 + Math.random() * 0.3) * 0.2 )+")");
      /*backdrop.css("transition-duration", "0.1s");
      backdrop.css("transition-property", "transform");
      backdrop.css("transition-timing-function", "cubic-bezier(0, 0, 0.2, 1)");
      backdrop.css("transform", "scale(1.0)");*/
      if (transcript.length <= 1) {
        isFinal = false;
        continue;
      }
      if (event.results[i].isFinal || event.results[i][0].confidence >= 0.2) {
        final += transcript;
      } else {
        approx += transcript;
        isFinal = false;
      }
    }

    voicesearch.spoke = true;

    if (final.length > 0 || approx.length > 0) {
      $("#speech").text(final);
      $("#speech-approx").text(approx);
    } else {
      $("#speech").text(localized("search.voice.now"));
      $("#speech-approx").text(localized("search.voice.example"));
      isFinal = false;
    }

    if (isFinal && !voicesearch.speechTimeout) {
      if (voicesearch.speechTimeout) {
        clearTimeout(voicesearch.speechTimeout);
      }
      voicesearch.speechTimeout = setTimeout(function() {voicesearch.ignore = final; voicesearch.ignoreRegexp = new RegExp(voicesearch.ignore, "i"); voicesearch.stopListening(true)}, voicesearch.speechTimeoutTime);
    } else if (!isFinal && voicesearch.speechTimeout) {
      clearTimeout(voicesearch.speechTimeout);
      voicesearch.speechTimeout = null;
    }
  },
  onerror: function(event) {
    $("#speech").text(localized("search.voice.error"));
    $("#speech-approx").text("");
    setTimeout(voicesearch.hideSpeechOverlay, 5000);
    voicesearch.stopListening(false);
    voicesearch.startHotword(true);
  },
  onstart: function(event) {
    $("#speech").text(localized("search.voice.now"));
    $("#speech-approx").text(localized("search.voice.example"));
  },
  onend: function(event) {
    voicesearch.hideSpeechOverlay();
    voicesearch.stopListening(false);
  }
};
voicesearch.hotword = {
  name: "hotword",
  continuous: true,
  interimResults: true,
  onresult: function(event) {
    if (typeof(event.results) == "undefined") {
      voicesearch.stopHotword();
      return;
    }
    var final = "";
    var approx = "";
    for (var i = event.resultIndex; i < event.results.length; i++) {
      var transcript = event.results[i][0].transcript;
      if (transcript.toLowerCase().indexOf(voicesearch.ignore) >= 0) {
        transcript = transcript.substr(transcript.toLowerCase().indexOf(voicesearch.ignore) + voicesearch.ignore.length);
      }
      if (event.results[i].isFinal || event.results[i][0].confidence >= 0.2) {
        final += transcript;
      } else {
        approx += transcript;
      }
    }
    var text = final.toLowerCase()+" "+approx.toLowerCase();
    var hotword = null;
    for (var i = 0; i < voicesearch.hotwords.length && !hotword; i++) {
      if (text.indexOf(voicesearch.hotwords[i]) >= 0) {
        hotword = voicesearch.hotwords[i];
        break;
      }
    }
    for (var i = 0; i < voicesearch.hotwordsCustom.length && !hotword; i++) {
      if (text.indexOf(voicesearch.hotwordsCustom[i].toLowerCase()) >= 0) {
        hotword = voicesearch.hotwordsCustom[i].toLowerCase();
        break;
      }
    }
    if (hotword) {
      console.log("voicesearch: found hotword " + hotword);
      voicesearch.ignore = hotword;
      voicesearch.ignoreRegexp = new RegExp(voicesearch.ignore, "i");
      voicesearch.showSpeechOverlay();
      voicesearch.stop(false, true);
      voicesearch.startListening(true);
    }
  },
  onstart: function(event) {voicesearch.showHotwordHint();},
  onend: function(event) {voicesearch.hideHotwordHint();}
};

voicesearch.speechTimeout = null;
voicesearch.spoke = false;
voicesearch.animFloatShow = null;

voicesearch.context = voicesearch.hotword;

voicesearch.showSpeechOverlay = function() {
  var floatOuter = $("#float-outer");
  floatOuter.css("pointer-events", "auto");
  var startElem = $("#fkbx-spch");
  if (startElem.css("display") == "none") {
    startElem = $("#fkbx-hspch");
  }
  var startX = Math.round(startElem.offset().left + startElem.outerWidth()/2);
  var startY = Math.round(startElem.offset().top + startElem.outerHeight()/2);
  floatOuter.css("webkitAnimationName", null);
  floatOuter.css("display", "block");
  floatOuter.css("opacity", 1);
  if (!voicesearch.animFloatShow) {
    var styles = document.styleSheets;
    for (var i = 0; i < styles.length; i++) {
      if (!styles[i].cssRules) {
        continue;
      }
      for (var ii = 0; ii < styles[i].cssRules.length; ii++) {
        if (styles[i].cssRules[ii].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && styles[i].cssRules[ii].name == "float-show") {
          voicesearch.animFloatShow = styles[i].cssRules[ii];
          voicesearch.animFloatShow.deleteRule("0%");
          voicesearch.animFloatShow.deleteRule("50%");
          voicesearch.animFloatShow.deleteRule("100%");
          voicesearch.animFloatShow.appendRule("0% {top: "+(startY-$(window).scrollTop()-1)+"px; left: "+(startX-$(window).scrollLeft()-1)+"px; width: 2px; height: 2px; border-radius: "+Math.round(Math.max($(window).width(), $(window).height())/2)+"px;}");
          voicesearch.animFloatShow.appendRule("50% {top: "+Math.round($(window).height()/2 - Math.round(Math.max($(window).width(), $(window).height())/2))+"px; left: "+Math.round($(window).width()/2 - Math.round(Math.max($(window).width(), $(window).height())/2))+"px; width: "+Math.round(Math.max($(window).width(), $(window).height()))+"px; height: "+Math.round(Math.max($(window).width(), $(window).height()))+"px;}");
          voicesearch.animFloatShow.appendRule("100% {border-radius: 0;}");
          break;
        }
      }
    }
  }
  floatOuter.css("webkitAnimationName", "float-show");
  setTimeout(function() {
    floatOuter.css("width", "100%");
    floatOuter.css("height", "100%");
    floatOuter.css("top", 0);
    floatOuter.css("left", 0);
  }, 500);
};

voicesearch.hideSpeechOverlay = function() {
  $("#float-outer").css("pointer-events", "none");
  $("#float-outer").velocity({
    opacity: 0
  }, 300, function() {
    $("#float-outer").css("display", "none");
  });
};

voicesearch.showHotwordHint = function() {
  $("#fkbx-spch").css("display", "none");
  $("#fkbx-hspch, #fkbx-hht").css("display", "block");
}

voicesearch.hideHotwordHint = function() {
  $("#fkbx-spch").css("display", "block");
  $("#fkbx-hspch, #fkbx-hht").css("display", "none");
}

voicesearch.startListening = function(keepSession) {
  $("#speech").text(localized("search.voice.allow"));
  $("#speech-approx").text("");
  voicesearch.spoke = false;

  voicesearch.start(voicesearch.speech, keepSession);
}

voicesearch.stopListening = function(parseQuery) {
  if (voicesearch.speechTimeout) {
    clearTimeout(voicesearch.speechTimeout);
    voicesearch.speechTimeout = null;
  }
  voicesearch.stop(true, true);
  if (parseQuery && voicesearch.spoke) {
    var query = $("#speech").text()+" "+$("#speech-approx").text();
    for (var i = 0; i < voicesearch.handlers.length; i++) {
      if (voicesearch.handlers[i].handler(query)) {
        break;
      }
    }
  } else {
    voicesearch.startHotword(true);
  }
  voicesearch.spoke = false;
}

voicesearch.startHotword = function(keepSession) {
  voicesearch.start(voicesearch.hotword, keepSession);
};

voicesearch.stopHotword = function(keepSession) {
  voicesearch.stop(false, keepSession);
};

voicesearch.start = function(context, keepSession) {
  console.log("voicesearch: start with new context " + (context || {name: "undefined"}).name + " while" + (keepSession ? "" : " not") + " keeping the session");

  for (var key in (voicesearch.context || {})) {
    voicesearch.recognition[key] = null;
  }
  if (context) {
    voicesearch.context = context;
  }
  for (var key in (voicesearch.context || {})) {
    voicesearch.recognition[key] = voicesearch.context[key];
  }

  voicesearch.recognition.lang = loc.lang+"-"+loc.country;

  for (var key in (voicesearch.override || {})) {
    voicesearch.recognition[key] = voicesearch.override[key];
  }

  if (!keepSession || !voicesearch.active) {
    voicesearch.recognition.start();
  } else if (voicesearch.recognition.onstart && voicesearch.context) {
    voicesearch.recognition.onstart();
  }
};

voicesearch.stop = function(force, keepSession) {
  console.log("voicesearch: stop on context " + (voicesearch.context || {name: "undefined"}).name + (force ? ", enforcing it" : "") + " while" + (keepSession ? "" : " not") + " keeping the session");

  if (force) {
    voicesearch.recognition.onend = null;
    voicesearch.active = !keepSession;
  }

  if (!keepSession) {
    voicesearch.recognition.stop();
  } else if (voicesearch.recognition.onend && voicesearch.context) {
    voicesearch.recognition.onend();
  }

  voicesearch.active = keepSession;
};

voicesearch.setAlwaysListening = function(value) {
  voicesearch.alwaysListening = value;
  localStorage.setItem("voicesearch:alwaysListening", value);
  $("#settings-hotword-alwayslistening").prop("checked", value);
};

$(document).ready(function() {
  $("#fkbx-spch, #fkbx-hspch").click(function(event) {
    voicesearch.showSpeechOverlay();
    voicesearch.startListening(true);
  });
  //TODO initialize and remove when listening
  $(".dark").click(function() {
    voicesearch.hideSpeechOverlay();
    voicesearch.stopListening(false);
  });
  $("#button-g").click(function() {
    voicesearch.hideSpeechOverlay();
    voicesearch.stopListening(true);
  });

  voicesearch.startHotword();
});


text:
package org.elasticsearch.index.analysis;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.synonym.SolrSynonymParser;
import org.apache.lucene.analysis.synonym.SynonymGraphFilter;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.analysis.synonym.WordnetSynonymParser;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;

import java.io.IOException;
import java.io.Reader;

public class SynonymGraphTokenFilterFactory extends SynonymTokenFilterFactory {
    public SynonymGraphTokenFilterFactory(IndexSettings indexSettings, Environment env, AnalysisRegistry analysisRegistry,
                                     String name, Settings settings) throws IOException {
        super(indexSettings, env, analysisRegistry, name, settings);
    }

    @Override
    public TokenStream create(TokenStream tokenStream) {
        throw new IllegalStateException("Call createPerAnalyzerSynonymGraphFactory to specialize this factory for an analysis chain first");
    }

    Factory createPerAnalyzerSynonymGraphFactory(Analyzer analyzerForParseSynonym, Environment env){
        return new Factory("synonymgraph", analyzerForParseSynonym, getRulesFromSettings(env));
    }

    public class Factory implements TokenFilterFactory{

        private final String name;
        private final SynonymMap synonymMap;

        public Factory(String name, final Analyzer analyzerForParseSynonym, Reader rulesReader) {
            this.name = name;

            try {
                SynonymMap.Builder parser;
                if ("wordnet".equalsIgnoreCase(format)) {
                    parser = new WordnetSynonymParser(true, expand, analyzerForParseSynonym);
                    ((WordnetSynonymParser) parser).parse(rulesReader);
                } else {
                    parser = new SolrSynonymParser(true, expand, analyzerForParseSynonym);
                    ((SolrSynonymParser) parser).parse(rulesReader);
                }
                synonymMap = parser.build();
            } catch (Exception e) {
                throw new IllegalArgumentException("failed to build synonyms", e);
            }
        }

        @Override
        public String name() {
            return this.name;
        }

        @Override
        public TokenStream create(TokenStream tokenStream) {
            // fst is null means no synonyms
            return synonymMap.fst == null ? tokenStream : new SynonymGraphFilter(tokenStream, synonymMap, ignoreCase);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
fi.vtt.routinelibrary.internal
</TITLE>

<META NAME="date" CONTENT="2013-02-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

fi.vtt.routinelibrary.internal

Classes

ApplicationsService

CellIdService

FileSystem

HTTPUploader

InternalRoutine

LoggerService

RoutineService

State


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.axway.grapes.sample.maven</groupId>
    <artifactId>model</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <groupId>org.axway.grapes.sample.maven.model</groupId>
  <artifactId>core</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>core</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>
</project>


text:
module Jekyll
  module Paginate
    module Tagger

      class TagPagination < Generator
        safe true
        priority :lowest

        def generate(site)
          if Paginate::Pager.pagination_enabled?(site)
            site.tags.each do |tag, posts|
              total = Paginate::Pager.calculate_pages(posts, site.config['paginate'])
              (1..total).each do |i|
                site.pages << TagIndexPage.new(site, tag, i)
              end
            end
          end
        end
      end

      class TagIndexPage < Page
        def initialize(site, tag, num_page)
          @site = site
          @base = site.source

          tag_dir = site.config['tag_dir'] || 'tags'
          @dir = File.join(tag_dir, tag)

          @name = Paginate::Pager.paginate_path(site, num_page)
          @name.concat '/' unless @name.end_with? '/'
          @name += 'index.html'

          self.process(@name)

          # tag_layout = site.config['tag_layout'] || 'index.html'
          # self.read_yaml(@base, tag_layout)
          self.read_yaml(File.join(@base, '_layouts'), 'tag_index.html')
          tag_title_prefix = site.config['tag_title_prefix'] || 'Tag: '
          self.data.merge!(
                           'tag'  => tag,
                           'title'     => "#{tag}#{tag_title_prefix}",
                           'paginator' => Paginate::Pager.new(site, num_page, site.tags[tag])
                          )
        end
      end

    end
  end
end


text:
define(["require", "exports", "./util", "./view"], function (require, exports, util_1, view_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const DEFAULT_PLOT_OPTIONS = {
        width: 1,
        snap: false,
    };
    class Graph extends view_1.View {
        constructor(parent, options) {
            super();
            this.options = options;
            this.lineDash = false;
            this.xTickPoints = [];
            this.yTickPoints = [];
            this.xStart = 0;
            this.xEnd = 1;
            this.yStart = 0;
            this.yEnd = 1;
            this.moveNum = 0;
            this.xStart = options.xStart;
            this.xEnd = options.xEnd;
            this.yStart = options.yStart;
            this.yEnd = options.yEnd;
            this.xTicks = options.xTicks || false;
            this.yTicks = options.yTicks || false;
            this.marginTopPct = options.marginTop || 0.05;
            this.marginBottomPct = options.marginBottom || 0.05;
            this.marginLeftPct = options.marginLeft || 0.05;
            this.marginRightPct = options.marginRight || 0.05;
            if (typeof (parent) == 'string') {
                parent = util_1.getElement(parent);
            }
            let canvas = document.createElement('canvas');
            this.ctx = canvas.getContext('2d');
            parent.appendChild(canvas);
            this.resizeCanvas();
            window.addEventListener('resize', () => {
                this.resizeCanvas();
                this.draw();
            });
            this.draw();
        }
        resizeCanvas() {
            let pr = util_1.pixelRatio();
            let ctx = this.ctx;
            let canvas = ctx.canvas;
            let parent = canvas.parentElement;
            canvas.width = pr * parent.offsetWidth;
            canvas.height = pr * parent.offsetHeight;
            canvas.style.width = `${parent.offsetWidth}px`;
            canvas.style.height = `${parent.offsetHeight}px`;
            this.marginTop = Math.floor(this.marginTopPct * canvas.width);
            this.marginBottom = Math.floor(this.marginBottomPct * canvas.width);
            this.marginLeft = Math.floor(this.marginLeftPct * canvas.width);
            this.marginRight = Math.floor(this.marginRightPct * canvas.width);
            let w = canvas.width - this.marginLeft - this.marginRight;
            let h = canvas.height - this.marginTop - this.marginBottom;
            this.xScale = w / (this.xEnd - this.xStart);
            this.yScale = h / (this.yEnd - this.yStart);
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
        }
        setMoveNum(moveNum) {
            if (moveNum != this.moveNum) {
                this.moveNum = moveNum;
                this.draw();
            }
        }
        drawImpl() {
            this.updateScale();
            let pr = util_1.pixelRatio();
            let ctx = this.ctx;
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            ctx.translate(this.marginLeft + 0.5, this.marginTop + 0.5);
            ctx.lineWidth = pr;
            ctx.strokeStyle = '#96928f';
            this.beginPath();
            this.moveTo(this.xStart, 0, true);
            this.lineTo(this.xEnd, 0, true);
            this.moveTo(0, this.yStart, true);
            this.lineTo(0, this.yEnd, true);
            if (this.xTicks) {
                this.xTickPoints = this.calculateTickPoints(this.xStart, this.xEnd);
                let y = 4 * pr / this.yScale;
                if (this.yEnd > this.yStart) {
                    y = -y;
                }
                for (let x of this.xTickPoints) {
                    this.moveTo(x, 0, true);
                    this.lineTo(x, y, true);
                }
            }
            if (this.yTicks) {
                this.yTickPoints = this.calculateTickPoints(this.yStart, this.yEnd);
                let x = 4 * pr / this.xScale;
                if (this.xEnd > this.xStart) {
                    x = -x;
                }
                for (let y of this.yTickPoints) {
                    this.moveTo(0, y, true);
                    this.lineTo(x, y, true);
                }
            }
            this.stroke();
        }
        drawText(text, x, y, snap = false) {
            x = this.xScale * (x - this.xStart);
            y = this.yScale * (y - this.yStart);
            if (snap) {
                x = Math.round(x);
                y = Math.round(y);
            }
            this.ctx.fillText(text, x, y);
        }
        drawPlot(points, options = DEFAULT_PLOT_OPTIONS) {
            if (points.length == 0) {
                return;
            }
            let pr = util_1.pixelRatio();
            let ctx = this.ctx;
            let snap = options.snap || false;
            ctx.lineWidth = (options.width || 1) * pr;
            if (options.style) {
                ctx.strokeStyle = options.style;
            }
            this.beginPath(options.dash || null);
            this.moveTo(points[0][0], points[0][1], snap);
            for (let i = Math.min(1, points.length - 1); i < points.length; ++i) {
                let p = points[i];
                this.lineTo(p[0], p[1], snap);
            }
            this.stroke();
        }
        beginPath(dash = null) {
            let ctx = this.ctx;
            if (dash != null) {
                ctx.lineCap = 'square';
                ctx.setLineDash(dash);
                this.lineDash = true;
            }
            else if (this.lineDash) {
                ctx.lineCap = 'round';
                ctx.setLineDash([]);
            }
            ctx.beginPath();
        }
        stroke() {
            this.ctx.stroke();
        }
        moveTo(x, y, snap = false) {
            x = this.xScale * (x - this.xStart);
            y = this.yScale * (y - this.yStart);
            if (snap) {
                x = Math.round(x);
                y = Math.round(y);
            }
            this.ctx.moveTo(x, y);
        }
        lineTo(x, y, snap = false) {
            x = this.xScale * (x - this.xStart);
            y = this.yScale * (y - this.yStart);
            if (snap) {
                x = Math.round(x);
                y = Math.round(y);
            }
            this.ctx.lineTo(x, y);
        }
        updateScale() {
            let canvas = this.ctx.canvas;
            let w = canvas.width - this.marginLeft - this.marginRight;
            let h = canvas.height - this.marginTop - this.marginBottom;
            this.xScale = w / (this.xEnd - this.xStart);
            this.yScale = h / (this.yEnd - this.yStart);
        }
        calculateTickPoints(start, end) {
            let x = Math.abs(end - start);
            let spacing = 1;
            if (x >= 1) {
                let scale = Math.pow(10, Math.max(0, Math.floor(Math.log10(x) - 1)));
                let top2 = Math.floor(x / scale);
                if (top2 <= 10) {
                    spacing = 1;
                }
                else if (top2 <= 20) {
                    spacing = 2;
                }
                else if (top2 <= 50) {
                    spacing = 5;
                }
                else {
                    spacing = 10;
                }
                spacing *= scale;
            }
            let min = Math.min(start, end);
            let max = Math.max(start, end);
            let positive = [];
            let negative = [];
            if (min <= 0 && max >= 0) {
                positive.push(0);
            }
            for (let x = spacing; x <= max; x += spacing) {
                positive.push(x);
            }
            for (let x = -spacing; x >= min; x -= spacing) {
                negative.push(x);
            }
            negative.reverse();
            return negative.concat(positive);
        }
    }
    exports.Graph = Graph;
});
//# sourceMappingURL=graph.js.map


text:
package ru.job4j.carMarket.model.dao.utils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.util.function.Function;

public class HiberUtil {
    private static final Logger LOGGER = LogManager.getLogger(HiberUtil.class);
    private static final HiberUtil INSTANCE = new HiberUtil();
    private static StandardServiceRegistry registry;
    private SessionFactory session;

    private HiberUtil() {
    }

    public static HiberUtil getInstance() {
        return INSTANCE;
    }

    private SessionFactory getSessionFactory() {
        if (session == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();
                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);
                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();
                // Create SessionFactory
                session = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return session;
    }

    public  <T> T tx(final Function<Session, T> command) {
        Session session = this.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            return command.apply(session);
        } catch (final Exception e) {
            session.getTransaction().rollback();
            LOGGER.error("error", e);
            throw e;
        } finally {
            if (tx.isActive()) {
                tx.commit();
            }
            session.close();
        }
    }

}


text:
/******************************************************************
Change Script 2.0.6.9 - Consolidated

1. pmt_iati_export - filterable activities in iati xml format.
******************************************************************/
UPDATE config SET changeset = 9, updated_date = current_date WHERE "version" = 2.0 AND iteration = 6;
-- SELECT pmt_version();

-- Drop statements
DROP FUNCTION IF EXISTS pmt_filter_iati() CASCADE;

-- select * from pmt_filter_iati('770','','',null,null, 'sparadee@spatialdev.com');

-- pmt_iati_export
CREATE OR REPLACE FUNCTION pmt_filter_iati(classification_ids character varying, organization_ids character varying, unassigned_tax_ids character varying, start_date date, end_date date, email text)
RETURNS BOOLEAN AS
$$
DECLARE
  activities int[];
  execute_statement text;
  filename text;
BEGIN

SELECT INTO activities string_to_array(array_to_string(array_agg(a_ids), ','), ',')::int[] FROM pmt_filter_projects($1,$2,$3,$4,$5);
RAISE NOTICE 'Activities: %', array_to_string(activities, ',') ;
IF activities IS NOT NULL THEN
 filename := '''/usr/local/pmt_dir/' || $6 || '_' || current_date || '.xml''';
 execute_statement:= 'COPY( ' ||
	  -- activities
	 'SELECT xmlelement(name "iati-activities", xmlattributes(current_date as "generated-datetime", ''1.03'' as "version"),  ' ||
		'( ' ||
		-- activity
		'SELECT xmlagg(xmlelement(name "iati-activity", xmlattributes(to_char(a.updated_date, ''YYYY-MM-DD'') as "last-updated-datetime"),  ' ||
					'xmlelement(name "title", a.title), ' ||
					'xmlelement(name "description", a.description), ' ||
					'xmlelement(name "activity-date", xmlattributes(''start-planned'' as "type", to_char(a.start_date, ''YYYY-MM-DD'') as "iso-date"), ''''), ' ||
					'xmlelement(name "activity-date", xmlattributes(''end-planned'' as "type", to_char(a.end_date, ''YYYY-MM-DD'') as "iso-date"), ''''), ' ||
					-- budget
					'( ' ||
						'SELECT xmlagg(xmlelement(name "budget",  ' ||
							'xmlelement(name "period-start", xmlattributes(to_char(f.start_date, ''YYYY-MM-DD'') as "iso-date"), ''''), ' ||
							'xmlelement(name "period-end", xmlattributes(to_char(f.end_date, ''YYYY-MM-DD'') as "iso-date"), ''''), ' ||
							'xmlelement(name "value",  f.amount) ' ||
						')) ' ||
						'FROM financial f ' ||
						'WHERE f.activity_id = a.activity_id ' ||
					'), ' ||
					-- sector
					'( ' ||
						'SELECT xmlagg(xmlelement(name "sector", xmlattributes(c.iati_code as "code"), c.iati_name))	 ' ||
						'FROM activity_taxonomy at ' ||
						'JOIN classification c ' ||
						'ON at.classification_id = c.classification_id	 ' ||
						'WHERE taxonomy_id = 15 AND at.activity_id = a.activity_id ' ||
					'), ' ||
					-- location
					'( ' ||
						'SELECT xmlagg(xmlelement(name "location",  ' ||
									'xmlelement(name "coordinates", xmlattributes(l.lat_dd as "latitude",l.long_dd as "longitude"), ''''), ' ||
									'xmlelement(name "adinistrative",  ' ||
											'xmlattributes( ' ||
												'( ' ||
												'SELECT c.iati_code ' ||
												'FROM location_taxonomy lt ' ||
												'JOIN classification c ' ||
												'ON lt.classification_id = c.classification_id ' ||
												'WHERE taxonomy_id = (SELECT taxonomy_id FROM taxonomy WHERE name = ''Country'') AND location_id = l.location_id ' ||
												'LIMIT 1 ' ||
												') as "code"), ' ||
											'(  ' ||
											'SELECT array_to_string(array_agg(name), '','') ' ||
											'FROM location_boundary_features ' ||
											'WHERE location_id = l.location_id ' ||
											')) ' ||
							      ') ' ||
							') ' ||
						'FROM location l ' ||
						'WHERE l.activity_id = a.activity_id ' ||
					') ' ||
				') ' ||
			') ' ||
		'FROM activity a		 ' ||
		'WHERE a.activity_id = ANY(ARRAY [' || array_to_string(activities, ',') || ']) ' ||
		') ' ||
	') ' ||
	') To ' || filename || ';';

	EXECUTE execute_statement;
	RETURN TRUE;
ELSE
	RETURN FALSE;
END IF;

RETURN TRUE;

END;$$ LANGUAGE plpgsql;


text: Just a class for testing


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Country',
            fields=[
                ('code', models.CharField(max_length=2, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=256)),
            ],
        ),
    ]


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;

namespace Orleankka.Core
{
    using Utility;

    class ActorPrototype
    {
        static readonly Dictionary<ActorType, ActorPrototype> cache =
                    new Dictionary<ActorType, ActorPrototype>();

        readonly GC gc;
        readonly Dispatcher dispatcher;

        bool closed;

        internal static void Register(ActorType type)
        {
            cache.Add(type, Define(type.Implementation));
        }

        internal static ActorPrototype Define(Type actor)
        {
            var instance = CreateInstance(actor);
            var prototype = CreatePrototype(actor);

            instance.Prototype = prototype;
            instance.Define();

            return prototype.Close();
        }

        static Actor CreateInstance(Type actor)
        {
            return (Actor) Activator.CreateInstance(actor, nonPublic: true);
        }

        static ActorPrototype CreatePrototype(Type actor)
        {
            return new ActorPrototype(actor);
        }

        ActorPrototype Close()
        {
            closed = true;
            return this;
        }

        internal static void Reset()
        {
            cache.Clear();
        }

        internal static ActorPrototype Of(ActorPath path)
        {
            var type = ActorType.Registered(path.Code);

            var prototype = cache.Find(type);
            if (prototype == null)
                throw new InvalidOperationException(
                    $"Can't find implementation for path '{path}'." +
                     "Make sure you've registered assembly containing this type");

            return prototype;
        }

        ActorPrototype(Type actor)
        {
            gc = new GC(actor);
            dispatcher = new Dispatcher(actor);
        }

        internal void KeepAlive(ActorEndpoint endpoint)
        {
            gc.KeepAlive(endpoint);
        }

        internal void RegisterHandler(MethodInfo method)
        {
            AssertClosed();
            dispatcher.Register(method);
        }

        void AssertClosed()
        {
            if (closed)
                throw new InvalidOperationException("Actor prototype can only be defined within Define() method");
        }

        internal void Dispatch(Actor target, object message, Action<object> fallback)
        {
            dispatcher.Dispatch(target, message, fallback);
        }

        internal object DispatchResult(Actor target, object message, Func<object, object> fallback)
        {
            return dispatcher.DispatchResult(target, message, fallback);
        }

        internal Task<object> DispatchAsync(Actor target, object message, Func<object, Task<object>> fallback)
        {
            return dispatcher.DispatchAsync(target, message, fallback);
        }
    }
}


text:
.class public interface abstract Landroid/app/IAppTask;
.super Ljava/lang/Object;
.source "IAppTask.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/app/IAppTask$Stub;
    }
.end annotation

# virtual methods
.method public abstract finishAndRemoveTask()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getTaskInfo()Landroid/app/ActivityManager$RecentTaskInfo;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract moveToFront()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract setExcludeFromRecents(Z)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract startActivity(Landroid/os/IBinder;Ljava/lang/String;Landroid/content/Intent;Ljava/lang/String;Landroid/os/Bundle;)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
// define the entries for the 'Styles' dropdown
CKEDITOR.stylesSet.add('flexcontent', [
    // Block-level styles.
    { name: '.clearfix', element: 'div', attributes: {'class':'clearfix'} },

    // Inline styles.
    { name: 'Sample', element: 'samp' },
    { name: 'Variable', element: 'var' },
    { name: 'Code', element: 'code' },
    { name: 'Command, KBD', element: 'key' },
    { name: 'empty <span>', element: 'span' },
    { name: 'Deleted Text', element: 'del' },

]);

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    // For the complete reference:
    // http://docs.ckeditor.com/#!/api/CKEDITOR.config

    // load the above styleSet 'flexcontent'
    config.stylesSet = 'flexcontent';

  // The toolbar groups arrangement, optimized for two toolbar rows.
    config.toolbar = [
          { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
          { name: 'editing', groups: [ 'find', 'selection' ] },
          { name: 'links', items: [ 'Link', 'hashtaglink', 'flexcontentlink', 'cmspagelink', 'Unlink', 'Anchor'] },
          { name: 'insert', items: [ 'Image', 'Table', 'SpecialChar' ] },
           { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source' ] },
          { name: 'tools', items: [ 'Maximize' ] },
          { name: 'others', items: [ '-' ] },
          '/',
          { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', '-', 'RemoveFormat' ] },
          { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
          { name: 'styles', items: [ 'Styles', 'Format' ] }
      ];

    // Remove some buttons, provided by the standard plugins, which we don't
    // need to have in the Standard(s) toolbar.
    config.removeButtons = 'Subscript,Superscript';

    // Se the most common block elements.
    config.format_tags = 'p;h1;h2;h3;pre';

    // utf8 need no entities!
    config.entities = false;
    config.basicEntities = false;
    config.entities_greek = false;
    config.entities_latin = false;
};


text:
import * as TesseractLib from 'tesseract.js';

TesseractLib.recognize("./demo.png", {
    lang: 'chi_sim',
}).progress(function (p) {
    console.log('progress', p);
}).then(function (result) {
    console.log(result.text)
});

TesseractLib.detect("./demo.png").then(function (result) {
    console.log(result)
});

TesseractLib.recognize("./demo.png")
    .progress(message => console.log(message))
    .catch(err => console.error(err))
    .then(result => console.log(result))
    .finally(resultOrError => console.log(resultOrError));

var job1 = TesseractLib.recognize("./demo.png");
job1.progress(message => console.log(message));
job1.catch(err => console.error(err));
job1.then(result => console.log(result));
job1.finally(resultOrError => console.log(resultOrError));

TesseractLib.create({
    workerPath: '/path/to/worker.js',
    langPath: 'https://cdn.rawgit.com/naptha/tessdata/gh-pages/3.02/',
    corePath: 'https://cdn.rawgit.com/naptha/tesseract.js-core/0.1.0/index.js',
});

Tesseract.recognize("./demo.png", {
    lang: 'chi_sim',
}).progress(function (p) {
    console.log('progress', p);
}).then(function (result) {
    console.log(result.text)
});

Tesseract.detect("./demo.png").then(function (result) {
    console.log(result)
});

Tesseract.recognize("./demo.png")
    .progress(message => console.log(message))
    .catch(err => console.error(err))
    .then(result => console.log(result))
    .finally(resultOrError => console.log(resultOrError));

var job2 = Tesseract.recognize("./demo.png");
job2.progress(message => console.log(message));
job2.catch(err => console.error(err));
job2.then(result => console.log(result));
job2.finally(resultOrError => console.log(resultOrError));

Tesseract.create({
    workerPath: '/path/to/worker.js',
    langPath: 'https://cdn.rawgit.com/naptha/tessdata/gh-pages/3.02/',
    corePath: 'https://cdn.rawgit.com/naptha/tesseract.js-core/0.1.0/index.js',
});


text:
var jsdom = require("jsdom");

module.exports = function(jasmine, htmlFile, callback) {
    jsdom.env({
        file: htmlFile,
        done: function (err, window) {
            if (err) {
                console.log('done' + err);
            }

            // prepare jquery instance using the window we have fixed (using jsdom)
            $ = require("../../bower_components/jquery/dist/jquery")(window);
            expect($).toBeDefined();

            // custom implementation to ensure the matchers is loaded using jquery instance we have prepared.
            jasmine.addMatchers(require('./jasmine-jquery-matchers')($));

            callback($, window);
        }
    })
};


text:
using System;
using Xwt.Drawing;

namespace Xwt.Backends
{
	public interface ISelectColorDialogBackend
	{
		/// <summary>
		/// Gets or sets the selected color
		/// </summary>
		Color Color { get; set; }

		/// <summary>
		/// Runs the dialog, allowing the user to select a color
		/// </summary>
		/// <param name='parent'>
		/// Parent window (the dialog will be modal to this window). It can be null.
		/// </param>
		/// <param name='title'>
		/// Title of the dialog
		/// </param>
		/// <param name='supportsAlpha'>
		/// <c>true</c> if the dialog has to allow selecting an alpha value for the color
		/// </param>
		/// <returns>
		/// <c>true</c> if the user clicked OK, <c>false</c> otherwise
		/// </returns>
		/// <remarks>
		/// The Run method will always be called once (and only once).
		/// The dialog must be shown in modal mode. The method returns when the user clicks on
		/// OK or Cancel. The dialog must be already closed when this method returns.
		/// </remarks>
		bool Run (IWindowFrameBackend parent, string title, bool supportsAlpha, Action<Color> colorChangedCallback);

		/// <summary>
		/// Close the native control
		/// </summary>
		void Close ();

		Size Size { get; }

		Point ScreenPosition { set; }
	}
}


text:
import md5
import argparse
import sys
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import glib
import hashlib
import threading
import time

clipboardfile =""

def callBack(*args):
    value =  clip.wait_for_text()
    global clipboardfile
    with open(clipboardfile,'w+') as afile:
        afile.write(value)

parser = argparse.ArgumentParser(description='process arguments for configuration')
parser.add_argument('-f', action="store",dest="filepath",help='filepath of the clipboard file')

class ClipBoardRunner(threading.Thread):

    def __init__(self, group=None, target=None, name=None,fileconfigpath="", kwargs=None, verbose=None):

        threading.Thread.__init__(self, group=group, target=target,name=name,verbose=verbose)
        self.filepath = fileconfigpath
        self.count = 0
        self.filehash = self.initializeHash()
        self.initialclipboard = ""
        self.tk = ""
        return

    def initializeHash(self):
        return self.getHash()

    def appendToClipboardfile(self,data):
        with open(self.filepath,'w+') as afile:
            afile.write(data)

    def run(self, *args):
        self.count +=1
        while(True):
            with open(self.filepath,'rb') as afile:
                buffer = afile.read()
                if self.isFileChanged():
                    self.filehash = self.getHash()
                    appendtoClipboard(buffer)
            if is_clipboardchanged(self.initialclipboard):
                buffer = getClipboardData()
                if buffer == None:
                    buffer=""
                self.initialclipboard = buffer
                self.appendToClipboardfile(buffer)
            time.sleep(1)

    def isFileChanged(self):
        newHash =  self.getHash()
        if newHash != self.filehash:
            return True
        return False

    def getHash(self):
        hash1 = hashlib.md5()
        with open(self.filepath,'rb') as afile:
            buffer = afile.read(8192)
            hash1.update(buffer)
            filehash = hash1.hexdigest()
        return filehash

def appendtoClipboard(data):
    clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
    clipboard.set_text(data)
    clipboard.store()

def getClipboardData():
    clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
    bufdata = clipboard.wait_for_text()
    return bufdata

def is_clipboardchanged(strtemp):
    clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)

    try:
        if strtemp != clipboard.wait_for_text():
           return True
    except:
        pass
    return False

if __name__ == "__main__":
    args = parser.parse_args()
    global clipboardfile
    clipboardfile = args.filepath
    myclipboard = ClipBoardRunner(fileconfigpath=clipboardfile)
    myclipboard.setDaemon(True)
    myclipboard.initialclipboard=""
    myclipboard.start()
    myclipboard.join()


text:
deps = %w(
consolekit
cryptsetup-bin
dconf-gsettings-backend
fontconfig
fontconfig-config
gconf-service
gconf2
gvfs
libasound2
libasyncns0
libavahi-glib1
libbonobo2-0
libcanberra0
libgconf2-4
libgif4
libgtk2.0-0
libice-dev
libjson0
liblcms2-2
libnspr4
libnss3
libnss3-1d
libpcsclite1
libpthread-stubs0
libpthread-stubs0-dev
libpulse0
libsm-dev
libxau-dev
libxcb1-dev
libxt-dev
ttf-dejavu-extra
libgnome2-0
libgnomevfs2-0
)

if platform_family?('debian')
  deps.each do |dep|
    instance_eval <<-PACKAGE
      package '#{dep}' do
        action :install
      end
    PACKAGE
  end
end


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/lib/stdlib.C $                                            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2010,2014              */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <kernel/heapmgr.H>
#include <kernel/pagemgr.H>
#include <kernel/console.H>

#ifdef HOSTBOOT_MEMORY_LEAKS
#include <arch/ppc.H>

/** Memory allocation function type
 *
 *  These are used as parameters to the magic instruction so that the debug
 *  tools can determine what memory allocation function was being called.
 */
enum MemoryLeak_FunctionType
{
    MEMORYLEAK_MALLOC = 0,
    MEMORYLEAK_REALLOC = 1,
    MEMORYLEAK_FREE = 2
};

/** @fn memoryleak_magic_instruction
 *  @brief Triggers the simics memoryleak analysis magic hap-handler.
 *
 *  Arranges the memory allocation parameters into registers according to the
 *  Power ABI and triggers the magic instruction.  The ABI puts parameter 0-3
 *  into registers r3-r6.
 *
 *  Function attribute of "noinline" is required to ensure that the compiler
 *  treats this as a real function instead of attempting to inline it.  If it
 *  were to inline it then the parameters wouldn't end up in the right register.
 */
static void memoryleak_magic_instruction(MemoryLeak_FunctionType func,
                                         size_t size,
                                         void* ptr,
                                         void* ptr2) __attribute__((noinline));

static void memoryleak_magic_instruction(MemoryLeak_FunctionType func,
                                         size_t size,
                                         void* ptr,
                                         void* ptr2)
{
    MAGIC_INSTRUCTION(MAGIC_MEMORYLEAK_FUNCTION);
    return;
}
#endif

#ifdef MEM_ALLOC_PROFILE
// alloc profile
uint16_t g_0 = 0;
uint16_t g_8 = 0;
uint16_t g_16 = 0;
uint16_t g_32 = 0;
uint16_t g_64 = 0;
uint16_t g_128 = 0;
uint16_t g_256 = 0;
uint16_t g_512 = 0;
uint16_t g_1k = 0;
uint16_t g_2k = 0;
uint16_t g_big = 0;
#endif

void* malloc(size_t s)
{
#ifdef MEM_ALLOC_PROFILE
    if(s == 0) ++g_0;
    else if (s <= 8) ++g_8;
    else if (s <= 16) ++g_16;
    else if (s <= 32) ++g_32;
    else if (s <= 64) ++g_64;
    else if (s <= 128) ++g_128;
    else if (s <= 256) ++g_256;
    else if (s <= 512) ++g_512;
    else if (s <= 1024) ++g_1k;
    else if (s <= 2048) ++g_2k;
    else ++g_big;
#endif

    void* result = HeapManager::allocate(s);

#ifdef HOSTBOOT_MEMORY_LEAKS
    memoryleak_magic_instruction(MEMORYLEAK_MALLOC, s, result, NULL);
#endif

    return result;
}

void free(void* p)
{
    if (NULL == p) return;

#ifdef HOSTBOOT_MEMORY_LEAKS
    memoryleak_magic_instruction(MEMORYLEAK_FREE, 0, p, NULL);
#endif

    HeapManager::free(p);
}

void* realloc(void* p, size_t s)
{
    if (NULL == p) return malloc(s);

    void* result = HeapManager::realloc(p,s);

#ifdef HOSTBOOT_MEMORY_LEAKS
    memoryleak_magic_instruction(MEMORYLEAK_REALLOC, s, result, p);
#endif

    return result;
}

void* calloc(size_t num, size_t size)
{
    // Allocate a block of memory for an array of 'num' elements, each of them
    // 'size' bytes long and initialize to zero
    size_t total_size = num * size;
    void* mem = NULL;

    if (total_size)
    {
        mem = malloc(total_size);
        memset(mem, 0, total_size);
    }

    return mem;
}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.LabServices.Models
{
    /// <summary> The restriction details. </summary>
    public partial class AvailableLabServicesSkuRestrictions
    {
        /// <summary> Initializes a new instance of AvailableLabServicesSkuRestrictions. </summary>
        internal AvailableLabServicesSkuRestrictions()
        {
            Values = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of AvailableLabServicesSkuRestrictions. </summary>
        /// <param name="labServicesSkuRestrictionType"> The type of restriction. </param>
        /// <param name="values"> The values of the restriction. </param>
        /// <param name="reasonCode"> The reason for the restriction. </param>
        internal AvailableLabServicesSkuRestrictions(LabServicesSkuRestrictionType? labServicesSkuRestrictionType, IReadOnlyList<string> values, LabServicesSkuRestrictionReasonCode? reasonCode)
        {
            LabServicesSkuRestrictionType = labServicesSkuRestrictionType;
            Values = values;
            ReasonCode = reasonCode;
        }

        /// <summary> The type of restriction. </summary>
        public LabServicesSkuRestrictionType? LabServicesSkuRestrictionType { get; }
        /// <summary> The values of the restriction. </summary>
        public IReadOnlyList<string> Values { get; }
        /// <summary> The reason for the restriction. </summary>
        public LabServicesSkuRestrictionReasonCode? ReasonCode { get; }
    }
}


text:
namespace password_manager {

class MockPasswordFormManagerForUI : public PasswordFormManagerForUI {
 public:
  MockPasswordFormManagerForUI();

  MockPasswordFormManagerForUI(const MockPasswordFormManagerForUI&) = delete;
  MockPasswordFormManagerForUI& operator=(const MockPasswordFormManagerForUI&) =
      delete;

  ~MockPasswordFormManagerForUI() override;

  MOCK_METHOD(const GURL&, GetURL, (), (const override));
  MOCK_METHOD(const std::vector<const PasswordForm*>&,
              GetBestMatches,
              (),
              (const override));
  MOCK_METHOD(std::vector<const PasswordForm*>,
              GetFederatedMatches,
              (),
              (const override));
  MOCK_METHOD(const PasswordForm&, GetPendingCredentials, (), (const override));
  MOCK_METHOD(metrics_util::CredentialSourceType,
              GetCredentialSource,
              (),
              (const override));
  MOCK_METHOD(PasswordFormMetricsRecorder*, GetMetricsRecorder, (), (override));
  MOCK_METHOD(base::span<const InteractionsStats>,
              GetInteractionsStats,
              (),
              (const override));
  MOCK_METHOD(std::vector<const PasswordForm*>,
              GetInsecureCredentials,
              (),
              (const override));
  MOCK_METHOD(bool, IsBlocklisted, (), (const override));
  MOCK_METHOD(bool, WasUnblocklisted, (), (const override));
  MOCK_METHOD(bool, IsMovableToAccountStore, (), (const override));
  MOCK_METHOD(void, Save, (), (override));
  MOCK_METHOD(void, Update, (const PasswordForm&), (override));
  MOCK_METHOD(void,
              OnUpdateUsernameFromPrompt,
              (const std::u16string&),
              (override));
  MOCK_METHOD(void,
              OnUpdatePasswordFromPrompt,
              (const std::u16string&),
              (override));
  MOCK_METHOD(void, OnNopeUpdateClicked, (), (override));
  MOCK_METHOD(void, OnNeverClicked, (), (override));
  MOCK_METHOD(void, OnNoInteraction, (bool), (override));
  MOCK_METHOD(void, Blocklist, (), (override));
  MOCK_METHOD(void, OnPasswordsRevealed, (), (override));
  MOCK_METHOD(void, MoveCredentialsToAccountStore, (), (override));
  MOCK_METHOD(void, BlockMovingCredentialsToAccountStore, (), (override));
};

}  // namespace password_manager

#endif  // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_FORM_MANAGER_FOR_UI_H_


text:
'use strict';

var express = require('express');
//var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var useragent = require('express-useragent');

var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);

mongoose.connect(process.env.MONGO_URI);

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(useragent.express());

app.route('/')
	.get(function(req, res){
		var ip = req.ip;
		var lang = req.get("Accept-Language").split(',')[0];
		var opsys = req.useragent.os;
		console.log(opsys);

		var sendObj = {
			"ip": ip,
			"Language": lang,
			"OS": opsys
		};

		res.send(JSON.stringify(sendObj));
	});

app.use(passport.initialize());
app.use(passport.session());

//routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});


text:
import readline
from Queue import Empty

class ZMQCompleter(object):
    """Client-side completion machinery.

    How it works: self.complete will be called multiple times, with
    state=0,1,2,... When state=0 it should compute ALL the completion matches,
    and then return them for each value of state."""

    def __init__(self, shell, km):
        self.shell = shell
        self.km =  km
        self.matches = []

    def complete_request(self,text):
        line = readline.get_line_buffer()
        cursor_pos = readline.get_endidx()

        # send completion request to kernel
        # Give the kernel up to 0.5s to respond
        msg_id = self.km.shell_channel.complete(text=text, line=line,
                                                        cursor_pos=cursor_pos)

        msg = self.km.shell_channel.get_msg(timeout=0.5)
        if msg['parent_header']['msg_id'] == msg_id:
            return msg["content"]["matches"]
        return []

    def rlcomplete(self, text, state):
        if state == 0:
            try:
                self.matches = self.complete_request(text)
            except Empty:
                print('WARNING: Kernel timeout on tab completion.')

        try:
            return self.matches[state]
        except IndexError:
            return None

    def complete(self, text, line, cursor_pos=None):
        return self.rlcomplete(text, 0)


text:
package com.google.android.accessibility.talkback;

import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.Nullable;
import com.google.android.accessibility.talkback.Pipeline.SyntheticEvent;
import com.google.android.accessibility.talkback.actor.voicecommands.VoiceCommandProcessor;
import com.google.android.accessibility.talkback.eventprocessor.ProcessorAccessibilityHints;
import com.google.android.accessibility.talkback.interpreters.AccessibilityEventIdleInterpreter;
import com.google.android.accessibility.talkback.interpreters.AccessibilityFocusInterpreter;
import com.google.android.accessibility.talkback.interpreters.AutoScrollInterpreter;
import com.google.android.accessibility.talkback.interpreters.DirectionNavigationInterpreter;
import com.google.android.accessibility.talkback.interpreters.FullScreenReadInterpreter;
import com.google.android.accessibility.talkback.interpreters.InputFocusInterpreter;
import com.google.android.accessibility.talkback.interpreters.PassThroughModeInterpreter;
import com.google.android.accessibility.talkback.interpreters.ScrollPositionInterpreter;
import com.google.android.accessibility.talkback.interpreters.StateChangeEventInterpreter;
import com.google.android.accessibility.talkback.interpreters.SubtreeChangeEventInterpreter;
import com.google.android.accessibility.talkback.interpreters.UiChangeEventInterpreter;
import com.google.android.accessibility.utils.Performance.EventId;

/** Wrapper around all event-interpreters, for use in Pipeline. */
public class Interpreters {

  //////////////////////////////////////////////////////////////////////////////////
  // Member data
  // TODO: Move all event-interpreters into pipeline-interpreters.

  private final InputFocusInterpreter inputFocusInterpreter;
  private final AutoScrollInterpreter autoScrollInterpreter; // Listens to ScrollEventInterpreter
  private final ScrollPositionInterpreter
      scrollPositionInterpreter; // Listens ScrollEventInterpreter
  private final AccessibilityFocusInterpreter accessibilityFocusInterpreter;
  private final FullScreenReadInterpreter continuousReadInterpreter;
  private final StateChangeEventInterpreter stateChangeEventInterpreter;
  private final DirectionNavigationInterpreter directionNavigationInterpreter;
  private final ProcessorAccessibilityHints processorAccessibilityHints;
  private final VoiceCommandProcessor voiceCommandProcessor;
  @Nullable private final PassThroughModeInterpreter passThroughModeInterpreter;
  private final SubtreeChangeEventInterpreter subtreeChangeEventInterpreter;
  private final AccessibilityEventIdleInterpreter accessibilityEventIdleInterpreter;
  private final UiChangeEventInterpreter uiChangeEventInterpreter;

  private final int eventTypeMask; // Union of all sub-interpreter masks

  //////////////////////////////////////////////////////////////////////////////////
  // Construction

  public Interpreters(
      InputFocusInterpreter inputFocusInterpreter,
      AutoScrollInterpreter autoScrollInterpreter,
      ScrollPositionInterpreter scrollPositionInterpreter,
      AccessibilityFocusInterpreter accessibilityFocusInterpreter,
      FullScreenReadInterpreter continuousReadInterpreter,
      StateChangeEventInterpreter stateChangeEventInterpreter,
      DirectionNavigationInterpreter directionNavigationInterpreter,
      ProcessorAccessibilityHints processorAccessibilityHints,
      VoiceCommandProcessor voiceCommandProcessor,
      PassThroughModeInterpreter passThroughModeInterpreter,
      SubtreeChangeEventInterpreter subtreeChangeEventInterpreter,
      AccessibilityEventIdleInterpreter accessibilityEventIdleInterpreter,
      UiChangeEventInterpreter uiChangeEventInterpreter) {

    this.inputFocusInterpreter = inputFocusInterpreter;
    this.autoScrollInterpreter = autoScrollInterpreter;
    this.scrollPositionInterpreter = scrollPositionInterpreter;
    this.accessibilityFocusInterpreter = accessibilityFocusInterpreter;
    this.continuousReadInterpreter = continuousReadInterpreter;
    this.stateChangeEventInterpreter = stateChangeEventInterpreter;
    this.directionNavigationInterpreter = directionNavigationInterpreter;
    this.processorAccessibilityHints = processorAccessibilityHints;
    this.voiceCommandProcessor = voiceCommandProcessor;
    this.passThroughModeInterpreter = passThroughModeInterpreter;
    this.subtreeChangeEventInterpreter = subtreeChangeEventInterpreter;
    this.accessibilityEventIdleInterpreter = accessibilityEventIdleInterpreter;
    this.uiChangeEventInterpreter = uiChangeEventInterpreter;

    eventTypeMask =
        inputFocusInterpreter.getEventTypes()
            | continuousReadInterpreter.getEventTypes()
            | stateChangeEventInterpreter.getEventTypes()
            | subtreeChangeEventInterpreter.getEventTypes()
            | ((passThroughModeInterpreter != null)
                ? passThroughModeInterpreter.getEventTypes()
                : 0);
  }

  public void setActorState(ActorState actorState) {
    inputFocusInterpreter.setActorState(actorState);
    autoScrollInterpreter.setActorState(actorState);
    accessibilityFocusInterpreter.setActorState(actorState);
    continuousReadInterpreter.setActorState(actorState);
    stateChangeEventInterpreter.setActorState(actorState);
    directionNavigationInterpreter.setActorState(actorState);
    if (passThroughModeInterpreter != null) {
      passThroughModeInterpreter.setActorState(actorState);
    }
  }

  public void setPipelineInterpretationReceiver(Pipeline.InterpretationReceiver pipeline) {
    autoScrollInterpreter.setPipelineInterpretationReceiver(pipeline);
    scrollPositionInterpreter.setPipeline(pipeline);
    accessibilityFocusInterpreter.setPipeline(pipeline);
    continuousReadInterpreter.setPipeline(pipeline);
    stateChangeEventInterpreter.setPipeline(pipeline);
    directionNavigationInterpreter.setPipeline(pipeline);
    processorAccessibilityHints.setPipelineInterpretationReceiver(pipeline);
    voiceCommandProcessor.setPipelineInterpretationReceiver(pipeline);
    if (passThroughModeInterpreter != null) {
      passThroughModeInterpreter.setPipeline(pipeline);
    }
    subtreeChangeEventInterpreter.setPipeline(pipeline);
    accessibilityEventIdleInterpreter.setPipeline(pipeline);
    uiChangeEventInterpreter.setPipeline(pipeline);
  }

  //////////////////////////////////////////////////////////////////////////////////
  // Methods
  // TODO: Ensure the flow of interpreting events goes with one-way.

  public int getEventTypes() {
    return eventTypeMask;
  }

  /** Handles accessibility-event, asynchronously returning interpretations to pipeline. */
  public void onAccessibilityEvent(AccessibilityEvent event, EventId eventId) {
    inputFocusInterpreter.onAccessibilityEvent(event, eventId);
    continuousReadInterpreter.onAccessibilityEvent(event, eventId);
    stateChangeEventInterpreter.onAccessibilityEvent(event, eventId);
    subtreeChangeEventInterpreter.onAccessibilityEvent(event, eventId);
    if (passThroughModeInterpreter != null) {
      passThroughModeInterpreter.onAccessibilityEvent(event, eventId);
    }
  }

  public void onIdle() {
    accessibilityEventIdleInterpreter.onIdle();
  }

  /** Handles internally-generated events, asynchronously sends interpretations to pipeline. */
  public void interpret(EventId eventId, SyntheticEvent event) {
    if (event.eventType == SyntheticEvent.Type.SCROLL_TIMEOUT) {
      autoScrollInterpreter.handleAutoScrollFailed();
    }
  }

  ///////////////////////////////////////////////////////////////////////////////
  // Interpreter pass-through methods, to keep interpreters private

}


text:
package io.crate.sql.parser;

import org.antlr.v4.runtime.RecognitionException;

import java.util.Locale;

import static java.lang.String.format;

public class ParsingException extends RuntimeException {

    private final int line;
    private final int charPositionInLine;

    ParsingException(String message, RecognitionException cause, int line, int charPositionInLine) {
        super(message, cause);

        this.line = line;
        this.charPositionInLine = charPositionInLine;
    }

    ParsingException(String message) {
        this(message, null, 1, 0);
    }

    int getLineNumber() {
        return line;
    }

    int getColumnNumber() {
        return charPositionInLine + 1;
    }

    public String getErrorMessage() {
        return super.getMessage();
    }

    @Override
    public String getMessage() {
        return format(Locale.ENGLISH, "line %s:%s: %s", getLineNumber(), getColumnNumber(), getErrorMessage());
    }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.support.test.InstrumentationRegistry;

import androidx.test.filters.SmallTest;

import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.CriteriaNotSatisfiedException;
import org.chromium.content_public.browser.ContactsPicker;
import org.chromium.content_public.browser.ContactsPickerListener;
import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.content_public.browser.test.RenderFrameHostTestExt;
import org.chromium.content_public.browser.test.util.FencedFrameUtils;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.content_shell_apk.ContentShellActivityTestRule;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.ServerCertificate;
import org.chromium.ui.base.WindowAndroid;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Tests contacts Web API functionality.
 */
@RunWith(BaseJUnit4ClassRunner.class)
public class ContactsProviderTest {
    private static final String TEST_URL = "/content/test/data/android/title1.html";
    private static final String FENCED_FRAME_URL =
            "/content/test/data/android/fenced_frames/title1.html";
    private static final String CONTACTS_SCRIPT = "var result = null;"
            + "((async() => {"
            + "  try {"
            + "    const contacts = await navigator.contacts.select("
            + "        ['name', 'email'], { multiple: true });"
            + "    if (contacts) result = 'success'"
            + "  } catch(e) { result = e.message; }"
            + "})())";

    @Rule
    public ContentShellActivityTestRule mActivityTestRule = new ContentShellActivityTestRule();

    @Before
    public void setUp() {
        try {
            mActivityTestRule.launchContentShellWithUrlSync(TEST_URL);
        } catch (Throwable t) {
            Assert.fail("Couldn't load test page.");
        }
    }

    @After
    public void tearDown() {}

    private static String executeJavaScript(
            final RenderFrameHost frame, String js, boolean userGesture) {
        RenderFrameHostTestExt rfh = TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> new RenderFrameHostTestExt(frame));
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<String> result = new AtomicReference<String>();
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            if (userGesture) {
                rfh.executeJavaScriptWithUserGesture(js);
                latch.countDown();
            } else {
                rfh.executeJavaScript(js, (String r) -> {
                    result.set(r);
                    latch.countDown();
                });
            }
        });

        try {
            Assert.assertTrue(latch.await(CallbackHelper.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return result.get();
    }

    private String hasValue(final RenderFrameHost frame) throws TimeoutException {
        return executeJavaScript(frame, "!!result", false);
    }

    private String getValue(final RenderFrameHost frame) {
        return executeJavaScript(frame, "result", false);
    }

    private void waitUntilHasValue(final RenderFrameHost frame) {
        CriteriaHelper.pollInstrumentationThread(() -> {
            try {
                Criteria.checkThat(hasValue(frame), Matchers.equalTo("true"));
            } catch (TimeoutException e) {
                throw new CriteriaNotSatisfiedException(e);
            }
        });
    }

    /**
     * Tests that Contacts API gets contacts correctly with the user gesture in the primary page.
     */
    @Test
    @SmallTest
    public void testGetContactsInPrimaryPageWithUserGesture() {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            ContactsPicker.setContactsPickerDelegate(
                    (WindowAndroid windowAndroid, ContactsPickerListener listener, boolean multiple,
                            boolean names, boolean emails, boolean tels, boolean addresses,
                            boolean icons, String formattedOrigin) -> {
                        List<ContactsPickerListener.Contact> contacts = new ArrayList();
                        List<String> contactsNames = new ArrayList();
                        contactsNames.add("test");
                        contacts.add(new ContactsPickerListener.Contact(contactsNames,
                                /*contactEmails*/ null,
                                /*contactTel*/ null, /*contactAddresses*/ null,
                                /*contactIcons*/ null));

                        listener.onContactsPickerUserAction(
                                ContactsPickerListener.ContactsPickerAction.CONTACTS_SELECTED,
                                contacts,
                                /*percentageShared=*/0, /*propertiesRequested=*/0);
                        return true;
                    });
        });

        RenderFrameHost frame = TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> mActivityTestRule.getWebContents().getMainFrame());
        executeJavaScript(frame, CONTACTS_SCRIPT, true);
        waitUntilHasValue(frame);
        Assert.assertEquals("\"success\"", getValue(frame));
    }

    /**
     * Tests that Contacts API fails to get contacts without the user gesture in the primary page.
     */
    @Test
    @SmallTest
    public void testGetContactsInPrimaryPageWithoutUserGesture() throws Exception {
        RenderFrameHost frame = TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> mActivityTestRule.getWebContents().getMainFrame());
        executeJavaScript(frame, CONTACTS_SCRIPT, false);
        waitUntilHasValue(frame);
        Assert.assertEquals("\"Failed to execute 'select' on 'ContactsManager':"
                        + " A user gesture is required to call this method\"",
                getValue(frame));
    }

    /**
     * Tests that Contacts API fails to get contacts with the user gesture in the fenced frame.
     */
    @Test
    @SmallTest
    @CommandLineFlags.Add({"enable-features=FencedFrames<Study", "force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:implementation_type/mparch"})
    public void
    testDontGetContactsInFencedFrame() throws TimeoutException {
        EmbeddedTestServer testServer = EmbeddedTestServer.createAndStartHTTPSServer(
                InstrumentationRegistry.getInstrumentation().getContext(),
                ServerCertificate.CERT_OK);
        String url = testServer.getURL(FENCED_FRAME_URL);
        RenderFrameHost frame = TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> mActivityTestRule.getWebContents().getMainFrame());
        RenderFrameHost fencedFrame =
                FencedFrameUtils.createFencedFrame(mActivityTestRule.getWebContents(), frame, url);
        executeJavaScript(fencedFrame, CONTACTS_SCRIPT, true);
        waitUntilHasValue(fencedFrame);
        Assert.assertEquals("\"Unable to open a contact selector\"", getValue(fencedFrame));
    }
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Repository;

use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;

/**
 * This factory is used to create default repository objects for documents at runtime.
 */
final class DefaultRepositoryFactory extends AbstractRepositoryFactory
{
    /**
     * {@inheritdoc}
     */
    protected function instantiateRepository($repositoryClassName, DocumentManager $documentManager, ClassMetadata $metadata)
    {
        return new $repositoryClassName($documentManager, $documentManager->getUnitOfWork(), $metadata);
    }
}


text:
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Auth import Auth
from PLC.Slices import Slice, Slices
from PLC.Methods.AddSlice import AddSlice

class SliceCreate(AddSlice):
    """
    Deprecated. See AddSlice.
    """

    status = "deprecated"

    accepts = [
        Auth(),
        Slice.fields['name'],
        AddSlice.accepts[1]
        ]

    returns = Parameter(int, 'New slice_id (> 0) if successful')

    def call(self, auth, name, slice_fields = {}):
        slice_fields['name'] = name
        return AddSlice.call(self, auth, slice_fields)


text:
<?php

namespace Pimcore\Model\Tool\Qrcode;

use Pimcore\Model;

class Config {

    /**
     * @var string
     */
    public $name = "";

    /**
     * @var string
     */
    public $description = "";

    /**
     * @var string
     */
    public $url = "";

    /**
     * @var
     */
    public $foreColor = "";

    /**
     * @var string
     */
    public $backgroundColor = "";

    /**
     * @var bool
     */
    public $googleAnalytics = true;

    /**
     * @param $name
     * @return Config
     * @throws \Exception
     */
    public static function getByName ($name) {
        $code = new self();
        $code->setName($name);
        if(!$code->load()) {
            throw new \Exception("qr-code definition : " . $name . " does not exist");
        }

        return $code;
    }

    /**
     * @static
     * @return string
     */
    public static function getWorkingDir () {
        $dir = PIMCORE_CONFIGURATION_DIRECTORY . "/qrcodes";
        if(!is_dir($dir)) {
            \Pimcore\File::mkdir($dir);
        }

        return $dir;
    }

    /**
     * @return void
     */
    public function save () {

        $arrayConfig = object2array($this);

        $config = new \Zend_Config($arrayConfig);
        $writer = new \Zend_Config_Writer_Xml(array(
            "config" => $config,
            "filename" => $this->getConfigFile()
        ));
        $writer->write();

        return true;
    }

    /**
     * @return void
     */
    public function load () {

        $configXml = new \Zend_Config_Xml($this->getConfigFile());
        $configArray = $configXml->toArray();

        foreach ($configArray as $key => $value) {
            $setter = "set" . ucfirst($key);
            if(method_exists($this, $setter)) {
                $this->$setter($value);
            }
        }

        return true;
    }

    /**
     * @return void
     */
    public function delete() {
        if(is_file($this->getConfigFile())) {
            unlink($this->getConfigFile());
        }
    }

    /**
     * @return string
     */
    protected function getConfigFile () {
        return self::getWorkingDir() . "/" . $this->getName() . ".xml";
    }

    /**
     * @param $description
     * @return $this
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param $url
     * @return $this
     */
    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @param $backgroundColor
     * @return $this
     */
    public function setBackgroundColor($backgroundColor)
    {
        $this->backgroundColor = $backgroundColor;
        return $this;
    }

    /**
     * @return string
     */
    public function getBackgroundColor()
    {
        return $this->backgroundColor;
    }

    /**
     * @param $foreColor
     * @return $this
     */
    public function setForeColor($foreColor)
    {
        $this->foreColor = $foreColor;
        return $this;
    }

    /**
     * @return string
     */
    public function getForeColor()
    {
        return $this->foreColor;
    }

    /**
     * @param $googleAnalytics
     * @return $this
     */
    public function setGoogleAnalytics($googleAnalytics)
    {
        $this->googleAnalytics = (bool) $googleAnalytics;
        return $this;
    }

    /**
     * @return boolean
     */
    public function getGoogleAnalytics()
    {
        return $this->googleAnalytics;
    }
}


text:
While all Toggl apps are open source, not all things can be made public. This includes, but is not limited to, analytics services' keys and testing credentials. When in doubt, read the company policy before making something public.

Below is a list of all the environment variables you need to configure before building and the purposes they serve:

- iOS analytics' services :bar_chart:
`TOGGL_AD_UNIT_ID_FOR_BANNER_TEST`
`TOGGL_AD_UNIT_ID_FOR_INTERSTITIAL_TEST`
`TOGGL_CLIENT_ID`
`TOGGL_REVERSED_CLIENT_ID`
`TOGGL_API_KEY`
`TOGGL_GCM_SENDER_ID`
`TOGGL_PROJECT_ID`
`TOGGL_STORAGE_BUCKET`
`TOGGL_GOOGLE_APP_ID`
`TOGGL_ADJUST_APP_TOKEN`

- Android Google login :busts_in_silhouette:
`TOGGL_DROID_GOOGLE_SERVICES_API_KEY`
`TOGGL_DROID_GOOGLE_SERVICES_CLIENT_ID`
`TOGGL_DROID_GOOGLE_SERVICES_MOBILE_SDK_APP_ID`
`TOGGL_DROID_GOOGLE_SERVICES_PROJECT_NUMBER`
`TOGGL_DROID_GOOGLE_SERVICES_PROJECT_ID`

- App Center crash tracking :boom:
`TOGGL_APP_CENTER_ID_IOS`
`TOGGL_APP_CENTER_ID_DROID`

# Adhoc builds that use the staging environment

We are using a separate Firebase project for the staging env. Targets that are currently using that project are:
- `Build.Release.iOS.AdHoc`
- `Build.Release.Android.AdHoc`.

The two targets listed above will use a staging version of the Google Services env vars. These vars are:
```
TOGGL_GCM_SENDER_ID_STAGING
TOGGL_DATABASE_URL_STAGING
TOGGL_PROJECT_ID_STAGING
TOGGL_STORAGE_BUCKET_STAGING
TOGGL_DROID_GOOGLE_SERVICES_API_KEY_STAGING
TOGGL_CLIENT_ID_STAGING
TOGGL_REVERSED_CLIENT_ID_STAGING
TOGGL_API_KEY_STAGING
TOGGL_GOOGLE_APP_ID_STAGING
```

# new 'puter who dis? :computer:

To configure this on a macOS:

```
$ touch ~/.bash_profile
$ open ~/.bash_profile
```

Then add the following lines to `.bash_profile`:
```
export TOGGL_AD_UNIT_ID_FOR_BANNER_TEST=""
export TOGGL_AD_UNIT_ID_FOR_INTERSTITIAL_TEST=""
export TOGGL_CLIENT_ID=""
export TOGGL_REVERSED_CLIENT_ID=""
export TOGGL_API_KEY=""
export TOGGL_GCM_SENDER_ID=""
export TOGGL_PROJECT_ID=""
export TOGGL_STORAGE_BUCKET=""
export TOGGL_GOOGLE_APP_ID=""
export TOGGL_DATABASE_URL=""
export TOGGL_APP_CENTER_ID_IOS=""
export TOGGL_APP_CENTER_ID_DROID=""
export TOGGL_DROID_GOOGLE_SERVICES_API_KEY=""
export TOGGL_DROID_GOOGLE_SERVICES_CLIENT_ID=""
export TOGGL_DROID_GOOGLE_SERVICES_MOBILE_SDK_APP_ID=""
export TOGGL_DROID_GOOGLE_SERVICES_PROJECT_NUMBER=""
export TOGGL_DROID_GOOGLE_SERVICES_PROJECT_ID=""
export TOGGL_ADJUST_APP_TOKEN=""
export TOGGL_GCM_SENDER_ID_STAGING=""
export TOGGL_DATABASE_URL_STAGING=""
export TOGGL_PROJECT_ID_STAGING=""
export TOGGL_STORAGE_BUCKET_STAGING=""
export TOGGL_DROID_GOOGLE_SERVICES_API_KEY_STAGING=""
export TOGGL_CLIENT_ID_STAGING=""
export TOGGL_REVERSED_CLIENT_ID_STAGING=""
export TOGGL_API_KEY_STAGING=""
export TOGGL_GOOGLE_APP_ID_STAGING=""
```

Finish it off with:

```
$ source ~/.bash_profile
```

NOTE: Replace `bash_profile` with `zshrc` if you're using `zsh`


text:
package com.rarchives.ripme.tst.ripper.rippers;

import java.io.IOException;
import java.net.URL;

import com.rarchives.ripme.ripper.rippers.BatoRipper;

public class BatoRipperTest extends RippersTest {
    public void testRip() throws IOException {
        BatoRipper ripper = new BatoRipper(new URL("https://bato.to/chapter/1207152"));
        testRipper(ripper);
    }

    public void testGetGID() throws IOException {
        URL url = new URL("https://bato.to/chapter/1207152");
        BatoRipper ripper = new BatoRipper(url);
        assertEquals("1207152", ripper.getGID(url));
    }

    public void testGetAlbumTitle() throws IOException {
        URL url = new URL("https://bato.to/chapter/1207152");
        BatoRipper ripper = new BatoRipper(url);
        assertEquals("bato_1207152_I_Messed_Up_by_Teaching_at_a_Black_Gyaru_School!_Ch.2", ripper.getAlbumTitle(url));
    }
}


text:
using namespace llvm;

#define DEBUG_TYPE "pgo-icall-prom-analysis"

// The minimum call count for the direct-call target to be considered as the
// promotion candidate.
static cl::opt<unsigned>
    ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
                      cl::init(1000),
                      cl::desc("The minimum count to the direct call target "
                               "for the promotion"));

// The percent threshold for the direct-call target (this call site vs the
// total call count) for it to be considered as the promotion target.
static cl::opt<unsigned>
    ICPPercentThreshold("icp-percent-threshold", cl::init(33), cl::Hidden,
                        cl::ZeroOrMore,
                        cl::desc("The percentage threshold for the promotion"));

// Set the maximum number of targets to promote for a single indirect-call
// callsite.
static cl::opt<unsigned>
    MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
                     cl::desc("Max number of promotions for a single indirect "
                              "call callsite"));

ICallPromotionAnalysis::ICallPromotionAnalysis() {
  ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
}

bool ICallPromotionAnalysis::isPromotionProfitable(uint64_t Count,
                                                   uint64_t TotalCount) {
  if (Count < ICPCountThreshold)
    return false;

  unsigned Percentage = (Count * 100) / TotalCount;
  return (Percentage >= ICPPercentThreshold);
}

// Indirect-call promotion heuristic. The direct targets are sorted based on
// the count. Stop at the first target that is not promoted. Returns the
// number of candidates deemed profitable.
uint32_t ICallPromotionAnalysis::getProfitablePromotionCandidates(
    const Instruction *Inst, uint32_t NumVals, uint64_t TotalCount) {
  ArrayRef<InstrProfValueData> ValueDataRef(ValueDataArray.get(), NumVals);

  DEBUG(dbgs() << " \nWork on callsite " << *Inst << " Num_targets: " << NumVals
               << "\n");

  uint32_t I = 0;
  for (; I < MaxNumPromotions && I < NumVals; I++) {
    uint64_t Count = ValueDataRef[I].Count;
    assert(Count <= TotalCount);
    DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
                 << "  Target_func: " << ValueDataRef[I].Value << "\n");

    if (!isPromotionProfitable(Count, TotalCount)) {
      DEBUG(dbgs() << " Not promote: Cold target.\n");
      return I;
    }
    TotalCount -= Count;
  }
  return I;
}

ArrayRef<InstrProfValueData>
ICallPromotionAnalysis::getPromotionCandidatesForInstruction(
    const Instruction *I, uint32_t &NumVals, uint64_t &TotalCount,
    uint32_t &NumCandidates) {
  bool Res =
      getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
                               ValueDataArray.get(), NumVals, TotalCount);
  if (!Res) {
    NumCandidates = 0;
    return ArrayRef<InstrProfValueData>();
  }
  NumCandidates = getProfitablePromotionCandidates(I, NumVals, TotalCount);
  return ArrayRef<InstrProfValueData>(ValueDataArray.get(), NumVals);
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Chat Web Example</title>

Chat - Web Example

<form onSubmit='sock.send(document.getElementById("input").value); return false;'>
Input text: <input id="input" focus="true" />
<input type="submit" disabled="true" id="send" value="Send" />
</form>

Messages from server:

<textarea cols=80 rows=20 id="output">
</textarea>

status: connecting...


text:
package com.gor.sellphotos.dto;

import com.gor.sellphotos.dao.Utilisateur;

public class ResponsableDTO  {

	private Utilisateur utilisateur;

	private EcoleDTO ecole;

    /**
     * @return the utilisateur
     */
    public Utilisateur getUtilisateur() {
        return utilisateur;
    }

    /**
     * @param utilisateur the utilisateur to set
     */
    public void setUtilisateur(Utilisateur utilisateur) {
        this.utilisateur = utilisateur;
    }

    /**
     * @return the ecole
     */
    public EcoleDTO getEcole() {
        return ecole;
    }

    /**
     * @param ecole the ecole to set
     */
    public void setEcole(EcoleDTO ecole) {
        this.ecole = ecole;
    }

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.PR_GET_DUMPABLE.html">

Redirecting to constant.PR_GET_DUMPABLE.html...


text:
<!DOCTYPE html>

  <link href="https://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="Hugo 0.60.1" />

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

  <title>Cassandra server in 10 minutes · rushiagr</title>
  <meta name="description" content="" />

  <link type="text/css" rel="stylesheet" href="http://www.rushiagr.com/css/print.css" media="print">
  <link type="text/css" rel="stylesheet" href="http://www.rushiagr.com/css/poole.css">
  <link type="text/css" rel="stylesheet" href="http://www.rushiagr.com/css/syntax.css">
  <link type="text/css" rel="stylesheet" href="http://www.rushiagr.com/css/hyde.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abril+Fatface|PT+Sans:400,400i,700">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.png">

rushiagr

       Yet another tech guy

Home

 About

 Github

 LinkedIn

© 2019. All rights reserved.

Cassandra server in 10 minutes

  <time datetime=2016-12-08T19:05:21+0530 class="post-date">Thu, Dec 8, 2016</time>

Want to quickly find out how a Cassandra server feels? In this blog post, we'll
create a single-node Cassandra cluster on an Ubuntu Xenial (16.04) system. It's
not really a ‘cluster’, but you can access the Cassandra shell cqlsh and try
out all of its commands. Since we are just looking for a quick start, we're
installing one of the latest Cassandra versions – version 3.7. Even more, the
steps here are totally scriptable, so you can just blindly paste the lines and
it'll work! OK let's get started.

Note: Jump straight to the last portion to get all the commands at one place
without explanation

Let's go to the temporary directory where we'll download Sun's Java. Here I am
downloading Java's ‘Server JRE’ file. I have it hosted in Amazon cloud which
you can use. You can bring your own JRE or JDK file too. Just make sure you
make appropriate replacements in the command.

cd /tmp

Now actually download the JRE file

wget http://eezydb.s3.amazonaws.com/server-jre-8u101-linux-x64.tar.gz

Create the directory where you want to expand this compressed file

sudo mkdir -p /usr/lib/jvm

Now uncompress it

sudo tar -xzvf server-jre-8u101-linux-x64.tar.gz -C /usr/lib/jvm

Now update system's Java pointers and make this Java the preferred Java to be
used

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_101/bin/java" 1
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_101/bin/java

You can check our Java is the preferred Java by checking Java version.

java -version

The output should say something like java version "1.8.0_101".

Add Cassandra repositories at appropriate place so that our beloved apt-get
utility can find the place from where to download Cassandra packages.

echo "deb http://www.apache.org/dist/cassandra/debian 37x main" | sudo tee -a /etc/apt/sources.list
echo "deb-src http://www.apache.org/dist/cassandra/debian 37x main" | sudo tee -a /etc/apt/sources.list

Now add the cryptographic keys at proper places. Don't ask me why do we have to
do it :)

gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 749D6EEC0353B12C
sudo apt-key add ~/.gnupg/pubring.gpg

Now update repository pointers, and install Cassandra!

sudo apt-get --yes --quiet update
sudo apt-get install --yes --quiet cassandra

Cassandra should be installed and running by now. You can check it by checking
status of Cassandra service

sudo service cassandra status

Press q to exit. I don't know why they make us press q, but anyway..

Cassandra server is running by now. You can check that by checking the status
of nodetool utility.

sudo nodetool status

The state should be UN, i.e. ‘U'p and ‘N'ormal. If the output is different,
then wait a few seconds and try again.

There are a few more steps to get the cqlsh command line utility working.
Let's get them done too.

Install pip utility which will install Python packages. If you already have
pip utility, no need to execute this step. Note that this is just one of many
ways to install pip.

sudo apt-get install --yes --quiet python-pip

Now install pip package cassandra-driver. You can install it in virtual
environment also. You can safely ignore my last sentence if you have never
heard the term ‘Python virtual environments’ before.

sudo pip install cassandra-driver

I wish everything worked after this, but it won't. Just set this environment
variable and then you should be good to log in into cqlsh shell.

export CQLSH_NO_BUNDLED=true

Now ‘actually’ log into cqlsh shell

cqlsh

The output should be something like:

ubuntu@hostname:~$ cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.7 | CQL spec 3.4.2 | Native protocol v4]
Use HELP for help.
cqlsh>

Voila! Note that you need to export CQLSH_NO_BUNDLED=true in every terminal
shell from where you want to access cqlsh. So if you log out of the system
and log back in, you need to re-run this command.

Now you can follow any cqlsh tutorial to try out commands to create
keyspaces, tables, rows, etc.

Everything at one place

You can just paste these lines in a file and run that file as a script, and it'll set everything up for you.

cd /tmp
wget http://eezydb.s3.amazonaws.com/server-jre-8u101-linux-x64.tar.gz
sudo mkdir -p /usr/lib/jvm
sudo tar -xzvf server-jre-8u101-linux-x64.tar.gz -C /usr/lib/jvm
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_101/bin/java" 1
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_101/bin/java
echo "deb http://www.apache.org/dist/cassandra/debian 37x main" | sudo tee -a /etc/apt/sources.list
echo "deb-src http://www.apache.org/dist/cassandra/debian 37x main" | sudo tee -a /etc/apt/sources.list
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 749D6EEC0353B12C
sudo apt-key add ~/.gnupg/pubring.gpg
sudo apt-get --yes --quiet update
sudo apt-get install --yes --quiet cassandra python-pip
sudo pip instlal cassandra-driver
export CQLSH_NO_BUNDLED=true
cqlsh

If you like this, please share! If you have any suggestions, please comment!

Until next time!

Comments

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus


text:
package com.google.cloud.dataflow.sdk.coders;

import com.google.cloud.dataflow.sdk.testing.CoderProperties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.Arrays;
import java.util.List;

/**
 * Test case for {@link BigEndianLongCoder}.
 */
@RunWith(JUnit4.class)
public class BigEndianLongCoderTest {

  private static final List<Long> TEST_VALUES = Arrays.asList(
      -11L, -3L, -1L, 0L, 1L, 5L, 13L, 29L,
      Integer.MAX_VALUE + 131L,
      Integer.MIN_VALUE - 29L,
      Long.MAX_VALUE,
      Long.MIN_VALUE);

  @Test
  public void testDecodeEncodeEqual() throws Exception {
    Coder<Long> coder = BigEndianLongCoder.of();
    for (Long value : TEST_VALUES) {
      CoderProperties.coderDecodeEncodeEqual(coder, value);
    }
  }
}


text:
translateData = {
  // sidebar
  "C̲ontent":true,
  "Shortcut: ALT+C":true,
  "In̲dex":true,
  "Shortcut: ALT+N":true,
  "Filter":true,
  "Directives":true,
  "Built-in Variables":true,
  "Built-in Functions":true,
  "Control Flow Statements":true,
  "Declarations":true,
  "Operators":true,
  "Commands":true,
  "S̲earch":true,
  "Shortcut: ALT+S":true,
  "Search":true,
  "Highlight keywords":true,
  "Go to previous/next occurrence":true,
  // header
  "Hide/Show sidebar":true,
  "Home page":true,
  "en":true,
  "Change language":true,
  "v1":true,
  "Change AHK version":true,
  "Edit page on GitHub":true,
  "https://github.com/Lexikos/AutoHotkey_L-Docs/edit/master/docs/":true,
  "Go back":true,
  "Go forward":true,
  "Change font size":true,
  "Print current document":true,
  "Open Settings":true,
  "Change to dark/light theme":true,
  // ALT+... shortcuts (needs uppercase)
  "C":true,
  "N":true,
  "S":true,
  // content
  "Select code":true,
  "Download code":true,
  "Back to top":true,
  "Applies to:\nAutoHotkey_L Revision {0} and later\nAutoHotkey v1.0.90.00 and later":true,
  "Applies to AutoHotkey {0} and later":true
};


text:
{% extends "people/_base_organizations.html" %}

{% block content %}

     People / Organizations

{% for alpha in object_list|groupby('sort_letter') %}

{{ alpha.grouper }}

        {% for organization in alpha.list %}

{{ organization.name|smartypants }}

        {% endfor %}

{% endfor %}

{% endblock content %}

{% block site_js_extra %}

{% endblock %}


text:
using System;
using System.Windows.Controls;

namespace WpfConverters.Converters.Format
{
    public class TreeViewLineConverter : BaseValueConverterExtension
    {
        public override Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
        {
            TreeViewItem item = (TreeViewItem)value;
            ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);
            return ic.ItemContainerGenerator.IndexFromContainer(item) == ic.Items.Count - 1;
        }

        public override Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
        {
            return false;
        }
    }
}