text:
/* global describe, it */
const { PassThrough } = require('stream')
const { strictEqual, deepEqual } = require('assert')
const irc = require('slate-irc')
const twitch = require('../src/twitch')

describe('Moderators', function () {
  describe('mod', () => {
    it('sends a .mod privmsg to Twitch', done => {
      let stream = PassThrough()
      let client = irc(stream)
      client.use(twitch())

      stream.on('data', line => {
        strictEqual(line, 'PRIVMSG #channel :.mod helpful_user\r\n')
        done()
      })

      client.mod('#channel', 'helpful_user')
    })
  })

  describe('unmod', () => {
    it('sends a .unmod privmsg to Twitch', done => {
      let stream = PassThrough()
      let client = irc(stream)
      client.use(twitch())

      stream.on('data', line => {
        strictEqual(line, 'PRIVMSG #channel :.unmod awol_mod\r\n')
        done()
      })

      client.unmod('#channel', 'awol_mod')
    })
  })

  describe('mods', () => {
    it('sends a .mods privmsg to Twitch', done => {
      let stream = PassThrough()
      let client = irc(stream)
      client.use(twitch())

      stream.on('data', line => {
        strictEqual(line, 'PRIVMSG #channel :.mods\r\n')
        done()
      })

      client.mods('#channel')
    })

    it('emits a "mods" event when Twitch replies', done => {
      let stream = PassThrough()
      let client = irc(stream)
      client.use(twitch({ tags: false }))

      client.on('mods', mods => {
        deepEqual(mods, [ 'me', 'myself', 'i' ])
        done()
      })

      stream.on('data', line => {
        if (line === 'PRIVMSG #channel :.mods\r\n') {
          stream.write(':tmi.twitch.tv NOTICE #channel ' +
                       ':The moderators of this room are: me, myself, i\r\n')
        }
      })

      client.mods('#channel')
    })
  })
})


text:
using System;
using Cuyahoga.Core.Domain;

namespace Cuyahoga.Core.Service.Content
{
	/// <summary>
	/// Decorator for IContentItemService that adds auditing (created and modified by etc.) to content items.
	/// </summary>
	/// <remarks>
	/// We might have to merge this one with the versioningdecorator.
	/// </remarks>
	/// <typeparam name="T"></typeparam>
	public class AuditContentDecorator<T> : AbstractContentItemServiceDecorator<T> where T : IContentItem
	{
		private readonly ICuyahogaContextProvider _cuyahogaContextProvider;

		public AuditContentDecorator(IContentItemService<T> contentItemService, ICuyahogaContextProvider cuyahogaContextProvider) : base(contentItemService)
		{
			this._cuyahogaContextProvider = cuyahogaContextProvider;
		}

		/// <summary>
		/// Add 'who did what and when' while saving the content item to the database.
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public override T Save(T entity)
		{
			ICuyahogaContext cuyahogaContext = this._cuyahogaContextProvider.GetContext();
			if (entity.IsNew)
			{
				entity.CreatedAt = DateTime.Now;
				entity.CreatedBy = cuyahogaContext.CurrentUser;
			}
			entity.ModifiedAt = DateTime.Now;
			entity.ModifiedBy = cuyahogaContext.CurrentUser;
			return base.Save(entity);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package javax.swing;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleSelection;
import javax.accessibility.AccessibleStateSet;
import javax.swing.plaf.MenuBarUI;

import javax.swing.border.Border;

/**
 * JMenuBar is a container for menu's. For a menu bar to be seen on the
 * screen, at least one menu should be added to it. Just like adding
 * components to container, one can use add() to add menu's to the menu bar.
 * Menu's will be displayed in the menu  bar in the order they were added.
 * The JMenuBar uses selectionModel to keep track of selected menu index.
 * JMenuBar's selectionModel will fire ChangeEvents to its registered
 * listeners when the selected index changes.
 */
public class JMenuBar extends JComponent implements Accessible, MenuElement
{
  /**
   * Provides accessibility support for JMenuBar.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  protected class AccessibleJMenuBar extends AccessibleJComponent
    implements AccessibleSelection
  {

    /**
     * Returns the number of selected items in the menu bar. Possible values
     * are 0 if nothing is selected, or 1 if one
     * item is selected.
     *
     * @return the number of selected items in the menu bar
     */
    public int getAccessibleSelectionCount()
    {
      int count = 0;
      if (getSelectionModel().getSelectedIndex() != -1)
        count = 1;
      return count;
    }

    /**
     * Returns the selected with index i menu, or
     * null if the specified menu is not selected.
     *
     * @param i the index of the menu to return
     *
     * @return the selected with index i menu, or
     *         null if the specified menu is not selected
     */
    public Accessible getAccessibleSelection(int i)
    {
      if (getSelectionModel().getSelectedIndex() != i)
        return null;
      return getMenu(i);
    }

    /**
     * Returns true if the specified menu is selected,
     * false otherwise.
     *
     * @param i the index of the menu to check
     *
     *@return true if the specified menu is selected,
     *        false otherwise
     */
    public boolean isAccessibleChildSelected(int i)
    {
      return getSelectionModel().getSelectedIndex() == i;
    }

    /**
     * Selects the menu with index i. If another menu is already
     * selected, this will be deselected.
     *
     * @param i the menu to be selected
     */
    public void addAccessibleSelection(int i)
    {
      getSelectionModel().setSelectedIndex(i);
    }

    /**
     * Deselects the menu with index i.
     *
     * @param i the menu index to be deselected
     */
    public void removeAccessibleSelection(int i)
    {
      if (getSelectionModel().getSelectedIndex() == i)
        getSelectionModel().clearSelection();
    }

    /**
     * Deselects all possibly selected menus.
     */
    public void clearAccessibleSelection()
    {
      getSelectionModel().clearSelection();
    }

    /**
     * In menu bars it is not possible to select all items, so this method
     * does nothing.
     */
    public void selectAllAccessibleSelection()
    {
      // In menu bars it is not possible to select all items, so this method
      // does nothing.
    }

    /**
     * Returns the accessible role of JMenuBar, which is
     * {@link AccessibleRole#MENU_BAR}.
     *
     * @return the accessible role of JMenuBar, which is
     *         {@link AccessibleRole#MENU_BAR}
     */
    public AccessibleRole getAccessibleRole()
    {
      return AccessibleRole.MENU_BAR;
    }

    /**
     * Returns the AccessibleSelection for this object. This
     * method returns this, since the
     * AccessibleJMenuBar manages its selection itself.
     *
     * @return the AccessibleSelection for this object
     */
    public AccessibleSelection getAccessibleSelection()
    {
      return this;
    }

    /**
     * Returns the state of this AccessibleJMenuBar.
     *
     * @return the state of this AccessibleJMenuBar.
     */
    public AccessibleStateSet getAccessibleStateSet()
    {
      AccessibleStateSet stateSet = super.getAccessibleStateSet();
      // TODO: Figure out what state must be added to the super state set.
      return stateSet;
    }
  }

  private static final long serialVersionUID = -8191026883931977036L;

  /** JMenuBar's model. It keeps track of selected menu's index */
  private transient SingleSelectionModel selectionModel;

  /* borderPainted property indicating if the menuBar's border will be painted*/
  private boolean borderPainted;

  /* margin between menu bar's border and its menues*/
  private Insets margin;

  /**
   * Creates a new JMenuBar object.
   */
  public JMenuBar()
  {
    selectionModel = new DefaultSingleSelectionModel();
    borderPainted = true;
    updateUI();
  }

  /**
   * Adds menu to the menu bar
   *
   * @param c menu to add
   *
   * @return reference to the added menu
   */
  public JMenu add(JMenu c)
  {
    c.setAlignmentX(Component.LEFT_ALIGNMENT);
    super.add(c);
    return c;
  }

  /**
   * This method overrides addNotify() in the Container to register
   * this menu bar with the current keyboard manager.
   */
  public void addNotify()
  {
    super.addNotify();
    KeyboardManager.getManager().registerJMenuBar(this);
  }

  public AccessibleContext getAccessibleContext()
  {
    if (accessibleContext == null)
      accessibleContext = new AccessibleJMenuBar();
    return accessibleContext;
  }

  /**
   * Returns reference to this menu bar
   *
   * @return reference to this menu bar
   */
  public Component getComponent()
  {
    return this;
  }

  /**
   * Returns component at the specified index.
   *
   * @param i index of the component to get
   *
   * @return component at the specified index. Null is returned if
   * component at the specified index doesn't exist.
   * @deprecated Replaced by getComponent(int)
   */
  public Component getComponentAtIndex(int i)
  {
    return getComponent(i);
  }

  /**
   * Returns index of the specified component
   *
   * @param c Component to search for
   *
   * @return index of the specified component. -1 is returned if
   * specified component doesnt' exist in the menu bar.
   */
  public int getComponentIndex(Component c)
  {
    Component[] comps = getComponents();

    int index = -1;

    for (int i = 0; i < comps.length; i++)
      {
	if (comps[i].equals(c))
	  {
	    index = i;
	    break;
	  }
      }

    return index;
  }

  /**
   * DOCUMENT ME!
   *
   * @return DOCUMENT ME!
   */
  public JMenu getHelpMenu()
  {
    return null;
  }

  /**
   * Returns margin betweeen menu bar's border and its menues
   *
   * @return margin between menu bar's border and its menues
   */
  public Insets getMargin()
  {
    if (margin == null)
      return new Insets(0, 0, 0, 0);
    else
      return margin;
  }

  /**
   * Return menu at the specified index. If component at the
   * specified index is not a menu, then null is returned.
   *
   * @param index index to look for the menu
   *
   * @return menu at specified index, or null if menu doesn't exist
   * at the specified index.
   */
  public JMenu getMenu(int index)
  {
    if (getComponentAtIndex(index) instanceof JMenu)
      return (JMenu) getComponentAtIndex(index);
    else
      return null;
  }

  /**
   * Returns number of menu's in this menu bar
   *
   * @return number of menu's in this menu bar
   */
  public int getMenuCount()
  {
    return getComponentCount();
  }

  /**
   * Returns selection model for this menu bar. SelectionModel
   * keeps track of the selected menu in the menu bar. Whenever
   * selected property of selectionModel changes, the ChangeEvent
   * will be fired its ChangeListeners.
   *
   * @return selection model for this menu bar.
   */
  public SingleSelectionModel getSelectionModel()
  {
    return selectionModel;
  }

  /**
   * Method of MenuElement interface. It returns subcomponents
   * of the menu bar, which are all the menues that it contains.
   *
   * @return MenuElement[] array containing menues in this menu bar
   */
  public MenuElement[] getSubElements()
  {
    MenuElement[] subElements = new MenuElement[getComponentCount()];

    int j = 0;
    boolean doResize = false;
    MenuElement menu;
    for (int i = 0; i < getComponentCount(); i++)
      {
        menu = getMenu(i);
        if (menu != null)
          {
            subElements[j++] = (MenuElement) menu;
          }
        else
          doResize = true;
      }

    if (! doResize)
      return subElements;
    else
      {
        MenuElement[] subElements2 = new MenuElement[j];
        for (int i = 0; i < j; i++)
          subElements2[i] = subElements[i];

        return subElements2;
      }
  }

  /**
    * Set the "UI" property of the menu bar, which is a look and feel class
    * responsible for handling the menuBar's input events and painting it.
    *
    * @return The current "UI" property
    */
  public MenuBarUI getUI()
  {
    return (MenuBarUI) ui;
  }

  /**
   * This method returns a name to identify which look and feel class will be
   * the UI delegate for the menu bar.
   *
   * @return The Look and Feel classID. "MenuBarUI"
   */
  public String getUIClassID()
  {
    return "MenuBarUI";
  }

  /**
   * Returns true if menu bar paints its border and false otherwise
   *
   * @return true if menu bar paints its border and false otherwise
   */
  public boolean isBorderPainted()
  {
    return borderPainted;
  }

  /**
   * Returns true if some menu in menu bar is selected.
   *
   * @return true if some menu in menu bar is selected and false otherwise
   */
  public boolean isSelected()
  {
    return selectionModel.isSelected();
  }

  /**
   * This method does nothing by default. This method is need for the
   * MenuElement interface to be implemented.
   *
   * @param isIncluded true if menuBar is included in the selection
   * and false otherwise
   */
  public void menuSelectionChanged(boolean isIncluded)
  {
    // Do nothing - needed for implementation of MenuElement interface
  }

  /**
   * Paints border of the menu bar, if its borderPainted property is set to
   * true.
   *
   * @param g The graphics context with which to paint the border
   */
  protected void paintBorder(Graphics g)
  {
    if (borderPainted)
      {
        Border border = getBorder();
        if (border != null)
          getBorder().paintBorder(this, g, 0, 0, getSize(null).width,
                                  getSize(null).height);
      }
  }

  /**
   * A string that describes this JMenuBar. Normally only used
   * for debugging.
   *
   * @return A string describing this JMenuBar
   */
  protected String paramString()
  {
    StringBuffer sb = new StringBuffer();
    sb.append(super.paramString());
    sb.append(",margin=");
    if (getMargin() != null)
      sb.append(getMargin());
    sb.append(",paintBorder=").append(isBorderPainted());
    return sb.toString();
  }

  /**
   * Process key events forwarded from MenuSelectionManager. This method
   * doesn't do anything. It is here to conform to the MenuElement interface.
   *
   * @param e event forwarded from MenuSelectionManager
   * @param path path to the menu element from which event was generated
   * @param manager MenuSelectionManager for the current menu hierarchy
   *
   */
  public void processKeyEvent(KeyEvent e, MenuElement[] path,
                              MenuSelectionManager manager)
  {
    // Do nothing - needed for implementation of MenuElement interface
  }

  /**
   * This method overrides JComponent.processKeyBinding to allow the
   * JMenuBar to check all the child components (recursiveley) to see
   * if they'll consume the event.
   *
   * @param ks the KeyStroke for the event
   * @param e the KeyEvent for the event
   * @param condition the focus condition for the binding
   * @param pressed true if the key is pressed
   */
  protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition,
                                      boolean pressed)
  {
    // See if the regular JComponent behavior consumes the event
    if (super.processKeyBinding(ks, e, condition, pressed))
      return true;

    // If not, have to recursively check all the child menu elements to see
    // if they want it
    MenuElement[] children = getSubElements();
    for (int i = 0; i < children.length; i++)
      if (processKeyBindingHelper(children[i], ks, e, condition, pressed))
        return true;
    return false;
  }

  /**
   * This is a helper method to recursively check the children of this
   * JMenuBar to see if they will consume a key event via key bindings.
   * This is used for menu accelerators.
   * @param menuElement the menuElement to check (and check all its children)
   * @param ks the KeyStroke for the event
   * @param e the KeyEvent that may be consumed
   * @param condition the focus condition for the binding
   * @param pressed true if the key was pressed
   * @return true menuElement or one of its children consume
   * the event (processKeyBinding returns true for menuElement or one of
   * its children).
   */
  static boolean processKeyBindingHelper(MenuElement menuElement, KeyStroke ks,
                                         KeyEvent e, int condition,
                                         boolean pressed)
  {
    if (menuElement == null)
      return false;

    // First check the menuElement itself, if it's a JComponent
    if (menuElement instanceof JComponent
        && ((JComponent) menuElement).processKeyBinding(ks, e, condition,
                                                        pressed))
      return true;

    // If that didn't consume it, check all the children recursively
    MenuElement[] children = menuElement.getSubElements();
    for (int i = 0; i < children.length; i++)
      if (processKeyBindingHelper(children[i], ks, e, condition, pressed))
        return true;
    return false;
  }

  /**
   * Process mouse events forwarded from MenuSelectionManager. This method
   * doesn't do anything. It is here to conform to the MenuElement interface.
   *
   * @param event event forwarded from MenuSelectionManager
   * @param path path to the menu element from which event was generated
   * @param manager MenuSelectionManager for the current menu hierarchy
   *
   */
  public void processMouseEvent(MouseEvent event, MenuElement[] path,
                                MenuSelectionManager manager)
  {
    // Do nothing - needed for implementation of MenuElement interface
  }

  /**
   * This method overrides removeNotify() in the Container to
   * unregister this menu bar from the current keyboard manager.
   */
  public void removeNotify()
  {
    KeyboardManager.getManager().unregisterJMenuBar(this);
    super.removeNotify();
  }

  /**
   * Sets painting status of the border. If 'b' is true then menu bar's
   * border will be painted, and it will not be painted otherwise.
   *
   * @param b indicates if menu bar's border should be painted.
   */
  public void setBorderPainted(boolean b)
  {
    if (b != borderPainted)
      {
	boolean old = borderPainted;
	borderPainted = b;
	firePropertyChange("borderPainted", old, b);
	revalidate();
	repaint();
      }
  }

  /**
   * Sets help menu for this menu bar
   *
   * @param menu help menu
   *
   * @specnote The specification states that this method is not yet implemented
   *           and should throw an exception.
   */
  public void setHelpMenu(JMenu menu)
  {
    // We throw an Error here, just as Sun's JDK does.
    throw new Error("setHelpMenu() not yet implemented.");
  }

  /**
   * Sets the menu bar's "margin" bound property,  which represents
   * distance between the menubar's border and its menus.
   * icon. When marging property is modified, PropertyChangeEvent will
   * be fired to menuBar's PropertyChangeListener's.
   *
   * @param m distance between the menubar's border and its menus.
   *
   */
  public void setMargin(Insets m)
  {
    if (m != margin)
      {
	Insets oldMargin = margin;
	margin = m;
	firePropertyChange("margin", oldMargin, margin);
      }
  }

  /**
   * Changes menu bar's selection to the specified menu.
   * This method updates selected index of menu bar's selection model,
   * which results in a model firing change event.
   *
   * @param sel menu to select
   */
  public void setSelected(Component sel)
  {
    int index = getComponentIndex(sel);
    selectionModel.setSelectedIndex(index);
  }

  /**
   * Sets menuBar's selection model to the one specified
   *
   * @param model SingleSelectionModel that needs to be set for this menu bar
   */
  public void setSelectionModel(SingleSelectionModel model)
  {
    if (selectionModel != model)
      {
	SingleSelectionModel oldModel = selectionModel;
	selectionModel = model;
	firePropertyChange("model", oldModel, selectionModel);
      }
  }

  /**
   * Set the "UI" property of the menu bar, which is a look and feel class
   * responsible for handling menuBar's input events and painting it.
   *
   * @param ui The new "UI" property
   */
  public void setUI(MenuBarUI ui)
  {
    super.setUI(ui);
  }

  /**
   * Set the "UI" property to a class constructed, via the {@link
   * UIManager}, from the current look and feel.
   */
  public void updateUI()
  {
    setUI((MenuBarUI) UIManager.getUI(this));
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.uff.ic.oceano.core.tools.metrics.extractors.java;

import br.uff.ic.oceano.core.tools.metrics.MetricException;
import br.uff.ic.oceano.core.model.MetricValue;
import br.uff.ic.oceano.core.model.Revision;
import br.uff.ic.oceano.core.tools.metrics.extractors.AbstractMetricExtractor;
import br.uff.ic.oceano.core.tools.metrics.util.ClassLoaderUtil;
import java.util.HashSet;
import java.util.Set;
import org.aspectj.apache.bcel.classfile.ClassFormatException;

/**
 *
 * @author wallace
 */
public class CohesionAmongMethodsInClassExtractorJava extends AbstractMetricExtractor {

    public CohesionAmongMethodsInClassExtractorJava() {
    }

    public MetricValue extractMetric(Revision revision) throws MetricException {
        return extractMetricWithMetricService(revision);
    }

    public MetricValue extractMetric(Revision revision, String path) throws MetricException {

        try {
            Class clazz = ClassLoaderUtil.loadClass(revision,path);
            java.lang.reflect.Method[] methods = clazz.getDeclaredMethods();

            Set totalUniqueTypes = new HashSet();
            Set uniqueParameterTypes = new HashSet();
            int sum = 0;
            for (int i = 0; i < methods.length; i++) {
                Class[] parameters = methods[i].getParameterTypes();
                for (int j = 0; j < parameters.length; j++) {
                    totalUniqueTypes.add(parameters[j].getName());
                    uniqueParameterTypes.add(parameters[j].getName());
                }
                //count only unique types
                sum += uniqueParameterTypes.size();
                uniqueParameterTypes.clear();
            }

            double aux2 = methods.length * totalUniqueTypes.size();
            double cam = 0;
            if (aux2 != 0) {
                cam = sum / aux2;
            } else {
                cam = Double.NaN;
            }
            return createMetricValue(revision, cam);

        } catch (ClassFormatException ex) {
            throw new MetricException(ex);
        } catch (Exception ex) {
            throw new MetricException(ex);
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<TITLE></TITLE>

	<form data-dojo-type="dijit.form.Form">

				资源名称:
				<input id="internal_sys_resource_SearchForm_resourcenameText" name="resourcename" data-dojo-type="dijit.form.ValidationTextBox" maxlength="100" />

				<input id="internal_sys_resource_SearchForm_searchallChk" name="searchall" data-dojo-type="dijit.form.CheckBox"/>查询全部子级
				<button dojoType="dijit.form.Button" label="查询"></button>

	</form>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace Gallery.Common.Web
{
    public class CachedTrace
    {
        public string CallStack { get; private set; }
        public DateTime DateTime { get; private set; }
        public Stack LogicalOperationStack { get; private set; }
        public int ProcessId { get; private set; }
        public string ThreadId { get; private set; }
        public long Timestamp { get; private set; }
        public string Source { get; private set; }
        public TraceEventType EventType { get; private set; }
        public int Id { get; private set; }
        public string Message { get; private set; }
        public string Format { get; private set; }
        public object[] Args { get; private set; }

        public CachedTrace(TraceEventCache eventCache, string source, TraceEventType eventType, int id)
        {
            CallStack = eventCache.Callstack;
            DateTime = eventCache.DateTime;
            LogicalOperationStack = eventCache.LogicalOperationStack;
            ProcessId = eventCache.ProcessId;
            ThreadId = eventCache.ThreadId;
            Timestamp = eventCache.Timestamp;
            Source = source;
            EventType = eventType;
            Id = id;
        }

        public CachedTrace(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
            : this(eventCache, source, eventType, id)
        {
            Message = message;
        }

        public CachedTrace(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
            : this(eventCache, source, eventType, id)
        {
            Format = format;
            Args = args;
        }
    }
}


text: Basic sever for web-app, write in javascript for node and mongo


text:
// Wrap an existing disposable (which may not already have been once()d)
// so that it will only dispose its underlying resource at most once.
export const disposeOnce = disposable =>
  new DisposeOnce(disposable)

class DisposeOnce {
  constructor (disposable) {
    this.disposed = false
    this.disposable = disposable
  }

  dispose () {
    if (!this.disposed) {
      this.disposed = true
      this.disposable.dispose()
      this.disposable = undefined
    }
  }
}


text:
use warnings;
use strict;
use FindBin qw($RealBin);
use Getopt::Long;

my $order = 3; # order of language model (default trigram)
my $corpusPath; # input text data
my $lmPath; # generated language model
my $cores = 2; # number of CPUs used
my $irstPath; # bin directory of IRSTLM
my $tempPath = "tmp"; # temp dir
my $pruneSingletons = 1; # 1 = prune singletons, 0 = keep singletons
my $smoothing = "msb"; # smoothing method: wb = witten-bell, sb = kneser-ney, msb = modified-kneser-ney
my $dummy;

GetOptions("order=s"  => \$order,
           "text=s"   => \$corpusPath,
           "lm=s"     => \$lmPath,
           "cores=s"  => \$cores,
           "irst-dir=s"  => \$irstPath,
           "temp-dir=s"  => \$tempPath,
           "p=i" => \$pruneSingletons,   # irstlm parameter: prune singletons
           "s=s" => \$smoothing, # irstlm parameter: smoothing method
	   "interpolate!" => \$dummy,  #ignore
	   "kndiscount!" => \$dummy    #ignore
	   ) or exit 1;

#die("ERROR: please set order") unless defined($order);
die("ERROR: please set text") unless defined($corpusPath);
die("ERROR: please set lm") unless defined($lmPath);
die("ERROR: please set irst-dir") unless defined($irstPath);

$tempPath .= "/irstlm-build-tmp.$$";
`mkdir -p $tempPath`;

# add <s> and </s>
my $cmd = "cat $corpusPath | $irstPath/add-start-end.sh > $tempPath/setagged";
print STDERR "EXECUTING $cmd\n";
`$cmd`;

# collect n-gram counts
$cmd = "$irstPath/ngt -i=$tempPath/setagged -n=$order -b=yes -o=$tempPath/counts";
print STDERR "EXECUTING $cmd\n";
`$cmd`;

# build lm
$cmd = "$irstPath/tlm -o=$lmPath -lm=$smoothing -bo=yes -n=$order -tr=$tempPath/counts";
$cmd .= " -ps=no" unless $pruneSingletons;
print STDERR "EXECUTING $cmd\n";
`$cmd`;

$cmd = "rm -rf $tempPath";
print STDERR "EXECUTING $cmd\n";
`$cmd`;

print STDERR "FINISH.\n";


text:
package com.github.iprodigy.physics.util.abstraction;

@FunctionalInterface
public interface Quantifiable<T extends Number> {
	T getMagnitude();
}


text:
package site.iway.helpers;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ScrollView;

import site.iway.helpers.R;

public class ExtendedScrollView extends ScrollView {

    public ExtendedScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        resolveAttrs(context, attrs);
    }

    public ExtendedScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        resolveAttrs(context, attrs);
    }

    public ExtendedScrollView(Context context) {
        super(context);
        resolveAttrs(context, null);
    }

    private void resolveAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExtendedScrollView);
        mFlingable = a.getBoolean(R.styleable.ExtendedScrollView_flingable, true);
        a.recycle();
    }

    private boolean mFlingable = true;

    public void setFlingable(boolean flingable) {
        mFlingable = flingable;
    }

    public boolean getFlingable() {
        return mFlingable;
    }

    @Override
    public void fling(int velocityY) {
        if (mFlingable) {
            super.fling(velocityY);
        }
    }

    private OnScrollChangedListener mOnScrollChangedListener;

    public void setOnScrollChangedListener(OnScrollChangedListener l) {
        mOnScrollChangedListener = l;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mOnScrollChangedListener != null) {
            mOnScrollChangedListener.onScrollChanged(this, l, t, oldl, oldt);
        }
    }

}


text:
package org.apache.cassandra.db;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;

/**
 * SCHEMA_{KEYSPACES, COLUMNFAMILIES, COLUMNS}_CF are used to store Keyspace/ColumnFamily attributes to make schema
 * load/distribution easy, it replaces old mechanism when local migrations where serialized, stored in system.Migrations
 * and used for schema distribution.
 *
 * SCHEMA_KEYSPACES_CF layout:
 *
 * <key (AsciiType)>
 *   ascii => json_serialized_value
 *   ...
 * </key>
 *
 * Where <key> is a name of keyspace e.g. "ks".
 *
 * SCHEMA_COLUMNFAMILIES_CF layout:
 *
 * <key (AsciiType)>
 *     composite(ascii, ascii) => json_serialized_value
 * </key>
 *
 * Where <key> is a name of keyspace e.g. "ks"., first component of the column name is name of the ColumnFamily, last
 * component is the name of the ColumnFamily attribute.
 *
 * SCHEMA_COLUMNS_CF layout:
 *
 * <key (AsciiType)>
 *     composite(ascii, ascii, ascii) => json_serialized value
 * </key>
 *
 * Where <key> is a name of keyspace e.g. "ks".
 *
 * Column names where made composite to support 3-level nesting which represents following structure:
 * "ColumnFamily name":"column name":"column attribute" => "value"
 *
 * Example of schema (using CLI):
 *
 * schema_keyspaces
 * ----------------
 * RowKey: ks
 *  => (column=durable_writes, value=true, timestamp=1327061028312185000)
 *  => (column=name, value="ks", timestamp=1327061028312185000)
 *  => (column=replication_factor, value=0, timestamp=1327061028312185000)
 *  => (column=strategy_class, value="org.apache.cassandra.locator.NetworkTopologyStrategy", timestamp=1327061028312185000)
 *  => (column=strategy_options, value={"datacenter1":"1"}, timestamp=1327061028312185000)
 *
 * schema_columnfamilies
 * ---------------------
 * RowKey: ks
 *  => (column=cf:bloom_filter_fp_chance, value=0.0, timestamp=1327061105833119000)
 *  => (column=cf:caching, value="NONE", timestamp=1327061105833119000)
 *  => (column=cf:column_type, value="Standard", timestamp=1327061105833119000)
 *  => (column=cf:comment, value="ColumnFamily", timestamp=1327061105833119000)
 *  => (column=cf:default_validation_class, value="org.apache.cassandra.db.marshal.BytesType", timestamp=1327061105833119000)
 *  => (column=cf:gc_grace_seconds, value=864000, timestamp=1327061105833119000)
 *  => (column=cf:id, value=1000, timestamp=1327061105833119000)
 *  => (column=cf:key_alias, value="S0VZ", timestamp=1327061105833119000)
 *  ... part of the output omitted.
 *
 * schema_columns
 * --------------
 * RowKey: ks
 *  => (column=cf:c:index_name, value=null, timestamp=1327061105833119000)
 *  => (column=cf:c:index_options, value=null, timestamp=1327061105833119000)
 *  => (column=cf:c:index_type, value=null, timestamp=1327061105833119000)
 *  => (column=cf:c:name, value="aGVsbG8=", timestamp=1327061105833119000)
 *  => (column=cf:c:validation_class, value="org.apache.cassandra.db.marshal.AsciiType", timestamp=1327061105833119000)
 */
public class DefsTables
{
    private static final Logger logger = LoggerFactory.getLogger(DefsTables.class);

    /**
     * Load keyspace definitions for the system keyspace (system.SCHEMA_KEYSPACES_CF)
     *
     * @return Collection of found keyspace definitions
     */
    public static Collection<KSMetaData> loadFromKeyspace()
    {
        List<Row> serializedSchema = SystemKeyspace.serializedSchema(SystemKeyspace.SCHEMA_KEYSPACES_CF);

        List<KSMetaData> keyspaces = new ArrayList<KSMetaData>(serializedSchema.size());

        for (Row row : serializedSchema)
        {
            if (Schema.invalidSchemaRow(row) || Schema.ignoredSchemaRow(row))
                continue;

            keyspaces.add(KSMetaData.fromSchema(row, serializedColumnFamilies(row.key)));
        }

        return keyspaces;
    }

    public static ByteBuffer searchComposite(String name, boolean start)
    {
        assert name != null;
        ByteBuffer nameBytes = UTF8Type.instance.decompose(name);
        int length = nameBytes.remaining();
        byte[] bytes = new byte[2 + length + 1];
        bytes[0] = (byte)((length >> 8) & 0xFF);
        bytes[1] = (byte)(length & 0xFF);
        ByteBufferUtil.arrayCopy(nameBytes, 0, bytes, 2, length);
        bytes[bytes.length - 1] = (byte)(start ? 0 : 1);
        return ByteBuffer.wrap(bytes);
    }

    private static Row serializedColumnFamilies(DecoratedKey ksNameKey)
    {
        ColumnFamilyStore cfsStore = SystemKeyspace.schemaCFS(SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF);
        return new Row(ksNameKey, cfsStore.getColumnFamily(QueryFilter.getIdentityFilter(ksNameKey,
                                                                                SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF,
                                                                                System.currentTimeMillis())));
    }

    /**
     * Merge remote schema in form of row mutations with local and mutate ks/cf metadata objects
     * (which also involves fs operations on add/drop ks/cf)
     *
     * @param mutations the schema changes to apply
     *
     * @throws ConfigurationException If one of metadata attributes has invalid value
     * @throws IOException If data was corrupted during transportation or failed to apply fs operations
     */
    public static synchronized void mergeSchema(Collection<RowMutation> mutations) throws ConfigurationException, IOException
    {
        // current state of the schema
        Map<DecoratedKey, ColumnFamily> oldKeyspaces = SystemKeyspace.getSchema(SystemKeyspace.SCHEMA_KEYSPACES_CF);
        Map<DecoratedKey, ColumnFamily> oldColumnFamilies = SystemKeyspace.getSchema(SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF);

        for (RowMutation mutation : mutations)
            mutation.apply();

        if (!StorageService.instance.isClientMode())
            flushSchemaCFs();

        // with new data applied
        Map<DecoratedKey, ColumnFamily> newKeyspaces = SystemKeyspace.getSchema(SystemKeyspace.SCHEMA_KEYSPACES_CF);
        Map<DecoratedKey, ColumnFamily> newColumnFamilies = SystemKeyspace.getSchema(SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF);

        Set<String> keyspacesToDrop = mergeKeyspaces(oldKeyspaces, newKeyspaces);
        mergeColumnFamilies(oldColumnFamilies, newColumnFamilies);

        // it is safe to drop a keyspace only when all nested ColumnFamilies where deleted
        for (String keyspaceToDrop : keyspacesToDrop)
            dropKeyspace(keyspaceToDrop);

        Schema.instance.updateVersionAndAnnounce();
    }

    private static Set<String> mergeKeyspaces(Map<DecoratedKey, ColumnFamily> before, Map<DecoratedKey, ColumnFamily> after)
    {
        List<Row> created = new ArrayList<>();
        List<String> altered = new ArrayList<>();
        Set<String> dropped = new HashSet<>();

        /*
         * - we don't care about entriesOnlyOnLeft() or entriesInCommon(), because only the changes are of interest to us
         * - of all entriesOnlyOnRight(), we only care about ones that have live columns; it's possible to have a ColumnFamily
         *   there that only has the top-level deletion, if:
         *      a) a pushed DROP KEYSPACE change for a keyspace hadn't ever made it to this node in the first place
         *      b) a pulled dropped keyspace that got dropped before it could find a way to this node
         * - of entriesDiffering(), we don't care about the scenario where both pre and post-values have zero live columns:
         *   that means that a keyspace had been recreated and dropped, and the recreated keyspace had never found a way
         *   to this node
         */
        MapDifference<DecoratedKey, ColumnFamily> diff = Maps.difference(before, after);

        for (Map.Entry<DecoratedKey, ColumnFamily> entry : diff.entriesOnlyOnRight().entrySet())
            if (entry.getValue().getColumnCount() > 0)
                created.add(new Row(entry.getKey(), entry.getValue()));

        for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering().entrySet())
        {
            String keyspaceName = AsciiType.instance.compose(entry.getKey().key);

            ColumnFamily pre  = entry.getValue().leftValue();
            ColumnFamily post = entry.getValue().rightValue();

            if (pre.getColumnCount() > 0 && post.getColumnCount() > 0)
                altered.add(keyspaceName);
            else if (pre.getColumnCount() > 0)
                dropped.add(keyspaceName);
            else if (post.getColumnCount() > 0) // a (re)created keyspace
                created.add(new Row(entry.getKey(), post));
        }

        for (Row row : created)
            addKeyspace(KSMetaData.fromSchema(row, Collections.<CFMetaData>emptyList()));
        for (String name : altered)
            updateKeyspace(name);
        return dropped;
    }

    // see the comments for mergeKeyspaces()
    private static void mergeColumnFamilies(Map<DecoratedKey, ColumnFamily> before, Map<DecoratedKey, ColumnFamily> after)
    {
        List<CFMetaData> created = new ArrayList<>();
        List<CFMetaData> altered = new ArrayList<>();
        List<CFMetaData> dropped = new ArrayList<>();

        MapDifference<DecoratedKey, ColumnFamily> diff = Maps.difference(before, after);

        for (Map.Entry<DecoratedKey, ColumnFamily> entry : diff.entriesOnlyOnRight().entrySet())
            if (entry.getValue().getColumnCount() > 0)
                created.addAll(KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), entry.getValue())).values());

        for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering().entrySet())
        {
            String keyspaceName = AsciiType.instance.compose(entry.getKey().key);

            ColumnFamily pre  = entry.getValue().leftValue();
            ColumnFamily post = entry.getValue().rightValue();

            if (pre.getColumnCount() > 0 && post.getColumnCount() > 0)
            {
                MapDifference<String, CFMetaData> delta =
                    Maps.difference(Schema.instance.getKSMetaData(keyspaceName).cfMetaData(),
                                    KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), post)));

                dropped.addAll(delta.entriesOnlyOnLeft().values());
                created.addAll(delta.entriesOnlyOnRight().values());
                Iterables.addAll(altered, Iterables.transform(delta.entriesDiffering().values(), new Function<MapDifference.ValueDifference<CFMetaData>, CFMetaData>()
                {
                    public CFMetaData apply(MapDifference.ValueDifference<CFMetaData> pair)
                    {
                        return pair.rightValue();
                    }
                }));
            }
            else if (pre.getColumnCount() > 0)
            {
                dropped.addAll(Schema.instance.getKSMetaData(keyspaceName).cfMetaData().values());
            }
            else if (post.getColumnCount() > 0)
            {
                created.addAll(KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), post)).values());
            }
        }

        for (CFMetaData cfm : created)
            addColumnFamily(cfm);
        for (CFMetaData cfm : altered)
            updateColumnFamily(cfm.ksName, cfm.cfName);
        for (CFMetaData cfm : dropped)
            dropColumnFamily(cfm.ksName, cfm.cfName);
    }

    private static void addKeyspace(KSMetaData ksm)
    {
        assert Schema.instance.getKSMetaData(ksm.name) == null;
        Schema.instance.load(ksm);

        if (!StorageService.instance.isClientMode())
        {
            Keyspace.open(ksm.name);
            MigrationManager.instance.notifyCreateKeyspace(ksm);
        }
    }

    private static void addColumnFamily(CFMetaData cfm)
    {
        assert Schema.instance.getCFMetaData(cfm.ksName, cfm.cfName) == null;
        KSMetaData ksm = Schema.instance.getKSMetaData(cfm.ksName);
        ksm = KSMetaData.cloneWith(ksm, Iterables.concat(ksm.cfMetaData().values(), Collections.singleton(cfm)));

        logger.info("Loading " + cfm);

        Schema.instance.load(cfm);

        // make sure it's init-ed w/ the old definitions first,
        // since we're going to call initCf on the new one manually
        Keyspace.open(cfm.ksName);

        Schema.instance.setKeyspaceDefinition(ksm);

        if (!StorageService.instance.isClientMode())
        {
            Keyspace.open(ksm.name).initCf(cfm.cfId, cfm.cfName, true);
            MigrationManager.instance.notifyCreateColumnFamily(cfm);
        }
    }

    private static void updateKeyspace(String ksName)
    {
        KSMetaData oldKsm = Schema.instance.getKSMetaData(ksName);
        assert oldKsm != null;
        KSMetaData newKsm = KSMetaData.cloneWith(oldKsm.reloadAttributes(), oldKsm.cfMetaData().values());

        Schema.instance.setKeyspaceDefinition(newKsm);

        if (!StorageService.instance.isClientMode())
        {
            Keyspace.open(ksName).createReplicationStrategy(newKsm);
            MigrationManager.instance.notifyUpdateKeyspace(newKsm);
        }
    }

    private static void updateColumnFamily(String ksName, String cfName)
    {
        CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
        assert cfm != null;
        cfm.reload();

        if (!StorageService.instance.isClientMode())
        {
            Keyspace keyspace = Keyspace.open(cfm.ksName);
            keyspace.getColumnFamilyStore(cfm.cfName).reload();
            MigrationManager.instance.notifyUpdateColumnFamily(cfm);
        }
    }

    private static void dropKeyspace(String ksName)
    {
        KSMetaData ksm = Schema.instance.getKSMetaData(ksName);
        String snapshotName = Keyspace.getTimestampedSnapshotName(ksName);

        CompactionManager.instance.interruptCompactionFor(ksm.cfMetaData().values(), true);

        // remove all cfs from the keyspace instance.
        for (CFMetaData cfm : ksm.cfMetaData().values())
        {
            ColumnFamilyStore cfs = Keyspace.open(ksm.name).getColumnFamilyStore(cfm.cfName);

            Schema.instance.purge(cfm);

            if (!StorageService.instance.isClientMode())
            {
                if (DatabaseDescriptor.isAutoSnapshot())
                    cfs.snapshot(snapshotName);
                Keyspace.open(ksm.name).dropCf(cfm.cfId);
            }
        }

        // remove the keyspace from the static instances.
        Keyspace.clear(ksm.name);
        Schema.instance.clearKeyspaceDefinition(ksm);
        if (!StorageService.instance.isClientMode())
        {
            MigrationManager.instance.notifyDropKeyspace(ksm);
        }
    }

    private static void dropColumnFamily(String ksName, String cfName)
    {
        KSMetaData ksm = Schema.instance.getKSMetaData(ksName);
        assert ksm != null;
        ColumnFamilyStore cfs = Keyspace.open(ksName).getColumnFamilyStore(cfName);
        assert cfs != null;

        // reinitialize the keyspace.
        CFMetaData cfm = ksm.cfMetaData().get(cfName);

        Schema.instance.purge(cfm);
        Schema.instance.setKeyspaceDefinition(makeNewKeyspaceDefinition(ksm, cfm));

        CompactionManager.instance.interruptCompactionFor(Arrays.asList(cfm), true);

        if (!StorageService.instance.isClientMode())
        {
            if (DatabaseDescriptor.isAutoSnapshot())
                cfs.snapshot(Keyspace.getTimestampedSnapshotName(cfs.name));
            Keyspace.open(ksm.name).dropCf(cfm.cfId);
            MigrationManager.instance.notifyDropColumnFamily(cfm);
        }
    }

    private static KSMetaData makeNewKeyspaceDefinition(KSMetaData ksm, CFMetaData toExclude)
    {
        // clone ksm but do not include the new def
        List<CFMetaData> newCfs = new ArrayList<CFMetaData>(ksm.cfMetaData().values());
        newCfs.remove(toExclude);
        assert newCfs.size() == ksm.cfMetaData().size() - 1;
        return KSMetaData.cloneWith(ksm, newCfs);
    }

    private static void flushSchemaCFs()
    {
        SystemKeyspace.forceBlockingFlush(SystemKeyspace.SCHEMA_KEYSPACES_CF);
        SystemKeyspace.forceBlockingFlush(SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF);
        SystemKeyspace.forceBlockingFlush(SystemKeyspace.SCHEMA_COLUMNS_CF);
        SystemKeyspace.forceBlockingFlush(SystemKeyspace.SCHEMA_TRIGGERS_CF);
    }
}


text:
<?php
namespace IPLocation\Tools;

/**
 * This class is used to figure out the client's IP.
 */
class IP
{
    /**
	 * An array of server keys where the client's IP may possibly exist.
     * Possible keys are: HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR,
     * HTTP_X_FORWARDED, HTTP_X_CLUSTER_CLIENT_IP, HTTP_FORWARDED_FOR,
     * HTTP_FORWARDED and REMOTE_ADDR.
     * TODO: Figure out the order of most-acurate to least-acurate and which
     * are viable. Order of array must be by viability and accuracy.
	 * @var array
	 */
    private $serverIpKeys = array('REMOTE_ADDR', 'HTTP_CLIENT_IP');

    /**
	 * IP address of the client.
	 * @var string
	 */
    private $ip;

    /**
	 * At object creation, the IP is set.
     * @param string
	 */
    public function __construct($inIp = '')
    {
        $this->setIp($inIp);
    }

    /**
	 * Setting the IP either through a paramater passed in, from the server
     * keys or directly from the chosen API.
     * @param string
     * @return bool
	 */
    public function setIp($inIp = '')
    {
        if ($this->validateIp($inIp)) {
            $this->ip = $inIp;
            return true;
        } elseif ($this->setIpFromServerKeys()) {
            return true;
        }

        $this->ip = '';
        return false;
    }

    /**
	 * Cycles through server keys to find a valid IP and sets one as the IP.
     * Some keys such as HTTP_X_FORWARDED_FOR may have multiple results if
     * multiple proxies are used.
     * @return bool
	 */
    public function setIpFromServerKeys()
    {
        foreach ($this->serverIpKeys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $keyIp) {
                    if ($this->validateIp($keyIp)) {
                        $this->ip = $keyIp;
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
	 * Returns the IP.
     * @return string
	 */
    public function getIp()
    {
        return $this->ip;
    }

    /**
	 * Verifies if the IP is public. Reserved and private ranges aren't allowed.
     * @return bool
	 */
    private function validateIp($inIp)
    {
        if (filter_var($inIp, FILTER_VALIDATE_IP,
                FILTER_FLAG_NO_RES_RANGE |
                FILTER_FLAG_NO_PRIV_RANGE) === false) {
            return false;
        }

        return true;
    }
}


text:
require 'rubygems'
require 'net/http'
require 'uri'
require 'fileutils'
require 'json'
require 'optparse'

##########################################################################
####################### YOU CAN EDIT THIS PART ###########################
##########################################################################

# Put your favorite Reddits here
reddits = ['Pics', 'WTF']

# Desired sorting
sort_type = 'hot' # hot, new, controversial, top

# Folder to save pictures to
dir = 'Saved Reddit Pics'

# Maximum image links to fetch
limit = 20

##########################################################################
#################### DONT EDIT ANYTHING PAST HERE ########################
##########################################################################

# Holds command-line arguments parsed with OptionParser
# Also holds default values pulled from above
options = {
  :limit => limit,
  :output_dir => dir,
  :sort => sort_type,
  :reddits => reddits
}

# Adapted from examples at http://ruby.about.com/od/advancedruby/a/optionparser2.htm
optparse = OptionParser.new do |opts|
  # Syntax is approximately:
  # opts.on(single letter switch, word-length switch, class to typecast to OR a list of acceptable values, help text)
  # When using a class to typecast to, some rudimentary type-checking is put into place and exceptions will be raised
  # but are not particularly descriptive by default, so the output for bad values could be improved significantly.
  # Example:
  # ./reddit_image_save.rb -l abc
  # ./reddit_image_save.rb:61:in `<main>': invalid argument: -l abc (OptionParser::InvalidArgument)

  opts.on( '-l', '--limit LIMIT', Integer, 'Maximum number of images to download') do |limit|
    options[:limit] = limit
  end
  opts.on( '-o', '--output-dir DIR', String, 'Directory to save to') do |dir|
    options[:output_dir] = dir
  end
  opts.on( '-r', '--reddits a,b,c', Array, 'Comma-separated list of subreddits to download from') do |reddits|
    options[:reddits] = reddits
  end
  opts.on( '-s', '--sort SORT', [:hot, :new, :controversial, :top], 'Reddit sort style (choose from: hot, new, controversial, top)') do |sort|
    options[:sort] = sort
  end
  opts.on( '-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end

optparse.parse!

# Generate custom Reddit URL
def generate_custom_url(reddit_list, sort, limit)
  "http://www.reddit.com/r/#{reddit_list.sort.join('+')}/#{sort}.json?limit=#{limit}"
end

custom_url = generate_custom_url(options[:reddits], options[:sort], options[:limit])
puts "Your Personal URL:  #{custom_url.gsub('.json', '')}\n"
puts "--------------------#{print '-' * custom_url.length}"

# Get source of page
def get_page_source(page_url)
  url = URI.parse(page_url)
  req = Net::HTTP::Get.new(url.path)
  Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end
end
res = get_page_source(custom_url)

# Add URLs and Title to hash
urls = {}
doc = JSON.parse(res.body)
doc['data']['children'].each do |link|
  urls[link['data']['title']] = link['data']['url']
end

# Fix ugly imgur URLs
urls.each_pair do |name, url|
  # imgur.com -> i.imgur.com
  if url =~ /^((http:\/\/)|(www))+imgur\.com.*$/
    url.insert(url.index(/(?i)(imgur\.com).*$/), 'i.')

    # i.imgur.com/1234 -> i.imgur.com/1234.jpg
    unless url =~ /^.*\.(?i)((bmp)|(gif)|(jpeg)|(jpg)|(png)|(tiff))$/
      url.concat(".jpg")
    end
  end
end

def is_picture?(file)
  valid = true
  valid = false if file =~ /^.+\.(?i)((bmp)|(gif)|(jpeg)|(jpg)|(png)|(tiff))$/
  valid = true  if file =~ /^.+\.(?i)(php)/
  valid
end

# Remove non-pictures
urls.reject! do |name, url|
  is_picture?(url)
end

# Make directory for pictures
FileUtils.mkdir_p options[:output_dir]

# Follow redirects
def fetch(uri_str, limit = 10)
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0
  response = Net::HTTP.get_response(URI.parse(uri_str))
  case response
  when Net::HTTPSuccess     then response
  when Net::HTTPRedirection then fetch(response['location'], limit - 1)
  else
    response.error!
  end
end

# Make file names safe
def sanitize(s)
  sani = ""
  s.each_byte do |c|
    if (c == 32 || (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122))
      sani += c.chr
    end
  end
  sani.gsub!(' ', '_')
  sani
end

def download_file(url, path)
  response = fetch(url)
  Net::HTTP.start(URI.parse(url).host) do |http|
    ext = url.match(/\.([^\.]+)$/).to_a.last
    open(path, 'w') do |file|
      file.write(response.body)
    end
  end
end

# Download files
urls.each_pair do |name, url|
    puts "Downloading: #{name}\n\t#{url}\n\n"
    ext = url.match(/\.([^\.]+)$/).to_a.last
    unless File.exist?("#{options[:output_dir]}/#{sanitize(name)}.#{ext.downcase}")
      download_file(url, "#{options[:output_dir]}/#{sanitize(name)}.#{ext.downcase}")
    end
end

puts 'Downloading Complete'


text:
* [
      cwRichardKim
      /
      RKNotificationHub
](https://github.com/cwRichardKim/RKNotificationHub):
      Make any UIView a full fledged notification center

* [
      kevinzhow
      /
      PNChart
](https://github.com/kevinzhow/PNChart):
      A simple and beautiful chart lib used in Piner and CoinsMan for iOS

* [
      atljeremy
      /
      JFMinimalNotifications
](https://github.com/atljeremy/JFMinimalNotifications):
      An iOS UIView for presenting a minimalistic notification that doesn't block the UI and is highly configurable.

* [
      rsms
      /
      peertalk
](https://github.com/rsms/peertalk):
      iOS and Mac Cocoa library for communicating over USB

* [
      rickytan
      /
      RTImageAssets
](https://github.com/rickytan/RTImageAssets):
      A Xcode plugin to automatically generate @2x, @1x image from @3x image for you, or upscale to @3x from @2x

* [
      uranusjr
      /
      macdown
](https://github.com/uranusjr/macdown):
      Open source Markdown editor for OS X.

* [
      ReactiveCocoa
      /
      ReactiveCocoa
](https://github.com/ReactiveCocoa/ReactiveCocoa):
      A framework for composing and transforming streams of values

* [
      cwRichardKim
      /
      RKDropdownAlert
](https://github.com/cwRichardKim/RKDropdownAlert):
      iOS / Objective C: an extremely simple UIAlertView alternative

* [
      hackiftekhar
      /
      IQKeyboardManager
](https://github.com/hackiftekhar/IQKeyboardManager):
      IQKeyboardManager is a drop-in universal library which allows you to prevent issues of the keyboard sliding up and covering UITextField/UITextView without needing you to writing any code and much more.

* [
      omergul123
      /
      LLSimpleCamera
](https://github.com/omergul123/LLSimpleCamera):
      A simple, customizable camera control for iOS.

* [
      magicalpanda
      /
      MagicalRecord
](https://github.com/magicalpanda/MagicalRecord):
      Super Awesome Easy Fetching for Core Data 1!!!11!!!!1!

* [
      facebook
      /
      AsyncDisplayKit
](https://github.com/facebook/AsyncDisplayKit):
      Smooth asynchronous user interfaces for iOS apps.

* [
      FabrizioBrancati
      /
      BFKit
](https://github.com/FabrizioBrancati/BFKit):
      BFKit is a collection of useful classes to develop Apps faster

* [
      sibahota059
      /
      SPHChatCollectionView
](https://github.com/sibahota059/SPHChatCollectionView):
      SPHChatCollectionView to use in chat screens. (Supports iOS 8)

* [
      wikimedia
      /
      WikipediaMobile
](https://github.com/wikimedia/WikipediaMobile):
      Wikipedia on Mobile (PhoneGap)

* [
      cbpowell
      /
      MarqueeLabel
](https://github.com/cbpowell/MarqueeLabel):
      A drop-in replacement for UILabel, which automatically adds a scrolling marquee effect when the label's text will not fit inside the specified frame.

* [
      owncloud
      /
      ios
](https://github.com/owncloud/ios):
      the issues tracker for the iOS app

* [
      spritebuilder
      /
      SpriteBuilder
](https://github.com/spritebuilder/SpriteBuilder):
      Objective-C Game Development Suite

* [
      li6185377
      /
      LKDBHelper-SQLite-ORM
](https://github.com/li6185377/LKDBHelper-SQLite-ORM):
      数据库的全自动操作,支持 列->实体属性 映射,NSArray,NSDictionary,Object... ALL Supported,Automatic Operation ...

* [
      AFNetworking
      /
      AFNetworking
](https://github.com/AFNetworking/AFNetworking):
      A delightful iOS and OS X networking framework

* [
      BradLarson
      /
      GPUImage
](https://github.com/BradLarson/GPUImage):
      An open source iOS framework for GPU-based image and video processing

* [
      facebookarchive
      /
      three20
](https://github.com/facebookarchive/three20):
      Three20 is an Objective-C library for iPhone developers

* [
      RestKit
      /
      RestKit
](https://github.com/RestKit/RestKit):
      RestKit is a framework for consuming and modeling RESTful web resources on iOS and OS X

* [
      rs
      /
      SDWebImage
](https://github.com/rs/SDWebImage):
      Asynchronous image downloader with cache support with an UIImageView category

* [
      jdg
      /
      MBProgressHUD
](https://github.com/jdg/MBProgressHUD):
      MBProgressHUD + Customizations

####go
* [
      dockerboard
      /
      dockerboard
](https://github.com/dockerboard/dockerboard):
      [WIP]Simple dashboards, visualizations, managements for your dockers.

* [
      golang
      /
      go
](https://github.com/golang/go):
      The Go programming language

* [
      docker
      /
      docker
](https://github.com/docker/docker):
      Docker - the open-source application container engine

* [
      johnwilson
      /
      bytengine
](https://github.com/johnwilson/bytengine):
      content management server

* [
      influxdb
      /
      influxdb
](https://github.com/influxdb/influxdb):
      Scalable datastore for metrics, events, and real-time analytics

* [
      astaxie
      /
      build-web-application-with-golang
](https://github.com/astaxie/build-web-application-with-golang):
      A golang ebook intro how to build a web with golang

* [
      spf13
      /
      hugo
](https://github.com/spf13/hugo):
      A Fast and Flexible Static Site Generator built with love by spf13 in GoLang

* [
      chrislusf
      /
      weed-fs
](https://github.com/chrislusf/weed-fs):
      Seaweed-FS is a simple and highly scalable distributed file system. There are two objectives: to store billions of files! to serve the files fast! Instead of supporting full POSIX file system semantics, Seaweed-FS choose to implement only a key~file mapping. Similar to the word "NoSQL", you can call it as "NoFS".

* [
      GoogleCloudPlatform
      /
      kubernetes
](https://github.com/GoogleCloudPlatform/kubernetes):
      Container Cluster Manager

* [
      robbiev
      /
      devdns
](https://github.com/robbiev/devdns):
      DNS server that replies the same address ("127.0.0.1" by default) to all type A queries

* [
      gin-gonic
      /
      gin
](https://github.com/gin-gonic/gin):
      Gin is a web framework written in Golang. It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

* [
      coreos
      /
      rocket
](https://github.com/coreos/rocket):
      App Container runtime

* [
      go-martini
      /
      martini
](https://github.com/go-martini/martini):
      Classy web framework for Go

* [
      gogits
      /
      gogs
](https://github.com/gogits/gogs):
      Gogs(Go Git Service) is a painless self-hosted Git Service written in Go.

* [
      google
      /
      cayley
](https://github.com/google/cayley):
      An open-source graph database

* [
      andres-erbsen
      /
      dename
](https://github.com/andres-erbsen/dename):
      NameCoin-style names using consensus instead of proof of work

* [
      wandoulabs
      /
      codis
](https://github.com/wandoulabs/codis):
      redis cluster powered by go

* [
      coreos
      /
      etcd
](https://github.com/coreos/etcd):
      A highly-available key value store for shared configuration and service discovery

* [
      xeipuuv
      /
      gojsonschema
](https://github.com/xeipuuv/gojsonschema):
      An implementation of JSON Schema, draft v4 - Go language

* [
      shipyard
      /
      shipyard
](https://github.com/shipyard/shipyard):
      Composable Docker Management

* [
      golang
      /
      gddo
](https://github.com/golang/gddo):
      Go Doc Dot Org

* [
      limetext
      /
      lime
](https://github.com/limetext/lime):
      Open source API-compatible alternative to Sublime Text

* [
      syncthing
      /
      syncthing
](https://github.com/syncthing/syncthing):
      Open Source Continuous File Synchronization

* [
      github
      /
      hub
](https://github.com/github/hub):
      hub helps you win at git.

* [
      revel
      /
      revel
](https://github.com/revel/revel):
      A high productivity, full-stack web framework for the Go language.

####javascript
* [
      cachethq
      /
      Cachet
](https://github.com/cachethq/Cachet):
      Cachet, the open source StatusPage.io alternative written in PHP

* [
      gorhill
      /
      uBlock
](https://github.com/gorhill/uBlock):
      µBlock - An efficient blocker for Chromium-based browsers. Fast and lean.

* [
      auchenberg
      /
      chrome-devtools-app
](https://github.com/auchenberg/chrome-devtools-app):
      Chrome DevTools packaged as an app via node-webkit

* [
      alvarotrigo
      /
      fullPage.js
](https://github.com/alvarotrigo/fullPage.js):
      fullPage plugin by Alvaro Trigo. Create full screen pages fast and simple

* [
      angular
      /
      angular.js
](https://github.com/angular/angular.js):
      HTML enhanced for web apps

* [
      staltz
      /
      cycle
](https://github.com/staltz/cycle):
      An honestly reactive web frontend framework

* [
      STRML
      /
      react-grid-layout
](https://github.com/STRML/react-grid-layout):
      A draggable and resizable grid layout with responsive breakpoints, for React.

* [
      Semantic-Org
      /
      Semantic-UI
](https://github.com/Semantic-Org/Semantic-UI):
      Semantic is a UI component framework based around useful principles from natural language.

* [
      mauriciosoares
      /
      core.js
](https://github.com/mauriciosoares/core.js):
      Lightweight framework for scalable applications

* [
      Matt-Esch
      /
      virtual-dom
](https://github.com/Matt-Esch/virtual-dom):
      A Virtual DOM and diffing algorithm

* [
      mbostock
      /
      d3
](https://github.com/mbostock/d3):
      A JavaScript visualization library for HTML and SVG.

* [
      joyent
      /
      node
](https://github.com/joyent/node):
      evented I/O for v8 javascript

* [
      facebook
      /
      react
](https://github.com/facebook/react):
      A declarative, efficient, and flexible JavaScript library for building user interfaces.

* [
      leanote
      /
      leanote
](https://github.com/leanote/leanote):
      Not Just A Notebook! (不只是笔记!) (golang + mongodb) http://leanote.org

* [
      Reactive-Extensions
      /
      RxJS
](https://github.com/Reactive-Extensions/RxJS):
      The Reactive Extensions for JavaScript

* [
      Leask
      /
      BRICKS
](https://github.com/Leask/BRICKS):
      BRICKS is a list for all the domains blocked by the Chinese GFW.

* [
      knsv
      /
      mermaid
](https://github.com/knsv/mermaid):
      Generation of diagram and flowchart from text in a similar manner as markdown

* [
      zxlie
      /
      WeixinApi
](https://github.com/zxlie/WeixinApi):
      专门用于微信公众平台的Javascript API

* [
      webpack
      /
      webpack
](https://github.com/webpack/webpack):
      Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jade, coffee, css, less, ... and your custom stuff.

* [
      FelisCatus
      /
      SwitchyOmega
](https://github.com/FelisCatus/SwitchyOmega):
      Manage and switch between multiple proxies quickly & easily.

* [
      iojs
      /
      io.js
](https://github.com/iojs/io.js):
      Evented IO for V8 JavaScript

* [
      TryGhost
      /
      Ghost
](https://github.com/TryGhost/Ghost):
      Just a blogging platform

* [
      gulpjs
      /
      gulp
](https://github.com/gulpjs/gulp):
      The streaming build system

* [
      driftyco
      /
      ionic
](https://github.com/driftyco/ionic):
      Advanced HTML5 mobile development framework and SDK. Build great hybrid apps with web technologies you already know and love. Best friends with AngularJS.

* [
      neilj
      /
      Squire
](https://github.com/neilj/Squire):
      HTML5 rich text editor. Try the demo integration at

####ruby
* [
      inf0rmer
      /
      blanket
](https://github.com/inf0rmer/blanket):
      A dead simple API wrapper

* [
      rails
      /
      rails
](https://github.com/rails/rails):
      Ruby on Rails

* [
      Homebrew
      /
      homebrew
](https://github.com/Homebrew/homebrew):
      The missing package manager for OS X.

* [
      sagivo
      /
      algorithms
](https://github.com/sagivo/algorithms):
      algorithms playground for common questions

* [
      cantino
      /
      huginn
](https://github.com/cantino/huginn):
      Build agents that monitor and act on your behalf. Your agents are standing by!

* [
      jekyll
      /
      jekyll
](https://github.com/jekyll/jekyll):
      Jekyll is a blog-aware, static site generator in Ruby

* [
      thoughtbot
      /
      trail-map
](https://github.com/thoughtbot/trail-map):
      Trails to help designers and developers learn various topics.

* [
      ruby
      /
      ruby
](https://github.com/ruby/ruby):
      The Ruby Programming Language

* [
      rom-rb
      /
      rom
](https://github.com/rom-rb/rom):
      Persistence and mapping toolkit for Ruby

* [
      rubinius
      /
      rubinius
](https://github.com/rubinius/rubinius):
      Rubinius, the Ruby Environment

* [
      rapid7
      /
      metasploit-framework
](https://github.com/rapid7/metasploit-framework):
      Metasploit Framework

* [
      plataformatec
      /
      devise
](https://github.com/plataformatec/devise):
      Flexible authentication solution for Rails with Warden.

* [
      amatsuda
      /
      kaminari
](https://github.com/amatsuda/kaminari):
      A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for Rails 3 and 4

* [
      github
      /
      ruby
](https://github.com/github/ruby):
      The Ruby Programming Language

* [
      RailsApps
      /
      rails_apps_composer
](https://github.com/RailsApps/rails_apps_composer):
      A gem with recipes to create Rails application templates for Rails starter apps.

* [
      locomotivecms
      /
      engine
](https://github.com/locomotivecms/engine):
      a brand new CMS system with super sexy UI and cool features

* [
      jorgemanrubia
      /
      mailgun_rails
](https://github.com/jorgemanrubia/mailgun_rails):
      Rails Action Mailer adapter for Mailgun

* [
      opf
      /
      openproject
](https://github.com/opf/openproject):
      OpenProject is a web based project management system built on Ruby on Rails

* [
      emberjs
      /
      ember-rails
](https://github.com/emberjs/ember-rails):
      Ember for Rails 3.1+

* [
      amro
      /
      gibbon
](https://github.com/amro/gibbon):
      Gibbon is an API wrapper for MailChimp's API

* [
      lusis
      /
      chef-kibana
](https://github.com/lusis/chef-kibana):
      A Chef cookbook for Kibana3

* [
      garethr
      /
      garethr-docker
](https://github.com/garethr/garethr-docker):
      Puppet module for managing docker

* [
      opscode-cookbooks
      /
      apt
](https://github.com/opscode-cookbooks/apt):
      Development repository for Opscode Cookbook apt

* [
      lusis
      /
      chef-logstash
](https://github.com/lusis/chef-logstash):
      Semi-official Logstash cookbook

* [
      gitlabhq
      /
      gitlabhq
](https://github.com/gitlabhq/gitlabhq):
      Open source software to collaborate on code. Follow us on twitter @gitlabhq


text:
{% load staticfiles %}
<script type="text/javascript">

 {% if SEGMENT_ID %}

    !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.0.1";

        analytics.load('{{SEGMENT_ID}}');

        {% if pageType %}
        analytics.page('{{ pageType }}');
        {% endif %}

    }}();
 {% endif %}

</script>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool
//     Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EventManager.Server.Data.Model
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	public class EventAttendance : Entity
	{
		public virtual Event Event
		{
			get;
			set;
		}

		public string UserId
		{
			get;
			set;
		}

		public virtual Payment Payment
		{
			get;
			set;
		}

	}
}


text:
title: Android? More Android?
date: 2015-01-27T22:16:13+00:00
author: Frank S
layout: post
---

It isn't a secret that I view my blog's read count every hour.  Ok I lied again, more like every 10 min.  From the looks of it there are quite themany people interested in my Note 2 posts.  Here's a todo list for upcoming posts hopefully this week:

Odin new firmware for bootloader and modem

Odin recovery (twrp/philz cwm)

Odin root

Hosting all the files on top of providing link to originals for convenience (maybe)

Cool apps

Let me know what you think in the comments.  What would you like to see more of?


text:
using System.Collections.Generic;

namespace Abp.Localization
{
    public interface ILanguageManager
    {
        LanguageInfo CurrentLanguage { get; }

        IReadOnlyList<LanguageInfo> GetLanguages();
    }
}


text:
use std;

use gl::{
    self, types::{GLfloat, GLuint, GLvoid},
};

use tutcommon::glutils;

// An array of 3 vectors which represents 3 vertices.
static G_VERTEX_BUFFER_DATA: [GLfloat; 9] = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0];

#[doc = "Moved out drawing GL stuff to avoid mess with the other code."]
#[derive(Default)]
pub struct GLScene {
    vertex_array_id: GLuint,  //VAO id.
    vertex_buffer_id: GLuint, //VBO id.
    program_id: GLuint,       //Shader program id.
}

impl GLScene {
    #[doc = "Create scene and init it."]
    pub fn new() -> GLScene {
        let mut vertex_array_id = 0;

        unsafe {
            // create Vertex Array Object and set it as the current one:
            gl::GenVertexArrays(1, &mut vertex_array_id);
            gl::BindVertexArray(vertex_array_id);
        }

        // Create and compile our GLSL program from the shaders
        let program_id = glutils::load_program(
            "data/tut02/SimpleVertexShader.vertexshader",
            "data/tut02/SimpleFragmentShader.fragmentshader",
        );

        let mut vertex_buffer_id = 0;

        unsafe {
            // Generate 1 buffer.
            gl::GenBuffers(1, &mut vertex_buffer_id);

            // Set it current.
            gl::BindBuffer(gl::ARRAY_BUFFER, vertex_buffer_id);

            // Send vertices to buffer.
            gl::BufferData(
                gl::ARRAY_BUFFER,
                std::mem::size_of_val(&G_VERTEX_BUFFER_DATA) as isize,
                &G_VERTEX_BUFFER_DATA as *const _ as *const GLvoid,
                gl::STATIC_DRAW,
            );
        }

        GLScene {
            vertex_array_id,
            vertex_buffer_id,
            program_id,
        }
    }

    #[doc = "Render scene each frame."]
    pub fn draw(&self) {
        unsafe {
            //1st attribute buffer : vertices
            gl::EnableVertexAttribArray(0);
            gl::BindBuffer(gl::ARRAY_BUFFER, self.vertex_buffer_id);
            gl::VertexAttribPointer(
                // attribute 0. No particular reason for 0, but must match the
                // layout in the shader.
                0,
                3,                // size
                gl::FLOAT,        // type
                gl::FALSE,        // normalized?
                0,                // stride
                std::ptr::null(), // array buffer offset
            );

            // Use our shader
            gl::UseProgram(self.program_id);

            // Draw the triangle!
            // Starting from vertex 0; 3 vertices total -> 1 triangle.
            gl::DrawArrays(gl::TRIANGLES, 0, 3);

            gl::DisableVertexAttribArray(0);
        }
    }
}

#[doc = "Always clean up after yourself."]
impl Drop for GLScene {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteProgram(self.program_id);

            gl::DeleteBuffers(1, &self.vertex_buffer_id);

            gl::DeleteVertexArrays(1, &self.vertex_array_id);
        }
    }
}


text:
<?php
/**
 * The template for displaying search forms in Sparkling
 *
 * @package sparkling
 */
?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">

		<?php _ex( 'Search for:', 'label', 'sparkling' ); ?>
		<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder', 'sparkling' ); ?>" value="<?php echo esc_attr( get_search_query() ); ?>" name="s">

	<input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button', 'sparkling' ); ?>">
</form>


text:
package org.apache.ignite.spring;

import org.apache.ignite.IgniteCache;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring cache test.
 */
public class GridSpringCacheManagerSelfTest extends GridCommonAbstractTest {
    /** */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** */
    private static final String CACHE_NAME = "testCache";

    /** */
    private static final String DYNAMIC_CACHE_NAME = "dynamicCache";

    /** */
    private GridSpringCacheTestService svc;

    /** */
    private GridSpringDynamicCacheTestService dynamicSvc;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(gridName);

        CacheConfiguration cache = new CacheConfiguration();

        cache.setName(CACHE_NAME);

        cfg.setCacheConfiguration(cache);

        TcpDiscoverySpi disco = new TcpDiscoverySpi();

        disco.setIpFinder(IP_FINDER);

        cfg.setDiscoverySpi(disco);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override public String getTestGridName() {
        return "testGrid";
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        startGrid();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopAllGrids();
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        BeanFactory factory = new ClassPathXmlApplicationContext("org/apache/ignite/spring/spring-caching.xml");

        svc = (GridSpringCacheTestService)factory.getBean("testService");
        dynamicSvc = (GridSpringDynamicCacheTestService)factory.getBean("dynamicTestService");

        svc.reset();
        dynamicSvc.reset();
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        grid().cache(CACHE_NAME).removeAll();

        grid().destroyCache(DYNAMIC_CACHE_NAME);
    }

    /**
     * @throws Exception If failed.
     */
    public void testSimpleKey() throws Exception {
        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i, svc.simpleKey(i));
            assertEquals("value" + i, svc.simpleKey(i));
        }

        assertEquals(3, svc.called());

        IgniteCache<Integer, String> c = grid().cache(CACHE_NAME);

        assertEquals(3, c.size());

        for (int i = 0; i < 3; i++)
            assertEquals("value" + i, c.get(i));
    }

    /**
     * @throws Exception If failed.
     */
    public void testComplexKey() throws Exception {
        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i + "suffix" + i, svc.complexKey(i, "suffix" + i));
            assertEquals("value" + i + "suffix" + i, svc.complexKey(i, "suffix" + i));
        }

        assertEquals(3, svc.called());

        IgniteCache<GridSpringCacheTestKey, String> c = grid().cache(CACHE_NAME);

        assertEquals(3, c.size());

        for (int i = 0; i < 3; i++)
            assertEquals("value" + i + "suffix" + i, c.get(new GridSpringCacheTestKey(i, "suffix" + i)));
    }

    /**
     * @throws Exception If failed.
     */
    public void testSimpleKeyPut() throws Exception {
        IgniteCache<Integer, String> c = grid().cache(CACHE_NAME);

        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i + "odd", svc.simpleKeyPut(i));

            assertEquals(i + 1, c.size());
            assertEquals("value" + i + "odd", c.get(i));

            assertEquals("value" + i + "even", svc.simpleKeyPut(i));

            assertEquals(i + 1, c.size());
            assertEquals("value" + i + "even", c.get(i));
        }

        assertEquals(6, svc.called());
    }

    /**
     * @throws Exception If failed.
     */
    public void testComplexKeyPut() throws Exception {
        IgniteCache<GridSpringCacheTestKey, String> c = grid().cache(CACHE_NAME);

        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i + "suffix" + i + "odd", svc.complexKeyPut(i, "suffix" + i));

            assertEquals(i + 1, c.size());
            assertEquals("value" + i + "suffix" + i + "odd", c.get(new GridSpringCacheTestKey(i, "suffix" + i)));

            assertEquals("value" + i + "suffix" + i + "even", svc.complexKeyPut(i, "suffix" + i));

            assertEquals(i + 1, c.size());
            assertEquals("value" + i + "suffix" + i + "even", c.get(new GridSpringCacheTestKey(i, "suffix" + i)));
        }

        assertEquals(6, svc.called());
    }

    /**
     * @throws Exception If failed.
     */
    public void testSimpleKeyEvict() throws Exception {
        IgniteCache<Integer, String> c = grid().cache(CACHE_NAME);

        for (int i = 0; i < 3; i++)
            c.put(i, "value" + i);

        assertEquals(3, c.size());

        assertEquals("value0", c.get(0));
        assertEquals("value1", c.get(1));
        assertEquals("value2", c.get(2));

        svc.simpleKeyEvict(2);

        assertEquals(2, c.size());

        assertEquals("value0", c.get(0));
        assertEquals("value1", c.get(1));
        assertNull(c.get(2));
    }

    /**
     * @throws Exception If failed.
     */
    public void testComplexKeyEvict() throws Exception {
        IgniteCache<GridSpringCacheTestKey, String> c = grid().cache(CACHE_NAME);

        for (int i = 0; i < 3; i++)
            c.put(new GridSpringCacheTestKey(i, "suffix" + i), "value" + i);

        assertEquals(3, c.size());

        assertEquals("value0", c.get(new GridSpringCacheTestKey(0, "suffix" + 0)));
        assertEquals("value1", c.get(new GridSpringCacheTestKey(1, "suffix" + 1)));
        assertEquals("value2", c.get(new GridSpringCacheTestKey(2, "suffix" + 2)));

        svc.complexKeyEvict(2, "suffix" + 2);

        assertEquals(2, c.size());

        assertEquals("value0", c.get(new GridSpringCacheTestKey(0, "suffix" + 0)));
        assertEquals("value1", c.get(new GridSpringCacheTestKey(1, "suffix" + 1)));
        assertNull(c.get(new GridSpringCacheTestKey(2, "suffix" + 2)));
    }

    /**
     * @throws Exception If failed.
     */
    public void testEvictAll() throws Exception {
        IgniteCache<Integer, String> c = grid().cache(CACHE_NAME);

        for (int i = 0; i < 3; i++)
            c.put(i, "value" + i);

        assertEquals(3, c.size());

        assertEquals("value0", c.get(0));
        assertEquals("value1", c.get(1));
        assertEquals("value2", c.get(2));

        svc.evictAll();

        assertEquals(0, c.size());
    }

    /**
     * @throws Exception If failed.
     */
    public void testDynamicCache() throws Exception {
        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i, dynamicSvc.cacheable(i));
            assertEquals("value" + i, dynamicSvc.cacheable(i));
        }

        assertEquals(3, dynamicSvc.called());

        IgniteCache<Integer, String> c = grid().cache(DYNAMIC_CACHE_NAME);

        // Check that correct config is used.
        assertEquals(2, c.getConfiguration(CacheConfiguration.class).getBackups());

        assertEquals(3, c.size());

        for (int i = 0; i < 3; i++)
            assertEquals("value" + i, c.get(i));
    }

    /**
     * @throws Exception If failed.
     */
    public void testDynamicCachePut() throws Exception {
        for (int i = 0; i < 3; i++) {
            assertEquals("value" + i, dynamicSvc.cachePut(i));
            assertEquals("value" + i, dynamicSvc.cachePut(i));
        }

        assertEquals(6, dynamicSvc.called());

        IgniteCache<Integer, String> c = grid().cache(DYNAMIC_CACHE_NAME);

        // Check that correct config is used.
        assertEquals(2, c.getConfiguration(CacheConfiguration.class).getBackups());

        assertEquals(3, c.size());

        for (int i = 0; i < 3; i++)
            assertEquals("value" + i, c.get(i));
    }

    /**
     * @throws Exception If failed.
     */
    public void testDynamicCacheEvict() throws Exception {
        CacheConfiguration<Integer, String> cacheCfg = new CacheConfiguration<>();

        cacheCfg.setName(DYNAMIC_CACHE_NAME);

        IgniteCache<Integer, String> c = grid().createCache(cacheCfg);

        for (int i = 0; i < 3; i++)
            c.put(i, "value" + i);

        assertEquals(3, c.size());

        for (int i = 0; i < 2; i++) {
            dynamicSvc.cacheEvict(i);
            dynamicSvc.cacheEvict(i);
        }

        assertEquals(4, dynamicSvc.called());

        assertEquals(1, c.size());

        assertEquals("value2", c.get(2));
    }

    /**
     * @throws Exception If failed.
     */
    public void testDynamicCacheEvictAll() throws Exception {
        CacheConfiguration<Integer, String> cacheCfg = new CacheConfiguration<>();

        cacheCfg.setName(DYNAMIC_CACHE_NAME);

        IgniteCache<Integer, String> c = grid().createCache(cacheCfg);

        for (int i = 0; i < 3; i++)
            c.put(i, "value" + i);

        assertEquals(3, c.size());

        dynamicSvc.cacheEvictAll();
        dynamicSvc.cacheEvictAll();

        assertEquals(2, dynamicSvc.called());

        assertEquals(0, c.size());
    }
}


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

package com.github.castagna.kafka.connect.exchange;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.Map;
import java.util.Properties;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class ExchangeSourceTaskTest {

	private static ExchangeSourceTask task;
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		Properties properties = new Properties();
		properties.load(VersionUtil.class.getResourceAsStream("/exchange-source-example.properties"));
		properties.put("task", "0");
		properties.put("maxTasks", "3");
		Map<String, String> settings = ExchangeSourceConnectorConfigTest.properties2Map(properties);

		task = new ExchangeSourceTask();
		task.start(settings);
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		task.stop();
	}

	@Test
	public void testConfiguration() {
		assertEquals(0, task.task);
		assertEquals(3, task.maxTasks);
	}

	@Test
	public void testCredentialsLoaded() {
		assertFalse(task.emails.isEmpty());
		assertFalse(task.passwords.isEmpty());
		assertFalse(task.domains.isEmpty());
		assertEquals(2, task.emails.size());
		assertEquals(2, task.passwords.size());
		assertEquals(2, task.domains.size());
		assertEquals("paolo@domain.com", task.emails.get(0));
		assertEquals("password1", task.passwords.get(0));
		assertEquals("london", task.domains.get(0));
		assertEquals("david@domain.com", task.emails.get(1));
		assertEquals("password4", task.passwords.get(1));
		assertEquals("madrid", task.domains.get(1));
	}
}


text:
Add your mmc agent certificate, key and CA certificate here
or during docker run mount a data volume with those files to /container/service/mmc-agent/assets/certs


text:
require "os/linux/glibc"

class BrewedGlibcNotOlderRequirement < Requirement
  fatal true

  satisfy(build_env: false) do
    Glibc.version >= OS::Linux::Glibc.system_version
  end

  def message
    <<~EOS
      Your system's glibc version is #{OS::Linux::Glibc.system_version}, and Homebrew's glibc version is #{Glibc.version}.
      Installing a version of glibc that is older than your system's can break formulae installed from source.
    EOS
  end

  def display_s
    "System glibc < #{Glibc.version}"
  end
end

class GlibcBaseRequirement < Requirement
  def message
    tool = self.class::TOOL
    version = self.class::VERSION
    <<~EOS
      #{[tool, version].compact.join(" ")} is required to build glibc.
      Install #{tool} with your host package manager if you have sudo access:
        sudo apt-get install #{tool}
        sudo yum install #{tool}
    EOS
  end

  def display_s
    "#{self.class::TOOL} #{self.class::VERSION}".strip
  end
end

class GawkRequirement < GlibcBaseRequirement
  fatal true
  satisfy(build_env: false) { which(TOOL).present? }
  TOOL = "gawk".freeze
  VERSION = "3.1.2 (or later)".freeze
end

class MakeRequirement < GlibcBaseRequirement
  fatal true
  satisfy(build_env: false) { which(TOOL).present? }
  TOOL = "make".freeze
  VERSION = "3.79 (or later)".freeze
end

class SedRequirement < GlibcBaseRequirement
  fatal true
  satisfy(build_env: false) { which(TOOL).present? }
  TOOL = "sed".freeze
  VERSION = nil
end

class LinuxKernelRequirement < Requirement
  fatal true

  MINIMUM_LINUX_KERNEL_VERSION = "2.6.32".freeze

  satisfy(build_env: false) do
    OS.kernel_version >= MINIMUM_LINUX_KERNEL_VERSION
  end

  def message
    <<~EOS
      Linux kernel version #{MINIMUM_LINUX_KERNEL_VERSION} or later is required by glibc.
      Your system has Linux kernel version #{OS.kernel_version}.
    EOS
  end

  def display_s
    "Linux kernel #{MINIMUM_LINUX_KERNEL_VERSION} (or later)"
  end
end

class Glibc < Formula
  desc "GNU C Library"
  homepage "https://www.gnu.org/software/libc/"
  url "https://ftp.gnu.org/gnu/glibc/glibc-2.23.tar.gz"
  sha256 "2bd08abb24811cda62e17e61e9972f091f02a697df550e2e44ddcfb2255269d2"
  license all_of: ["GPL-2.0-or-later", "LGPL-2.1-or-later"]

  livecheck do
    skip "glibc is pinned to the version present in Homebrew CI"
  end

  bottle do
    sha256 x86_64_linux: "8f5509c5a5fe85b923c196da5bb969d759a70a6a0e228110c5440a8719dc4c8e"
  end

  depends_on "binutils" => :build
  depends_on GawkRequirement => :build
  depends_on "linux-headers@4.4" => :build
  depends_on MakeRequirement => :build
  depends_on SedRequirement => :build
  depends_on BrewedGlibcNotOlderRequirement
  depends_on :linux
  depends_on LinuxKernelRequirement

  # GCC 4.7 or later is required.
  fails_with gcc: "4.6"

  def install
    # Fix Error: `loc1@GLIBC_2.2.5' can't be versioned to common symbol 'loc1'
    # See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=869717
    # Fixed in glibc 2.24
    inreplace "misc/regexp.c", /^(char \*loc[12s]);$/, "\\1 __attribute__ ((nocommon));"

    # Setting RPATH breaks glibc.
    %w[
      LDFLAGS LD_LIBRARY_PATH LD_RUN_PATH LIBRARY_PATH
      HOMEBREW_DYNAMIC_LINKER HOMEBREW_LIBRARY_PATHS HOMEBREW_RPATH_PATHS
    ].each { |x| ENV.delete x }

    # Use brewed ld.so.preload rather than the hotst's /etc/ld.so.preload
    inreplace "elf/rtld.c", '= "/etc/ld.so.preload";', '= SYSCONFDIR "/ld.so.preload";'

    mkdir "build" do
      args = [
        "--disable-debug",
        "--disable-dependency-tracking",
        "--disable-silent-rules",
        "--prefix=#{prefix}",
        "--enable-obsolete-rpc",
        "--without-selinux",
        "--with-binutils=#{Formula["binutils"].bin}",
        "--with-headers=#{Formula["linux-headers"].include}",
      ]
      system "../configure", *args
      system "make", "all"
      system "make", "install"
      prefix.install_symlink "lib" => "lib64"
    end
  end

  def post_install
    # Install ld.so symlink.
    ln_sf lib/"ld-linux-x86-64.so.2", HOMEBREW_PREFIX/"lib/ld.so"

    # Compile locale definition files
    mkdir_p lib/"locale"

    # Get all extra installed locales from the system, except C locales
    locales = ENV.map do |k, v|
      v if k[/^LANG$|^LC_/] && v != "C" && !v.start_with?("C.")
    end.compact

    # en_US.UTF-8 is required by gawk make check
    locales = (locales + ["en_US.UTF-8"]).sort.uniq
    ohai "Installing locale data for #{locales.join(" ")}"
    locales.each do |locale|
      lang, charmap = locale.split(".", 2)
      if charmap.present?
        charmap = "UTF-8" if charmap == "utf8"
        system bin/"localedef", "-i", lang, "-f", charmap, locale
      else
        system bin/"localedef", "-i", lang, locale
      end
    end

    # Set the local time zone
    sys_localtime = Pathname("/etc/localtime")
    brew_localtime = prefix/"etc/localtime"
    (prefix/"etc").install_symlink sys_localtime if sys_localtime.exist? && brew_localtime.exist?

    # Set zoneinfo correctly using the system installed zoneinfo
    sys_zoneinfo = Pathname("/usr/share/zoneinfo")
    brew_zoneinfo = share/"zoneinfo"
    share.install_symlink sys_zoneinfo if sys_zoneinfo.exist? && !brew_zoneinfo.exist?
  end

  test do
    assert_match "Usage", shell_output("#{lib}/ld-#{version}.so 2>&1", 127)
    safe_system "#{lib}/libc-#{version}.so", "--version"
    safe_system "#{bin}/locale", "--version"
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>zkwm</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="zkw.html" title="zkw" />
    <link rel="next" href="ScoregensTop.html" title="Instructions de partition et routines GEN" />

          zkwm

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          zkwm

zkwm —
      Ecrit dans une variable zk au taux-k avec mixage.

Description

      Ecrit dans une variable zk au taux-k avec mixage.

Syntaxe

zkwm ksig, kndx [, imix]

Initialisation

      imix (facultatif) -- indique si le mixage sera fait.

Exécution

     ksig -- valeur à écrire dans l'espace zk.

      kndx -- pointe sur la position zk ou za vers laquelle écrire.

      zkwm est un opcode de mixage, il ajoute le signal à la valeur courante
      de la variable. Si aucun imix n'est specifié, le mixage aura toujours
      lieu. imix = 0 provoquera l'écrasement des données comme dans
      ziw, zkw, et zaw. Toutes autres
      valeurs entraînera un mixage.

      Avertissement : lors de l'utilisation des opcodes de mixage
      ziwm, zkwm, et zawm, il faut
      faire attention à ce que les variables qui reçoivent le mixage soient remises à zéro à la
      fin (ou au début) de chaque cycle-k ou -a. Leur ajouter indéfiniment des signaux
      peut engendrer des valeurs astronomiques.

      Une approche possible serait d'établir certains intervalles de variables zk ou za à utiliser
      pour le mixage, puis d'utiliser ensuite zkcl ou zacl
      pour effacer ces variables.

Exemples

      Voici un exemple de l'opcode zkwm. Il utilise le fichier
      zkwm.csd.

            Exemple 1111. Exemple de l'opcode zkwm.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
; Audio out   Audio in    No messages
-odac           -iadc     -d     ;;;RT audio I/O
; For Non-realtime ouput leave only the line below:
; -o zkwm.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

; Initialize the global variables.
sr = 44100
kr = 4410
ksmps = 10
nchnls = 1

; Initialize the ZAK space.
; Create 1 a-rate variable and 1 k-rate variable.
zakinit 1, 1

; Instrument #1 -- a basic instrument.
instr 1
  ; Generate a k-rate signal.
  ; The signal goes from 30 to 20,000 then back to 30.
  kramp linseg 30, p3/2, 20000, p3/2, 30

  ; Mix the signal into the zk variable #1.
  zkwm kramp, 1
endin

; Instrument #2 -- another basic instrument.
instr 2
  ; Generate another k-rate signal.
  ; This is a low frequency oscillator.
  klfo lfo 3500, 2

  ; Mix this signal into the zk variable #1.
  zkwm klfo, 1
endin

; Instrument #3 -- generates audio output.
instr 3
  ; Read zk variable #1, containing a mix of both signals.
  kamp zkr 1

  ; Create a sine waveform. Its amplitude will vary
  ; according to the values in zk variable #1.
  a1 oscil kamp, 880, 1

  ; Generate the audio output.
  out a1

  ; Clear the zk variable, get it ready for
  ; another pass.
  zkcl 0, 1
endin

</CsInstruments>
<CsScore>

; Table #1, a sine wave.
f 1 0 16384 10 1

; Play Instrument #1 for 5 seconds.
i 1 0 5
; Play Instrument #2 for 5 seconds.
i 2 0 5
; Play Instrument #3 for 5 seconds.
i 3 0 5
e

</CsScore>
</CsoundSynthesizer>

Voir aussi

      zaw,
      zawm,
      ziw,
      ziwm,
      zkcl,
      zkw,
      zkr

Crédits

            Auteur : Robin Whittle

            Australie

            Mai 1997

Nouveau dans la version 3.45

Exemple écrit par Kevin Conder.

          Précédent

            Niveau supérieur

           Suivant

          zkw

            Sommaire

           Instructions de partition et routines GEN


text:
using CrossStitch.Core.Messages.Master;

namespace CrossStitch.Core.Modules.Master.Handlers
{
    public class StartStitchCommandHandler : StitchCommandHandler
    {
        public StartStitchCommandHandler(MasterDataRepository data, JobManager jobManager, IStitchRequestHandler stitches, IClusterMessageSender sender)
            : base(data, jobManager, stitches, sender)
        {
        }

        public override bool HandleLocal(CommandRequest request)
        {
            return _stitches.StartInstance(request.Target);
        }
    }
}


text:
Hblank effect megademo

A megademo to go with the publication on Hblank effects. It provides example code for each of the effects.


text:
<!DOCTYPE html>
<title>Layout Instability: on-screen content-visibility:auto content</title>
<link rel="help" href="https://wicg.github.io/layout-instability/" />