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

package org.chromium.android_webview.common;

import android.os.StrictMode;

import org.chromium.base.BuildInfo;
import org.chromium.base.CommandLine;

/**
 * Utility class for WebView's CommandLine - this is compiled into a separate target that can be
 * reached from WebView's separate minidump-uploading Services.
 */
public class CommandLineUtil {
    protected CommandLineUtil() {}

    public static final String WEBVIEW_COMMAND_LINE_FILE = "/data/local/tmp/webview-command-line";

    private static final String COMMAND_LINE_UTIL_INTERNAL =
            "org.chromium.android_webview.common.CommandLineUtilInternal";

    private static CommandLineUtil sInstance;

    private static CommandLineUtil getInstance() {
        if (sInstance != null) return sInstance;
        try {
            sInstance = (CommandLineUtil) Class.forName(COMMAND_LINE_UTIL_INTERNAL).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | IllegalArgumentException e) {
            sInstance = new CommandLineUtil();
        }
        return sInstance;
    }

    /**
     * Initialize the CommandLine for WebView - this should be initialized on the same thread where
     * we subsequently access CommandLine.
     */
    public static void initCommandLine() {
        if (BuildInfo.isDebugAndroid()) {
            // Suppress the StrictMode violation as this codepath is only hit on debuggable builds.
            StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
            CommandLine.initFromFile(CommandLineUtil.WEBVIEW_COMMAND_LINE_FILE);
            StrictMode.setThreadPolicy(oldPolicy);
        } else {
            CommandLine.init(null);
        }
        getInstance().initCommandLineInternal(CommandLine.getInstance());
    }

    protected void initCommandLineInternal(CommandLine commandLine) {}
}


text:
status=published
type=page
layout=default
title=Apache Geode (incubating) | Home
slug=home
~~~~~~

Performance is key. Consistency is a must.

Geode is an open source, distributed, in-memory database for scale-out applications.

Elastic performance

All data is stored in-memory for low latency. Performance scales linearly as nodes are added. Data is distributed automatically between nodes to optimize performance.

Database consistency

Data is persisted in write-optimized disk storage. Consistency checking is configurable between highest performance caching and ACID transactions.

Resilient clustering

Clusters fail-over to other nodes in case of failures, and rebalance remaining resources. Clusters self-heal when nodes return to operation.

Community

To get in touch with other users and contributors of the Apache Geode (incubating) community:

Contributors: dev@geode.incubator.apache.org
                            (subscribe,
                             unsubscribe,  archive)

JIRA notifications: issues@geode.incubator.apache.org
                            (subscribe,
                             unsubscribe,  archive)

Commits: commits@geode.incubator.apache.org
                            (subscribe,  unsubscribe, archive)

User questions at Stack Overflow

We use the Apache Geode JIRA for issue tracking

For other ways to contribute, see the Apache Geode (incubating) community page

Contributors

Development on the code base for Geode was started in 2002 as the commercial product GemFire. The open source version of Geode was released in April, 2015. Primary committers include members of the GemFire engineering team, customers, and ASF members.

If you'd like to participate in Apache Geode (incubating), learn how to contribute.

Getting Started

Read the quick start guide.

Check out the Getting Started page

redpajama_set_name: RedPajamaGithub


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

    <title>Pmd (Gradle API 2.1)</title>
    <meta name="date" content="2014-09-08">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Property

Constructor

Method

 | Detail:

            Field
Property

Constructor

Method

Package: org.gradle.api.plugins.quality

[Groovy] Class Pmd

org.gradle.api.plugins.quality.Pmd

All Implemented Interfaces and Traits:

Reporting, VerificationTask

class Pmd
extends SourceTask

 Runs a set of static code analysis rules on Java source code files and
 generates a report of problems found.

See Also:

PmdPlugin

Properties Summary

Properties

                            Type
                            Name and description

                            boolean
                            consoleOutput
Whether or not to write PMD results to System.out.

                            boolean
                            ignoreFailures
Whether or not to allow the build to continue if there are warnings.

                            FileCollection
                            pmdClasspath
The class path containing the PMD library to be used.

                            FileCollection
                            ruleSetFiles
The custom rule set files to be used.

                            List<String>
                            ruleSets
The built-in rule sets to be used.

                            TargetJdk
                            targetJdk
The target JDK to use with PMD.

Constructor Summary

Constructors

                            Constructor and description

                                Pmd
                                ()

Methods Summary

Methods

                            Type
                            Name and description

                            IsolatedAntBuilder
                            getAntBuilder()

                            Instantiator
                            getInstantiator()

                            PmdReports
                            getReports()
Returns the reports to be generated by this task.

                            PmdReports
                            reports(Closure closure)
Configures the reports to be generated by this task.

                            void
                            run()

                            boolean
                            stdOutIsAttachedToTerminal()

Property Detail

@Incubating
boolean consoleOutput

 Whether or not to write PMD results to System.out.

boolean ignoreFailures

 Whether or not to allow the build to continue if there are warnings.

 Example: ignoreFailures = true

@InputFiles
FileCollection pmdClasspath

 The class path containing the PMD library to be used.

@InputFiles
FileCollection ruleSetFiles

 The custom rule set files to be used. See the official documentation for
 how to author a rule set file.

 Example: ruleSetFiles = files("config/pmd/myRuleSets.xml")

@Input
List<String> ruleSets

 The built-in rule sets to be used. See the official list of built-in rule sets.

 Example: ruleSets = ["basic", "braces"]

@Input
TargetJdk targetJdk

 The target JDK to use with PMD.

Constructor Detail

Pmd()

Method Detail

@Inject
IsolatedAntBuilder getAntBuilder()

@Inject
Instantiator getInstantiator()

PmdReports getReports()

 Returns the reports to be generated by this task.

PmdReports reports(Closure closure)

 Configures the reports to be generated by this task.

@TaskAction
void run()

boolean stdOutIsAttachedToTerminal()

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Property

Constructor

Method

 | Detail:

            Field
Property

Constructor

Method

Gradle API 2.1


text:
flex-image-fill (incomplete, need to add the flex classes) experimental

<div class="position-relative image-ratio-16-9">
<img class="flex-image-fill" src="../../image/brand/fpo.jpg" title="click for full-screen demonstration" />
</div>

For use with flex image classes. Stretch the image to fill the container edge-to-edge. Apply the flex-image-fill class as in the above example. Requires position-relative as a parent class, and an image source <src="../../image/brand/fpo.jpg">.


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Drawing;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Drawing.Imaging;

namespace ComicStreamer.Tests
{
    [TestClass()]
    public class UnitTest1
    {
        readonly string BaseUrl = "http://192.168.1.82:32500";

        [TestMethod()]
        public async Task GetDBInfoTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);

            string response = await cs.GetDBInfo();

            if (response.Length > 0)
            {
                Console.WriteLine(response);
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetVersionTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            string response = await cs.GetVersion();

            if (response.Length > 0)
            {
                Console.WriteLine(response);
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetDeletedComicsTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            var response = await cs.GetDeletedComics("2017-2-19");

            if (response.Length > 0)
            {
                Console.WriteLine(response);
            }
            else
            {
                Assert.Fail();
            }

            response = await cs.GetDeletedComics("2017-2-21");

            if (response.Length > 0)
            {
                Console.WriteLine(response);
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetComicInfoTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            var response = await cs.GetComicInfo(98);

            string series = (string)response["comics"][0]["series"];

            Console.WriteLine(response.ToString(Formatting.Indented));

            Console.WriteLine("Series = " + (string)response["comics"][0]["series"]);

            if (!series.Equals("The Fuse", StringComparison.OrdinalIgnoreCase))
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetComicPageTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            Byte[] response = await cs.GetComicPage(98);

            if (response.Length > 0)
            {
                using (Image image = Image.FromStream(new MemoryStream(response)))
                {
                    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
                }
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task SetBookmarkTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            cs.SetBookmark(98, "10");

            var response = await cs.GetComicInfo(98);
            string lastread_page = (string)response["comics"][0]["lastread_page"];

            if (!lastread_page.Equals("10"))
            {
                Assert.Fail();
            }

            cs.SetBookmark(98);
        }

        [TestMethod()]
        public async Task GetThumbnailTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            Byte[] response = await cs.GetThumbnail(98);

            if (response.Length > 0)
            {
                using (Image image = Image.FromStream(new MemoryStream(response)))
                {
                    image.Save("thumbnail.jpg", ImageFormat.Jpeg);  // Or Png
                }
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetComicFileTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            Byte[] file = await cs.GetComicFile(98);

            var response = await cs.GetComicInfo(98);

            string filename = System.IO.Path.GetFileName((string)response["comics"][0]["path"]);

            if (file.Length > 0 && filename.Length > 0)
            {
                File.WriteAllBytes(filename, file);
            }
            else
            {
                Assert.Fail();
            }
        }

        [TestMethod()]
        public async Task GetComicListTest()
        {
            // Test getting all comics
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            JObject list = await cs.GetComicList();
            JArray comics = (JArray)list["comics"];

            Console.WriteLine("Found " + comics.Count + " comics");

            if (comics.Count > 100)
            {
                // Test getting all of one series
                list = await cs.GetComicList("The Fuse");
                comics = (JArray)list["comics"];

                Console.WriteLine("Found " + comics.Count + " issues of The Fuse");

                Console.WriteLine(comics.ToString(Formatting.Indented));

                if (comics.Count == 0 && comics.Count > 100)
                {
                    Assert.Fail();
                }
            }
        }

        [TestMethod()]
        public async Task GetFoldersTest()
        {
            ComicStreamerSharp cs = new ComicStreamerSharp(BaseUrl);
            JObject list = await cs.GetFolders();

            if (list.Count == 0)
            {
                Assert.Fail();
            }
        }

    }
}


text:
package dummy;

import a.b.En;
import a.b.X;

import java.lang.annotation.Documented;
import java.util.Date;

/**
 * @author Kohsuke Kawaguchi
 */
public class TestCode {

    PrivateClass p = new PrivateClass();
    AnotherLocal al = new AnotherLocal();

    TestCode tc = null; // self reference

    public class Base {
        public void run() {}
    }

    @Deprecated
    public class Inner extends Base {
        public void run() {}
    }

    public class Derived extends Inner implements Runnable {
        public void run() {
            super.run();
        }
    }

    public class Derived2 extends Inner implements Runnable {
        public void run() {
            super.run();
        }
    }

    public static void abc() {
        class Bar {}
        main(new String[0]);
    }

    public static void main(String[] args) {
        class Bar {}
        X x = new X();
        x.foo(3);
        x.foo(5L);
        x.l.add(x.l);
        System.out.println(new Date().toGMTString());
        System.out.println(x.y);
        L:
        switch(En.ABC) {
        case ABC:
        case DEF:
            break L;
        }
        Comparable<String> c = new Comparable<String>() {
            public int compareTo(String o) {
                class Foo {}
                Foo f = new Foo();
                // TODO
                throw new UnsupportedOperationException(o);
            }

            Comparable<String> c = new Comparable<String>() {
                public int compareTo(String o) {
                    class Foo {}
                    TestCode tc = new TestCode();
                    Foo f = new Foo();
                    // TODO
                    throw new UnsupportedOperationException(o);
                }
            };
        };
    }

    static {
        ; // initializer block
    }

    private int fieldDecl = 3;
    private final String anotherField = "555";

    @Documented
    @interface Foo {}
}

class PrivateClass {}

/*
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
long tail
v*/


text:
<?php

namespace Application\Sonata\ClientOperationsBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Application\Sonata\ClientOperationsBundle\Entity\V09DES
 *
 * @ORM\Table("et_operations_V09DES")
 * @ORM\Entity
 */
class V09DES extends AbstractSellEntity
{

    /**
     * @var string $no_TVA_tiers
     *
     * @Assert\NotBlank()
     * @ORM\Column(name="no_TVA_tiers", type="string", length=255)
     */
    private $no_TVA_tiers;

    /**
     * @var string $mois_complementaire
     *
     * @ORM\Column(name="mois_complementaire", type="text", nullable=true)
     */
    private $mois_complementaire;

    /**
     * Set no_TVA_tiers
     *
     * @param string $noTVATiers
     * @return V09DES
     */
    public function setNoTVATiers($noTVATiers)
    {
        $this->no_TVA_tiers = $noTVATiers;

        return $this;
    }

    /**
     * Get no_TVA_tiers
     *
     * @return string
     */
    public function getNoTVATiers()
    {
        return $this->no_TVA_tiers;
    }

    /**
     * Set mois_complementaire
     *
     * @param string $moisComplementaire
     * @return V09DES
     */
    public function setMoisComplementaire($moisComplementaire)
    {
        $this->mois_complementaire = $moisComplementaire;

        return $this;
    }

    /**
     * Get mois_complementaire
     *
     * @return string
     */
    public function getMoisComplementaire()
    {
        return $this->mois_complementaire;
    }

}


text:
module.exports = {
  name: 'config/default'
};


text:
Initial template name : [Stylish Portfolio](http://startbootstrap.com/template-overviews/stylish-portfolio/) templated by [Start Bootstrap](http://startbootstrap.com/).

See the site in action at https://volny.github.io/stylish-portfolio-jekyll/


text:
package com.scottbezek.difflib.unified;

import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;

/**
 * Represents an "absolute" line in the side-by-side diff.
 */
@Immutable
public class SideBySideLine {

    private final int mLeftLineNumber;
    private final CharSequence mLeftLine;
    private final int mRightLineNumber;
    private final CharSequence mRightLine;

    public SideBySideLine(int leftLineNumber, @CheckForNull CharSequence leftLine,
            int rightLineNumber, @CheckForNull CharSequence rightLine) {
        mLeftLineNumber = leftLineNumber;
        mLeftLine = leftLine;
        mRightLineNumber = rightLineNumber;
        mRightLine = rightLine;
    }

    public int getLeftLineNumber() {
        return mLeftLineNumber;
    }

    @CheckForNull
    public CharSequence getLeftLine() {
        return mLeftLine;
    }

    public int getRightLineNumber() {
        return mRightLineNumber;
    }

    @CheckForNull
    public CharSequence getRightLine() {
        return mRightLine;
    }

    @Override
    public String toString() {
        return mLeftLineNumber + ":" + mLeftLine + "\t" + mRightLineNumber + ":" + mRightLine;
    }
}


text:
Whoops = {
  setupFilters: function() {
    function checkboxBehavior(afterChecked) {
      if (afterChecked === undefined) {
        afterChecked = function(){}
      }

      return function(i, list){
        var all = $($(list).find("input").get(0));
        var allowedValues = $(list).find("input").slice(1);
        var form = $(this).parents("form");

        all.change(function(event){
          if ($(this).attr("checked")) {
            allowedValues.attr("checked", false);
            afterChecked(form);
          } else {
            $(this).attr("checked", true);
          }
        })

        $(allowedValues).change(function(event){
          if ($(this).attr("checked")) {
            all.attr("checked", false);
          }
          afterChecked(form);
        })
      }
    }

    $("#new_whoops_filter ul").each(checkboxBehavior(function(form){form.submit()}));
    $("#new-notification-rule .filters ul").each(checkboxBehavior());

    $("#reset").click(function(){
      window.location = window.location.pathname
      return false
    })
  },

  setupEventLinks: function() {
    $("#instances a").click(function(){
      $(".selected").removeClass("selected")
      $(this).parents("li").addClass("selected")
      $.get(this.href,function(data){
        $("#event-details").html(data)
      }, 'html')
      return false;
    })
  },

  setupInfo: function() {
    $(".info-revealer").click(function() {
      $(".info").toggle(300)
    })
  },

  setup: function() {
    this.setupFilters();
    this.setupEventLinks();
    this.setupInfo();
  }
}

$(function(){
  Whoops.setup();
})

jQuery.ajaxSetup({
  beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})


text:
function listTagsHelper(tags, options){
  if (!options && (!tags || !tags.hasOwnProperty('length'))){
    options = tags;
    tags = this.site.tags;
  }

  if (!tags || !tags.length) return '';
  options = options || {};

  var style = options.hasOwnProperty('style') ? options.style : 'list';
  var showCount = options.hasOwnProperty('show_count') ? options.show_count : true;
  var className = options.class || 'tag';
  var orderby = options.orderby || 'name';
  var order = options.order || 1;
  var transform = options.transform;
  var separator = options.hasOwnProperty('separator') ? options.separator : ', ';
  var result = '';
  var self = this;

  // Sort the tags
  tags = tags.sort(orderby, order);

  // Ignore tags with zero posts
  tags = tags.filter(function(tag){
    return tag.length;
  });

  // Limit the number of tags
  if (options.amount) tags = tags.limit(options.amount);

  if (style === 'list'){
    result += '
';

    tags.forEach(function(tag){
      result += '
';

      result += '';
      result += transform ? transform(tag.name) : tag.name;
      result += '';

      if (showCount){
        result += '' + tag.length + '';
      }

      result += '
';
    });

    result += '
';
  } else {
    tags.forEach(function(tag, i){
      if (i) result += separator;

      result += '';
      result += transform ? transform(tag.name) : tag.name;

      if (showCount){
        result += '' + tag.length + '';
      }

      result += '';
    });
  }

  return result;
}

module.exports = listTagsHelper;


text:
package org.apache.arrow.vector.complex.impl;

import org.apache.arrow.vector.complex.writer.BaseWriter;
import org.apache.arrow.vector.complex.writer.BaseWriter.MapOrListWriter;
import org.apache.arrow.vector.complex.writer.BigIntWriter;
import org.apache.arrow.vector.complex.writer.BitWriter;
import org.apache.arrow.vector.complex.writer.Float4Writer;
import org.apache.arrow.vector.complex.writer.Float8Writer;
import org.apache.arrow.vector.complex.writer.IntWriter;
import org.apache.arrow.vector.complex.writer.VarBinaryWriter;
import org.apache.arrow.vector.complex.writer.VarCharWriter;

public class MapOrListWriterImpl implements MapOrListWriter {

  public final BaseWriter.MapWriter map;
  public final BaseWriter.ListWriter list;

  public MapOrListWriterImpl(final BaseWriter.MapWriter writer) {
    this.map = writer;
    this.list = null;
  }

  public MapOrListWriterImpl(final BaseWriter.ListWriter writer) {
    this.map = null;
    this.list = writer;
  }

  public void start() {
    if (map != null) {
      map.start();
    } else {
      list.startList();
    }
  }

  public void end() {
    if (map != null) {
      map.end();
    } else {
      list.endList();
    }
  }

  public MapOrListWriter map(final String name) {
    assert map != null;
    return new MapOrListWriterImpl(map.map(name));
  }

  public MapOrListWriter listoftmap(final String name) {
    assert list != null;
    return new MapOrListWriterImpl(list.map());
  }

  public MapOrListWriter list(final String name) {
    assert map != null;
    return new MapOrListWriterImpl(map.list(name));
  }

  public boolean isMapWriter() {
    return map != null;
  }

  public boolean isListWriter() {
    return list != null;
  }

  public VarCharWriter varChar(final String name) {
    return (map != null) ? map.varChar(name) : list.varChar();
  }

  public IntWriter integer(final String name) {
    return (map != null) ? map.integer(name) : list.integer();
  }

  public BigIntWriter bigInt(final String name) {
    return (map != null) ? map.bigInt(name) : list.bigInt();
  }

  public Float4Writer float4(final String name) {
    return (map != null) ? map.float4(name) : list.float4();
  }

  public Float8Writer float8(final String name) {
    return (map != null) ? map.float8(name) : list.float8();
  }

  public BitWriter bit(final String name) {
    return (map != null) ? map.bit(name) : list.bit();
  }

  public VarBinaryWriter binary(final String name) {
    return (map != null) ? map.varBinary(name) : list.varBinary();
  }

}


text:
'use strict';

// Configuring the Teachers module
angular.module('teachers').run(['Menus',
  function (Menus) {
    // Add the teachers dropdown item
    Menus.addMenuItem('topbar', {
      title: 'Teachers',
      state: 'teachers',
      type: 'dropdown',
      roles: ['*']
    });

    // Add the dropdown list item
    Menus.addSubMenuItem('topbar', 'teachers', {
      title: 'List Teachers',
      state: 'teachers.list'
    });

    // Add the dropdown create item
    Menus.addSubMenuItem('topbar', 'teachers', {
      title: 'Create Teachers',
      state: 'teachers.create',
      roles: ['user']
    });
  }
]);


text:
MathJax.Localization.addTranslation("qqq","HTML-CSS",{
        version: "2.7.0-beta",
        isLoaded: true,
        strings: {
          LoadWebFont: "This is displayed in MathJax message box when the HTML-CSS output is loading a Web font.\n\nParameters:\n* %1 - the font name",
          CantLoadWebFont: "This is displayed in MathJax message box when the HTML-CSS output fails to load a Web font. The first argument is the font name",
          FirefoxCantLoadWebFont: "This is displayed in MathJax message box when the HTML-CSS output fails to load a Web font in Firefox",
          CantFindFontUsing: "This is displayed in MathJax message box when the HTML-CSS output fails to load a Web font from a given list.\n\nParameters:\n* %1 - a list of fonts tried, comma-separated",
          WebFontsNotAvailable: "This is displayed in MathJax message box when the HTML-CSS fails to load Web fonts"
        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/qqq/HTML-CSS.js");


text:
function Post(){
  return {
    templateUrl: 'posts/post.html'
  }
}

angular
  .module("fishTank")
  .directive("post", Post)


text:
require 'active_record'
require 'csv'
require 'date'
require 'yaml'
require 'ruby-progressbar'

module Serper
  class Analyser
    def initialize(connection)
      ActiveRecord::Base.establish_connection(connection)
    end

    def import_keywords(file)
      CSV.foreach(file) do |l|
        Keyword.find_or_create_by(:term => l[0]) do |r|
          r.pv = l[1]
          r.category = l[2]
          r.url_type = l[3]
          r.url_id = l[4]
        end
      end
    end

    def run(date=Date.today,skip=true)
      puts "Serper Analyser on #{date}"
      ENGINES.keys.each do |engine_name|
        puts engine_name
        search_engine(engine_name,date,skip)
      end
    end

    def search_engine(engine_name,date,skip=true)
      p = ProgressBar.create(:title => "Searching #{engine_name} - #{date}", :total => Keyword.all.count, :format => '%t (%c/%C) %a %E |%w')
      Keyword.all.each do |k|
        check_exists = Weight.where(:engine => engine_name, :date => date, :keyword_id => k.id)
        if check_exists.any?
          if skip
            next
          else
            check_exists.destroy_all
          end
        end

        serp = Serper.search(engine_name,k.term)
        serp.weights.each do |w|
          Weight.create(:date => date,
                        :keyword_id => k.id,
                        :engine => engine_name,
                        :side => w[:side],
                        :part => w[:part],
                        :source => w[:type],
                        :name => w[:name],
                        :site => w[:site],
                        :subdomain => w[:subdomain],
                        :path => w[:path],
                        :part_rank => w[:part_rank],
                        :side_rank => w[:side_rank],
                        :side_weight => w[:side_weight],
                        :weight => w[:weight]
          )
        end

        p.increment
      end
    end

    def migrate!
      ActiveRecord::Schema.define do
        create_table :serper_keywords do |t|
          t.string :term
          t.integer :pv
          t.string :category
          t.string :url_type
          t.integer :url_id

          t.timestamps

          t.index :term
        end

        create_table :serper_weights do |t|
          t.date :date
          t.string :engine
          t.integer :keyword_id
          t.string :side # Left Right
          t.string :part
          t.string :source # SEO SEM Special
          t.string :name
          t.string :site
          t.string :subdomain
          t.string :path
          t.integer :part_rank
          t.integer :side_rank
          t.float :side_weight
          t.float :weight

          t.timestamps

          t.index [:date, :engine, :keyword_id, :side, :side_rank], name: 'weights_pk_index'
        end
      end
    end

    class Keyword < ActiveRecord::Base
      self.table_name = 'serper_keywords'
    end

    class Weight < ActiveRecord::Base
      self.table_name = 'serper_weights'
    end
  end
end


text:
<?= $title ?>

				<?
				//	$posts_latest_first = array_reverse($posts);
				$posts_latest_first = $posts;
					foreach ($posts_latest_first as $key => $value) {
						echo "
" . $value['post_title'] . " <button class='button'>view</button>" . " <button disabled class='delete_button btn btn-primary button'>edit</button> " . "<button class='delete_button btn btn-warning button alert'>delete</button>
";
					} ?>

<button class="button btn btn-link">View Timeline</button>


text:
<!DOCTYPE html>

  <link href="../js/bootstrap-combined.min.css" rel="stylesheet" type="text/css"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"/>
  <link href="../js/bootstrap.min.css" rel="stylesheet" type="text/css"/>

  <link href="../css/commonstyles.css" rel="stylesheet" type="text/css"/>
  <link href="../css/checkboxes.css" rel="stylesheet" type="text/css"/>
  <link href="../css/sample1.css" rel="stylesheet" type="text/css"/>

            <button class="btn btn-link pull-left" style="padding-bottom: 0px; margin-top: 5px; margin-bottom: -5px;" ng-click="toggleNodeSize()">
             Default size Weighted size
            </button>
            <button class="btn btn-link pull-left hidden-xs" style="padding-bottom: 0px; margin-top: 5px; margin-bottom: -15px;" ng-show="showMore.origin != 'newWindow'" ng-click="openInNewWindow()"> Open</button>
            <button class="btn btn-link pull-left hidden-xs" style="padding-bottom: 0px; margin-top: 5px; margin-bottom: -15px;" ng-click="saveNetworkImage()"> Create image</button>
            <button class="btn btn-link pull-left hidden-xs" style="padding-bottom: 0px; margin-top: 5px; margin-bottom: -15px;" ng-click="exportData()"> Export</button>
            <button class="btn btn-primary btn-xs pull-right" style="margin-top: 5px; margin-bottom: -15px; margin-right: 1px; background-color: #f5f5f5; border-color: #e3e3e3; color: black;" ng-show="!showgraphSidebar">LEGEND</button>
            <button class="btn btn-primary btn-xs pull-right" style="margin-top: 5px; margin-bottom: -15px; margin-right: 1px;" ng-click="showgraphSidebar = !showgraphSidebar; re_fit()">

            </button>

Header information


text:
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe http://java.sun.com/xml/jaxb
// nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.04.19 um 09:36:45 AM CEST
//

package de.immobilienscout24.rest.schema.offer.listelement._1;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.immobilienscout24.rest.schema.common._1.Adapter1;
import de.immobilienscout24.rest.schema.common._1.CareTypes;
import de.immobilienscout24.rest.schema.common._1.PetsAllowedType;
import de.immobilienscout24.rest.schema.common._1.YesNotApplicableType;

/**
 * Altenpflegeeinrichtungen.
 *
 *
Java-Klasse fr OfferSeniorCare complex type.
 *
 *
Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *
 *

 * <complexType name="OfferSeniorCare">
 *   <complexContent>
 *     <extension base="{http://rest.immobilienscout24.de/schema/offer/listelement/1.0}OfferRealEstateForList">
 *       <sequence>
 *         <group ref="{http://rest.immobilienscout24.de/schema/common/1.0}BaseSeniorCareGroup"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OfferSeniorCare", propOrder = {
    "shortDescription",
    "petsAllowed",
    "trialLivingPossible",
    "careTypes",
    "balcony"
})
public class OfferSeniorCare
    extends OfferRealEstateForList
{

    @XmlJavaTypeAdapter(Adapter1 .class)
    protected String shortDescription;
    @XmlElement(required = true)
    protected PetsAllowedType petsAllowed;
    @XmlElement(required = true)
    protected YesNotApplicableType trialLivingPossible;
    @XmlElement(required = true)
    protected CareTypes careTypes;
    protected boolean balcony;

    /**
     * Ruft den Wert der shortDescription-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getShortDescription() {
        return shortDescription;
    }

    /**
     * Legt den Wert der shortDescription-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setShortDescription(String value) {
        this.shortDescription = value;
    }

    /**
     * Ruft den Wert der petsAllowed-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link PetsAllowedType }
     *
     */
    public PetsAllowedType getPetsAllowed() {
        return petsAllowed;
    }

    /**
     * Legt den Wert der petsAllowed-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link PetsAllowedType }
     *
     */
    public void setPetsAllowed(PetsAllowedType value) {
        this.petsAllowed = value;
    }

    /**
     * Ruft den Wert der trialLivingPossible-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link YesNotApplicableType }
     *
     */
    public YesNotApplicableType getTrialLivingPossible() {
        return trialLivingPossible;
    }

    /**
     * Legt den Wert der trialLivingPossible-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link YesNotApplicableType }
     *
     */
    public void setTrialLivingPossible(YesNotApplicableType value) {
        this.trialLivingPossible = value;
    }

    /**
     * Ruft den Wert der careTypes-Eigenschaft ab.
     *
     * @return
     *     possible object is
     *     {@link CareTypes }
     *
     */
    public CareTypes getCareTypes() {
        return careTypes;
    }

    /**
     * Legt den Wert der careTypes-Eigenschaft fest.
     *
     * @param value
     *     allowed object is
     *     {@link CareTypes }
     *
     */
    public void setCareTypes(CareTypes value) {
        this.careTypes = value;
    }

    /**
     * Ruft den Wert der balcony-Eigenschaft ab.
     *
     */
    public boolean isBalcony() {
        return balcony;
    }

    /**
     * Legt den Wert der balcony-Eigenschaft fest.
     *
     */
    public void setBalcony(boolean value) {
        this.balcony = value;
    }

}


text:
using System.Windows.Input;

namespace MipsSim.ViewModel.Commands
{
    /// <summary>
    /// Command to save registers to file
    /// </summary>
    public class SaveCpuCommand : BaseCommand, ICommand
    {
        private RegisterViewerViewModel _vm;

        public SaveCpuCommand(RegisterViewerViewModel vm)
        {
            _vm = vm;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            _vm.SaveCurrentCpu();
        }
    }
}


text:
snake-pirate
============

python <-> r

Moving over `trtools.rpy` to its project...


text:
import lib.univie as univie

def event_omitted(cid, i, omit):
	for o in omit:
		l = o.split()
		try:
			if int(cid) == int(l[0]) and int(i) == int(l[1]):
				return True
		except Exception:
			pass
	return False

def html_format_course(course, new=False, omit=[]):
	fade = ''
	if new:
		fade = ' fade'
	output = "

↺ Course: " + str(course.courseId) + "
"

	dayOfWeek = {'MO':'monday', 'TU':'tuesday', 'WE':'wednesday', 'TH':'thursday', 'FR':'friday', 'SA':'saturday', 'SO':'sonday'}
	i = 0
	for e in course.events:
		hiddenstyle = ""
		if event_omitted(course.courseId, i, omit):
			hiddenstyle = "style='display:none'"

		special = ""
		if e.specialEvent != None:
			special = e.specialEvent + " "
		title = "
" + (special + e.title).encode('iso-8859-15') + "
"
		if e.recurrence != None and e.frequency != None:
			dateTime = "every " + dayOfWeek[e.recurrence] + ", "
		else:
			dateTime = ""
		if e.dateUntil == None:
			dateTime = dateTime + e.date_to_str(e.dateStart) + " "
		else:
			dateTime = dateTime + e.date_to_str(e.dateStart) + " until " + e.date_to_str(e.dateUntil)
		dateTime = dateTime + " from " + e.time_to_str(e.timeStart) + " to " + e.time_to_str(e.timeEnd)
		location = "
Location: 	" + e.location.encode('iso-8859-15') + "
"
		description = "
Description: 	 " + e.description.encode('iso-8859-15') + "
"

		output = output + \
"""

		x

""" + title + "
" + dateTime + "

" + location + description + """

"""

		i = i + 1

	output = output + "
"

	return output


text:
from PyQt5 import QtCore, QtGui, QtWidgets
from androguard.gui.xrefwindow import XrefDialogString

class StringsWindow(QtWidgets.QWidget):
    def __init__(self, parent=None, win=None, session=None):
        super().__init__(parent)
        self.mainwin = win
        self.session = session
        self.title = "Strings"

        self.filterPatternLineEdit = QtWidgets.QLineEdit()
        self.filterPatternLabel = QtWidgets.QLabel("&Filter string pattern:")
        self.filterPatternLabel.setBuddy(self.filterPatternLineEdit)
        self.filterPatternLineEdit.textChanged.connect(self.filterRegExpChanged)

        self.stringswindow = StringsValueWindow(self, win, session)

        sourceLayout = QtWidgets.QVBoxLayout()
        sourceLayout.addWidget(self.stringswindow)
        sourceLayout.addWidget(self.filterPatternLabel)
        sourceLayout.addWidget(self.filterPatternLineEdit)

        self.setLayout(sourceLayout)

    def filterRegExpChanged(self, value):
        regExp = QtCore.QRegExp(value)
        self.stringswindow.proxyModel.setFilterRegExp(regExp)

class StringsValueWindow(QtWidgets.QTreeView):
    def __init__(self, parent=None, win=None, session=None):
        super().__init__(parent)
        self.mainwin = win
        self.session = session
        self.title = "Strings"

        self.reverse_strings = {}

        self.proxyModel = QtCore.QSortFilterProxyModel()
        self.proxyModel.setDynamicSortFilter(True)

        self.model = QtGui.QStandardItemModel(self.session.get_nb_strings(), 4,
                                              self)

        self.model.setHeaderData(0, QtCore.Qt.Horizontal, "String")
        self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Usage")
        self.model.setHeaderData(2, QtCore.Qt.Horizontal, "Filename")
        self.model.setHeaderData(3, QtCore.Qt.Horizontal, "Digest")

        row = 0
        for digest, filename, strings_analysis in self.session.get_strings():
            for string_value in strings_analysis:
                self.model.setData(self.model.index(
                    row, 0, QtCore.QModelIndex()), repr(strings_analysis[string_value].get_value()))
                self.model.setData(
                    self.model.index(row, 1, QtCore.QModelIndex()),
                    len(strings_analysis[string_value].get_xref_from()))
                self.model.setData(self.model.index(
                    row, 2, QtCore.QModelIndex()), filename)
                self.model.setData(self.model.index(
                    row, 3, QtCore.QModelIndex()), digest)
                self.reverse_strings[repr(strings_analysis[string_value].get_value()) + digest
                                     ] = strings_analysis[string_value]
                row += 1

        self.proxyModel.setSourceModel(self.model)

        self.setRootIsDecorated(False)
        self.setAlternatingRowColors(True)
        self.setModel(self.proxyModel)
        self.setSortingEnabled(True)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)

        self.doubleClicked.connect(self.slotDoubleClicked)

    def slotDoubleClicked(self, mi):
        mi = self.proxyModel.mapToSource(mi)
        row = mi.row()
        column = mi.column()

        if column == 0:
            xwin = XrefDialogString(
                parent=self.mainwin,
                win=self.mainwin,
                string_analysis=self.reverse_strings[self.model.item(row).text(
                ) + self.model.item(row, 3).text()])
            xwin.show()


text:
package org.scalatest.tools

import org.scalatest._
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.util.Iterator
import java.util.Set
import java.io.StringWriter
import org.scalatest.events._
import PrintReporter._

/**
 * A Reporter that prints test status information in HTML format to a file.
 */
private[scalatest] class HtmlReporter(pw: PrintWriter, presentAllDurations: Boolean,
        presentInColor: Boolean, presentStackTraces: Boolean, presentFullStackTraces: Boolean) extends ResourcefulReporter {

  /**
  * Construct a PrintReporter with passed
  * String file name. Information about events reported to instances of this
  * class will be written to the specified file using the
  * default character encoding.
  *
  * @param filename the String name of the file to which to print reported info
  * @throws NullPointerException if passed filename reference is null
  * @throws IOException if unable to open the specified file for writing
  */
  def this(
    filename: String,
    presentAllDurations: Boolean,
    presentInColor: Boolean,
    presentShortStackTraces: Boolean,
    presentFullStackTraces: Boolean
  ) =
    this(
      new PrintWriter(new BufferedOutputStream(new FileOutputStream(new File(filename)), BufferSize)),
      presentAllDurations,
      presentInColor,
      presentShortStackTraces,
      presentFullStackTraces
    )

  private def withPossibleLineNumber(stringToPrint: String, throwable: Option[Throwable]): String = {
    throwable match {
      case Some(testFailedException: TestFailedException) =>
        testFailedException.failedCodeFileNameAndLineNumberString match {
          case Some(lineNumberString) =>
            Resources("printedReportPlusLineNumber", stringToPrint, lineNumberString)
          case None => stringToPrint
        }
      case _ => stringToPrint
    }
  }

  private def printPossiblyInColor(text: String, ansiColor: String) {
    pw.println(if (presentInColor) ansiColor + text + ansiReset else text)
  }

  // Called for TestFailed, InfoProvided (because it can have a throwable in it), and SuiteAborted
  private def stringsToPrintOnError(noteResourceName: String, errorResourceName: String, message: String, throwable: Option[Throwable],
    formatter: Option[Formatter], suiteName: Option[String], testName: Option[String], duration: Option[Long]): List[String] = {

    val stringToPrint =
      formatter match {
        case Some(IndentedText(formattedText, _, _)) =>
          Resources("specTextAndNote", formattedText, Resources(noteResourceName))
        case _ =>
          // Deny MotionToSuppress directives in error events, because error info needs to be seen by users
            suiteName match {
              case Some(sn) =>
                testName match {
                  case Some(tn) => Resources(errorResourceName, sn + ": " + tn)
                  case None => Resources(errorResourceName, sn)
                }
              // Should not get here with built-in ScalaTest stuff, but custom stuff could get here.
              case None => Resources(errorResourceName, Resources("noNameSpecified"))
            }
    }

    val stringToPrintWithPossibleLineNumber = withPossibleLineNumber(stringToPrint, throwable)

    val stringToPrintWithPossibleLineNumberAndDuration =
      duration match {
        case Some(milliseconds) =>
          if (presentAllDurations)
            Resources("withDuration", stringToPrintWithPossibleLineNumber, makeDurationString(milliseconds))
          else
            stringToPrintWithPossibleLineNumber
        case None => stringToPrintWithPossibleLineNumber
      }

    // If there's a message, put it on the next line, indented two spaces, unless this is an IndentedText
    val possiblyEmptyMessage =
      formatter match {
        case Some(IndentedText(_, _, _)) => ""
        case _ =>
          Reporter.messageOrThrowablesDetailMessage(message, throwable)
      }

    // I don't want to put a second line out there if the event's message contains the throwable's message,
    // or if niether the event message or throwable message has any message in it.
    val throwableIsATestFailedExceptionWithRedundantMessage =
      throwable match {
        case Some(t) =>
          t.isInstanceOf[TestFailedException] && ((t.getMessage != null &&
          !t.getMessage.trim.isEmpty && possiblyEmptyMessage.indexOf(t.getMessage.trim) != -1) || // This part is where a throwable message exists
          (possiblyEmptyMessage.isEmpty && (t.getMessage == null || t.getMessage.trim.isEmpty))) // This part detects when both have no message
        case None => false
      }

    def getStackTrace(throwable: Option[Throwable]): List[String] =
      throwable match {
        case Some(throwable) =>

          def useConciseTestFailedExceptionForm =
            !presentFullStackTraces && (
              throwable match {
                case tfe: TestFailedException => tfe.cause.isEmpty // If there's a cause inside, show the whole stack trace
                case _ => false
              }
            )

          def stackTrace(throwable: Throwable, isCause: Boolean): List[String] = {
            val className = throwable.getClass.getName
            val labeledClassName = if (isCause) Resources("DetailsCause") + ": " + className else className
            val labeledClassNameWithMessage =
              if (throwable.getMessage != null && !throwable.getMessage.trim.isEmpty)
                if (!useConciseTestFailedExceptionForm)
                  "  " + labeledClassName + ": " + throwable.getMessage.trim
                else
                  "  " + throwable.getMessage.trim // Don't show "org.scalatest.TestFailedException: " if no stack trace to follow
              else
                "  " + labeledClassName

            if (!useConciseTestFailedExceptionForm) {
              val stackTraceElements = throwable.getStackTrace.toList map { "  " + _.toString } // Indent each stack trace item two spaces
              val cause = throwable.getCause

              val stackTraceThisThrowable = labeledClassNameWithMessage :: stackTraceElements
              if (cause == null)
                stackTraceThisThrowable
              else
                stackTraceThisThrowable ::: stackTrace(cause, true) // Not tail recursive, but shouldn't be too deep
            }
            else List(labeledClassNameWithMessage)
          }
          if (!throwableIsATestFailedExceptionWithRedundantMessage || !useConciseTestFailedExceptionForm)
            stackTrace(throwable, false)
          else List()
        case None => List()
      }

    if (possiblyEmptyMessage.isEmpty)
      stringToPrintWithPossibleLineNumberAndDuration :: getStackTrace(throwable)
    else
      stringToPrintWithPossibleLineNumberAndDuration :: "  " + possiblyEmptyMessage :: getStackTrace(throwable)
  }

  private def stringToPrintWhenNoError(resourceName: String, formatter: Option[Formatter], suiteName: String, testName: Option[String]): Option[String] =
    stringToPrintWhenNoError(resourceName, formatter, suiteName, testName, None)

  private def stringToPrintWhenNoError(resourceName: String, formatter: Option[Formatter], suiteName: String, testName: Option[String], duration: Option[Long]): Option[String] = {

    formatter match {
      case Some(IndentedText(formattedText, _, _)) =>
        duration match {
          case Some(milliseconds) =>
            if (presentAllDurations)
              Some(Resources("withDuration", formattedText, makeDurationString(milliseconds)))
            else
              Some(formattedText)
          case None => Some(formattedText)
        }
      case Some(MotionToSuppress) => None
      case _ =>
        val arg =
          testName match {
            case Some(tn) => suiteName + ": " + tn
            case None => suiteName
          }
        val unformattedText = Resources(resourceName, arg)
        duration match {
          case Some(milliseconds) =>
            if (presentAllDurations)
              Some(Resources("withDuration", unformattedText, makeDurationString(milliseconds)))
            else
              Some(unformattedText)
          case None => Some(unformattedText)
        }

    }
  }

  def apply(event: Event) {

    event match {

      case RunStarting(ordinal, testCount, configMap, formatter, payload, threadName, timeStamp) =>

        if (testCount < 0)
          throw new IllegalArgumentException

        val string = Resources("runStarting", testCount.toString)
        printPossiblyInColor(string, ansiCyan)

      case RunCompleted(ordinal, duration, summary, formatter, payload, threadName, timeStamp) =>

        makeFinalReport("runCompleted", duration, summary)

      case RunStopped(ordinal, duration, summary, formatter, payload, threadName, timeStamp) =>

        makeFinalReport("runStopped", duration, summary)

      case RunAborted(ordinal, message, throwable, duration, summary, formatter, payload, threadName, timeStamp) =>

        val lines = stringsToPrintOnError("abortedNote", "runAborted", message, throwable, formatter, None, None, duration)
        for (line <- lines) printPossiblyInColor(line, ansiRed)

      case SuiteStarting(ordinal, suiteName, suiteClassName, formatter, rerunnable, payload, threadName, timeStamp) =>

        val stringToPrint = stringToPrintWhenNoError("suiteStarting", formatter, suiteName, None)

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiGreen)
          case None =>
        }

      case SuiteCompleted(ordinal, suiteName, suiteClassName, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

        val stringToPrint = stringToPrintWhenNoError("suiteCompleted", formatter, suiteName, None, duration)

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiGreen)
          case None =>
        }

      case SuiteAborted(ordinal, message, suiteName, suiteClassName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

        val lines = stringsToPrintOnError("abortedNote", "suiteAborted", message, throwable, formatter, Some(suiteName), None, duration)
        for (line <- lines) printPossiblyInColor(line, ansiRed)

      case TestStarting(ordinal, suiteName, suiteClassName, testName, formatter, rerunnable, payload, threadName, timeStamp) =>

        val stringToPrint = stringToPrintWhenNoError("testStarting", formatter, suiteName, Some(testName))

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiGreen)
          case None =>
        }

      case TestSucceeded(ordinal, suiteName, suiteClassName, testName, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

        val stringToPrint = stringToPrintWhenNoError("testSucceeded", formatter, suiteName, Some(testName), duration)

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiGreen)
          case None =>
        }

      case TestIgnored(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) =>

        val stringToPrint =
          formatter match {
            case Some(IndentedText(formattedText, _, _)) => Some(Resources("specTextAndNote", formattedText, Resources("ignoredNote")))
            case Some(MotionToSuppress) => None
            case _ => Some(Resources("testIgnored", suiteName + ": " + testName))
          }

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiYellow)
          case None =>
        }

      case TestFailed(ordinal, message, suiteName, suiteClassName, testName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) =>

        val lines = stringsToPrintOnError("failedNote", "testFailed", message, throwable, formatter, Some(suiteName), Some(testName), duration)
        for (line <- lines) printPossiblyInColor(line, ansiRed)

      case InfoProvided(ordinal, message, nameInfo, aboutAPendingTest, throwable, formatter, payload, threadName, timeStamp) =>

        val (suiteName, testName) =
          nameInfo match {
            case Some(NameInfo(suiteName, _, testName)) => (Some(suiteName), testName)
            case None => (None, None)
          }
        val lines = stringsToPrintOnError("infoProvidedNote", "infoProvided", message, throwable, formatter, suiteName, testName, None)
        val shouldBeYellow =
          aboutAPendingTest match {
            case Some(isPending) => isPending
            case None => false
          }
        for (line <- lines) printPossiblyInColor(line, if (shouldBeYellow) ansiYellow else ansiGreen)

      case TestPending(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) =>

        val stringToPrint =
          formatter match {
            case Some(IndentedText(formattedText, _, _)) => Some(Resources("specTextAndNote", formattedText, Resources("pendingNote")))
            case Some(MotionToSuppress) => None
            case _ => Some(Resources("testPending", suiteName + ": " + testName))
          }

        stringToPrint match {
          case Some(string) => printPossiblyInColor(string, ansiYellow)
          case None =>
        }

     // case _ => throw new RuntimeException("Unhandled event")
    }

    pw.flush()
  }

  // Closes the print writer. Subclasses StandardOutReporter and StandardErrReporter override dispose to do nothing
  // so that those aren't closed.
  override def dispose() {
    pw.close()
  }

  private def printResourceString(resourceName: String) {

    pw.println(Resources(resourceName))
    pw.flush()
  }

  private def makeFinalReport(resourceName: String, duration: Option[Long], summaryOption: Option[Summary]) {

    summaryOption match {
      case Some(summary) =>

        import summary._

        duration match {
          case Some(msSinceEpoch) =>
            printPossiblyInColor(Resources(resourceName + "In", makeDurationString(msSinceEpoch)), ansiCyan)
          case None =>
            printPossiblyInColor(Resources(resourceName), ansiCyan)
        }

        // totalNumberOfTestsRun=Total number of tests run was: {0}
        printPossiblyInColor(Resources("totalNumberOfTestsRun", testsCompletedCount.toString), ansiCyan)

        // Suite Summary: completed {0}, aborted {1}
        printPossiblyInColor(Resources("suiteSummary", suitesCompletedCount.toString, suitesAbortedCount.toString), ansiCyan)

        // Test Summary: succeeded {0}, failed {1}, ignored, {2}, pending {3}
        printPossiblyInColor(Resources("testSummary", testsSucceededCount.toString, testsFailedCount.toString, testsIgnoredCount.toString, testsPendingCount.toString), ansiCyan)

        // *** 1 SUITE ABORTED ***
        if (suitesAbortedCount == 1)
          printPossiblyInColor(Resources("oneSuiteAborted"), ansiRed)

        // *** {0} SUITES ABORTED ***
        else if (suitesAbortedCount > 1)
          printPossiblyInColor(Resources("multipleSuitesAborted", suitesAbortedCount.toString), ansiRed)

        // *** 1 TEST FAILED ***
        if (testsFailedCount == 1)
          printPossiblyInColor(Resources("oneTestFailed"), ansiRed)

        // *** {0} TESTS FAILED ***
        else if (testsFailedCount > 1)
          printPossiblyInColor(Resources("multipleTestsFailed", testsFailedCount.toString), ansiRed)

        else if (suitesAbortedCount == 0) // Maybe don't want to say this if the run aborted or stopped because "all"
          printPossiblyInColor(Resources("allTestsPassed"), ansiGreen)

      case None =>
    }

    pw.flush()

    println("THAT'S ALL FOLKS!")
  }

  // We subtract one from test reports because we add "- " in front, so if one is actually zero, it will come here as -1
  // private def indent(s: String, times: Int) = if (times <= 0) s else ("  " * times) + s

  // Stupid properties file won't let me put spaces at the beginning of a property
  // "  {0}" comes out as "{0}", so I can't do indenting in a localizable way. For now
  // just indent two space to the left.  //  if (times <= 0) s
  //  else Resources("indentOnce", indent(s, times - 1))
}


text:
#ifdef HAVE_CONFIG_H
#  include <dtn-config.h>
#endif

#include <stdlib.h>

#include "BundleRouter.h"
#include "bundling/BundleDaemon.h"
#include "bundling/BundleActions.h"
#include "bundling/BundleList.h"
#include "storage/BundleStore.h"

#include "StaticBundleRouter.h"
#include "FloodBundleRouter.h"
#include "ProphetRouter.h"
#include "DTLSRRouter.h"
#include "ExternalRouter.h"
#include "TcaRouter.h"

namespace dtn {

//----------------------------------------------------------------------
BundleRouter::Config::Config()
    : type_("static"),
      add_nexthop_routes_(true),
      open_discovered_links_(true),
      default_priority_(0),
      max_route_to_chain_(10),
      storage_quota_(0),
      subscription_timeout_(600),

      /********************************* Tartarini ****************************/
      bundle_fwd_order_(BundleList::SORT_FIFO),
      prioritymap_()
      /************************************************************************/
{}

BundleRouter::Config BundleRouter::config_;

//----------------------------------------------------------------------
BundleRouter*
BundleRouter::create_router(const char* type)
{
    if (strcmp(type, "static") == 0) {
        return new StaticBundleRouter();
    }
    else if (strcmp(type, "prophet") == 0) {
        return new ProphetRouter();
    }
    else if (strcmp(type, "flood") == 0) {
        return new FloodBundleRouter();
    }
    else if (strcmp(type, "dtlsr") == 0) {
        return new DTLSRRouter();
    }
    else if (!strcmp(type, "tca_router")) {
        return new TcaRouter(TcaRouter::TCA_ROUTER);
    }
    else if (!strcmp(type, "tca_gateway")) {
        return new TcaRouter(TcaRouter::TCA_GATEWAY);
    }
#if defined(XERCES_C_ENABLED) && defined(EXTERNAL_DP_ENABLED)
    else if (strcmp(type, "external") == 0) {
        return new ExternalRouter();
    }
#endif
    else {
        PANIC("unknown type %s for router", type);
    }
}

//----------------------------------------------------------------------
BundleRouter::BundleRouter(const char* classname, const std::string& name)
    : BundleEventHandler(classname, "/dtn/route"),
      name_(name)
{
    logpathf("/dtn/route/%s", name.c_str());

    actions_ = BundleDaemon::instance()->actions();

    // XXX/demmer maybe change this?
    pending_bundles_ = BundleDaemon::instance()->pending_bundles();
    custody_bundles_ = BundleDaemon::instance()->custody_bundles();
}

//----------------------------------------------------------------------
bool
BundleRouter::should_fwd(const Bundle* bundle, const LinkRef& link,
                         ForwardingInfo::action_t action)
{
    ForwardingInfo info;
    bool found = bundle->fwdlog()->get_latest_entry(link, &info);

    if (found) {
        ASSERT(info.state() != ForwardingInfo::NONE);
    } else {
        ASSERT(info.state() == ForwardingInfo::NONE);
    }

    // check if we've already sent or are in the process of sending
    // the bundle on this link
    if (info.state() == ForwardingInfo::TRANSMITTED ||
        info.state() == ForwardingInfo::QUEUED)
    {
        log_debug("should_fwd bundle %d: "
                  "skip %s due to forwarding log entry %s",
                  bundle->bundleid(), link->name(),
                  ForwardingInfo::state_to_str(info.state()));
        return false;
    }

    // check if we've already sent or are in the process of sending
    // the bundle to the node via some other link
    if (link->remote_eid() != EndpointID::NULL_EID())
    {
        size_t count = bundle->fwdlog()->get_count(
            link->remote_eid(),
            ForwardingInfo::TRANSMITTED | ForwardingInfo::QUEUED);

        if (count > 0)
        {
            log_debug("should_fwd bundle %d: "
                      "skip %s since already sent or queued %zu times for remote eid %s",
                      bundle->bundleid(), link->name(),
                      count, link->remote_eid().c_str());
            return false;
        }

        // check whether transmission was suppressed. this could be
        // coupled with the previous one but it's better to have a
        // separate log message
        count = bundle->fwdlog()->get_count(
            link->remote_eid(),
            ForwardingInfo::SUPPRESSED);

        if (count > 0)
        {
            log_debug("should_fwd bundle %d: "
                      "skip %s since transmission suppressed to remote eid %s",
                      bundle->bundleid(), link->name(),
                      link->remote_eid().c_str());
            return false;
        }
    }

    // if the bundle has a a singleton destination endpoint, then
    // check if we already forwarded it or are planning to forward it
    // somewhere else. if so, we shouldn't forward it again
    if (bundle->singleton_dest() && action == ForwardingInfo::FORWARD_ACTION)
    {
        size_t count = bundle->fwdlog()->get_count(
            ForwardingInfo::TRANSMITTED |
            ForwardingInfo::QUEUED,
            action);

        if (count > 0) {
            log_debug("should_fwd bundle %d: "
                      "skip %s since already transmitted or queued (count %zu)",
                      bundle->bundleid(), link->name(), count);
            return false;
        } else {
            log_debug("should_fwd bundle %d: "
                      "link %s ok since transmission count=%zu",
                      bundle->bundleid(), link->name(), count);
        }
    }

    // otherwise log the reason why we should send it
    log_debug("should_fwd bundle %d: "
              "match %s: forwarding log entry %s",
              bundle->bundleid(), link->name(),
              ForwardingInfo::state_to_str(info.state()));

    return true;
}

//----------------------------------------------------------------------
void
BundleRouter::initialize()
{
}

//----------------------------------------------------------------------
BundleRouter::~BundleRouter()
{
}

//----------------------------------------------------------------------
bool
BundleRouter::accept_bundle(Bundle* bundle, int* errp)
{
    // XXX/demmer this decision should be abstracted into a
    // StoragePolicy class of some sort. for now just use a
    // statically-configured payload limit
    BundleStore* bs = BundleStore::instance();
    if (bs->payload_quota() != 0 &&
        (bs->total_size() + bundle->payload().length() > bs->payload_quota()))
    {
        log_info("accept_bundle: rejecting bundle *%p since "
                 "cur size %llu + bundle size %zu > quota %llu",
                 bundle, U64FMT(bs->total_size()), bundle->payload().length(),
                 U64FMT(bs->payload_quota()));
        *errp = BundleProtocol::REASON_DEPLETED_STORAGE;
        return false;
    }

    *errp = 0;
    return true;
}

//----------------------------------------------------------------------
bool
BundleRouter::can_delete_bundle(const BundleRef& bundle)
{
    size_t num_mappings = bundle->num_mappings();
    if (num_mappings > 1) {
        log_debug("can_delete_bundle(*%p): not deleting because "
                  "bundle has %zu list mappings",
                  bundle.object(), num_mappings);
        return false;
    }

    return true;
}

//----------------------------------------------------------------------
void
BundleRouter::delete_bundle(const BundleRef& bundle)
{
    (void)bundle;
}

//----------------------------------------------------------------------
void
BundleRouter::tcl_dump_state(oasys::StringBuffer* buf)
{
    buf->append("{}");
}

//----------------------------------------------------------------------
void
BundleRouter::recompute_routes()
{
}

//----------------------------------------------------------------------
void
BundleRouter::shutdown()
{
}

} // namespace dtn


text:
<?php

namespace Nikoms\PhpUnitSplitter\Model;

use Nikoms\PhpUnitSplitter\Stats;
use Nikoms\PhpUnitSplitter\TestCaseId;

/**
 * Class Groups
 */
class Groups
{
    /**
     * @var Group[]
     */
    private $groups = [];

    /**
     * @var Stats
     */
    private $stats;

    /**
     * Groups constructor.
     *
     * @param int          $numberOfGroups
     * @param Stats $stats
     */
    public function __construct($numberOfGroups, Stats $stats)
    {
        for ($i = 0; $i < $numberOfGroups; $i++) {
            $this->groups[] = new Group($i);
        }

        $this->stats = $stats;
    }

    /**
     * @param \PHPUnit_Framework_TestCase $testCase
     *
     * @return $this
     */
    public function addInBestGroup(\PHPUnit_Framework_TestCase $testCase)
    {
        $testCaseId = TestCaseId::fromTestCase($testCase);
        $this->stats->assureTestIsStored($testCaseId);

        $this->getFasterGroup()->addToRun($testCaseId, $this->stats->getAverage($testCaseId));

        return $this;
    }

    /**
     * @return Group[]
     */
    public function toArray()
    {
        return $this->groups;
    }

    /**
     * @return $this
     */
    public function reset()
    {
        foreach ($this->groups as $group) {
            $group->delete();
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function save()
    {
        $this->stats->save();

        foreach ($this->groups as $group) {
            $group->save();
        }

        return $this;
    }

    /**
     * @return Group
     */
    private function getFasterGroup()
    {
        $fasterGroup = $this->groups[0];

        foreach ($this->groups as $group) {
            if ($fasterGroup->getEstimatedTime() > $group->getEstimatedTime()) {
                $fasterGroup = $group;
                continue;
            }
            if ($fasterGroup->count() > $group->count()) {
                $fasterGroup = $group;
                continue;
            }
        }

        return $fasterGroup;
    }
}


text:
<?php

use PHPUnit\Framework\TestCase;
use Fraudshield\Reports\GlobalReport;

class MapReportTest extends TestCase
{
    protected $mr;

    protected function setUp()
    {
        $this->mr = new GlobalReport();
    }

    /** @test */
    public function it_sets_start_end_date_to_today_if_empty()
    {
        $mr = new GlobalReport();
        $today = date("Y-m-d");
        $this->assertEquals($today, $mr->dateStart);
        $this->assertEquals($today, $mr->dateEnd);
    }

    /** @test */
    public function it_can_generate_report_with_tracker_id_and_start_date_and_end_date()
    {
        $start = "2017-05-01";
        $end = "2017-06-01";
        $mr = new GlobalReport($start, $end);

        $this->assertEquals($start, $mr->dateStart);
        $this->assertEquals($end, $mr->dateEnd);
    }

    /** @test */
    public function it_can_add_data_source()
    {
        $this->mr->addDataSource('sub_id');

        $this->assertContains('sub_id', $this->mr->dataSources);
    }

    /** @test */
    public function it_can_chaine_add_data_source()
    {
        $this->mr->addDataSource('sub_id')->addDataSource('partner');

        $this->assertContains('sub_id', $this->mr->dataSources);
        $this->assertContains('partner', $this->mr->dataSources);
    }

    /** @test
     * @expectedException Exception
     */
    public function it_throws_exception_when_adding_invalid_data_source()
    {
        $this->mr->addDataSource('some_invalid_data_source');
    }

    /** @test
     * @expectedException Exception
     */
    public function it_throws_exception_when_adding_more_than_allowed_number_data_source()
    {
        $this->mr
            ->addDataSource('sub_id')
            ->addDataSource('partner')
            ->addDataSource('affiliate')
            ->addDataSource('pikachu')
            ->addDataSource('quagsire')
            ->addDataSource('product');
    }

    /** @test
     */
    public function it_can_add_filters()
    {
        $this->mr->addFilter('tracker_id', 50);
        $this->assertArrayHasKey('tracker_id', $this->mr->filters);

    }

    /** @test
     * @expectedException Exception
     */
    public function it_throws_exception_when_adding_invalid_filter()
    {
        $this->mr->addFilter('invalid_filter', 50);
    }

    /** @test
     */
    public function it_can_add_data_source_as_filter()
    {
        $this->mr->addDataSource('sub_id');
        $this->mr->addFilter('sub_id', 500);

        $this->assertArrayHasKey('sub_id', $this->mr->filters);
    }

    /** @test
     * @expectedException Exception
     */
    public function it_throws_exception_when_using_invalid_date()
    {
        $start = "2017-May-01";
        $end = "2017-06-01";
        $fr = new GlobalReport($start, $end);
    }

}


text:
#include <assert.h>
#include <map>
#include <string>
#include <iostream>

#include "xdispatch_internal.h"

__XDISPATCH_USE_NAMESPACE

// static member variables, initialized during library initialization
static std::map<std::string, semaphore> user_lock_semaphores;
static synclock rw_lock;

void init_synchronized_feature() {
  // initialize the static variables manually
  // during library initialization to ensure
  // everything is set up properly on first use
  user_lock_semaphores = std::map<std::string, semaphore>();
  rw_lock = synclock();
}

synclock::synclock()
  : _semaphore(1), _lock_active(false) {}

synclock::synclock(const semaphore& s, const bool auto_lock)
  : _semaphore(s), _lock_active(false) {

  XDISPATCH_ASSERT(s.native_semaphore ());

  if(auto_lock)
    this->lock();
}

synclock::synclock(const synclock &other, const bool auto_lock)
  : _semaphore(other._semaphore), _lock_active(false)  {
  // this could have ugly side-effects like the semaphore
  // getting assigned a new value but the old one not getting released
  // so we need to ensure that no lock is currently active
  XDISPATCH_ASSERT(! other._lock_active);

  if(auto_lock)
    this->lock();
}

synclock::synclock(const std::string& key, const bool auto_lock)
  : _semaphore(1), _lock_active(false)  {

  if (user_lock_semaphores.count(key) != 0)
    _semaphore = user_lock_semaphores[ key ];
  else {
    XDISPATCH_SYNC_HEADER( rw_lock ){
      // in the meantime the semaphore might have been created
      if(user_lock_semaphores.count(key) != 0)
        _semaphore = user_lock_semaphores[ key ];
      else {
        // if not create it
        user_lock_semaphores.insert( std::pair<std::string, semaphore>(key,_semaphore) );
      }
    }
  }

  if(auto_lock)
    this->lock();
}

synclock&  synclock::operator = (const synclock& other) {
  // this could have ugly side-effects like the semaphore
  // getting assigned a new value but the old one not getting released
  // so we need to ensure that no lock is currently active
  XDISPATCH_ASSERT(! _lock_active);
  XDISPATCH_ASSERT(! other._lock_active)
  _semaphore = other._semaphore;

  return (*this);
}

synclock::~synclock() {
  // in a rare case there might an exception have
  // been thrown and due to this the synclock is
  // not unlocked properly. We need to handle this rare
  // case by testing for an exception and doing an unlock
  // during destruction.
  // FIXME: After a call to return within the owning loop this
  //        is needed as well because no other call to unlock happens...
  if(_lock_active) // && std::uncaught_exception())
    this->unlock();

  // the _lock_active variable is
  // used as some kind of state variable
  // to notify if the current object is holding
  // the semaphore.
  // As such it has to be false on construction
  // and false on deletion, i.e. the calls to lock()
  // must be balanced to the calls of unlock()
  XDISPATCH_ASSERT(! _lock_active);
}

synclock::operator bool() const{
  return _lock_active;
}

synclock& synclock::lock(){
  XDISPATCH_ASSERT(! _lock_active);

  // lock() - and unlock() are called from the same thread,
  // so no race condition here. Thread-safety is
  // provided by the used semaphores
  _semaphore.acquire ();
  _lock_active = true;

  return *this;
}

synclock& synclock::unlock(){
  XDISPATCH_ASSERT(_lock_active);

  // lock() - and unlock() are called from the same thread,
  // so no race condition here. Thread-safety is
  // provided by the used semaphores
  _lock_active = false;
  _semaphore.release ();

  return *this;
}

void xdispatch::init_semaphore_for_synclock(void* dt){
  XDISPATCH_ASSERT( dt );
  semaphore* sem_ptr = (semaphore*)(dt);
  XDISPATCH_ASSERT( sem_ptr );

  (*sem_ptr) = semaphore(1);
}


text:
<?php

namespace Usuario\Entity;

use Vivo\Entity\AbstractEntity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Math\Rand,
    Zend\Crypt\Key\Derivation\Pbkdf2;
use Zend\Stdlib\Hydrator;

/**
 * Usuario
 *
 * @ORM\Table(name="usuario", uniqueConstraints={@ORM\UniqueConstraint(name="login", columns={"login"})})
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Usuario\Entity\UsuarioRepository")
 */
class Usuario extends AbstractEntity {

    /**
     * @var string
     *
     * @ORM\Column(name="login", type="string", length=50, nullable=false)
     */
    private $login;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=50, nullable=false)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="senha", type="string", length=255, nullable=false)
     */
    private $senha;

    /**
     * @var string
     *
     * @ORM\Column(name="salt", type="string", length=255, nullable=false)
     */
    private $salt;

    /**
     * @var integer
     *
     * @ORM\Column(name="status", type="integer", nullable=true)
     */
    private $status;

    /**
     * @var string
     *
     * @ORM\Column(name="chave_ativacao", type="string", length=255, nullable=false)
     */
    private $chaveAtivacao;

    /**
     * @var \Pessoa
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Pessoa")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id", referencedColumnName="id")
     * })
     */
    private $id;

    public function __construct(array $options = null) {
        (new Hydrator\ClassMethods())->hydrate($options, $this);

        $this->salt = base64_encode(Rand::getBytes(8, true));
        $this->chaveAtivacao = md5($this->email . $this->salt);
    }

    public function getLogin() {
        return $this->login;
    }

    public function getEmail() {
        return $this->email;
    }

    public function getSenha() {
        return $this->senha;
    }

    public function getSalt() {
        return $this->salt;
    }

    public function getStatus() {
        return $this->status;
    }

    public function getChaveAtivacao() {
        return $this->chaveAtivacao;
    }

    public function getId() {
        return $this->id;
    }

    public function setLogin($login) {
        $this->login = $login;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function setSenha($senha) {
        $this->senha = $this->encryptPassword($senha);
    }

    public function setSalt($salt) {
        $this->salt = $salt;
    }

    public function setStatus($status) {
        $this->status = $status;
    }

    public function setChaveAtivacao($chaveAtivacao) {
        $this->chaveAtivacao = $chaveAtivacao;
    }

    public function setId(Pessoa $id) {
        $this->id = $id;
    }

    public function encryptPassword($password) {
        return base64_encode(Pbkdf2::calc('sha256', $password, $this->salt, 10000, strlen($password * 2)));
    }

    public function getArrayCopy() {
        return get_object_vars($this);
    }

}


text:
"""
This trivial program snoops all PV search requests and prints them out.
Its only purpose is to demonstrate how channel access disconvers PVs.
"""
import pcaspy.cas as cas
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s: %(message)s')

class SnooperServer(cas.caServer):
    def __init__(self):
        cas.caServer.__init__(self)

    def __del__(self):
        cas.asCaStop()

    def pvExistTest(self, context, addr, fullname):
        logging.debug('%s\t%s', addr.stringConvert(1024), fullname)
        return cas.pverDoesNotExistHere

    def pvAttach(self, context, fullname):
        return cas.S_casApp_pvNotFound

    def process(self, second):
        cas.process(second)

if __name__ == '__main__':
    snooper = SnooperServer()
    while True:
        snooper.process(0.1)


text:
"""
Code that might be useful when using Flask
"""


text:
<DataObjectMetadata name="pp1_cv">
  <DataSet type="Static">
    <general>
      <outputs>cv_m1_ans</outputs>
      <sampleTag>RAVEN_sample_ID</sampleTag>
    </general>
  </DataSet>

</DataObjectMetadata>


text:
from .container import Container as IContainer
from .expandcollapse import ExpandCollapse as IExpandCollapse
from .invoke import Invoke as IInvoke
from .selection import Selection as ISelection
from .selectionitem import SelectionItem as ISelectionItem
from .table import Table as ITable
from .text import Text as IText
from .toggle import Toggle as IToggle
from .value import Value as IValue


text:
class TestCase < TestCaseTemplate
  def attack
    nil
  end
end


text:
<component name="libraryTable">
  <library name="Maven: com.netflix.netflix-commons:netflix-eventbus:0.3.0">
    <CLASSES>
      <root url="jar://D:/maven-repo/com/netflix/netflix-commons/netflix-eventbus/0.3.0/netflix-eventbus-0.3.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://D:/maven-repo/com/netflix/netflix-commons/netflix-eventbus/0.3.0/netflix-eventbus-0.3.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://D:/maven-repo/com/netflix/netflix-commons/netflix-eventbus/0.3.0/netflix-eventbus-0.3.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package io.druid.cli;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.druid.client.cache.CacheConfig;
import io.druid.client.coordinator.CoordinatorClient;
import io.druid.guice.Binders;
import io.druid.guice.CacheModule;
import io.druid.guice.DruidProcessingModule;
import io.druid.guice.IndexingServiceFirehoseModule;
import io.druid.guice.Jerseys;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.LazySingleton;
import io.druid.guice.LifecycleModule;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.NodeTypeConfig;
import io.druid.guice.PolyBind;
import io.druid.guice.QueryRunnerFactoryModule;
import io.druid.guice.QueryableModule;
import io.druid.guice.QueryablePeonModule;
import io.druid.guice.annotations.Json;
import io.druid.indexing.common.RetryPolicyConfig;
import io.druid.indexing.common.RetryPolicyFactory;
import io.druid.indexing.common.TaskToolboxFactory;
import io.druid.indexing.common.actions.LocalTaskActionClientFactory;
import io.druid.indexing.common.actions.RemoteTaskActionClientFactory;
import io.druid.indexing.common.actions.TaskActionClientFactory;
import io.druid.indexing.common.actions.TaskActionToolbox;
import io.druid.indexing.common.config.TaskConfig;
import io.druid.indexing.common.config.TaskStorageConfig;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.HeapMemoryTaskStorage;
import io.druid.indexing.overlord.IndexerMetadataStorageCoordinator;
import io.druid.indexing.overlord.TaskRunner;
import io.druid.indexing.overlord.TaskStorage;
import io.druid.indexing.overlord.ThreadPoolTaskRunner;
import io.druid.indexing.worker.executor.ExecutorLifecycle;
import io.druid.indexing.worker.executor.ExecutorLifecycleConfig;
import io.druid.java.util.common.lifecycle.Lifecycle;
import io.druid.java.util.common.logger.Logger;
import io.druid.metadata.IndexerSQLMetadataStorageCoordinator;
import io.druid.query.QuerySegmentWalker;
import io.druid.query.lookup.LookupModule;
import io.druid.segment.loading.DataSegmentArchiver;
import io.druid.segment.loading.DataSegmentKiller;
import io.druid.segment.loading.DataSegmentMover;
import io.druid.segment.loading.OmniDataSegmentArchiver;
import io.druid.segment.loading.OmniDataSegmentKiller;
import io.druid.segment.loading.OmniDataSegmentMover;
import io.druid.segment.loading.SegmentLoaderConfig;
import io.druid.segment.loading.StorageLocationConfig;
import io.druid.segment.realtime.firehose.ChatHandlerProvider;
import io.druid.segment.realtime.firehose.NoopChatHandlerProvider;
import io.druid.segment.realtime.firehose.ServiceAnnouncingChatHandlerProvider;
import io.druid.segment.realtime.plumber.CoordinatorBasedSegmentHandoffNotifierConfig;
import io.druid.segment.realtime.plumber.CoordinatorBasedSegmentHandoffNotifierFactory;
import io.druid.segment.realtime.plumber.SegmentHandoffNotifierFactory;
import io.druid.server.coordination.ServerType;
import io.druid.server.http.SegmentListerResource;
import io.druid.server.initialization.jetty.ChatHandlerServerModule;
import io.druid.server.initialization.jetty.JettyServerInitializer;
import io.druid.server.metrics.DataSourceTaskIdHolder;
import org.eclipse.jetty.server.Server;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;

/**
 */
@Command(
    name = "peon",
    description = "Runs a Peon, this is an individual forked \"task\" used as part of the indexing service. "
                  + "This should rarely, if ever, be used directly."
)
public class CliPeon extends GuiceRunnable
{
  @Arguments(description = "task.json status.json", required = true)
  public List<String> taskAndStatusFile;

  @Option(name = "--nodeType", title = "nodeType", description = "Set the node type to expose on ZK")
  public String nodeType = "indexer-executor";

  private static final Logger log = new Logger(CliPeon.class);

  @Inject
  private Properties properties;

  public CliPeon()
  {
    super(log);
  }

  @Override
  protected List<? extends Module> getModules()
  {
    return ImmutableList.<Module>of(
        new DruidProcessingModule(),
        new QueryableModule(),
        new QueryRunnerFactoryModule(),
        new Module()
        {
          @Override
          public void configure(Binder binder)
          {
            binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/peon");
            binder.bindConstant().annotatedWith(Names.named("servicePort")).to(-1);
            binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(-1);

            PolyBind.createChoice(
                binder,
                "druid.indexer.task.chathandler.type",
                Key.get(ChatHandlerProvider.class),
                Key.get(ServiceAnnouncingChatHandlerProvider.class)
            );
            final MapBinder<String, ChatHandlerProvider> handlerProviderBinder = PolyBind.optionBinder(
                binder, Key.get(ChatHandlerProvider.class)
            );
            handlerProviderBinder.addBinding("announce")
                                 .to(ServiceAnnouncingChatHandlerProvider.class).in(LazySingleton.class);
            handlerProviderBinder.addBinding("noop")
                                 .to(NoopChatHandlerProvider.class).in(LazySingleton.class);
            binder.bind(ServiceAnnouncingChatHandlerProvider.class).in(LazySingleton.class);

            binder.bind(NoopChatHandlerProvider.class).in(LazySingleton.class);

            binder.bind(TaskToolboxFactory.class).in(LazySingleton.class);

            JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class);
            JsonConfigProvider.bind(binder, "druid.peon.taskActionClient.retry", RetryPolicyConfig.class);

            configureTaskActionClient(binder);

            binder.bind(RetryPolicyFactory.class).in(LazySingleton.class);

            // Build it to make it bind even if nothing binds to it.
            Binders.dataSegmentKillerBinder(binder);
            binder.bind(DataSegmentKiller.class).to(OmniDataSegmentKiller.class).in(LazySingleton.class);
            Binders.dataSegmentMoverBinder(binder);
            binder.bind(DataSegmentMover.class).to(OmniDataSegmentMover.class).in(LazySingleton.class);
            Binders.dataSegmentArchiverBinder(binder);
            binder.bind(DataSegmentArchiver.class).to(OmniDataSegmentArchiver.class).in(LazySingleton.class);

            binder.bind(ExecutorLifecycle.class).in(ManageLifecycle.class);
            LifecycleModule.register(binder, ExecutorLifecycle.class);
            binder.bind(ExecutorLifecycleConfig.class).toInstance(
                new ExecutorLifecycleConfig()
                    .setTaskFile(new File(taskAndStatusFile.get(0)))
                    .setStatusFile(new File(taskAndStatusFile.get(1)))
            );

            binder.bind(TaskRunner.class).to(ThreadPoolTaskRunner.class);
            binder.bind(QuerySegmentWalker.class).to(ThreadPoolTaskRunner.class);
            binder.bind(ThreadPoolTaskRunner.class).in(ManageLifecycle.class);

            JsonConfigProvider.bind(binder, "druid.realtime.cache", CacheConfig.class);
            binder.install(new CacheModule());

            JsonConfigProvider.bind(
                binder,
                "druid.segment.handoff",
                CoordinatorBasedSegmentHandoffNotifierConfig.class
            );
            binder.bind(SegmentHandoffNotifierFactory.class)
                  .to(CoordinatorBasedSegmentHandoffNotifierFactory.class)
                  .in(LazySingleton.class);

            // Override the default SegmentLoaderConfig because we don't actually care about the
            // configuration based locations.  This will override them anyway.  This is also stopping
            // configuration of other parameters, but I don't think that's actually a problem.
            // Note, if that is actually not a problem, then that probably means we have the wrong abstraction.
            binder.bind(SegmentLoaderConfig.class)
                  .toInstance(new SegmentLoaderConfig().withLocations(Arrays.<StorageLocationConfig>asList()));
            binder.bind(CoordinatorClient.class).in(LazySingleton.class);

            binder.bind(JettyServerInitializer.class).to(QueryJettyServerInitializer.class);
            Jerseys.addResource(binder, SegmentListerResource.class);
            binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig(ServerType.fromString(nodeType)));
            LifecycleModule.register(binder, Server.class);
          }

          private void configureTaskActionClient(Binder binder)
          {
            PolyBind.createChoice(
                binder,
                "druid.peon.mode",
                Key.get(TaskActionClientFactory.class),
                Key.get(RemoteTaskActionClientFactory.class)
            );
            final MapBinder<String, TaskActionClientFactory> taskActionBinder = PolyBind.optionBinder(
                binder, Key.get(TaskActionClientFactory.class)
            );
            taskActionBinder.addBinding("local")
                            .to(LocalTaskActionClientFactory.class).in(LazySingleton.class);
            // all of these bindings are so that we can run the peon in local mode
            JsonConfigProvider.bind(binder, "druid.indexer.storage", TaskStorageConfig.class);
            binder.bind(TaskStorage.class).to(HeapMemoryTaskStorage.class).in(LazySingleton.class);
            binder.bind(TaskActionToolbox.class).in(LazySingleton.class);
            binder.bind(IndexerMetadataStorageCoordinator.class).to(IndexerSQLMetadataStorageCoordinator.class).in(
                LazySingleton.class
            );
            taskActionBinder.addBinding("remote")
                            .to(RemoteTaskActionClientFactory.class).in(LazySingleton.class);

          }

          @Provides
          @LazySingleton
          public Task readTask(@Json ObjectMapper mapper, ExecutorLifecycleConfig config)
          {
            try {
              return mapper.readValue(config.getTaskFile(), Task.class);
            }
            catch (IOException e) {
              throw Throwables.propagate(e);
            }
          }

          @Provides
          @LazySingleton
          @Named(DataSourceTaskIdHolder.DATA_SOURCE_BINDING)
          public String getDataSourceFromTask(final Task task)
          {
            return task.getDataSource();
          }

          @Provides
          @LazySingleton
          @Named(DataSourceTaskIdHolder.TASK_ID_BINDING)
          public String getTaskIDFromTask(final Task task)
          {
            return task.getId();
          }
        },
        new QueryablePeonModule(),
        new IndexingServiceFirehoseModule(),
        new ChatHandlerServerModule(properties),
        new LookupModule()
    );
  }

  @Override
  public void run()
  {
    try {
      Injector injector = makeInjector();
      try {
        final Lifecycle lifecycle = initLifecycle(injector);
        final Thread hook = new Thread(
            new Runnable()
            {
              @Override
              public void run()
              {
                log.info("Running shutdown hook");
                lifecycle.stop();
              }
            }
        );
        Runtime.getRuntime().addShutdownHook(hook);
        injector.getInstance(ExecutorLifecycle.class).join();

        // Sanity check to help debug unexpected non-daemon threads
        final Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for (Thread thread : threadSet) {
          if (!thread.isDaemon() && thread != Thread.currentThread()) {
            log.info("Thread [%s] is non daemon.", thread);
          }
        }

        // Explicitly call lifecycle stop, dont rely on shutdown hook.
        lifecycle.stop();
        Runtime.getRuntime().removeShutdownHook(hook);
      }
      catch (Throwable t) {
        log.error(t, "Error when starting up.  Failing.");
        System.exit(1);
      }
      log.info("Finished peon task");
    }
    catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
}


text:
unified_mode true

include Resolver::Cookbook::Helpers

property :config_file, String,
          default: lazy { RESOLVER_RESOLV_CONF_DEFAULT },
          description: 'The path to the resolver configuration file on disk'

property :cookbook, String,
          default: 'resolver',
          description: 'Template source cookbook'

property :template, String,
          default: 'resolv.conf.erb',
          description: 'Template source file'

property :owner, String,
          default: lazy { RESOLVER_CONF_USER_DEFAULT },
          description: 'Generated file owner'

property :group, String,
          default: lazy { resolver_conf_group_default },
          description: 'Generated file group'

property :mode, String,
          default: '0644',
          description: 'Generated file mode'

property :nameservers, [String, Array],
          coerce: proc { |p| p.is_a?(String) ? p.split(',') : p },
          required: true,
          description: 'The DNS servers to configure for system name resolution'

property :domain, String,
          description: 'The DNS domain name for the host'

property :search, [String, Array],
          coerce: proc { |p| p.is_a?(String) ? p.split(',') : p },
          description: 'The DNS domain search list for the host',
          callbacks: {
            'with glibc < 2.26 the number of search domains are limited to 6' => lambda { |p|
              p.count <= 6 || (node['languages']['c']['glibc']['version'].to_f >= 2.26)
            },
            'with glibc < 2.26 the total length of the search list is limited to 256 character' => lambda { |p|
              p.join(' ').length <= 256 || (node['languages']['c']['glibc']['version'].to_f >= 2.26)
            },
          }

property :sortlist, [String, Array],
          coerce: proc { |p| p.is_a?(Array) ? p : [p] },
          description: 'The DNS sort list for the host'

property :options, Hash,
          description: 'Additional options to add to the resolver configuration file'

property :override_system_configuration, [true, false],
          default: lazy { resolver_override_default(config_file) },
          description: 'Override the system DNS configuration, for use with NetworkManager/resolvconf/systemd-resolved'

action :set do
  if new_resource.override_system_configuration
    directory '/etc/NetworkManager/conf.d' do
      recursive true
    end

    template '/etc/NetworkManager/conf.d/90-dns-none.conf' do
      cookbook new_resource.cookbook
      source '90-dns-none.conf.erb'

      owner new_resource.owner
      group new_resource.group
      mode new_resource.mode

      action :create
    end if ::Dir.exist?('/etc/NetworkManager')
  end

  template new_resource.config_file do
    cookbook new_resource.cookbook
    source new_resource.template

    owner new_resource.owner
    group new_resource.group
    mode new_resource.mode

    force_unlink new_resource.override_system_configuration
    manage_symlink_source !new_resource.override_system_configuration

    variables(
      nameservers: new_resource.nameservers,
      domain: new_resource.domain,
      search: new_resource.search,
      sortlist: new_resource.sortlist,
      options: new_resource.options
    )
    helpers(Resolver::Cookbook::TemplateHelpers)

    action :create
  end
end


text:
package org.gradle.internal.logging.services;

import org.gradle.internal.Factory;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.gradle.internal.logging.config.LoggingRouter;
import org.gradle.internal.logging.config.LoggingSourceSystem;

public class DefaultLoggingManagerFactory implements Factory<LoggingManagerInternal> {
    private final LoggingSourceSystem slfLoggingSystem;
    private final LoggingSourceSystem javaUtilLoggingSystem;
    private final LoggingSourceSystem stdOutLoggingSystem;
    private final LoggingSourceSystem stdErrLoggingSystem;
    private final DefaultLoggingManager rootManager;
    private final LoggingRouter loggingRouter;
    private boolean created;

    public DefaultLoggingManagerFactory(LoggingRouter loggingRouter, LoggingSourceSystem slf4j, LoggingSourceSystem javaUtilLoggingSystem, LoggingSourceSystem stdOutLoggingSystem, LoggingSourceSystem stdErrLoggingSystem) {
        this.loggingRouter = loggingRouter;
        this.slfLoggingSystem = slf4j;
        this.javaUtilLoggingSystem = javaUtilLoggingSystem;
        this.stdOutLoggingSystem = stdOutLoggingSystem;
        this.stdErrLoggingSystem = stdErrLoggingSystem;
        rootManager = newManager();
    }

    public LoggingManagerInternal getRoot() {
        return rootManager;
    }

    @Override
    public LoggingManagerInternal create() {
        if (!created) {
            created = true;
            return getRoot();
        }
        return newManager();
    }

    private DefaultLoggingManager newManager() {
        return new DefaultLoggingManager(slfLoggingSystem, javaUtilLoggingSystem, stdOutLoggingSystem, stdErrLoggingSystem, loggingRouter);
    }
}


text:
/**
 * @license Highcharts JS v7.2.2 (2020-08-24)
 * @module highcharts/modules/pareto
 * @requires highcharts
 *
 * Pareto series type for Highcharts
 *
 * (c) 2010-2019 Sebastian Bochan
 *
 * License: www.highcharts.com/license
 */
'use strict';
import '../../modules/pareto.src.js';