text:
package com.microsoft.bingads.campaignmanagement;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="AdGroups" type="{https://bingads.microsoft.com/CampaignManagement/v9}ArrayOfAdGroup" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "adGroups"
})
@XmlRootElement(name = "GetAdGroupsByCampaignIdResponse")
public class GetAdGroupsByCampaignIdResponse {

    @XmlElement(name = "AdGroups", nillable = true)
    protected ArrayOfAdGroup adGroups;

    /**
     * Gets the value of the adGroups property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfAdGroup }
     *
     */
    public ArrayOfAdGroup getAdGroups() {
        return adGroups;
    }

    /**
     * Sets the value of the adGroups property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfAdGroup }
     *
     */
    public void setAdGroups(ArrayOfAdGroup value) {
        this.adGroups = value;
    }

}


text:
package udp

import (
	"bytes"
	"encoding/json"
	"log"
	"net"

	"github.com/influxdb/influxdb"
	"github.com/influxdb/influxdb/client"
)

const (
	udpBufferSize = 65536
)

// SeriesWriter defines the interface for the destination of the data.
type SeriesWriter interface {
	WriteSeries(database, retentionPolicy string, points []influxdb.Point) (uint64, error)
}

// UDPServer
type UDPServer struct {
	writer SeriesWriter
}

// NewUDPServer returns a new instance of a UDPServer
func NewUDPServer(w SeriesWriter) *UDPServer {
	u := UDPServer{
		writer: w,
	}
	return &u
}

// ListenAndServe binds the server to the given UDP interface.
func (u *UDPServer) ListenAndServe(iface string) error {
	addr, err := net.ResolveUDPAddr("udp", iface)
	if err != nil {
		log.Printf("Failed resolve UDP address %s: %s", iface, err)
		return err
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		log.Printf("Failed set up UDP listener at address %s: %s", addr, err)
		return err
	}

	var bp client.BatchPoints
	buf := make([]byte, udpBufferSize)

	go func() {
		for {
			_, _, err := conn.ReadFromUDP(buf)
			if err != nil {
				log.Printf("Failed read UDP message: %s.", err)
				continue
			}

			dec := json.NewDecoder(bytes.NewReader(buf))
			if err := dec.Decode(&bp); err != nil {
				log.Printf("Failed decode JSON UDP message")
				continue
			}

			points, err := influxdb.NormalizeBatchPoints(bp)
			if err != nil {
				log.Printf("Failed normalize batch points")
				continue
			}

			if msgIndex, err := u.writer.WriteSeries(bp.Database, bp.RetentionPolicy, points); err != nil {
				log.Printf("Server write failed. Message index was %d: %s", msgIndex, err)
			}
		}
	}()
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
class SslHelper final
{
public:
	SslHelper(const SslHelper&) = delete;
	SslHelper& operator=(const SslHelper&) = delete;
	SslHelper(SslHelper&&) noexcept = delete;
	SslHelper& operator=(SslHelper&&) noexcept = delete;

private:
	SslHelper();
	~SslHelper();

	static SslHelper &getInstance()
	{
		static SslHelper instance;
		return instance;
	}

	std::shared_ptr<SSL_CTX> _serverContext;

public:
	static std::shared_ptr<SSL_CTX> getServerContext()
	{
		return getInstance()._serverContext;
	}

	static std::shared_ptr<SSL_CTX> getClientContext();
};


text:
package ht.sivgep.pharmacielakay;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by ingdjason on 6/4/17.
 */

public class PrefManager {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "app-welcome";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }

}


text:
import {CanActivate, CanActivateChild, CanDeactivate, CanLoad} from '../interfaces';
import {UrlTree} from '../url_tree';

/**
 * Simple function check, but generic so type inference will flow. Example:
 *
 * function product(a: number, b: number) {
 *   return a * b;
 * }
 *
 * if (isFunction<product>(fn)) {
 *   return fn(1, 2);
 * } else {
 *   throw "Must provide the `product` function";
 * }
 */
export function isFunction<T>(v: any): v is T {
  return typeof v === 'function';
}

export function isBoolean(v: any): v is boolean {
  return typeof v === 'boolean';
}

export function isUrlTree(v: any): v is UrlTree {
  return v instanceof UrlTree;
}

export function isCanLoad(guard: any): guard is CanLoad {
  return guard && isFunction<CanLoad>(guard.canLoad);
}

export function isCanActivate(guard: any): guard is CanActivate {
  return guard && isFunction<CanActivate>(guard.canActivate);
}

export function isCanActivateChild(guard: any): guard is CanActivateChild {
  return guard && isFunction<CanActivateChild>(guard.canActivateChild);
}

export function isCanDeactivate<T>(guard: any): guard is CanDeactivate<T> {
  return guard && isFunction<CanDeactivate<T>>(guard.canDeactivate);
}


text:
mkdir -p build
cd build
cmake -G Ninja $@ ..
ninja


text:
package org.javalite.activejdbc.test_models;

import org.javalite.activejdbc.Model;
import org.javalite.test.jspec.TestException;

/**
 * @author Igor Polevoy
 */
public class FruitCallbackChecker {

    public boolean
            beforeSaveCalled = false, afterSaveCalled = false,
            beforeDeleteCalled = false, afterDeleteCalled = false,
            beforeCreateCalled = false, afterCreateCalled = false;

    protected void checkBeforeSave(Model m){
        beforeSaveCalled = true;
        if(m.getId() != null)
            throw new TestException("new model must not have an ID before save()");
    }

    protected void checkBeforeCreate(Model m){
        beforeCreateCalled = true;
        if(m.getId() != null)
            throw new TestException("new model must not have an ID before insert()");
    }

    protected void checkAfterCreate(Model m){
           afterCreateCalled = true;
           if(m.getId() == null)
               throw new TestException("new model must have an ID after insert()");
    }

    protected void checkAfterSave(Model m){
        afterSaveCalled = true;
        if(m.getId() == null)
            throw new TestException("new model must have an ID after save()");
    }

    protected void checkBeforeDelete(Model m){
        beforeDeleteCalled = true;
        if(m.isFrozen())
            throw new TestException("new model must not be frozen before delete()");

    }
    protected void checkAfterDelete(Model m){
        afterDeleteCalled = true;
           if(!m.isFrozen())
            throw new TestException("new model must be frozen after delete()");
    }
}


text:
"""Tests for grr.server.flows.general.artifact_fallbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from absl import app

from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_server.flows.general import artifact_fallbacks
from grr.test_lib import action_mocks
from grr.test_lib import flow_test_lib
from grr.test_lib import test_lib
from grr.test_lib import vfs_test_lib

class TestSystemRootSystemDriveFallbackFlow(flow_test_lib.FlowTestsBaseclass):

  def testSystemRootFallback(self):
    client_id = self.SetupClient(0)

    with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                   vfs_test_lib.ClientVFSHandlerFixture):
      client_mock = action_mocks.ListDirectoryClientMock()

      session_id = flow_test_lib.TestFlowHelper(
          artifact_fallbacks.SystemRootSystemDriveFallbackFlow.__name__,
          client_mock,
          client_id=client_id,
          token=self.token,
          artifact_name="WindowsEnvironmentVariableSystemRoot")

      results = flow_test_lib.GetFlowResults(client_id, session_id)
      self.assertLen(results, 1)
      self.assertEqual(str(results[0].registry_data.GetValue()), r"C:\WINDOWS")

def main(argv):
  # Run the full test suite
  test_lib.main(argv)

if __name__ == "__main__":
  app.run(main)


text:
auth-service-java
=================

Java implementation of auth service for Rong Cloud.


text:
using System;
using System.Reactive.Linq;
using System.Reflection;

namespace Glimpse.Agent
{
    public class AgentBrokerObservations
    {
        private readonly IObservable<AgentBrokerPayload> _observable;

        public AgentBrokerObservations(IObservable<AgentBrokerPayload> observable)
        {
            _observable = observable;
        }

        public IObservable<AgentBrokerPayload> Listen<T>()
        {
            return _observable.Where(opts => typeof(T).GetTypeInfo().IsAssignableFrom(opts.Payload.GetType().GetTypeInfo()));
        }

        public IObservable<AgentBrokerPayload> ListenAll()
        {
            return _observable;
        }
    }
}


text:
package com.droidcoding.github.ui.misc;

import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;

/**
 * Created by Donglua on 15/9/18.
 */
public class DataBoundViewHolder<T extends ViewDataBinding> extends RecyclerView.ViewHolder {
  private T binding;

  public DataBoundViewHolder(T binding) {
    super(binding.getRoot());
    this.binding = binding;
  }

  public T getBinding() {
    return binding;
  }
}


text:
console.log('------------ Array Helpers ---------------------------------------------------------------------------------');

//forEach
console.log('------------ ES5 forEach -----------------------------------------------------------------------------------');
const colors = ['red', 'blue', 'green'];

//old way
for (var i = 0; i < colors.length; i++) {
  console.log(colors[i] + " - Using old for loop");
}

//ES6 way
console.log('------------ ES6 forEach -----------------------------------------------------------------------------------');
colors.forEach(function(color) {
  console.log(`${color} - Using forEach Array helper to output all the values in an array`);
});

var numbers = [1,2,3,4,5];
var sum = 0;
function adder(number) {
  sum += number
}
numbers.forEach(adder);
console.log(`${sum} - Using forEach to get the sum of an array.`);

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];

var areas = [];

images.forEach(function(image) {
    var area = image.height * image.width;
    areas.push(area);
});

console.log(`[${areas}] - Using forEach to loop and the push to a new array the total area of the images.`);

//map
console.log('------------ Old for loop ----------------------------------------------------------------------------------');

var numbers = [1,2,3];
var doubleNumbers = [];

//old way
for (var i = 0; i < numbers.length; i++) {
  doubleNumbers.push(numbers[i] *2);
}
console.log(`[${doubleNumbers}] - Using old for loop to double each number and then push into an array.`);

//ES6 way
console.log('------------ New map helper for looping --------------------------------------------------------------------');
var doubled = numbers.map(function(number) {
  return number * 2;
});
console.log(`[${doubled}] - Using map array helper to loop through and double each number and automatically return an array with the new values.`);

// implemented previous example in map instead of forEach for correct way of using the correct array helper method
console.log('------------ Using map to replace the forEach method above -------------------------------------------------');
var newArea = images.map(function(image) {
    return image.height * image.width;
});

console.log(`[${newArea}] - Using map instead of forEach is simpler and less code and is faster.`);

//example of plucking
console.log('------------ Using map to pluck values from an array of objects --------------------------------------------');
var cars = [
  {
	  model: 'buick',
      price: 'Cheap'
  },
  {
    model: 'Camero',
    price: 'Expensive'
  }
];

var prices = cars.map(function(car) {
  return car.price;
});

console.log(`[${prices}] - Old ES5 way`);

function pluck(array, property) {
    var items = array.map(function(item) {
        return item[property];
    });
    return items;
}
var paints = [{ color: 'red' }, { color: 'blue' }, { color: 'yellow' }];
console.log(`[${pluck(paints, 'color')}] - Using map to create a function that is reusable to pluck away a key/value pair from an array of objects.`);

console.log('------------ Using filter array helper ---------------------------------------------------------------------');
//Filter example
var products = [
  {
    name: 'soda',
    price: 2.00,
    qty: 1
  },
  {
    name: 'candy',
    price: 2.00,
    qty: 0
  },
  {
    name: 'medicine',
    price: 1.00,
    qty: 14
  },
  {
    name: 'game',
    price: 1.00,
    qty: 15
  },
];

let filteredProducts = [];

//old way
for (var i = 0; i < products.length; i++) {
  if (products[i].price === 1.00) {
    filteredProducts.push(products[i]);
  }
}

console.log(` ------------ Old ES5 way`);
console.log(filteredProducts);

//ES6 way
const filterPrice = products.filter(function(product){
  return product.price === 2;
});

console.log(` ------------ Using .filter() to check products and return curated list that meets the requirements`);
console.log(filterPrice);

//more advanced filter
filteredProducts = products.filter(function(product) {
  return product.price > 1 && product.qty > 0;
});

console.log(` ------------ Using .filter() to check products and return curated list that meets the requirements.`);
console.log(filteredProducts);

console.log('------------ Using find array helper -----------------------------------------------------------------------');
// Find Method
var users = [
  {name:'Alex'},
  {name:'Jill'},
  {name:'Kim'}
];

var user;

//old way
for (var i = 0; i < users.length; i++) {
  if (users[i].name === 'Alex') {
    user = users[i];
    break;
  }
}

console.log(` ------------ Old ES5 way`);
console.log(user);

// ES6 way
user = users.find(function(user) {
  return user.name === 'Alex';
});

console.log(` ------------ Using .find() to return the one that matched the checked value.`);
console.log(user);

// a practical example of using the find method
var posts = [
  {id: 1, title: 'Post One'},
  {id: 2, title: 'Post Two'},
  {id: 3, title: 'Post Three'},
];

var comment = {postId: 1, content: 'Great Post'};

function postForComment(posts, comment) {
  return posts.find(function(post) {
    return post.id === comment.postId;
  });
}
console.log(` ------------ Using .find() to for a more complex example to return the one that matched the checked value.`);
console.log(postForComment(posts, comment));

var accounts = [
  { balance: -10 },
  { balance: 12 },
  { balance: 0 }
];

var account = accounts.find(function(account) {
   return  account.balance === 12;
});

console.log(` ------------ Using .find() to return the one that matched the checked value.`);
console.log(account);

console.log('------------ Using every & some array helpers --------------------------------------------------------------');
// Every & Some Method
var computers = [
    {name: "Apple", ram: 24},
    {name: "Compaq", ram: 4},
    {name: "Acer", ram: 32}
];

var allComputersCanRunProgram = true;
var onlySomeComputersCanRunProgram = false;

//old way
for (var i = 0; i < computers.length; i++) {
    var computer = computers[i];

    if (computer.ram < 16) {
        allComputersCanRunProgram = false;
    } else {
        onlySomeComputersCanRunProgram = true;
    }
}
console.log(` ------------ Old ES5 way.`);
console.log(allComputersCanRunProgram, onlySomeComputersCanRunProgram);

allComputersCanRunProgram = computers.every(function(computer){
   return computer.ram > 16;
});

console.log(` ------------ Using .every() to check all values and only when all return true the function returns true.`);
console.log(allComputersCanRunProgram);

onlySomeComputersCanRunProgram = computers.some(function(computer){
   return computer.ram > 16;
});

console.log(` ------------ Using .some() to check all values and when any return true then the function returns true.`);
console.log(onlySomeComputersCanRunProgram);

var namesStrings = [
    "John",
    "Peter",
    "Alexa",
    "Danny"
];

var isNameLong = namesStrings.every(function(name){
   return name.length > 3;
});

console.log(` ------------ Using .every() to check all values and only when all return true the function returns true.`);
console.log(isNameLong);

var isAnyNameLong = namesStrings.some(function(name){
   return name.length > 5;
});

console.log(` ------------ Using .some() to check all values and when any return true then the function returns true.`);
console.log(isAnyNameLong);

console.log('------------ Using reduce array helper ---------------------------------------------------------------------');
// reduce method
var numbers = [10, 20, 30];
var sum = 0;

//old way
for (var i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

console.log(` ------------ Old ES5 way.`);
console.log(sum);

sum = numbers.reduce(function(sum, number) {
    return sum + number;
}, 0);

console.log(` ------------ Using .reduce() to return the sum of the number. Reduce stores a value that you can then do something with over and over again.`);
console.log(sum);

var primaryColors = [
    {color: "Red"},
    {color: "Blue"},
    {color: "Green"}
];
var previous = [];

previous = primaryColors.reduce(function(previous, primaryColor) {
    previous.push(primaryColor.color);
    return previous;
}, []);

console.log(` ------------ Using Reduce to show how we can build up a new array as you loop through the original array.`);
console.log(previous);

//More practical example of reduce to solve balancedParens problem.
function balancedParens(string) {
    return !string.split("").reduce(function(previous, char) {
        if (previous < 0) { return previous; }
        if (char === "(") { return ++previous; }
        if (char === ")") { return --previous; }
        return previous;
    }, 0);
}

console.log(` ------------ Using Reduce to loop over an array and how we can use the build in returned value to our advantage and see if a string is balanced.`);
console.log(balancedParens("(())"));
console.log(balancedParens(")("));

var desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

var deskTypes = desks.reduce(function(previous, desk) {
    if (desk.type === 'sitting') {++previous.sitting};
    if (desk.type === 'standing') {++previous.standing};
    return previous;
}, { sitting: 0, standing: 0 });

console.log(` ------------ Using Reduce to loop over an array and count certain types of values to get sum of each one.`);
console.log(deskTypes);

var numbers = [1, 1, 2, 3, 4, 4];
function unique(array) {
  return array.reduce(function(previous, number) {
        var findNum = previous.find(function(num) {
            return num === number;
        });
        if (!findNum) {previous.push(number)}
        return previous;
  }, []);
}

console.log(` ------------ Using Reduce to loop over an array and create a new array without any repeated values.`);
console.log(unique(numbers));


text:
@interface ContactSearchTableViewController : UITableViewController
@property (nonatomic, strong) NSMutableArray *searchResults;
@end


text:
using System;
using System.Data;

namespace org.ohdsi.cdm.framework.shared.Extensions
{
   public static class ReaderExtensions
   {
      public static T? GetValue<T>(this IDataReader reader, string fieldName) where T : struct
      {
         if (string.IsNullOrEmpty(fieldName))
            return null;

         var value = reader[fieldName];

         if (value is DBNull)
            return null;

         if (typeof(T) == typeof(decimal))
         {
            decimal? result = Convert.ToDecimal(value);
            return result as T?;
         }

         if (typeof(T) == typeof(long))
         {
            long? result = Convert.ToInt64(value);
            return result as T?;
         }

         if (typeof(T) == typeof(int))
         {
            int? result = Convert.ToInt32(value);
            return result as T?;
         }

         return reader[fieldName] as T?;
      }

      public static string GetString(this IDataReader reader, string fieldName)
      {
         return string.IsNullOrEmpty(fieldName) ? null : reader[fieldName].ToString().Trim();
      }

      public static int? GetInt(this IDataReader reader, string fieldName)
      {
         return reader.GetValue<int>(fieldName);
      }

      public static decimal? GetDecimal(this IDataReader reader, string fieldName)
      {
         return reader.GetValue<decimal>(fieldName);
      }

      public static DateTime GetDateTime(this IDataReader reader, string fieldName)
      {
         var result = reader.GetValue<DateTime>(fieldName);
         return !result.HasValue ? DateTime.MinValue : result.Value;
      }

      public static long? GetLong(this IDataReader reader, string fieldName)
      {
         return reader.GetValue<long>(fieldName);
      }
   }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment></comment>
<entry key="version"></entry>
<entry key="supportedLanguages">fr,en</entry>
<entry key="lastModified">1404049378484</entry>
<entry key="defaultLanguage">en</entry>
</properties>


text:
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
    import unittest2 as unittest
else:
    import unittest

class TestCase(unittest.TestCase):
    """
    Parent TestCase to use for all tests.
    """

    def assertListEqual(self, l1, l2, msg=None):
        """Assert that the contents of l1 and l2 are equal (disregarding
ordering)"""
        self.assertEqual(len(l1), len(l2))

        # OK, the lists are of the same size. Let's test that each
        # item in l1 is in l2. This assumes that what you provided in
        # l1 are what you expected to find in l2.
        for item in l1:
            if item not in l2:
                raise AssertionError("List 1 and list 2 are not equivalent: %s %s" % (
                    str(l1),
                    str(l2)))

        return True


text:
该命令把一个chart包打包成为一个带版本的压缩chart文件包。

带版本的chart压缩包,可以被Helm package 仓库使用

## 格式
```
  helm package [flags] [CHART_PATH] [...]
```

```
Flags:
      --app-version string   set the appVersion on the chart to this version
  -u, --dependency-update    update dependencies from "requirements.yaml" to dir "charts/" before packaging
  -d, --destination string   location to write the chart. (default ".")
  -h, --help                 help for package
      --key string           name of the key to use when signing. Used if --sign is true
      --keyring string       location of a public keyring (default "/Users/nick/.gnupg/pubring.gpg")
      --save                 save packaged chart to local chart repository (default true)
      --sign                 use a PGP private key to sign this package
      --version string       set the version on the chart to this semver version

Global Flags:
      --debug                           enable verbose output
      --home string                     location of your Helm config. Overrides $HELM_HOME (default "/Users/nick/.helm")
      --host string                     address of Tiller. Overrides $HELM_HOST
      --kube-context string             name of the kubeconfig context to use
      --kubeconfig string               absolute path to the kubeconfig file to use
      --tiller-connection-timeout int   the duration (in seconds) Helm will wait to establish a connection to tiller (default 300)
      --tiller-namespace string         namespace of Tiller (default "kube-system")

```


text:
var webpack = require('webpack');
var _ = require('lodash');
var path = require('path');
var Findit = require('findit');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var Webpac
/**
 * @param opts
 * opts.PROJECT_PATH - path to project
 * opts.PROJECT_CONFIG - config in project [application.js]
 * opts.PROJECT_ENV - environment build
 */

module.exports = function (opts) {
    "use strict";

    console.log(opts.PROJECT_PATH + '/config/application.js');
    var PROJECT_PATH = opts.PROJECT_PATH,
        PROJECT_CONFIG = opts.PROJECT_CONFIG,
        PROJECT_ENV = opts.PROJECT_ENV,
        sassPath = [
            'node_modules/',
            'bower_components/'
        ].map(function (m) {
            return path.resolve(PROJECT_PATH, m);
        }).join('&includePaths[]=');

    var CONFIG = {
        context: PROJECT_PATH,
        entry: {
            app: [
                path.resolve('./config/application.js')
            ]
        },
        output: {
            path: path.join(PROJECT_PATH, '/dist'),
            filename: '[name].js',
            publicPath: '/'
        },
        plugins: [
            new webpack.optimize.OccurenceOrderPlugin(true),
            new ExtractTextPlugin("[name].css", {
                allChunks: true
            }),
        ],
        resolve: {
            root: [
                path.resolve('bower_components'),
                path.resolve('node_modules'),
                path.resolve('public'),
                path.resolve('assets'),
                path.resolve('vendors'),
                path.resolve(PROJECT_PATH)
            ],
            modulesDirectories: ["bower_components", "node_modules"],
            extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx']
        },
        module: {
            loaders: [
                {
                    test: /\.txt/,
                    loader: 'file?name=[path][name].[ext]'
                }, {
                    test: /\.gif/,
                    loader: 'url-loader?limit=10000&mimetype=image/gif'
                }, {
                    test: /\.jpg/,
                    loader: 'url-loader?limit=10000&mimetype=image/jpg'
                }, {
                    test: /\.png/,
                    loader: 'url-loader?limit=10000&mimetype=image/png'
                }, {
                    test: /\.(woff|woff2)/,
                    loader: "url?limit=10000&mimetype=application/font-woff"
                },  {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url?limit=10000&mimetype=application/octet-stream"
                }, {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "file?name=[hash].[ext]"
                }, {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url?name=[hash].[ext]&limit=10000&mimetype=image/svg+xml"
                }, {
                    test: /\.js?$/,
                    exclude: /node_modules/,
                    loader: 'react-hot!babel?stage=0'
                }, {
                    test: /\.css$/,
                    loader: ExtractTextPlugin.extract("css-loader")
                },
                {
                    test: /\.scss$/,
                    loader: ExtractTextPlugin.extract("css-loader!sass-loader?sourceMap&includePaths=[]" + sassPath)
                },
            ]
        }
    };

    ///**
    // * ENTRY -> APP
    // */
    //if (_.has(PROJECT_CONFIG, 'app')) {
    //    CONFIG.entry.app = PROJECT_CONFIG.app;
    //}

    /**
     * OUTPUT
     */
    if (_.has(PROJECT_CONFIG, 'output')) {
        CONFIG.output = PROJECT_CONFIG.output;
    }

    /**
     * VENDORS
     */
    if (_.has(PROJECT_CONFIG, 'vendors')) {
        CONFIG.entry.vendors = PROJECT_CONFIG.vendors;
        CONFIG.plugins.push(new webpack.optimize.CommonsChunkPlugin({
            name: "vendors",
            minChunks: Infinity
        }));
    }

    /**
     * PLUGINS
     */
    if (_.has(PROJECT_CONFIG, 'plugins')) {
        PROJECT_CONFIG.plugins.forEach(function (plugin) {
            CONFIG.plugins.push(plugin);
        })
    }

    /**
     * EXTENSIONS
     */
    if (_.has(PROJECT_CONFIG, 'resolve.extensions')) {
        CONFIG.resolve.extensions = PROJECT_CONFIG.resolve.extensions;
    }

    /**
     * LOADERS
     */
    if (_.has(PROJECT_CONFIG, 'module.loaders')) {
        PROJECT_CONFIG.module.loaders.forEach(function (loader) {
            CONFIG.module.loaders.push(loader);
        })
    }

    /**
     * PROVIDE
     */
    if (_.has(PROJECT_CONFIG, 'provide')) {
        CONFIG.plugins.push(
            new webpack.ProvidePlugin(_.merge({
                React: "react",
                DOM: "react-dom",
                RRouter: "react-router",
                Immutable: "immutable"
            }, PROJECT_CONFIG.provide)
        ))
    }

    /**
     * TODO
     * ENVIRONMENTS
     */
    return new Promise(function (resolve, reject) {
        var find = Findit(PROJECT_PATH + '/config/environments');
        var define = {};

        if (_.has(PROJECT_CONFIG, 'define')) {
            define = PROJECT_CONFIG.define;
        }

        if (PROJECT_ENV === 'production' || PROJECT_ENV === 'development') {
            process.env.NODE_ENV = PROJECT_ENV;
        }

        find.on('file', function (file, stats) {
            "use strict";
            var filename = path.basename(file, '.js');

            define['_' + filename.toUpperCase() + '_'] = JSON.parse(PROJECT_ENV === filename);

            if (filename === 'production' || filename === 'development') {
                define["process.env.NODE_ENV"] = JSON.stringify(process.env.NODE_ENV);
            }

            if (filename === PROJECT_ENV) {
                var FILE_ENVIRONMENT = require(file);

                CONFIG = _.merge(FILE_ENVIRONMENT, CONFIG, {
                    entry: {
                        app: CONFIG.entry.app.concat(FILE_ENVIRONMENT.app || [])
                    },
                    plugins: CONFIG.plugins.concat(FILE_ENVIRONMENT.plugins)
                })
            }
        });

        // TODO
        find.on('end', function () {

            CONFIG.plugins.push(new webpack.DefinePlugin(define));
            resolve(CONFIG);
        })
    });
}


text:
package DDG::Goodie::IsAwesome::dl00;
# ABSTRACT: dl00's first Goodie

use DDG::Goodie;

zci answer_type => "is_awesome_dl00";
zci is_cached   => 1;

name "IsAwesome dl00";
description "My first Goodie, it let's the world know that dl00 is indeed as awesome as he says he is";
primary_example_queries "duckduckhack dl00";
category "special";
topics "special_interest", "geek";
code_url "https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/IsAwesome/dl00.pm";
attribution github => ["https://github.com/dl00", "dl00"];

triggers start => "duckduckhack dl00";

handle remainder => sub {
    return if $_;
    return "dl00 is awesome and successfully completed the initiation tutorial for DuckDuckHack."
};

1;


text:
package org.mockito.asm;

/**
 * A visitor to visit a Java method. The methods of this interface must be
 * called in the following order: [ <tt>visitAnnotationDefault</tt> ] (
 * <tt>visitAnnotation</tt> | <tt>visitParameterAnnotation</tt> |
 * <tt>visitAttribute</tt> )* [ <tt>visitCode</tt> ( <tt>visitFrame</tt> |
 * <tt>visit</tt>XInsn</tt> | <tt>visitLabel</tt> | <tt>visitTryCatchBlock</tt> |
 * <tt>visitLocalVariable</tt> | <tt>visitLineNumber</tt>)* <tt>visitMaxs</tt> ]
 * <tt>visitEnd</tt>. In addition, the <tt>visit</tt>XInsn</tt>
 * and <tt>visitLabel</tt> methods must be called in the sequential order of
 * the bytecode instructions of the visited code, <tt>visitTryCatchBlock</tt>
 * must be called before the labels passed as arguments have been
 * visited, and the <tt>visitLocalVariable</tt> and <tt>visitLineNumber</tt>
 * methods must be called after the labels passed as arguments have been
 * visited.
 *
 * @author Eric Bruneton
 */
public interface MethodVisitor {

    // -------------------------------------------------------------------------
    // Annotations and non standard attributes
    // -------------------------------------------------------------------------

    /**
     * Visits the default value of this annotation interface method.
     *
     * @return a visitor to the visit the actual default value of this
     *         annotation interface method, or <tt>null</tt> if this visitor
     *         is not interested in visiting this default value. The 'name'
     *         parameters passed to the methods of this annotation visitor are
     *         ignored. Moreover, exacly one visit method must be called on this
     *         annotation visitor, followed by visitEnd.
     */
    AnnotationVisitor visitAnnotationDefault();

    /**
     * Visits an annotation of this method.
     *
     * @param desc the class descriptor of the annotation class.
     * @param visible <tt>true</tt> if the annotation is visible at runtime.
     * @return a visitor to visit the annotation values, or <tt>null</tt> if
     *         this visitor is not interested in visiting this annotation.
     */
    AnnotationVisitor visitAnnotation(String desc, boolean visible);

    /**
     * Visits an annotation of a parameter this method.
     *
     * @param parameter the parameter index.
     * @param desc the class descriptor of the annotation class.
     * @param visible <tt>true</tt> if the annotation is visible at runtime.
     * @return a visitor to visit the annotation values, or <tt>null</tt> if
     *         this visitor is not interested in visiting this annotation.
     */
    AnnotationVisitor visitParameterAnnotation(
        int parameter,
        String desc,
        boolean visible);

    /**
     * Visits a non standard attribute of this method.
     *
     * @param attr an attribute.
     */
    void visitAttribute(Attribute attr);

    /**
     * Starts the visit of the method's code, if any (i.e. non abstract method).
     */
    void visitCode();

    /**
     * Visits the current state of the local variables and operand stack
     * elements. This method must(*) be called just before any
     * instruction i that follows an unconditionnal branch instruction
     * such as GOTO or THROW, that is the target of a jump instruction, or that
     * starts an exception handler block. The visited types must describe the
     * values of the local variables and of the operand stack elements just
     * before i is executed.

 (*) this is mandatory only
     * for classes whose version is greater than or equal to
     * {@link Opcodes#V1_6 V1_6}.

 Packed frames are basically
     * "deltas" from the state of the previous frame (very first frame is
     * implicitly defined by the method's parameters and access flags):

     *
{@link Opcodes#F_SAME} representing frame with exactly the same
     * locals as the previous frame and with the empty stack.

{@link Opcodes#F_SAME1}
     * representing frame with exactly the same locals as the previous frame and
     * with single value on the stack (nStack is 1 and
     * stack[0] contains value for the type of the stack item).

     *
{@link Opcodes#F_APPEND} representing frame with current locals are
     * the same as the locals in the previous frame, except that additional
     * locals are defined (nLocal is 1, 2 or 3 and
     * local elements contains values representing added types).

     *
{@link Opcodes#F_CHOP} representing frame with current locals are
     * the same as the locals in the previous frame, except that the last 1-3
     * locals are absent and with the empty stack (nLocals is 1,
     * 2 or 3).

{@link Opcodes#F_FULL} representing complete frame
     * data.

     *
     * @param type the type of this stack map frame. Must be
     *        {@link Opcodes#F_NEW} for expanded frames, or
     *        {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND},
     *        {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or
     *        {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for compressed
     *        frames.
     * @param nLocal the number of local variables in the visited frame.
     * @param local the local variable types in this frame. This array must not
     *        be modified. Primitive types are represented by
     *        {@link Opcodes#TOP}, {@link Opcodes#INTEGER},
     *        {@link Opcodes#FLOAT}, {@link Opcodes#LONG},
     *        {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or
     *        {@link Opcodes#UNINITIALIZED_THIS} (long and double are
     *        represented by a single element). Reference types are represented
     *        by String objects (representing internal names), and uninitialized
     *        types by Label objects (this label designates the NEW instruction
     *        that created this uninitialized value).
     * @param nStack the number of operand stack elements in the visited frame.
     * @param stack the operand stack types in this frame. This array must not
     *        be modified. Its content has the same format as the "local" array.
     */
    void visitFrame(
        int type,
        int nLocal,
        Object[] local,
        int nStack,
        Object[] stack);

    // -------------------------------------------------------------------------
    // Normal instructions
    // -------------------------------------------------------------------------

    /**
     * Visits a zero operand instruction.
     *
     * @param opcode the opcode of the instruction to be visited. This opcode is
     *        either NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2,
     *        ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1, FCONST_0,
     *        FCONST_1, FCONST_2, DCONST_0, DCONST_1, IALOAD, LALOAD, FALOAD,
     *        DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE, LASTORE, FASTORE,
     *        DASTORE, AASTORE, BASTORE, CASTORE, SASTORE, POP, POP2, DUP,
     *        DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP, IADD, LADD, FADD,
     *        DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, LDIV,
     *        FDIV, DDIV, IREM, LREM, FREM, DREM, INEG, LNEG, FNEG, DNEG, ISHL,
     *        LSHL, ISHR, LSHR, IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR,
     *        I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B,
     *        I2C, I2S, LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN,
     *        FRETURN, DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW,
     *        MONITORENTER, or MONITOREXIT.
     */
    void visitInsn(int opcode);

    /**
     * Visits an instruction with a single int operand.
     *
     * @param opcode the opcode of the instruction to be visited. This opcode is
     *        either BIPUSH, SIPUSH or NEWARRAY.
     * @param operand the operand of the instruction to be visited.
 When
     *        opcode is BIPUSH, operand value should be between Byte.MIN_VALUE
     *        and Byte.MAX_VALUE.
 When opcode is SIPUSH, operand value
     *        should be between Short.MIN_VALUE and Short.MAX_VALUE.
 When
     *        opcode is NEWARRAY, operand value should be one of
     *        {@link Opcodes#T_BOOLEAN}, {@link Opcodes#T_CHAR},
     *        {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE},
     *        {@link Opcodes#T_BYTE}, {@link Opcodes#T_SHORT},
     *        {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}.
     */
    void visitIntInsn(int opcode, int operand);

    /**
     * Visits a local variable instruction. A local variable instruction is an
     * instruction that loads or stores the value of a local variable.
     *
     * @param opcode the opcode of the local variable instruction to be visited.
     *        This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE,
     *        LSTORE, FSTORE, DSTORE, ASTORE or RET.
     * @param var the operand of the instruction to be visited. This operand is
     *        the index of a local variable.
     */
    void visitVarInsn(int opcode, int var);

    /**
     * Visits a type instruction. A type instruction is an instruction that
     * takes the internal name of a class as parameter.
     *
     * @param opcode the opcode of the type instruction to be visited. This
     *        opcode is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF.
     * @param type the operand of the instruction to be visited. This operand
     *        must be the internal name of an object or array class (see {@link
     *        Type#getInternalName() getInternalName}).
     */
    void visitTypeInsn(int opcode, String type);

    /**
     * Visits a field instruction. A field instruction is an instruction that
     * loads or stores the value of a field of an object.
     *
     * @param opcode the opcode of the type instruction to be visited. This
     *        opcode is either GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
     * @param owner the internal name of the field's owner class (see {@link
     *        Type#getInternalName() getInternalName}).
     * @param name the field's name.
     * @param desc the field's descriptor (see {@link Type Type}).
     */
    void visitFieldInsn(int opcode, String owner, String name, String desc);

    /**
     * Visits a method instruction. A method instruction is an instruction that
     * invokes a method.
     *
     * @param opcode the opcode of the type instruction to be visited. This
     *        opcode is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or
     *        INVOKEINTERFACE.
     * @param owner the internal name of the method's owner class (see {@link
     *        Type#getInternalName() getInternalName}).
     * @param name the method's name.
     * @param desc the method's descriptor (see {@link Type Type}).
     */
    void visitMethodInsn(int opcode, String owner, String name, String desc);

    /**
     * Visits a jump instruction. A jump instruction is an instruction that may
     * jump to another instruction.
     *
     * @param opcode the opcode of the type instruction to be visited. This
     *        opcode is either IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ,
     *        IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ,
     *        IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL.
     * @param label the operand of the instruction to be visited. This operand
     *        is a label that designates the instruction to which the jump
     *        instruction may jump.
     */
    void visitJumpInsn(int opcode, Label label);

    /**
     * Visits a label. A label designates the instruction that will be visited
     * just after it.
     *
     * @param label a {@link Label Label} object.
     */
    void visitLabel(Label label);

    // -------------------------------------------------------------------------
    // Special instructions
    // -------------------------------------------------------------------------

    /**
     * Visits a LDC instruction.
     *
     * @param cst the constant to be loaded on the stack. This parameter must be
     *        a non null {@link Integer}, a {@link Float}, a {@link Long}, a
     *        {@link Double} a {@link String} (or a {@link Type} for
     *        <tt>.class</tt> constants, for classes whose version is 49.0 or
     *        more).
     */
    void visitLdcInsn(Object cst);

    /**
     * Visits an IINC instruction.
     *
     * @param var index of the local variable to be incremented.
     * @param increment amount to increment the local variable by.
     */
    void visitIincInsn(int var, int increment);

    /**
     * Visits a TABLESWITCH instruction.
     *
     * @param min the minimum key value.
     * @param max the maximum key value.
     * @param dflt beginning of the default handler block.
     * @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is
     *        the beginning of the handler block for the <tt>min + i</tt> key.
     */
    void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels);

    /**
     * Visits a LOOKUPSWITCH instruction.
     *
     * @param dflt beginning of the default handler block.
     * @param keys the values of the keys.
     * @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is
     *        the beginning of the handler block for the <tt>keys[i]</tt> key.
     */
    void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels);

    /**
     * Visits a MULTIANEWARRAY instruction.
     *
     * @param desc an array type descriptor (see {@link Type Type}).
     * @param dims number of dimensions of the array to allocate.
     */
    void visitMultiANewArrayInsn(String desc, int dims);

    // -------------------------------------------------------------------------
    // Exceptions table entries, debug information, max stack and max locals
    // -------------------------------------------------------------------------

    /**
     * Visits a try catch block.
     *
     * @param start beginning of the exception handler's scope (inclusive).
     * @param end end of the exception handler's scope (exclusive).
     * @param handler beginning of the exception handler's code.
     * @param type internal name of the type of exceptions handled by the
     *        handler, or <tt>null</tt> to catch any exceptions (for "finally"
     *        blocks).
     * @throws IllegalArgumentException if one of the labels has already been
     *         visited by this visitor (by the {@link #visitLabel visitLabel}
     *         method).
     */
    void visitTryCatchBlock(Label start, Label end, Label handler, String type);

    /**
     * Visits a local variable declaration.
     *
     * @param name the name of a local variable.
     * @param desc the type descriptor of this local variable.
     * @param signature the type signature of this local variable. May be
     *        <tt>null</tt> if the local variable type does not use generic
     *        types.
     * @param start the first instruction corresponding to the scope of this
     *        local variable (inclusive).
     * @param end the last instruction corresponding to the scope of this local
     *        variable (exclusive).
     * @param index the local variable's index.
     * @throws IllegalArgumentException if one of the labels has not already
     *         been visited by this visitor (by the
     *         {@link #visitLabel visitLabel} method).
     */
    void visitLocalVariable(
        String name,
        String desc,
        String signature,
        Label start,
        Label end,
        int index);

    /**
     * Visits a line number declaration.
     *
     * @param line a line number. This number refers to the source file from
     *        which the class was compiled.
     * @param start the first instruction corresponding to this line number.
     * @throws IllegalArgumentException if <tt>start</tt> has not already been
     *         visited by this visitor (by the {@link #visitLabel visitLabel}
     *         method).
     */
    void visitLineNumber(int line, Label start);

    /**
     * Visits the maximum stack size and the maximum number of local variables
     * of the method.
     *
     * @param maxStack maximum stack size of the method.
     * @param maxLocals maximum number of local variables for the method.
     */
    void visitMaxs(int maxStack, int maxLocals);

    /**
     * Visits the end of the method. This method, which is the last one to be
     * called, is used to inform the visitor that all the annotations and
     * attributes of the method have been visited.
     */
    void visitEnd();
}


text:
<?php

namespace Compressit\Handler\Image\Driver;

use Compressit\Handler\Image\Image;
use Compressit\Handler\Image\Helper\ShellCommand;

/**
 * Compress PNG files using pngquant library
 *
 * Pngquant library must be installed to make benefit of this class
 *
 * @see http://pngquant.org/
 */
class Png implements DriverInterface
{
    /**
     * Output file extension
     * @const string
     */
    const EXT = '.png';

    /**
     * Path to file
     * @var string
     */
    protected $_file;

    /**
     * Path to tmp file
     * @var string
     */
    protected $_tmpFile;

    /**
     * Original file size
     * @var int
     */
    protected $_fileSize;

    /**
     * Minimum quality
     * @var int
     */
    protected $_qualityMin = 45;

    /**
     * Maximum quality
     * @var int
     */
    protected $_qualityMax = 65;

    public function __construct($file)
    {
       $this->_file = $file;
       $this->_fileSize = filesize($file);
    }

    /**
     * Compress/Minify file using Pngquant
     * @return array
     * @see http://pngquant.org/
     *
     * @uses Compressit\Handler\Image\Helper\ShellCommand
     */
    public function compress()
    {
        if(ShellCommand::exist('pngquant'))
        {
            // create tmp file to work with
            $this->_tmpFile = Image::TMPDIR.md5(time().microtime()).self::EXT;
            file_put_contents($this->_tmpFile, file_get_contents($this->_file));
            // store original file size
            $this->_fileSize = filesize($this->_tmpFile);
            $args = array($this->_qualityMin, $this->_qualityMax, $this->_tmpFile);
            $compressedFile = ShellCommand::exec('pngquant --quality=%d-%d - < %s', $args);
            file_put_contents($this->_tmpFile, $compressedFile);
        }
        else
        {
            // Maybe throw an error? But this will make pngquant and libpng libraries required.
            return false;
        }
        if(file_exists($this->_tmpFile))
        {
            clearstatcache();
            $compressedSize = filesize($this->_tmpFile);
            // If no compression return false
            if( ! $this->_fileSize or $this->_fileSize == $compressedSize)
                return false;
            $savings = round((1 -($compressedSize/$this->_fileSize)) * 100);
            return array(
                'path' => $this->_tmpFile,
                'mimeType' => 'image/png',
                'originalSize' => $this->_fileSize,
                'compressedSize' => $compressedSize,
                'savings' => $savings.'%'
            );
        }
        else
        {
            // This may happen if result file is under minimum quality or there was no file size reduction.
            return false;
        }
    }

    /**
     * @param string $file
     * @return $this
     */
    public function setFile($file)
    {
        $this->_file = $file;
        $this->_fileSize = filesize($file);
        return $this;
    }

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

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

    /**
     * @param int $qualityMax
     * @return $this
     */
    public function setQualityMax($qualityMax)
    {
        $this->_qualityMax = (int) $qualityMax;
        return $this;
    }

    /**
     * @return int
     */
    public function getQualityMax()
    {
        return $this->_qualityMax;
    }

    /**
     * @param int $qualityMin
     * @return $this
     */
    public function setQualityMin($qualityMin)
    {
        $this->_qualityMin = (int) $qualityMin;

        return $this;
    }

    /**
     * @return int
     */
    public function getQualityMin()
    {
        return $this->_qualityMin;
    }

    /**
     * @param int $suffix
     * @return $this
     */
    public function setSuffix($suffix)
    {
        $this->_suffix = $suffix;

        return $this;
    }

    /**
     * @return int
     */
    public function getSuffix()
    {
        return $this->_suffix;
    }
}


text:
<!DOCTYPE html>

{% load staticfiles %}

  {% block meta_tags %}
    <meta charset="utf-8">
    <meta name="HandheldFriendly" content="true" />
    <meta name="viewport" content="initial-scale=1.0 user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="Description" content="DataHub is a (GitHub-Like) Data Ecosystem for Individuals, Teams and People. It provides an efficient platform and easy to use tools/interfaces for publishing of your own data (hosting, sharing, collaboration), using other's data (querying, linking), and making sense of data (analysis, visualization)" />
  {% endblock meta_tags %}

  {% block title %} <title>DataHub</title> {% endblock title %}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">

  <link rel="stylesheet" type="text/css" href="/static/css/datahub.css" />
  {% block stylesheets %} {% endblock stylesheets %}
  {% block js %} {% endblock js %}
  {% block extra_head %} {% endblock extra_head %}

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation

        </button>
        DataHub

            {% block headlink-right %}
              {% if login != 'dh_anonymous' and login or user.is_authenticated  %}

 Home

 Public Data

 SQL Console

                       {% if login %}{{ login }}{% else %}{{ user.get_username }}{% endif %}

Manage Apps

Settings

Sign Out

              {% else %}

                   Public Data

                  Sign In
                  Sign Up

              {% endif %}

            {% endblock headlink-right %}

  {% block header %} {% endblock header %}
  {% block content %} {% endblock content %}
  {% block footer %}

              About
              Documentation
              GitHub Repo
              API

  {% endblock footer %}
  {% block google_analytics %}

  {% endblock google_analytics %}

  {% block modal_dialog %}

Confirm

Are you sure?

          <button type="button"
              class="btn btn-primary">OK</button>
          <button type="button"
              class="btn btn-default" data-dismiss="modal">Cancel</button>

Confirm

Are you sure?

          <form method="post" action="" style="margin-bottom:0">
            {% csrf_token %}
            <button type="submit" class="btn btn-primary btn-danger">OK</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          </form>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

New message

          <form>

              Variable:
              <input type="text" class="form-control" id="variable-text">

              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Send message</button>

          </form>

Processing...

  {% endblock modal_dialog %}

  {% block modal_js %}

  {% endblock modal_js %}


text:
<?php
/**
 * login css hijacking
 */
add_action('login_head', 'custom_login_css');

function custom_login_css() {
    echo '<link rel="stylesheet" href="' . get_template_directory_uri() . '/res/css/admin.css" type="text/css" media="all" />';
}

if (is_admin()) { // why execute all the code below at all if we're not in admin?

    // call in custom admin stylesheet - this will be global for admin and also login

    add_action('admin_print_styles', 'load_custom_admin_css');

    function load_custom_admin_css() {
        wp_enqueue_style('custom_admin_css', get_template_directory_uri() . '/res/css/admin.css');
    }

    // overriding footer "credit" text

    add_filter('admin_footer_text', 'custom_footer_text');

    function custom_footer_text($default_text) {
        return 'Site managed by VIA Studio | Powered by WordPress';
    }

    /**
     * cleaning up and customizing the dashboard
     */

    add_action('wp_dashboard_setup', 'custom_dashboard_widgets');

    function custom_dashboard_widgets() {
        $wp_meta_boxes = $GLOBALS['wp_meta_boxes'];

        // remove unnecessary widgets
        // var_dump($wp_meta_boxes['dashboard']); // use to get all the widget IDs
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
        unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
        unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);

        //custom dashboard widgets
        wp_add_dashboard_widget('custom_help_widget', 'Theme by VIA Studio', 'custom_dashboard_help'); // add a new custom widget for help and support
    }

    function custom_dashboard_help() {
        $guide_url = get_theme_mod('theme_option_guide_url_txt_input');
?>

<?php
        if (!empty($guide_url)) {
?>

            <a class="button button-primary button-hero" href="<?php echo $guide_url; ?>" target="_blank">View User Guide

<?php
        }
    }

    /**
     * custom contextual help - tack on our support information to the end of the contextual help
     */

    add_filter('contextual_help', 'custom_help_support', 100); //giving a very low priority to make sure it's always at the end

    function custom_help_support($help) {
        $help .= '

Additional support - Contact the web team at VIA Studio
                    by phone at 502-498-8477 or by email at support@viastudio.com.

                ';
        return $help;
    }

    /**
    * Editor Customizations
    */

    add_filter('mce_buttons_2', 'silencio_add_style_select');

    function silencio_add_style_select($buttons) {
        array_unshift($buttons, 'styleselect');
        return $buttons;
    }

    add_filter('tiny_mce_before_init', 'silencio_add_styles');

    function silencio_add_styles($settings) {

        $style_formats = array(
            array(
                'title' => 'Intro',
                'selector' => 'p',
                'classes' => 'intro'
            ),
            array(
                'title' => 'Button',
                'selector' => 'a',
                'classes' => 'btn'
            )
        );

        $settings['style_formats'] = json_encode($style_formats);

        return $settings;

    }

} //wrapper for admin functions


text:
:: Purpose:       Installs a package
:: Requirements:  Run this script with Administrator rights
:: Author:        vocatus on reddit.com/r/sysadmin ( vocatus.gate@gmail.com ) // PGP key ID: 0x07d1490f82a211a2
:: Version:       1.0.3 + Add proper console and logfile logging
::                1.0.2 + Add additional commands to remove Adobe scheduled tasks
::                1.0.1 * Expand wildcard mask to catch additional Flash Player Updater scheduled tasks
::                1.0.0 + Initial write

::::::::::
:: Prep :: -- Don't change anything in this section
::::::::::
@echo off
set SCRIPT_VERSION=1.0.3
set SCRIPT_UPDATED=2020-02-05
:: Get the date into ISO 8601 standard date format (yyyy-mm-dd) so we can use it
FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO set DTS=%%a
set CUR_DATE=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%

:: This is useful if we start from a network share; converts CWD to a drive letter
pushd "%~dp0"

:::::::::::::::
:: VARIABLES :: -- Set these to your desired values
:::::::::::::::
:: Log location and name. Do not use trailing slashes (\)
set LOGPATH=%SystemDrive%\logs
set LOGFILE=%COMPUTERNAME%_Adobe_Flash_Chrome_install.log

:: Package to install. Do not use trailing slashes (\)
set BINARY=install_flash_player_32_ppapi.msi
set FLAGS=ALLUSERS=1 /q /norestart

:: Create the log directory if it doesn't exist
if not exist %LOGPATH% mkdir %LOGPATH%

::::::::::::::::::
:: INSTALLATION ::
::::::::::::::::::
:: Attempt to kill any running instances first
echo %CUR_DATE% %TIME% Killing any running Chrome-based browsers first, please wait...
echo %CUR_DATE% %TIME% Killing any running Chrome-based browsers first, please wait...>> "%LOGPATH%\%LOGFILE%" 2>NUL
taskkill /f /im chrome.exe /t >> "%LOGPATH%\%LOGFILE%" 2>NUL
taskkill /f /im chromium.exe /t >> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Remove prior versions of the Flash player
echo %CUR_DATE% %TIME% Removing prior versions, please wait...
echo %CUR_DATE% %TIME% Removing prior versions, please wait...>> "%LOGPATH%\%LOGFILE%" 2>NUL
wmic product where "name like 'Adobe Flash Player%%PPAPI'" uninstall /nointeractive
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Install the package from the local folder (if all files are in the same directory)
echo %CUR_DATE% %TIME% Installing package...
echo %CUR_DATE% %TIME% Installing package...>> "%LOGPATH%\%LOGFILE%" 2>NUL
msiexec /i "%BINARY%" %FLAGS% >> "%LOGPATH%\%LOGFILE%" 2>NUL
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

echo %CUR_DATE% %TIME% Disabling telemetry and cleaning up...
echo %CUR_DATE% %TIME% Disabling telemetry and cleaning up...>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete the Adobe Acrobat Update Service
net stop AdobeARMservice >> "%LOGPATH%\%LOGFILE%" 2>NUL
sc delete AdobeARMservice >> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete the Adobe Acrobat Update Service (older version)
net stop armsvc >> "%LOGPATH%\%LOGFILE%" 2>NUL
sc delete armsvc >> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete the Adobe Flash Player Update Service
net stop AdobeFlashPlayerUpdateSvc >> "%LOGPATH%\%LOGFILE%" 2>NUL
sc delete AdobeFlashPlayerUpdateSvc >> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete scheduled tasks Adobe installs against our wishes
del /F /Q "%SystemDrive%\Windows\tasks\Adobe Acrobat Update*" >> "%LOGPATH%\%LOGFILE%" 2>NUL
del /F /Q "%SystemDrive%\Windows\tasks\Adobe Flash Player Update*" >> "%LOGPATH%\%LOGFILE%" 2>NUL
del /F /Q "%SystemDrive%\Windows\system32\tasks\Adobe Acrobat Update*" >> "%LOGPATH%\%LOGFILE%" 2>NUL
del /F /Q "%SystemDrive%\Windows\system32\tasks\Adobe Flash Player Update*" >> "%LOGPATH%\%LOGFILE%" 2>NUL
del /F /Q "%SystemDrive%\Windows\system32\tasks\Adobe Flash Player * Notifier" >> "%LOGPATH%\%LOGFILE%" 2>NUL
schtasks.exe /tn "Adobe Flash Player Updater" /delete /f >> "%LOGPATH%\%LOGFILE%" 2>NUL
schtasks.exe /tn "Adobe Flash Player PPAPI Notifier" /delete /f>> "%LOGPATH%\%LOGFILE%" 2>NUL
schtasks.exe /tn "Adobe Flash Player NPAPI Notifier" /delete /f >> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete the annoying Acrobat tray icon
if exist "%ProgramFiles(x86)%\Adobe\Acrobat 7.0\Distillr\acrotray.exe" (
	taskkill /im "acrotray.exe"
	del /f /q "%ProgramFiles(x86)%\Adobe\Acrobat 7.0\Distillr\acrotray.exe" >> "%LOGPATH%\%LOGFILE%" 2>NUL
)

echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Pop back to original directory. This isn't necessary in stand-alone runs of the script, but is needed when being called from another script
popd

:: Return exit code to SCCM/PDQ Deploy/etc
exit /B %EXIT_CODE%


text:
package core.framework.internal.log;

import core.framework.internal.stat.StatCollector;
import core.framework.internal.stat.Stats;
import core.framework.log.LogAppender;
import core.framework.log.message.StatMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;

/**
 * @author neo
 */
@ExtendWith(MockitoExtension.class)
class CollectStatTaskTest {
    @Mock
    LogAppender appender;
    private CollectStatTask task;

    @BeforeEach
    void createCollectStatTask() {
        task = new CollectStatTask(appender, new StatCollector());
    }

    @Test
    void message() {
        var stats = new Stats();
        stats.put("sys_load_avg", 1d);
        StatMessage message = task.message(stats);
        assertThat(message.id).isNotNull();
        assertThat(message.stats).containsOnly(entry("sys_load_avg", 1d));
    }

    @Test
    void run() {
        task.run();
        verify(appender).append(any(StatMessage.class));
    }
}


text:
<?php

namespace Thuata\ComponentBundle\Exception;

/**
 * <b>InvalidCardDecoratorProperty<b><br>
 * Thrown when a card decorator does not provide a particular preperty
 *
 * @package Thuata\ComponentBundle\Exception
 *
 * @author  Anthony Maudry <anthony.maudry@thuata.com>
 */
class InvalidCardDecoratorPropertyException extends \Exception
{
    const MESSAGE_FORMAT = 'Property "%s" was not found in card decorator "%s"';

    /**
     * InvalidCardDecoratorPropertyException constructor.
     *
     * @param string $decorator
     * @param string $property
     */
    public function __construct(string $decorator, string $property)
    {
        parent::__construct(sprintf(self::MESSAGE_FORMAT, $property, get_class($decorator)));
    }
}


text:
<?php

namespace Teknoo\East\CodeRunner\Registry;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Teknoo\East\CodeRunner\Entity\TaskRegistration;
use Teknoo\East\CodeRunner\Manager\Interfaces\TaskManagerInterface;
use Teknoo\East\CodeRunner\Registry\Interfaces\TasksManagerByTasksRegistryInterface;
use Teknoo\East\CodeRunner\Repository\TaskRegistrationRepository;
use Teknoo\East\CodeRunner\Service\DatesService;
use Teknoo\East\CodeRunner\Task\Interfaces\TaskInterface;
use Teknoo\East\Foundation\Promise\PromiseInterface;

/**
 * Class TasksManagerByTasksRegistry.
 * Default implementation of TasksManagerByTasksRegistryInterface to persist the task manager managing a task.
 * The registry is usable via an array access behavior, with tasks as key, to return and manipulate managers. Manager
 * are identified by their id referenced in the platform, but manager must be referenced into the registry.
 * The registry use TaskRegistration entity to persist and manage the relation.
 *
 * @copyright   Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com)
 * @license     http://teknoo.software/license/mit         MIT License
 * @author      Richard Déloge <richarddeloge@gmail.com>
 */
class TasksManagerByTasksRegistry implements TasksManagerByTasksRegistryInterface
{
    /**
     * @var DatesService
     */
    private $datesService;

    /**
     * @var TaskRegistrationRepository
     */
    private $taskRegistrationRepository;

    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * @var TaskManagerInterface[]
     */
    private $tasksManagersList = [];

    /**
     * TasksManagerByTasksRegistry constructor.
     *
     * @param DatesService               $datesService
     * @param TaskRegistrationRepository $repository
     * @param EntityManagerInterface     $entityManager
     */
    public function __construct(
        DatesService $datesService,
        TaskRegistrationRepository $repository,
        EntityManagerInterface $entityManager
    ) {
        $this->datesService = $datesService;
        $this->taskRegistrationRepository = $repository;
        $this->entityManager = $entityManager;
    }

    /**
     * {@inheritdoc}
     */
    public function addTaskManager(TaskManagerInterface $taskManager): TasksManagerByTasksRegistryInterface
    {
        $this->tasksManagersList[$taskManager->getIdentifier()] = $taskManager;
        $taskManager->addRegistry($this);

        return $this;
    }

    /**
     * To extract a task from a TaskRegistration entity.
     *
     * @param TaskInterface $task
     *
     * @return null|TaskRegistration
     */
    private function getTaskRegistration(TaskInterface $task)
    {
        $taskId = $task->getId();
        $taskRegistration = $this->taskRegistrationRepository->findByTaskId($taskId);

        if (!$taskRegistration instanceof TaskRegistration || $taskRegistration->getDeletedAt() instanceof \DateTime) {
            return null;
        }

        return $taskRegistration;
    }

    /**
     * {@inheritdoc}
     */
    public function get(TaskInterface $task, PromiseInterface $promise): TasksManagerByTasksRegistryInterface
    {
        $taskRegistration = $this->getTaskRegistration($task);

        if (!$taskRegistration instanceof TaskRegistration) {
            $promise->fail(new \DomainException('The task has not been registered'));

            return $this;
        }

        $taskManagerIdentifier = $taskRegistration->getTaskManagerIdentifier();

        if (!isset($this->tasksManagersList[$taskManagerIdentifier])) {
            $promise->fail(new \DomainException('The manager has not been referenced'));

            return $this;
        }

        $promise->success($this->tasksManagersList[$taskManagerIdentifier]);

        return $this;
    }

    /**
     * @param TaskRegistration $taskRegistration
     */
    private function save(TaskRegistration $taskRegistration)
    {
        $this->entityManager->persist($taskRegistration);
        $this->entityManager->flush();
    }

    /**
     * To create a new TaskRegistration instance to persist the manager owning a task.
     *
     * @param TaskInterface        $task
     * @param TaskManagerInterface $manager
     *
     * @return TaskRegistration
     */
    private function create(TaskInterface $task, TaskManagerInterface $manager): TaskRegistration
    {
        $taskExecution = new TaskRegistration();
        $taskExecution->setTask($task);
        $taskExecution->setTaskManagerIdentifier($manager->getIdentifier());

        $this->taskRegistrationRepository->clearRegistration($task->getId());

        return $taskExecution;
    }

    /**
     * {@inheritdoc}
     */
    public function register(TaskInterface $task, TaskManagerInterface $manager): TasksManagerByTasksRegistryInterface
    {
        $taskRegistration = $this->getTaskRegistration($task);

        if ($taskRegistration instanceof TaskRegistration) {
            $taskRegistration->setTaskManagerIdentifier($manager->getIdentifier());
        } else {
            $taskRegistration = $this->create($task, $manager);
        }

        $this->save($taskRegistration);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function remove(TaskInterface $task): TasksManagerByTasksRegistryInterface
    {
        $taskRegistration = $this->getTaskRegistration($task);

        if ($taskRegistration instanceof TaskRegistration) {
            $this->taskRegistrationRepository->clearRegistration($task->getId());
            $taskRegistration->setDeletedAt($this->datesService->getDate());

            $this->save($taskRegistration);
        }

        $this->taskRegistrationRepository->clearRegistration($task->getId());

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function clearAll(): TasksManagerByTasksRegistryInterface
    {
        $this->taskRegistrationRepository->clearAll($this->datesService->getDate());

        return $this;
    }
}


text:
package net.ozwolf.mockserver.raml.internal.validator;

import net.ozwolf.mockserver.raml.ExpectationError;
import net.ozwolf.mockserver.raml.internal.domain.ApiExpectation;
import net.ozwolf.mockserver.raml.internal.domain.ValidationErrors;

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

import static java.util.Optional.empty;
import static java.util.Optional.of;

public class ExpectationValidator {
    private final ApiExpectation expectation;
    private final List<Validator> validators;

    public ExpectationValidator(ApiExpectation expectation,
                                Validator... validators) {
        this.expectation = expectation;
        this.validators = Arrays.asList(validators);
    }

    public Optional<ExpectationError> validate() {
        ValidationErrors errors = new ValidationErrors();

        validators.stream().forEach(v -> errors.combineWith(v.validate()));

        if (!errors.isInError())
            return empty();

        return of(new ExpectationError(expectation, errors));
    }
}


text:
namespace GM.Application.AppCore.Entities.Topics
{
    /// <summary>
    /// A category of topics discussed at meetings. The categories should be globally meaningful for all
    /// types of government bodies. For example: "health", "environment", "safety"
    /// This is in contrast to topics, which may only have meaning within thecontext of a specific government
    /// body. For example: "Repaving Main Street", "Funds for new sewer plant"
    /// </summary>
    public class Category
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }
}


text:
import MySQLdb
import configparser

try:
	config = configparser.ConfigParser()
	config.read('db.cfg')

	# Read in the people connection info

	db_user = config['main_database']['user']
	db_pass = config['main_database']['pass']
	db_name = config['main_database']['name']
	db_host = config['main_database']['host']

	db = MySQLdb.connect(
		host = db_host,
		user = db_user,
		passwd = db_pass,
		db = db_name,
		charset = 'utf8mb4')

	cursor = db.cursor(MySQLdb.cursors.DictCursor)

except:
	sys.exit("It appears you haven't run setup.py yet. Please do this.")

query = "UPDATE settings SET value='Idle' WHERE setting='utility_status'"
cursor.execute(query)
db.commit()

query = ("INSERT INTO utility_log (level,status) VALUES "
	"('Error','facade-worker.py manually reset')")
cursor.execute(query)
db.commit()

cursor.close()
db.close()


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Biggy.Extensions;

namespace Biggy {
  public class BiggyList<T> : IBiggy<T> where T : new() {
    private readonly IBiggyStore<T> _store;
    private readonly IQueryableBiggyStore<T> _queryableStore;
    private readonly IUpdateableBiggyStore<T> _updateableStore;
    private List<T> _items;

    bool _inMemory;
    public bool InMemory {
      get {
        if (_store == null) {
          return true;
        } else {
          return _inMemory;
        }
      }
      set {
        if (_store == null) {
          _inMemory = true;
        } else {
          _inMemory = value;
        }
      }
    }

    public BiggyList(IBiggyStore<T> store, bool inMemory = false) {
      _store = store;
      _queryableStore = _store as IQueryableBiggyStore<T>;
      _updateableStore = _store as IUpdateableBiggyStore<T>;
      _items = _store.Load();
      this.InMemory = inMemory;

    }

    public BiggyList() {
      _items = new List<T>();
    }

    public virtual IEnumerator<T> GetEnumerator() {
      return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
      return GetEnumerator();
    }

    public virtual void Clear() {
      if (_store != null && !this.InMemory) {
        _store.Clear();
      }
      _items.Clear();
      Fire(Changed, items: null);
    }

    public virtual int Count() {
      return _items.Count;
    }

    public virtual T Update(T item) {
      T itemFromList = default(T);
      if (!_items.Contains(item)) {
        // Figure out what to do here. Retreive Key From Store and evaluate?
        throw new InvalidOperationException(
          @"The list does not contain a reference to the object passed as an argument.
          Make sure you are passing a valid reference, or override Equals on the type being passed.");
      } else {
        itemFromList = _items.ElementAt(_items.IndexOf(item));
        if (!ReferenceEquals(itemFromList, item)) {
          //// The items are "equal" but do not refer to the same instance.
          //// Somebody overrode Equals on the type passed as an argument. Replace:
          int index = _items.IndexOf(item);
          _items.RemoveAt(index);
          _items.Insert(index, item);
        }
        // From here forward, the item passed in refers to the item in the list.
      }
      if (_store != null && !this.InMemory) {
        if (_updateableStore != null && !this.InMemory) {
          _updateableStore.Update(item);
        } else {
          _store.SaveAll(_items);
        }
      }
      Fire(Changed, item: item);
      return item;
    }

    public virtual T Remove(T item) {
      _items.Remove(item);
      if (_store != null && !this.InMemory) {
        if (_updateableStore != null && !InMemory) {
          _updateableStore.Remove(item);
        } else {
          _store.SaveAll(_items);
        }
      }
      Fire(ItemRemoved, item: item);
      return item;
    }

    public List<T> Remove(List<T> items) {
      foreach (var item in items) {
        _items.Remove(item);
      }
      if (_store != null && !this.InMemory) {
        if (_updateableStore != null && !this.InMemory) {
          _updateableStore.Remove(items);
        } else {
          _store.SaveAll(_items);
        }
      }
      Fire(ItemsRemoved, items: items);
      return items;
    }

    public virtual T Add(T item) {
      if (_store != null && !this.InMemory) {
        _store.Add(item);
      }
      _items.Add(item);
      Fire(ItemAdded, item: item);
      return item;
    }

    public virtual List<T> Add(List<T> items) {
      if (_store != null && !this.InMemory) {
        _store.Add(items);
      }
      _items.AddRange(items);
      Fire(ItemsAdded, items: items);
      return items;
    }

    public virtual IQueryable<T> AsQueryable() {
      return _queryableStore != null && !this.InMemory ? _queryableStore.AsQueryable() : _items.AsQueryable();
    }

    protected virtual void Fire(EventHandler<BiggyEventArgs<T>> @event, T item = default(T), IList<T> items = null) {
      if (@event != null) {
        var args = new BiggyEventArgs<T> { Item = item, Items = items };
        @event(this, args);
      }
    }

    public event EventHandler<BiggyEventArgs<T>> ItemRemoved;
    public event EventHandler<BiggyEventArgs<T>> ItemsRemoved;
    public event EventHandler<BiggyEventArgs<T>> ItemAdded;
    public event EventHandler<BiggyEventArgs<T>> ItemsAdded;

    public event EventHandler<BiggyEventArgs<T>> Changed;
    public event EventHandler<BiggyEventArgs<T>> Loaded;
    public event EventHandler<BiggyEventArgs<T>> Saved;
  }
}


text:
from setuptools import setup
from os import path

readme_path = path.join(path.abspath(path.dirname(__file__)), 'README.rst')
long_description = open(readme_path).read()

install_requires = ['python3-xlib', 'enum34']

setup(
    name='i3ipc',
    version='1.1.4',
    description='An improved Python library for i3wm extensions',
    long_description=long_description,
    url='https://github.com/acrisci/i3ipc-python',
    author='Tony Crisci',
    author_email='tony@dubstepdish.com',
    license='BSD',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    keywords='i3 i3wm extensions add-ons',
    py_modules=['i3ipc'],
    install_requires=install_requires,
)


text:
import datetime
import json
import unittest
from unittest.mock import patch

from utils import Notifications, time_in_range

class MockRedis:
    db = {}

    @staticmethod
    def set(key, value):
        MockRedis.db[key] = value.encode()

    @staticmethod
    def get(key):
        return MockRedis.db.get(key)

class NotificationsTestCase(unittest.TestCase):
    def setUp(self):
        Notifications.store = MockRedis
        self.notifications = [
            {'uuid': 'test', 'type': 'warning', 'title': 'Test Title', 'text': '
Test Text
'},
            {'uuid': 'second', 'type': 'success', 'title': 'Second title', 'text': 'Test Notification'}
        ]
        Notifications.store.set(Notifications.STORE_KEY, json.dumps(self.notifications))

    def test_list_method_should_return_proper_notifications_list(self):
        self.assertEqual(Notifications.list(), self.notifications)

    @patch('utils.uuid.uuid4', return_value='in-test')
    def test_add_method_should_append_notification_to_list_and_return_uuid(self, uuid4):
        result = Notifications.add('warning', 'No title', 'No text')
        self.assertEqual(result, 'in-test')
        expected_list = self.notifications[:]
        expected_list.append({'uuid': 'in-test', 'type': 'warning', 'title': 'No title', 'text': 'No text'})
        self.assertEqual(Notifications.list(), expected_list)

    def test_remove_method_should_remove_notification_from_list(self):
        Notifications.remove('second')
        expected_list = self.notifications[:1]
        self.assertEqual(Notifications.list(), expected_list)

    def test_remove_method_when_no_such_notification_in_list_should_do_nothing(self):
        Notifications.remove('0de8916f-7595-41b0-8e46-c9eea962b0b8')
        self.assertEqual(Notifications.list(), self.notifications)

class UtilsTestcase(unittest.TestCase):
    def test_time_in_range_when_time_is_in_range_should_return_true(self):
        test_time = datetime.time(23, 45)
        self.assertTrue(time_in_range(datetime.time(20, 12), datetime.time(5, 44), test_time))
        self.assertTrue(time_in_range(datetime.time(13, 10), datetime.time(23, 46), test_time))

    def test_time_in_range_when_time_is_not_in_range_should_return_false(self):
        test_time = datetime.time(23, 45)
        self.assertFalse(time_in_range(datetime.time(23, 46), datetime.time(5, 44), test_time))
        self.assertFalse(time_in_range(datetime.time(13, 10), datetime.time(23, 40), test_time))


text:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code will host a data story.


text:
package org.jboss.weld.environment.se.test.beandiscovery.priority;

import static javax.interceptor.Interceptor.Priority.APPLICATION;

import javax.annotation.Priority;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Priority(APPLICATION)
@Interceptor
@Normalized
public class NormalizingInterceptor {

    public static int invocations = 0;

    @AroundInvoke
    public Object equalize(InvocationContext ctx) throws Exception {
        invocations++;
        return ctx.proceed();
    }

    static void reset() {
        invocations = 0;
    }

}


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

<TITLE>
AGateway.GatewayAttributes (SMSLib 3.5.3)
</TITLE>

<META NAME="date" CONTENT="2013-03-06">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.smslib

Class AGateway.GatewayAttributes

java.lang.Object
  org.smslib.AGateway.GatewayAttributes

Enclosing class:
AGateway

public static class AGateway.GatewayAttributes
extends java.lang.Object

Field Summary

static int
BIGMESSAGES

static int
CUSTOMFROM

static int
DELIVERYREPORTS

static int
FLASHSMS

static int
PORTADDRESSING

static int
RECEIVE

static int
SEND

static int
WAPSI

Constructor Summary

AGateway.GatewayAttributes()

Method Summary

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

SEND

public static final int SEND

See Also:
Constant Field Values

RECEIVE

public static final int RECEIVE

See Also:
Constant Field Values

CUSTOMFROM

public static final int CUSTOMFROM

See Also:
Constant Field Values

BIGMESSAGES

public static final int BIGMESSAGES

See Also:
Constant Field Values

WAPSI

public static final int WAPSI

See Also:
Constant Field Values

PORTADDRESSING

public static final int PORTADDRESSING

See Also:
Constant Field Values

FLASHSMS

public static final int FLASHSMS

See Also:
Constant Field Values

DELIVERYREPORTS

public static final int DELIVERYREPORTS

See Also:
Constant Field Values

Constructor Detail

AGateway.GatewayAttributes

public AGateway.GatewayAttributes()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

SMSLib 3.5.3

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

(c) 2002-2011, http://smslib.org


text:
module TimelineEventsHelper

  def action(action_txt)
    content_tag("span", action_txt, :class => "action")
  end

  def user_action(event_type, events, display_action=true)
    case event_type

    when "new_tagging" then

      action("tagged") + " " +
        events.map do |e|
        link_to(e.secondary_subject, e.secondary_subject) +
          " with #{link_to(e.subject.tag, e.subject.tag)}".html_safe
      end.to_sentence.html_safe

    when "new_package_rating" then

      action("rated") + " " +
        events.map do |e|
        link_to(e.secondary_subject, e.secondary_subject) +
          "#{e.subject.aspect == 'overall' ? '' : '\'s documentation'}" +
          " with " + content_tag("span", "#{e.cached_value} stars", :class => "red")
      end.to_sentence.html_safe

    when "new_package_user" then

      action("uses") + " " +
        events.map do |e|
          link_to(e.secondary_subject, e.secondary_subject)
        end.to_sentence.html_safe

    when "new_review" then

      action("reviewed") + " " +
        events.map do |e|
          link_to(e.secondary_subject, e.secondary_subject) +
            " with " + link_to("these words", [e.subject.package, e.subject])
        end.to_sentence.html_safe

    end
  end

  def timeline_event(item, display_time_ago=true, li=true)

    output = if item.package_event?
               case item.event_type

               when "new_package" then
                 return "" if item.subject.nil?
                 # Maybe include version number here
                 link_to(item.subject, item.subject) + " was " + action("released")

               when "new_version" then

                 link_to(item.secondary_subject, item.secondary_subject) + " was " +
                   action("upgraded") + " to version " +
                   link_to(item.subject, package_version_path(item.subject.package, item.subject))
               end

             elsif item.user_event?

               link_to(item.actor, item.actor) + " " +
                 if item.kind_of? FilteredEvent
                   item.events.map { |(k,v)| user_action(k, v) }.to_sentence.html_safe
                 else
                   user_action(item.event_type, [item])
                 end

             else

               case item.event_type

               when "updated_task_view" then
                 link_to(item.subject, item.subject) + " was " + action("updated") +
                   " to version #{item.cached_value}"
               end

             end

    output = "performed an unkown action" if output.blank?

    output += " (#{time_ago_in_words(item.created_at)} ago)" if display_time_ago
    content_tag(:li, output) if li
  end

end


text:
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Security;
using System.Security.Permissions;

namespace MS.Internal.Ink
{
    internal class ISFClipboardData : ClipboardData
    {
        //-------------------------------------------------------------------------------
        //
        // Constructors
        //
        //-------------------------------------------------------------------------------

        #region Constructors

        // The default constructor
        internal ISFClipboardData() { }

        // The constructor which takes StrokeCollection argument
        internal ISFClipboardData(StrokeCollection strokes)
        {
            _strokes = strokes;
        }

        // Checks if the data can be pasted.
        internal override bool CanPaste(IDataObject dataObject)
        {
            return dataObject.GetDataPresent(StrokeCollection.InkSerializedFormat, false);
        }

        #endregion Constructors

        //-------------------------------------------------------------------------------
        //
        // Protected Methods
        //
        //-------------------------------------------------------------------------------

        #region Protected Methods

        // Checks if there is stroke data in this instance
        protected override bool CanCopy()
        {
            return (Strokes != null && Strokes.Count != 0);
        }

        // Copies the internal strokes to the IDataObject
        /// <SecurityNote>
        ///    Critical: This code asserts to set data on a data object
        /// </SecurityNote>
        [SecurityCritical]
        protected override void DoCopy(IDataObject dataObject)
        {
            // samgeo - Presharp issue
            // Presharp gives a warning when local IDisposable variables are not closed
            // in this case, we can't call Dispose since it will also close the underlying stream
            // which needs to be open for consumers to read
#pragma warning disable 1634, 1691
#pragma warning disable 6518

            // Save the data in the data object.
            MemoryStream stream = new MemoryStream();
            Strokes.Save(stream);
            stream.Position = 0;
            (new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert
            try
            {
                dataObject.SetData(StrokeCollection.InkSerializedFormat, stream);
            }
            finally
            {
                UIPermission.RevertAssert();
            }
#pragma warning restore 6518
#pragma warning restore 1634, 1691
        }

        // Retrieves the stroks from the IDataObject
        protected override void DoPaste(IDataObject dataObject)
        {
            // Check if we have ink data
            MemoryStream stream = dataObject.GetData(StrokeCollection.InkSerializedFormat) as MemoryStream;

            StrokeCollection newStrokes = null;
            bool fSucceeded = false;
            if ( stream != null && stream != Stream.Null )
            {
                try
                {
                    // Now add these ink strokes to the InkCanvas ink collection.
                    newStrokes = new StrokeCollection(stream);
                    fSucceeded = true;
                }
                catch ( ArgumentException )
                {
                    // If an invalid stream was passed in, we should get ArgumentException here.
                    // We catch this specific exception and eat it.
                    fSucceeded = false;
                }
            }

            // Depending on whether we are succeeded or not, we set the correct stroke collection here.
            _strokes = fSucceeded ? newStrokes : new StrokeCollection();
        }

        #endregion Protected Methods

        //-------------------------------------------------------------------------------
        //
        // Internal Properties
        //
        //-------------------------------------------------------------------------------

        #region Internal Properties

        // Gets the strokes
        internal StrokeCollection Strokes
        {
            get
            {
                return _strokes;
            }
        }

        #endregion Internal Properties

        //-------------------------------------------------------------------------------
        //
        // Private Fields
        //
        //-------------------------------------------------------------------------------

        #region Private Fields

        StrokeCollection    _strokes;

        #endregion Private Fields

    }
}


text:
{% extends path+"/scenario_curtailment-v0-5b/_layout-case-simple_clear-assessment-complete.html" %}

{% block citizen_content %}

{{ data.nuggets | log }}

Back

	<form method="post" action="recommendedReviewPeriod">

Step 2 of 2

Starting and finishing tasks

David cannot plan, start and finish everyday tasks.

      Relevant statements

{{ taggedstatementDL1 }}

{{ taggedstatementDL2 }}

{{ taggedstatementDL3 }}

{{ taggedstatementDL4 }}

{{ taggedstatementDL5 }}

{{ taggedstatementDL6 }}

{{ taggedstatementDL7 }}

{{ taggedstatementDL8 }}

{{ taggedstatementDL9 }}

{{ taggedstatementDL10 }}

{{ taggedstatementDL11 }}

{{ taggedstatementDL12 }}

{{ taggedstatementDL13 }}

{{ taggedstatementDL14 }}

{{ taggedstatementDL15 }}

{{ taggedstatementDL16 }}

{{ taggedstatementDL17 }}

{{ taggedstatementDL18 }}

			Write your justification.
			<textarea class="form-control form-control-3-4" name="justificationStatement" id="justificationStatement" rows="8"></textarea>

<input type="submit" class="button" value="Save and continue" id="submitButton">

		</form>

{% endblock %}


text:
div.export-container {
  width: 48%;
  float: left;
  padding: .5em;
}

div.export-container table {
  width: 100%;
}

div.export-container table input,
div.export-container table th,
div.export-container table td {
  padding: 0 0 0 .5em;
  margin: 0;
}