text:
package com.teletalk.jserver.rmi.adapter;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Level;

import com.teletalk.jserver.JServerConstants;
import com.teletalk.jserver.SubComponent;
import com.teletalk.jserver.SubSystem;
import com.teletalk.jserver.log.AppenderComponent;
import com.teletalk.jserver.property.Property;
import com.teletalk.jserver.rmi.RmiManager;
import com.teletalk.jserver.rmi.remote.RemoteAppenderComponentData;
import com.teletalk.jserver.rmi.remote.RemoteProperty;
import com.teletalk.jserver.rmi.remote.RemotePropertyData;
import com.teletalk.jserver.rmi.remote.RemoteSubComponent;
import com.teletalk.jserver.rmi.remote.RemoteSubComponentData;
import com.teletalk.jserver.rmi.remote.RemoteSubSystemData;

/**
 * Adapter for remote interaction with a SubComponent object.
 *
 * @see com.teletalk.jserver.JServer
 *
 * @author Tobias Löfstrand
 *
 * @since Alpha
 */
public class SubComponentRmiAdapter extends UnicastRemoteObject implements RemoteSubComponent, RmiAdapter, Cloneable
{
   static final long serialVersionUID = -1767608923621613565L;

	/** Reference to a SubComponent object. */
	protected SubComponent adaptee;

	/**
	 * Constructs a new SubComponentRmiAdapter object.
	 *
	 * @param adaptee a SubComponent adaptee object.
	 *
	 * @exception RemoteException if there was an error creating this SubComponentRmiAdapter.
	 */
	public SubComponentRmiAdapter(SubComponent adaptee) throws RemoteException
	{
		super(RmiManager.getRmiManager().getExportAddresses()[0].getPort());

		this.adaptee = adaptee;
	}

	public Object clone()
	{
		try{
		return super.clone();
		}catch(Exception e){e.printStackTrace(); return null;}
	}

	/**
	 * Returns the name of the SubComponent.
	 *
	 * @return a String containing the name.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final String getName() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getName()");

			return adaptee.getName();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Returns the full name of the SubComponent.
	 *
	 * @return a String containing the full name.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final String getFullName() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getFullName()");

			return adaptee.getFullName();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Returns the status of the SubComponent.
	 *
	 * @return int indicating the status.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final int getStatus() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getStatus()");

			return adaptee.getStatus();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Indicates whether or not the SubComponent is enabled.
	 *
	 * @return boolean value inidcating if the state of the SubComponent is ENABLED.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final boolean isEnabled() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "isEnabled()");

			return adaptee.isEnabled();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

   /**
    * Engages the SubSystem.
    *
    * @exception RemoteException if there was an error during remote access of this method.
    *
    * @since 2.0
    */
   public final boolean engage() throws RemoteException
   {
      try
      {
         JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "engage()");

         return adaptee.engage();
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if(t instanceof Error)
            throw (Error)t;
         else
            throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

   /**
    * Reinitilizes the SubSystem.
    *
    * @exception RemoteException if there was an error during remote access of this method.
    *
    * @since 2.0
    */
   public final boolean reinitialize() throws RemoteException
   {
      try
      {
         JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "reinitialize()");

         return adaptee.reinitialize();
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if(t instanceof Error)
            throw (Error)t;
         else
            throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

   /**
    * Shuts down the SubSystem.
    *
    * @exception RemoteException if there was an error during remote access of this method.
    *
    * @since 2.0
    */
   public final boolean shutDown() throws RemoteException
   {
      try
      {
         JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "shutDown()");

         return adaptee.shutDown();
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if(t instanceof Error)
            throw (Error)t;
         else
            throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

	/**
	 * Enables the SubComponent.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
    *
    * @deprecated as of 2.0
	 */
	public boolean enable() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "enable()");

			return adaptee.engage();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Disables the SubComponent.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
    *
    * @deprecated as of 2.0
	 */
	public boolean disable() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "disable()");

			return adaptee.shutDown();
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Returns the properties contained in the SubComponent.
	 *
	 * @return a List containing RemoteProperty objects.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final List getProperties() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getProperties()");

			ArrayList result = new ArrayList();
			List properties = adaptee.getProperties();

			for(int i=0; i<properties.size(); i++)
			{
				result.add(((Property)properties.get(i)).getRmiAdapter());
			}

			return result;
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Gets the property with the specified name contained in this SubComponent.
	 *
	 * @param name the name of the Property.
	 *
	 * @return a RemoteProperty object or null if none was found.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public RemoteProperty getProperty(String name) throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getProperty(" + name + ")");

			Property p = adaptee.getProperty(name);
			RemoteProperty remote = null;

			if(p != null)
			{
				RmiAdapter r = p.getRmiAdapter();

				if(remote instanceof RemoteProperty)
					remote = (RemoteProperty)r;
			}

			return remote;
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Returns the child SubComponents of the SubComponent.
	 *
	 * @return a Vector containing RemoteSubComponent objects.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final List getSubComponents() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getSubComponents()");

			ArrayList result = new ArrayList();
			List subcomponents = adaptee.getSubComponents();

			for(int i=0; i<subcomponents.size(); i++)
			{
				result.add(((SubComponent)subcomponents.get(i)).getRmiAdapter());
			}

			return result;
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Gets the SubComponent with the specified name contained in this SubComponent.
	 *
	 * @param name the name of the SubComponent.
	 *
	 * @return a RemoteSubComponent or null if none was found.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public RemoteSubComponent getSubComponent(String name) throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getSubComponent(" + name + ")");

			SubComponent s = adaptee.getSubComponent(name);
			RemoteSubComponent remote = null;

			if(s != null)
			{
				RmiAdapter r = s.getRmiAdapter();

				if(remote instanceof RemoteSubComponent)
					remote = (RemoteSubComponent)r;
			}

			return remote;
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Returns a recursive listing of all child SubComponents of the SubComponent.
	 *
	 * @return a Vector containing RemoteSubComponent objects.
	 *
	 * @exception RemoteException if there was an error during remote access of this method.
	 */
	public final List getSubComponentsRecursively() throws RemoteException
	{
		try
		{
			JServerRmiAdapter.logMethodCall(adaptee.getFullName() + ".SubComponentRmiAdapter", "getSubComponentsRecursively()");

			ArrayList result = new ArrayList();
			List subcomponents = adaptee.getSubComponentTree();

			for(int i=0; i<subcomponents.size(); i++)
			{
				result.add(((SubComponent)subcomponents.get(i)).getRmiAdapter());
			}

			return result;
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a logmessage to the logmanager.
	 *
	 * @param level the loglevel.
	 * @param msg the message.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void log(int level, String msg) throws RemoteException
	{
		try
		{
			adaptee.log(Level.toLevel(level), msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a logmessage to the logmanager.
	 *
	 * @param level the loglevel.
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void log(int level, String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.log(Level.toLevel(level), origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a logmessage to the logmanager.
	 *
	 * @param level the loglevel.
	 * @param time the time of the log.
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 *
	 * @see com.teletalk.jserver.log.LogManager
    *
    * @deprecated as of 2.0
	 */
	public final void log(int level, java.util.Date time, String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.log(Level.toLevel(level), origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a debug LogMessage to the LogManager, if the debugMode property of this SubComponent is set to true.
	 *
	 * @param msg the message.
	 */
	public final void logDebug(String msg) throws RemoteException
	{
		try
		{
			adaptee.logDebug(msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a debug LogMessage to the LogManager, if the debugMode property of this SubComponent is set to true.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 */
	public final void logDebug(String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.logDebug(origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an information LogMessage to the LogManager
	 *
	 * @param msg the message.
	 */
	public final void logInfo(String msg) throws RemoteException
	{
		try
		{
			adaptee.logInfo(msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an information LogMessage to the LogManager.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 */
	public final void logInfo(String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.logInfo(origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a warning LogMessage to the LogManager.
	 *
	 * @param msg the message.
	 */
	public final void logWarning(String msg) throws RemoteException
	{
		try
		{
			adaptee.logWarning(msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a warning LogMessage to the LogManager.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 */
	public final void logWarning(String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.logWarning(origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a warning LogMessage to the LogManager.
	 *
	 * @param msg the message.
	 * @param error an error to be logged.
	 */
	public final void logWarning(String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logWarning(msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a warning LogMessage to the LogManager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 * @param error an error to be logged.
	 */
	public final void logWarning(String origin, String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logWarning(origin, msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. The level of the logmessage is set to ERROR_LEVEL.
	 *
	 * @param msg a description of the error.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(String msg) throws RemoteException
	{
		try
		{
			adaptee.logError(msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. The level of the logmessage is set to ERROR_LEVEL.
	 *
	 * @param origin of the LogMessage.
	 * @param msg a description of the error.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.logError(origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage. The level of the logmessage is set to ERROR_LEVEL.
	 *
	 * @param msg a msg of the error.
	 * @param error an error to be logged.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logError(msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage. The level of the logmessage is set to ERROR_LEVEL.
	 *
	 * @param origin of the LogMessage.
	 * @param msg a description of the error.
	 * @param error an error to be logged.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(String origin, String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logError(origin, msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage.
	 *
	 * @param level the loglevel.
	 * @param msg a description of the error.
	 * @param error an error to be logged.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(int level, String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.log(Level.toLevel(level), msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send an errorlogmessage to the logmanager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage.
	 *
	 * @param level the loglevel.
	 * @param origin of the LogMessage.
	 * @param msg a description of the error.
	 * @param error an error to be logged.
	 *
	 * @see com.teletalk.jserver.log.LogManager
	 */
	public final void logError(int level, String origin, String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.log(Level.toLevel(level), origin, msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error)
				throw (Error)t;
			else
				throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

	/**
	 * Convenience method to send a critical error LogMessage to the LogManager.
	 *
	 * @param msg the message.
    *
    * @deprecated replaced by {@link #logCriticalError(String, int)}
	 */
	public final void logCriticalError(String msg) throws RemoteException
	{
		try
		{
			adaptee.logCriticalError(msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

   /**
    * Convenience method to log a critical error message (org.apache.log4j.Level.FATAL).
    *
    * @param msg the message to log.
    * @param logMessageId the id associated with the log message. This id will be stored in the MDC as an java.lang.Integer object
    * under the key {@link JServerConstants#LOG_MESSAGE_ID_KEY}. The range 4095-65535 is reserved for JServer.
    */
   public void logCriticalError(String msg, int logMessageId) throws RemoteException
   {
      try
      {
         adaptee.logCriticalError(msg, logMessageId);
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

	/**
	 * Convenience method to send a critical error LogMessage to the LogManager.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
    *
    * @deprecated replaced by {@link #logCriticalError(String, String, int)}
	 */
	public final void logCriticalError(String origin, String msg) throws RemoteException
	{
		try
		{
			adaptee.logCriticalError(origin, msg);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

   /**
    * Convenience method to log a critical error message (org.apache.log4j.Level.FATAL).
    *
    * @param origin the origin of the logging event. The thread name will be set to this parameter when creating the logging event.
    * @param msg the message to log.
    * @param logMessageId the id associated with the log message. This id will be stored in the MDC as an java.lang.Integer object
    * under the key {@link JServerConstants#LOG_MESSAGE_ID_KEY}. The range 4095-65535 is reserved for JServer.
    */
   public void logCriticalError(String origin, String msg, int logMessageId) throws RemoteException
   {
      try
      {
         adaptee.logCriticalError(origin, msg, logMessageId);
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

	/**
	 * Convenience method to send a critical error LogMessage to the LogManager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage.
	 *
	 * @param msg the message.
	 * @param error an error to be logged.
    *
    * @deprecated replaced by {@link #logCriticalError(String, Throwable, int)}
	 */
	public final void logCriticalError(String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logCriticalError(msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

   /**
    * Convenience method to log a critical error message (org.apache.log4j.Level.FATAL).
    *
    * @param msg the message to log.
    * @param throwable a throwable to be associated with the logging event. This parameter may be null.
    * @param logMessageId the id associated with the log message. This id will be stored in the MDC as an java.lang.Integer object
    * under the key {@link JServerConstants#LOG_MESSAGE_ID_KEY}. The range 4095-65535 is reserved for JServer.
    */
   public void logCriticalError(String msg, Throwable error, int logMessageId) throws RemoteException
   {
      try
      {
         adaptee.logCriticalError(msg, error, logMessageId);
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if (t instanceof Error) throw (Error) t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

	/**
	 * Convenience method to send a critical error LogMessage to the LogManager. This method prints a stacktrace from
	 * the parameter error and adds it to the logmessage.
	 *
	 * @param origin of the LogMessage.
	 * @param msg the message.
	 * @param error an error to be logged.
    *
    * @deprecated replaced by {@link #logCriticalError(String, String, Throwable, int)}
	 */
	public final void logCriticalError(String origin, String msg, Throwable error) throws RemoteException
	{
		try
		{
			adaptee.logCriticalError(origin, msg, error);
		}
		catch(Throwable t)
		{
			adaptee.logError("Error occurred during remote execution of operation!", t);
			if(t instanceof Error) throw (Error)t;
			else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
		}
	}

   /**
    * Convenience method to log a critical error message (org.apache.log4j.Level.FATAL).
    *
    * @param origin the origin of the logging event. The thread name will be set to this parameter when creating the logging event.
    * @param msg the message to log.
    * @param throwable a throwable to be associated with the logging event. This parameter may be null.
    * @param logMessageId the id associated with the log message. This id will be stored in the MDC as an java.lang.Integer object
    * under the key {@link JServerConstants#LOG_MESSAGE_ID_KEY}. The range 4095-65535 is reserved for JServer.
    */
   public void logCriticalError(String origin, String msg, Throwable error, int logMessageId) throws RemoteException
   {
      try
      {
         adaptee.logCriticalError(origin, msg, error, logMessageId);
      }
      catch(Throwable t)
      {
         adaptee.logError("Error occurred during remote execution of operation!", t);
         if(t instanceof Error) throw (Error)t;
         else throw new RemoteException("Error occurred during remote execution of operation in " + adaptee.getFullName() + "!", t);
      }
   }

   /**
    * Generates recursive administration data for the specified component.
    *
    * @since 2.0
    */
   public static RemoteSubComponentData getRemoteSubComponentData(final SubComponent subComponent)
   {
      if( subComponent == null ) return null;

      try
      {
         final List subcomponents = subComponent.getSubComponents();
         boolean isAppenderComponent = (subComponent instanceof AppenderComponent);
         boolean isSubSystem = (subComponent instanceof SubSystem);
         final List properties =  subComponent.getProperties();

         ArrayList subSystemData = null; // To preserve backwards compatability
         ArrayList subComponentData = null;
         ArrayList propertyData = null;

         if(subcomponents.size() > 0)
         {
            SubComponent child;
            RemoteSubComponentData remoteSubComponentData;

            for(int i=0; i<subcomponents.size(); i++)
            {
               child = (SubComponent)subcomponents.get(i);

               if( isSubSystem && (child instanceof SubSystem) )
               {
                  if( subSystemData == null ) subSystemData = new ArrayList();

                  remoteSubComponentData = getRemoteSubComponentData(child);
                  if( remoteSubComponentData != null ) subSystemData.add( remoteSubComponentData );
               }
               else
               {
                  if( subComponentData == null ) subComponentData = new ArrayList();

                  remoteSubComponentData = getRemoteSubComponentData(child);
                  if( remoteSubComponentData != null ) subComponentData.add( remoteSubComponentData );
               }
            }
         }

         if(properties.size() > 0)
         {
            propertyData = new ArrayList();
            Property p;
            RemotePropertyData rpd;

            for(int i=0; i<properties.size(); i++)
            {
               p = (Property)properties.get(i);

               rpd = new RemotePropertyData(p.getName(), p.getValueAsString(), p.getMetaData(), p.getModificationMode(), PropertyRmiAdapter.getType(p));
               propertyData.add(rpd);
            }
         }

         if( isAppenderComponent ) return new RemoteAppenderComponentData(subComponent.getName(), subComponent.getStatus(), subComponentData , propertyData);
         else if( isSubSystem ) return new RemoteSubSystemData(subComponent.getName(), subComponent.getStatus(), subSystemData, subComponentData, propertyData);
         else return new RemoteSubComponentData(subComponent.getName(), subComponent.getStatus(), subComponentData , propertyData);
      }
      catch(Exception e)
      {
         subComponent.logError("Error while getting remote component data for " + subComponent.getFullName() + ".", e);
         return null;
      }
   }
}


text:
const gulp = require('gulp');
const HubRegistry = require('gulp-hub');
const browserSync = require('browser-sync');

const conf = require('./gulp.conf');

// Load some files into the registry
const clientHub = new HubRegistry([conf.path.client.tasks('*.js')]);
const serverHub = new HubRegistry([conf.path.server.tasks('*.js')]);
// Tell gulp to use the tasks just loaded
gulp.registry(clientHub);
gulp.registry(serverHub);

gulp.task('client:build', gulp.parallel('client:other', 'webpack:dist'));
gulp.task('test', gulp.series('karma:single-run'));
gulp.task('test:auto', gulp.series('karma:auto-run'));
gulp.task('serve:client', gulp.series('webpack:watch', 'watch', 'browsersync'));
gulp.task('serve:server', gulp.series('server:watch'));
gulp.task('serve', gulp.parallel('serve:server', 'serve:client'));
gulp.task('serve:dist', gulp.series('default', 'browsersync:dist'));
gulp.task('default', gulp.series('client:clean', 'client:build'));
gulp.task('watch', watch);

function reloadBrowserSync(cb) {
  browserSync.reload();
  cb();
}

function watch(done) {
  gulp.watch(conf.path.client.tmp('index.html'), reloadBrowserSync);
  done();
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Own\Services\Bus;

class MembershipCourtService
{
    public function __construct()
    {
    }
}


text:
poise_file '/poise_test' do
  content "I'm a little teapot\n"
end

poise_file '/poise_test.json' do
  content ['short and stout', {here: 'is my handle'}]
end

poise_file '/poise_test.yml' do
  content 'here' => 'is my spout', 'when' => ['I', 'get', 'all', 'steamed', 'up']
end

file '/poise_test_pattern' do
  content "I must shout\ntip me over\n"
end

poise_file '/poise_test_pattern' do
  content 'yell'
  pattern 'shout'
end


text:
#include <gtest/gtest.h>
#include <math.h>
#include <stdexcept>
#include <vector>
#include "testing_iamax.hpp"
#include "testing_asum.hpp"
#include "testing_axpy.hpp"
#include "testing_copy.hpp"
#include "testing_dot.hpp"
#include "testing_nrm2.hpp"
#include "testing_scal.hpp"
#include "testing_swap.hpp"
#include "utility.h"

using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::ValuesIn;
using ::testing::Combine;
using namespace std;

// only GCC/VS 2010 comes with std::tr1::tuple, but it is unnecessary,  std::tuple is good enough;
typedef std::tuple<int, vector<double>, vector<int>> blas1_tuple;

/* =====================================================================
README: This file contains testers to verify the correctness of
        BLAS routines with google test

        It is supposed to be played/used by advance / expert users
        Normal users only need to get the library routines without testers
      =================================================================== */

/*

When you see this error, do not hack this source code, hack the Makefile. It is due to compilation.

from 'testing::internal::CartesianProductHolder3<testing::internal::ParamGenerator<int>,
testing::internal::ParamGenerator<std::vector<double> >,
testing::internal::ParamGenerator<std::vector<int> > >'

to 'testing::internal::ParamGenerator<std::tuple<int, std::vector<double, std::allocator<double> >,
std::vector<int, std::allocator<int> > > >'

*/

/* =====================================================================
Advance users only: BrainStorm the parameters

Representative sampling is sufficient, endless brute-force sampling is not necessary
=================================================================== */

int N_range[] = {
    -1, 0, 5, 10, 500, 1000, 7111, 10000,
};

// vector of vector, each pair is a {alpha, beta};
// add/delete this list in pairs, like {2.0, 4.0}
vector<vector<double>> alpha_beta_range = {{1.0, 0.0}, {2.0, -1.0}};

// vector of vector, each pair is a {incx, incy};
// add/delete this list in pairs, like {1, 2}
// incx , incy must > 0, otherwise there is no real computation taking place,
// but throw a message, which will still be detected by gtest
vector<vector<int>> incx_incy_range = {
    {1, 1}, {1, 2}, {2, 1}, {1, -1}, {-1, 1}, {-1, -1},
};

/* ===============Google Unit Test==================================================== */

/* =====================================================================
     BLAS-1:  iamax, asum, axpy, copy, dot, nrm2, scal, swap
=================================================================== */

class parameterized : public ::TestWithParam<blas1_tuple>
{
    protected:
    parameterized() {}
    virtual ~parameterized() {}
    virtual void SetUp() {}
    virtual void TearDown() {}
};

Arguments setup_blas1_arguments(blas1_tuple tup)
{
    int N                     = std::get<0>(tup);
    vector<double> alpha_beta = std::get<1>(tup);
    vector<int> incx_incy     = std::get<2>(tup);

    // the first element of alpha_beta_range is always alpha, and the second is always beta
    double alpha = alpha_beta[0];
    double beta  = alpha_beta[1];

    int incx = incx_incy[0];
    int incy = incx_incy[1];

    Arguments arg;
    arg.N     = N;
    arg.alpha = alpha;
    arg.beta  = beta;
    arg.incx  = incx;
    arg.incy  = incy;

    arg.timing =
        0; // disable timing data print out. Not supposed to collect performance data in gtest

    return arg;
}

TEST(checkin_blas1_bad_arg, iamax_float) { testing_iamax_bad_arg<float>(); }
TEST(checkin_blas1_bad_arg, asum_float) { testing_asum_bad_arg<float, float>(); }
TEST(checkin_blas1_bad_arg, axpy_float) { testing_axpy_bad_arg<float>(); }
TEST(checkin_blas1_bad_arg, copy_float) { testing_copy_bad_arg<float>(); }
TEST(checkin_blas1_bad_arg, dot_float)
{
    rocblas_status status = testing_dot_bad_arg<float>();
    EXPECT_EQ(rocblas_status_success, status);
}

TEST(checkin_blas1_bad_arg, nrm2_float)
{
    rocblas_status status = testing_nrm2_bad_arg<float, float>();
    EXPECT_EQ(rocblas_status_success, status);
}

TEST(checkin_blas1_bad_arg, scal_float) { testing_scal_bad_arg<float>(); }
TEST(checkin_blas1_bad_arg, swap_float) { testing_swap_bad_arg<float>(); }

TEST_P(parameterized, iamax_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_iamax<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, iamax_double)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_iamax<double>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, asum_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_asum<float, float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, axpy_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_axpy<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, axpy_double)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_axpy<double>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, axpy_half)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_axpy<rocblas_half>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, copy_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_copy<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, dot_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_dot<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, dot_double)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_dot<double>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, nrm2_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_nrm2<float, float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, scal_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_scal<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

TEST_P(parameterized, swap_float)
{
    // GetParam return a tuple. Tee setup routine unpack the tuple
    // and initializes arg(Arguments) which will be passed to testing routine
    // The Arguments data struture have physical meaning associated.
    // while the tuple is non-intuitive.
    Arguments arg = setup_blas1_arguments(GetParam());

    rocblas_status status = testing_swap<float>(arg);

    EXPECT_EQ(rocblas_status_success, status);
}

// Values is for a single item; ValuesIn is for an array
// notice we are using vector of vector
// so each elment in xxx_range is a avector,
// ValuesIn take each element (a vector) and combine them and feed them to test_p
// The combinations are  { N, {alpha, beta}, {incx, incy} }
INSTANTIATE_TEST_CASE_P(checkin_blas1,
                        parameterized,
                        Combine(ValuesIn(N_range),
                                ValuesIn(alpha_beta_range),
                                ValuesIn(incx_incy_range)));


text:
<?php
/**
 * This is a Anax-MVC front controller for the web site
 * "Allt om naturfotografering".
 */
require __DIR__ . '/config_with_app.php';

$app->url->setUrlType(\Anax\Url\CUrl::URL_CLEAN);

$app->navbar->configure(ANAX_APP_PATH . 'config/navbar.php');
$app->theme->configure(ANAX_APP_PATH . 'config/theme.php');

/**
 * The home page for the website.
 *
 * Views the presentation of the website and redirects to different
 * controllers to show latest questions, the most popular tags and
 * the most active users.
 */
$app->router->add('', function () use ($app) {
    $app->theme->setTitle("Allt om landskapsfotografering");

    $content = $app->fileContent->get('index.md');
    $content = $app->textFilter->doFilter($content, 'shortcode, markdown');

    $app->views->add('me/page', [
        'content' => $content
    ], 'main-wide');

    $app->dispatcher->forward([
        'controller' => 'questions',
        'action'     => 'list-latest',
        'params'     => [4],
    ]);

    $app->dispatcher->forward([
        'controller' => 'tags',
        'action'     => 'list-popular',
        'params'     => [6],
    ]);

    $app->dispatcher->forward([
        'controller' => 'users',
        'action'     => 'list-active',
        'params'     => [4],
    ]);
});

/**
 * List all questions.
 *
 * Redirects to the Question controller to list all questions.
 */
$app->router->add('questions', function () use ($app) {
    $app->dispatcher->forward([
        'controller' => 'questions',
        'action'     => 'list',
    ]);
});

/**
 * List all tags.
 *
 * Redirects to the Tags controller to list all tags.
 */
$app->router->add('tags', function () use ($app) {
    $app->dispatcher->forward([
        'controller' => 'tags',
        'action'     => 'list',
    ]);
});

/**
 * List all users.
 *
 * Redirects to the Users controller to list all users.
 */
$app->router->add('users', function () use ($app) {
    $app->dispatcher->forward([
        'controller' => 'users',
        'action'     => 'list',
    ]);
});

/**
 * Show information about the page and the creator.
 *
 * Views information about the website and a byline with information of
 * the creator of the website.
 */
$app->router->add('about', function () use ($app) {
    $app->theme->setTitle("Om Oss");

    $content = $app->fileContent->get('about.md');
    $content = $app->textFilter->doFilter($content, 'shortcode, markdown');

    $app->views->add('me/page', [
        'content' => $content
    ], 'main-wide');

    $bylineContent = $app->fileContent->get('about/byline.md');
    $bylineContent = $app->textFilter->doFilter($bylineContent, 'shortcode, markdown');

    $app->views->add('me/byline', [
        'content' => $bylineContent
    ], 'main-wide');

});

/**
 * Show form to log in.
 *
 * Redirects to the UserLogin controller to view a form to log in.
 */
$app->router->add('login', function () use ($app) {
    $app->theme->setTitle("Logga in");

    if ($app->LoggedIn->isLoggedin()) {

        $acronym = $app->LoggedIn->getAcronym() !== false ? $app->LoggedIn->getAcronym() : "";

        $content = [
            'title'         => 'Meddelande!',
            'subtitle'      => 'Du är redan inloggad',
            'message'       => 'Du är inloggad som ' . $acronym,
        ];

        $app->dispatcher->forward([
            'controller' => 'errors',
            'action'     => 'view',
            'params'     => [$content]
        ]);
    } else {
        $app->dispatcher->forward([
            'controller' => 'user-login',
            'action'     => 'login',
        ]);
    }
});

/**
 * Show the user profile of a user.
 *
 * Views information about the user and the user related activities.
 */
$app->router->add('profile', function () use ($app) {

    $userId = $app->LoggedIn->getUserId();
    $userId = $userId ? $userId : null;

    $app->theme->setTitle("Profil");
    $app->dispatcher->forward([
        'controller' => 'users',
        'action'     => 'id',
        'params'     => [$userId],
    ]);
});

/**
 * Show form to create an account to be able to sign in.
 *
 * Shows information about the benefits to be member and a form to create
 * an account.
 */
$app->router->add('registration', function () use ($app) {
    $app->theme->setTitle("Skapa Konto");

    $app->dispatcher->forward([
        'controller' => 'users',
        'action'     => 'add',
    ]);
});

$app->router->handle();
$app->theme->render();
//echo $app->logger->renderLog();
//


text:
YouTube Playlist App for iOS and Android
===

The app was built for the purpose of demonstrating how to build a native mobile app using Appcelerator Titanium. The app displays videos that are listed under the SamsungMobile YouTube channel. The app has no affiliations with Samsung, SamsungMobile or with the Samsung Group.

---

Screenshots (Android)
---

![image](https://github.com/leejaew/Playlist/blob/master/Screenshots/Screenshot_2014-01-26-16-51-14.png?raw=true =216x384) ![image](https://github.com/leejaew/Playlist/blob/master/Screenshots/Screenshot_2014-01-26-16-51-30.png?raw=true =216x384)

![image](https://github.com/leejaew/Playlist/blob/master/Screenshots/Screenshot_2014-01-26-16-52-29.png?raw=true =216x384) ![image](https://github.com/leejaew/Playlist/blob/master/Screenshots/Screenshot_2014-01-26-16-53-13.png?raw=true =216x384)

---

Demo Video (Android)
---
[![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/LgtwEWRsocw/0.jpg)](http://www.youtube.com/watch?v=LgtwEWRsocw)


text:
compile:
	@browserify client/index.js -o build/upload.js


text:
package controller

import (
	"fmt"
	"github.com/sequoiia/unifi-proper-portal/model"
	"github.com/sequoiia/unifi-proper-portal/unifi"
	"log"
	"net/http"
)

var Uclient *unifi.Client

func UniFiClientInit() {
	if Uclient == nil {
		Uclient = unifi.NewClient(&unifi.ClientConfig{
			Username:        Config.UniFi.Username,
			Password:        Config.UniFi.Password,
			UniFiBaseUrlRaw: Config.UniFi.BaseUrl,
			Site:            Config.UniFi.Site,
			InsecureMode:    Config.UniFi.InsecureMode,
		})

		err := Uclient.Login()
		if err != nil {
			log.Println(err)
		}
	}
}

func UniFiCallback(w http.ResponseWriter, r *http.Request) {
	UniFiClientInit()

	guestDetails := model.GetUniFiGuestFromCallback(r)

	var cookies []*http.Cookie = []*http.Cookie{
		{
			Name:   "UPP_clientmac",
			Value:  guestDetails.ClientMacAddress,
			Path:   "/",
			Domain: Config.Domain,
		},
		{
			Name:   "UPP_apmac",
			Value:  guestDetails.AccessPointMacAddress,
			Path:   "/",
			Domain: Config.Domain,
		},
		{
			Name:   "UPP_redirecturl",
			Value:  guestDetails.RedirectUrl,
			Path:   "/",
			Domain: Config.Domain,
		},
		{
			Name:   "UPP_ssid",
			Value:  guestDetails.Ssid,
			Path:   "/",
			Domain: Config.Domain,
		},
		{
			Name:   "UPP_timestamp",
			Value:  fmt.Sprintf("%d", guestDetails.Timestamp),
			Path:   "/",
			Domain: Config.Domain,
		},
	}

	for i := 0; i < len(cookies); i++ {
		http.SetCookie(w, cookies[i])
	}

	http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}


text:
export * from './Button'
export * from './Hello'


text:
angular.module('ot.service.form', [
    'ot.dialog.form',
    'ot.service.core'
])
/**
 * Form service
 */
    .service('otFormService', function ($filter, $q, $http, $modal, ot) {
        var self = {};

        /**
         * Getting the form content from its configuration
         */
        self.getForm = function (formConfig) {
            if (formConfig.form) {
                var d = $q.defer();
                d.resolve(formConfig.form);
                return d.promise;
            } else if (formConfig.uri) {
                return ot.call($http.get(formConfig.uri));
            } else {
                throw "Neither `uri` or `form` is set for the form config.";
            }
        };

        /**
         * Gets a form description and displays it
         * @param formConfig.postForm (optional) function used to configure the form before it is actually displayed
         * @param formConfig.form (optional) form definition
         * @param formConfig.uri (optional) URI to get the form from (either `uri` or `form` must be set)
         * @param formConfig.title Title for the dialog
         * @param formConfig.submit Function to call with the raw form data. See {@link #submitDialog}
         * @param formConfig.size 'sm' (default) or 'lg'
         * @param formConfig.buttons Additional buttons. List of {"title", action}.
         */
        self.display = function (formConfig) {
            var d = $q.defer();

            self.getForm(formConfig).then(function (form) {
                // Post form treatment
                if (formConfig.postForm) {
                    form = formConfig.postForm(form);
                }
                // Size
                var size = 'sm';
                if (formConfig.size) {
                    size = formConfig.size;
                }
                // Dialog
                $modal.open({
                    templateUrl: 'app/dialog/dialog.form.tpl.html',
                    controller: 'otDialogForm',
                    size: size,
                    resolve: {
                        config: function () {
                            return {
                                formConfig: formConfig,
                                form: form
                            };
                        }
                    }
                }).result.then(
                    function success(data) {
                        d.resolve(data);
                    },
                    function error() {
                        d.reject();
                    }
                );
            });

            return d.promise;
        };

        /**
         * Creating from a form, using POST
         */
        self.create = function (uri, title, additionalFormConfig) {
            var formConfig = {
                uri: uri,
                title: title,
                submit: function (data) {
                    return ot.call($http.post(uri, data));
                }
            };
            if (additionalFormConfig) {
                angular.extend(formConfig, additionalFormConfig);
            }
            return self.display(formConfig);
        };

        /**
         * Updating from a form, using PUT
         */
        self.update = function (uri, title, additionalFormConfig) {
            var formConfig = {
                uri: uri,
                title: title,
                submit: function (data) {
                    return ot.call($http.put(uri, data));
                }
            };
            if (additionalFormConfig) {
                angular.extend(formConfig, additionalFormConfig);
            }
            return self.display(formConfig);
        };

        /**
         * Prepares a form before being displayed
         */
        self.prepareForDisplay = function (form) {
            // Form data
            var data = {
                dates: {},
                times: {}
            };
            angular.forEach(form.fields, function (field) {
                data[field.name] = field.value;
                if (field.regex) {
                    field.pattern = new RegExp(field.regex);
                }
                // Date-time handling
                if (field.type == 'dateTime') {
                    if (field.value) {
                        var dateTime = new Date(field.value);
                        data.dates[field.name] = dateTime;
                        data.times[field.name] = dateTime;
                    }
                }
                // Date handling
                if (field.type == 'date') {
                    if (field.value) {
                        data.dates[field.name] = new Date(field.value);
                    }
                }
            });
            // OK
            return data;
        };

        /**
         * Prepares a form before being submitted
         */
        self.prepareForSubmit = function (form, data) {
            var date;
            // Processing before submit
            angular.forEach(form.fields, function (field) {
                // Date-time handling
                if (field.type == 'dateTime') {
                    date = data.dates[field.name];
                    var time = data.times[field.name];
                    var dateTime = date;
                    dateTime.setHours(time.getHours());
                    dateTime.setMinutes(time.getMinutes());
                    dateTime.setSeconds(0);
                    dateTime.setMilliseconds(0);
                    data[field.name] = dateTime;
                }
                // Date handling
                else if (field.type == 'date') {
                    date = data.dates[field.name];
                    if (date) {
                        data[field.name] = $filter('date')(date, 'yyyy-MM-dd');
                    } else {
                        data[field.name] = '';
                    }
                }
                // Multi-selection
                else if (field.type == 'multi-selection') {
                    data[field.name] = field.items
                        .filter(function (item) {
                            return item.selected;
                        })
                        .map(function (item) {
                            return item.id;
                        });
                }
                // Custom mapping
                else if (field.prepareForSubmit) {
                    field.prepareForSubmit(data);
                }
            });
            // Cleaning of pseudo fields
            delete data.dates;
            delete data.times;
            // OK
            return data;
        };

        /**
         * Updates the value for a field
         */
        self.updateFieldValue = function (form, fieldName, value) {
            angular.forEach(form.fields, function (field) {
                if (field.name == fieldName) {
                    field.value = value;
                }
            });
            return form;
        };

        /**
         * Updates all values of a form.
         */
        self.updateForm = function (form, data) {
            angular.forEach(form.fields, function (field) {
                field.value = data[field.name];
            });
        };

        /**
         * Gets a field in a form
         */
        self.getField = function (form, fieldName) {
            for (var i = 0; i < form.fields.length; i++) {
                var field = form.fields[i];
                if (field.name == fieldName) {
                    return field;
                }
            }
            throw "Could not find any field with name " + fieldName;
        };

        /**
         * Gets the value for a field in a form
         */
        self.getFieldValue = function (form, fieldName) {
            return self.getField(form, fieldName).value;
        };

        /**
         * Flexible submit method to be used in dialog controllers.
         *
         * The submitFn is expected to return:
         *

         *
a true value
, which then closes the dialog
         *
a String message, which is displayed as an error message and the dialog is not closed
         *
a Object or Array - the dialog is closed and this object is returned as a result
         *
a Promise which is called and its success result is used to close the dialog
         *     whereas its error is displayed in the dialog without closing it.
         *

         *
         * Returns a promise with the result.
         */
        self.submitDialog = function (submitFn, submitData, modalInstance, messageContainer) {
            var d = $q.defer();
            var submit = submitFn(submitData);
            if (submit === true) {
                modalInstance.close('ok');
            } else if (angular.isString(submit)) {
                messageContainer.message = submit;
            } else if (submit.then && angular.isFunction(submit.then)) {
                submit.then(
                    function success(data) {
                        modalInstance.close(data);
                        d.resolve(data);
                    },
                    function error(message) {
                        messageContainer.message = message;
                        d.reject(message);
                    });
            } else if (angular.isObject(submit) || angular.isArray(submit)) {
                modalInstance.close(submit);
                d.resolve(submit);
            } else {
                throw 'Cannot handle submit result type';
            }
            return d.promise;
        };

        return self;
    })
;


text:
package github.bewantbe.audio_analyzer_for_android;

import android.content.res.Resources;
import android.media.MediaRecorder;
import android.util.Log;

/**
 * Basic properties of Analyzer.
 */

class AnalyzerParameters {
    final int RECORDER_AGC_OFF = MediaRecorder.AudioSource.VOICE_RECOGNITION;
    int audioSourceId = RECORDER_AGC_OFF;
    int sampleRate = 16000;
    int fftLen = 2048;
    String wndFuncName;
    int nFFTAverage = 2;
    boolean isAWeighting = false;
    final int BYTE_OF_SAMPLE = 2;
    final double SAMPLE_VALUE_MAX = 32767.0;   // Maximum signal value
    double spectrogramDuration = 4.0;

    AnalyzerParameters(Resources res) {
        getAudioSourceNameFromIdPrepare(res);
    }

    String[] audioSourceNames;
    int[] audioSourceIDs;
    private void getAudioSourceNameFromIdPrepare(Resources res) {
        audioSourceNames   = res.getStringArray(R.array.audio_source);
        String[] sasid = res.getStringArray(R.array.audio_source_id);
        audioSourceIDs = new int[audioSourceNames.length];
        for (int i = 0; i < audioSourceNames.length; i++) {
            audioSourceIDs[i] = Integer.parseInt(sasid[i]);
        }
    }

    // Get audio source name from its ID
    // Tell me if there is better way to do it.
    String getAudioSourceNameFromId(int id) {
        for (int i = 0; i < audioSourceNames.length; i++) {
            if (audioSourceIDs[i] == id) {
                return audioSourceNames[i];
            }
        }
        Log.i("AnalyzerParameters", "getAudioSourceName(): non-standard entry.");
        return ((Integer)(id)).toString();
    }

    String getAudioSourceName() {
        return getAudioSourceNameFromId(audioSourceId);
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\EventListener;

use Sylius\Bundle\ApiBundle\Command\Cart\BlameCart;
use Sylius\Bundle\ApiBundle\SectionResolver\ShopApiOrdersSubSection;
use Sylius\Bundle\CoreBundle\SectionResolver\SectionProviderInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Context\CartNotFoundException;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

final class ApiCartBlamerListener
{
    private CartContextInterface $cartContext;

    private SectionProviderInterface $uriBasedSectionContext;

    private MessageBusInterface $commandBus;

    public function __construct(
        CartContextInterface $cartContext,
        SectionProviderInterface $uriBasedSectionContext,
        MessageBusInterface $commandBus
    ) {
        $this->cartContext = $cartContext;
        $this->uriBasedSectionContext = $uriBasedSectionContext;
        $this->commandBus = $commandBus;
    }

    public function onInteractiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
    {
        if (!$this->uriBasedSectionContext->getSection() instanceof ShopApiOrdersSubSection) {
            return;
        }

        $user = $interactiveLoginEvent->getAuthenticationToken()->getUser();
        if (!$user instanceof ShopUserInterface) {
            return;
        }

        $cart = $this->getCart();
        if (null === $cart || null !== $cart->getCustomer()) {
            return;
        }

        $this->commandBus->dispatch(new BlameCart($user->getEmail(), $cart->getTokenValue()));
    }

    /**
     * @throws UnexpectedTypeException
     */
    private function getCart(): ?OrderInterface
    {
        try {
            $cart = $this->cartContext->getCart();
        } catch (CartNotFoundException $exception) {
            return null;
        }

        if (!$cart instanceof OrderInterface) {
            throw new UnexpectedTypeException($cart, OrderInterface::class);
        }

        return $cart;
    }
}


text:
require 'spec_helper'
require 'support/database_connection'
require 'support/dummy_module'

describe ModelBuilder do

  let(:builder) { ModelBuilder }
  let(:name) { 'TestModel' }
  let(:constant) { name.constantize }
  let(:default_age) { 17 }
  let(:options) do
    {
      includes: [Spec::Support::DummyModule],
      attributes: {
        name: :string,
        age: {
          type: :integer,
          default: default_age
        }
      },
      validates: [
        [:name, :age, presence: true],
        [:age, numericality: true]
      ]
    }
  end

  before { @build_result = builder.build name, options }

  describe '.build' do

    subject { @build_result }

    it { is_expected.to eq constant }
    it { expect(builder.dynamic_models).to include name }

    context 'module validations' do
      let(:name) { 'ModelBuilder::TestModel' }

      it { is_expected.to eq ModelBuilder.const_get(name) }
    end

    context 'options validations' do

      before { subject }

      subject(:instance) { constant.new }

      context 'includes validations' do

        it { expect(instance).to respond_to :dummy_method }

      end

      context 'attributes validations' do

        it { is_expected.to respond_to :name }
        it { is_expected.to respond_to :age }

        it { is_expected.to respond_to :name= }
        it { is_expected.to respond_to :age= }

        it { expect(instance.age).to eq default_age }

      end

      context 'validations validations' do

        before do
          instance.age = 'noop'
          instance.valid?
        end

        it { expect(instance.valid?).to be false }
        it { expect(instance.errors.messages.keys).to include :name }
        it { expect(instance.errors.messages.keys).to include :age }

      end

    end

  end

  describe '.clean' do

    it { expect(constant.all.count).to eq 0 }

  end

end


text:
using System.Xml.Linq;

namespace Orchard.ImportExport.Models {
    public class ImportActionContext {
        public XDocument RecipeDocument { get; set; }
        public string ExecutionId { get; set; }
    }
}


text:
class Movie < ActiveRecord::Base
  has_many :libraries
  has_one :user, through: :libraries
end


text:
import os
import sys
import json
import shutil
import glob
import setuptools
import pybind11
import platform

static_library_option = '--static-library'
static_library_native_option = '--static-library-native'
static_library_avx2_option = '--static-library-avx2'
included_library_option = '--included-library'
shared_library_without_avx_option = '--shared-library-without-avx'
shared_library_option = '--shared-library'
shared_library_avx2_option = '--shared-library-avx2'
version_file = 'VERSION'
package = 'ngt'
module = 'ngtpy'

static_library = False
if static_library_option in sys.argv:
    print('use the NGT static library')
    sys.argv.remove(static_library_option)
    static_library = True

static_library_native = False
if static_library_native_option in sys.argv:
    print('use the NGT static library with native')
    sys.argv.remove(static_library_native_option)
    static_library_native = True

static_library_avx2 = False
if static_library_avx2_option in sys.argv:
    print('use the NGT static library with avx2')
    sys.argv.remove(static_library_avx2_option)
    static_library_avx2 = True
    package = 'ngt_qbg'
    module = 'ngtpy_qbg'

included_library = False
if included_library_option in sys.argv:
    print('use the NGT included library')
    sys.argv.remove(included_library_option)
    included_library = True

shared_library_without_avx = False
if shared_library_without_avx_option in sys.argv:
    print('use the shared library without avx')
    sys.argv.remove(shared_library_without_avx_option)
    shared_library_without_avx = True

shared_library = False
if shared_library_option in sys.argv:
    print('use the shared library')
    sys.argv.remove(shared_library_option)
    shared_library = True

shared_library_avx2 = False
if shared_library_avx2_option in sys.argv:
    print('use the shared library with avx2')
    sys.argv.remove(shared_library_avx2_option)
    shared_library_avx2 = True
    package = 'ngt_qbg'
    module = 'ngtpy_qbg'

if sys.version_info.major >= 3:
    from setuptools import Extension

if os.path.isfile('../' + version_file):
    shutil.copyfile('../' + version_file, version_file)

with open(version_file, 'r') as fh:
    version = fh.read().rstrip('\n')

basedir = os.path.abspath(os.path.dirname(__file__))

gcc_compiler = True
if platform.system() == 'Darwin':
    gcc_compiler = False
    if 'CC' in os.environ:
        if 'gcc' in os.environ['CC']:
            gcc_compiler = True

if gcc_compiler:
    openmplib = 'gomp'
else:
    openmplib = 'omp'

with open('README.md', 'r', encoding='utf-8') as fh:
    long_description = fh.read()

args = {
    'name': package,
    'version': version,
    'author': 'Yahoo! JAPAN research',
    'author_email': 'miwasaki@yahoo-corp.jp',
    'url': 'https://github.com/yahoojapan/NGT',
    'description': 'python NGT',
    'long_description': long_description,
    'long_description_content_type': 'text/markdown',
    'license': 'Apache License Version 2.0',
    'install_requires': ['numpy', 'pybind11']
}

if sys.version_info.major >= 3:
    if static_library or included_library or shared_library_without_avx:
        params = {
            'include_dirs': ['/usr/local/include',
                             pybind11.get_include(True),
                             pybind11.get_include(False)],
            'extra_compile_args': ['-std=c++11', '-Ofast', '-DNDEBUG'],
            'sources': ['src/ngtpy.cpp']
        }
    elif static_library_avx2 or shared_library_avx2:
        params = {
            'include_dirs': ['/usr/local/include',
                             pybind11.get_include(True),
                             pybind11.get_include(False)],
            'extra_compile_args': ['-std=c++11', '-Ofast', '-march=haswell', '-DNDEBUG'],
            'sources': ['src/ngtpy_avx2.cpp']
        }
    else:
        params = {
            'include_dirs': ['/usr/local/include',
                             pybind11.get_include(True),
                             pybind11.get_include(False)],
            'extra_compile_args': ['-std=c++11', '-Ofast', '-march=native', '-DNDEBUG'],
            'sources': ['src/ngtpy.cpp']
        }
    if gcc_compiler:
        params['extra_compile_args'].append('-fopenmp')
        params['extra_compile_args'].append('-lrt')
    else:
        params['extra_compile_args'].append('-Xpreprocessor')
        params['extra_compile_args'].append('-fopenmp')

    shared_lib_params = {
        'library_dirs': ['/usr/local/lib', '/usr/local/lib64'],
        'libraries': ['ngt', openmplib, 'blas', 'lapack']
    }
    included_lib_params = {
        'library_dirs': ['/usr/local/lib', '/usr/local/lib64'],
        'libraries': ['ngt', openmplib, 'blas', 'lapack'],
        'extra_link_args': ['-static-libstdc++']
    }
    static_lib_params = {
        'library_dirs': ['/usr/local/lib', '/usr/local/lib64'],
        'extra_objects': ['../build-ngtpy-release/lib/NGT/libngt.a'],
        'libraries': [openmplib, 'blas', 'lapack'],
    }
    if static_library or static_library_native or static_library_avx2:
        params.update(static_lib_params)
    elif included_library:
        params.update(included_lib_params)
    else:
        params.update(shared_lib_params)

    module1 = Extension(module, **params)
    args['ext_modules'] = [module1]

setup_arguments = args

if os.path.isdir('scripts'):
    setup_arguments['scripts'] = [
        os.path.join('scripts', f) for f in os.listdir('scripts')
    ]

if __name__ == '__main__':
    setuptools.setup(**setup_arguments)


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fr">
<context>
    <name>MainUI</name>
    <message>
        <location filename="../MainUI.ui" line="14"/>
        <source>Lumina Desktop Information</source>
        <translation>Informations sur l'environnement Lumina</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="60"/>
        <source>General</source>
        <translation>Général</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="89"/>
        <source>Source Repository</source>
        <translation>Dépôt Source</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="124"/>
        <source>Lumina Website</source>
        <translation>Site Web de Lumina</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="152"/>
        <source>Bug Reports</source>
        <translation>Rapports de Bugs</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="179"/>
        <source>Desktop Version:</source>
        <translation>Version de l'environnement:</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="202"/>
        <source>OS Build:</source>
        <translation>Build du Système d'Exploitation :</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="218"/>
        <source>Qt Version:</source>
        <translation>Version de Qt :</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="276"/>
        <source>Ask the Community</source>
        <translation>Demander à la Communauté</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="233"/>
        <source>View Information</source>
        <translation>Afficher les informations</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="298"/>
        <source>License</source>
        <translation>Licence</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="315"/>
        <source>Acknowledgements</source>
        <translation>Remerciements</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="333"/>
        <source>Project Lead:</source>
        <translation>Chef de projet :</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="340"/>
        <source>Ken Moore</source>
        <translation>Ken Moore</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="353"/>
        <source>Contributors:</source>
        <translation>Contributeurs :</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="366"/>
        <source>Sponsors:</source>
        <translation>Sponsors :</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="428"/>
        <source>Open in web browser</source>
        <translation>Ouvrir dans un navigateur web</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="454"/>
        <source>Close</source>
        <translation>Fermer</translation>
    </message>
</context>
<context>
    <name>XDGDesktopList</name>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="618"/>
        <source>Multimedia</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="619"/>
        <source>Development</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="620"/>
        <source>Education</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="621"/>
        <source>Games</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="622"/>
        <source>Graphics</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="623"/>
        <source>Network</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="624"/>
        <source>Office</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="625"/>
        <source>Science</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="626"/>
        <source>Settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="627"/>
        <source>System</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="628"/>
        <source>Utility</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="629"/>
        <source>Wine</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../libLumina/LuminaXDG.cpp" line="630"/>
        <source>Unsorted</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
Haevas.powerpill
===

[![Build Status](http://img.shields.io/travis/Haevas/Haevas.powerpill.svg?style=flat-square)](https://travis-ci.org/Haevas/Haevas.powerpill)
[![Galaxy](http://img.shields.io/badge/galaxy-Haevas.powerpill-blue.svg?style=flat-square)](https://galaxy.ansible.com/list#/roles/5797)

An Ansible role for installing `powerpill` on Arch Linux based systems.

#### Requirements & dependencies

None

#### Role Variables

```yaml
powerpill_enabled: yes                                 # The role in enabled
powerpill_sync_deps: yes                               # Sync db and base-devel
```

See [this file](defaults/main.yml) for a full list and their default values.

#### Usage

Add `Haevas.powerpill` to your roles and enable it.

```yaml
- hosts: all

  roles:
  - Haevas.powerpill

  vars:
  - powerpill_enabled: yes
  - powerpill_sync_deps: yes
```

#### Contributing

Issues, feature requests, ideas are [appreciated](https://github.com/Haevas/Haevas.powerpill/issues). Pull requests are also very welcome. Preferably, create a topic branch and when submitting, squash your commits into one (with a descriptive message).

#### License

BSD. See the LICENSE file for details.


text:
package com.lingganhezi.myapp.service.handler;

import com.lingganhezi.myapp.service.MessageService;
import android.database.Cursor;
import android.os.Message;

public class MessageQueryHandler extends BaseServiceHandler<Cursor> {

	/**
	 *
	 * @param callback
	 *            Cursor类型,代表 message 所在的游标
	 */
	public MessageQueryHandler(Callback<Cursor> callback) {
		super();
		mCallback = callback;
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case MessageService.MSG_QUERY_MESSAGE_SUCCESS:
			callCallback(msg, true);
			break;
		default:
			callCallback(msg, false);
			break;
		}

		super.handleMessage(msg);
	}

}


text:
import React from 'react';
import Product from './Product';

class ProductsTable extends React.Component {

	render(){
			var rows = [];
			this.props.products.forEach( (product)=> {
				rows.push(<Product product={product} key={product.name} />);
			});

		return (

							Name
							SKU
							Sale Price

{rows}

			);
	}
}
module.exports = ProductsTable;


text:
"""Models for Text and Image Composition."""

import math
import numpy as np
import torch
import torchvision
import torch.nn.functional as F
from transformers import BertTokenizer, BertModel, BertForMaskedLM, BertConfig

class BertTextEncoder(torch.nn.Module):
  """Base class for image + text composition."""

  def __init__(self, pretrained=True, img_dim=256):
    super(BertTextEncoder, self).__init__()
    self.tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
    self.pretrained = pretrained
    ### Define an attention module using concat and additive
    self.query1 = torch.nn.Linear(768+img_dim, 512)
    self.key1 = torch.nn.Linear(768, 512)
    self.value1 = torch.nn.Linear(768, 512)
    self.query2 = torch.nn.Linear(768+img_dim, 512)
    self.key2 = torch.nn.Linear(768, 512)
    self.value2 = torch.nn.Linear(768, 512)
    if not pretrained:
      config = BertConfig.from_pretrained('bert-base-cased')
      config.hidden_size = 768
      config.num_attention_heads = 12
      self.textmodel = BertModel(config)
    else:
      self.textmodel = BertModel.from_pretrained('bert-base-cased')
      #self.downsample = torch.nn.Linear(768,512)

  def extract_text_feature(self, texts, img1d):
    x = []
    xlen = []
    mask = []
    attmask = []
    text_tokens = []
    for text in texts:
      t = '[CLS] '+text[0].upper()+text[1:]+' [SEP]'
      tokenized_text = self.tokenizer.tokenize(t)
      text_tokens.append(tokenized_text)
      indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text)
      x.append(indexed_tokens)
      xlen.append(len(indexed_tokens))
    maxlen = max(xlen)
    for i in range(len(x)):
      mask.append([0]+[1]*(xlen[i]-2)+[0]*(maxlen-xlen[i]+1))
      attmask.append([1]*(xlen[i])+[0]*(maxlen-xlen[i]))
      x[i] = x[i]+[0]*(maxlen-xlen[i])
    x = torch.tensor(x)
    mask = torch.tensor(mask, dtype=torch.float).unsqueeze(2)
    attmask = torch.tensor(attmask, dtype=torch.float).unsqueeze(2)
    itexts = torch.autograd.Variable(x).cuda()
    mask = torch.autograd.Variable(mask).cuda()
    attmask = torch.autograd.Variable(attmask).cuda()
    out = self.textmodel(itexts, attention_mask = attmask)
    xlen = (torch.tensor(xlen, dtype = torch.float)-2).view(-1,1).data.cuda()#remove special token
    assert tuple(out[0].shape) == (x.size()[0], maxlen, self.textmodel.config.hidden_size)

    puretext = torch.div(torch.sum(torch.mul(out[0],mask), dim=1),xlen)
    comb = torch.cat((puretext, img1d),dim=1).unsqueeze(1)
    masked_out = torch.mul(out[0],mask)
    mask_sfmax = (1-mask)*-10000.0

    query1 = self.query1(comb)
    key1 = self.key1(masked_out)
    value1 = self.value1(masked_out)
    logit1 = torch.sum(query1*key1,dim=2)/math.sqrt(512)+mask_sfmax[:,:,0]
    attn1 = torch.nn.functional.softmax(logit1,dim=1)
    out1 = torch.sum(attn1.unsqueeze(2)*value1,dim=1)

    query2 = self.query2(comb)
    key2 = self.key2(masked_out)
    value2 = self.value2(masked_out)
    logit2 = torch.sum(query2*key2,dim=2)/math.sqrt(512)+mask_sfmax[:,:,0]
    attn2 = torch.nn.functional.softmax(logit2,dim=1)
    out2 = torch.sum(attn2.unsqueeze(2)*value2,dim=1)

    rawtext = torch.cat((puretext, torch.zeros((puretext.shape[0],1024-768),device=puretext.device)),dim=1)
    return (out1, attn1), (out2, attn2), text_tokens,  rawtext


text:
[Week 1 Home](../)

# Computer Set-Up Instructions - Mac

## Learning Competencies
By the end of this lesson, you should be able to:
- Install technologies from the command line
- Clone and run scripts from a repository

## Summary
You will need to have your computer set up with the following tools for Phase 0 of Dev Bootcamp. Make sure to go through this guide step-by-step. You'll need to have each of these technologies installed to have a smooth start to Phase 0 and your future career!

While it's definitely possible to go through Phase 0 using Windows, you'll generally be much happier if you have OS X or at least Linux. This tutorial will cover the setup for a Mac.

## Releases
(i.e. directions - each release is necessary for the next release, so be sure to do everything in the order specified for all challenges)

## Release 0: Download Sublime Text
Download and follow instructions from [their site](http://www.sublimetext.com). Make sure to move it to your applications folder. You can choose to download either Sublime Text 2 or 3.

You don't have to purchase your license right away, you can "cancel" out of the dialog box as many times as you would like, but it is good practice to buy a license after you decide you like it. (Since eventually you're hoping to get paid for writing programs, you want to pay it forward in advance.)

## Release 1: Your Operating System
If you are using OS X, you should upgrade to Mavericks if you haven't already. You can get it from the App Store on your computer and it's free. To find out which operating system you're running, open the "About this Mac," Under OS X, you should see a version. Mavericks (10.9) and Yosemite (10.10) will both work for Phase 0.

Before installing, it's always good practice to backup your hard drive so you don't lose anything!

## Release 2: Install Command Line Tools
Release 2 - 12 will be run in your terminal. So open it, and type:

```shell
xcode-select --install
```

Follow the prompts to complete the install.

This is apple's C compiler which will enable you to compile native apps from source. (i.e. Ruby)

If you can't find the terminal, simply search "terminal" in spotlight.

## Release 3: Install Homebrew
Also called "Brew." Brew is like the app store for the command line (i.e. your terminal). If you ever need any command-line tool, try installing with Brew before other methods. (ex. ```brew install name-of-thing```)

Install brew by copying and pasting this beautiful code into your terminal:

```shell
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
It will prompt you for your password - so be ready to type it in.

## Release 4: Set up your Path
First you need to clone this GitHub repository into your computer and install the files. Type each line separately:

```shell
git clone https://github.com/supertopher/dotfiles.git
cd dotfiles
./install
```
**Note** This will change how your current terminal will appear. Check your .bash_profile to see what we changed!

Installing these files will configure your bash profile, enable autocomplete, always display rspec with color, and allow you to use "subl" as a shortcut to open sublime.

## Release 5: Configure Git
You then need to overwrite .gitconfig to your own username and password in GitHub. Use your name and your GitHub email address in the following format:

```shell
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com
```

Now make Sublime text your preferred editor for git:
```shell
git config --global core.editor "subl -w"
```

## Release 6: Set up Sublime
Follow [these instructions](https://github.com/Devbootcamp/phase-0-handbook/blob/master/text-editor-setup.md) in the Phase 0 Handbook to make Sublime your default text editor.

## Release 7: Install Rbenv
Type: ```brew install rbenv```

Now you have Rbenv! Sweet!

**NOTE:** If you already have RVM installed, you will not need to install Rbenv. Do not try to install both, they don't work well together and will mess up your machine. Rbenv is preferred in many of our locations, so if you have RVM and want to install Rbenv, you'll have to uninstall RVM first.

## Release 8: Install Ruby Build
Type: ```brew install ruby-build```

Rbenv uses this to install individual versions of Ruby. (Did you know you can have multiple versions of Ruby on your machine?)

**NOTE:** If you are using RVM instead of rbenv, you will not need to install ruby-build.

## Release 9: Install Ruby 2.0.0
Type: ```rbenv install 2.0.0-p481```

Now, you need to set the default Ruby in your computer to the Ruby we just installed.

Type: ``` rbenv global 2.0.0-p481```

**Restart your terminal**

NOTE: You just installed Ruby 2.0.0 as your default. When you are reading the Ruby Docs, make sure you are referring to this version, NOT Ruby 2.1.0.

## Release 10: Install Git
Type: ```brew install git```

This installs git and autocompletion for git.

## Release 11: Install Node
Node allows you to run Javascript in your terminal.

Type: ```brew install node```

You'll use this later in Phase 0.

## Release 12: Install Rspec
Type ```gem install rspec```

This will install RSpec, a Ruby testing framework.

**Important note: You should NEVER need to `sudo gem install ___` anything. If you get a permission issue, that means your system isn't using the rbenv/rvm version of rubygems.**

Go back to Release 9 and make sure you typed the second command to set your global version of Ruby.

## Release 13: Install SQLite
Type ```brew install SQLite3```

To overwrite your system copy of SQLite, we need to type an additional command:

```brew link sqlite3 --force```

## Release 14: Install Postgres
Type the following commands one at a time:

NOTE: If you have trouble installing postgres, don't worry about it. You won't need it until Phase 2. We wanted to have it set up in advance when your path was all sqeakly clean and wonderful, but if you have trouble, just move on.

```shell
brew install postgres
mkdir -p $HOME/Library/LaunchAgents
ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
```

You are now ready to start Phase 0!


text:
package org.waveprotocol.wave.model.experimental.schema;

/**
 * The result of the validation of attributes.
 *
 */
public abstract class AttributeValidationResult {

  /**
   * The type of the validation result.
   */
  public enum Type {
    VALID,
    ATTRIBUTE_NOT_ALLOWED,
    INVALID_ATTRIBUTE_VALUE,
    MISSING_REQUIRED_ATTRIBUTE,
    REMOVING_REQUIRED_ATTRIBUTE
  }

  /**
   * A result indicating the existence of an attribute that is not allowed.
   */
  public static final class AttributeNotAllowed extends AttributeValidationResult {

    private final String name;

    AttributeNotAllowed(String name) {
      this.name = name;
    }

    @Override
    public Type getType() {
      return Type.ATTRIBUTE_NOT_ALLOWED;
    }

    @Override
    public AttributeNotAllowed asAttributeNotAllowed() {
      return this;
    }

    /**
     * Returns the name of the disallowed attribute that was encountered.
     */
    public String getName() {
      return name;
    }

    @Override
    public String toString() {
      return "Attribute not allowed: " + name;
    }

  }

  /**
   * A result indicating that an attribute has an invalid value.
   */
  public static final class InvalidAttributeValue extends AttributeValidationResult {

    private final String name;
    private final String value;

    InvalidAttributeValue(String name, String value) {
      this.name = name;
      this.value = value;
    }

    @Override
    public Type getType() {
      return Type.INVALID_ATTRIBUTE_VALUE;
    }

    @Override
    public InvalidAttributeValue asInvalidAttributeValue() {
      return this;
    }

    /**
     * Returns the name of the attribute with the invalid value.
     */
    public String getName() {
      return name;
    }

    /**
     * Returns the invalid attribute value.
     */
    public String getValue() {
      return value;
    }

    @Override
    public String toString() {
      return "Invalid value for attribute " + name + ": " + value;
    }

  }

  /**
   * A result indicating that a required attribute is missing.
   */
  public static final class MissingRequiredAttribute extends AttributeValidationResult {

    private final String name;

    MissingRequiredAttribute(String name) {
      this.name = name;
    }

    @Override
    public Type getType() {
      return Type.MISSING_REQUIRED_ATTRIBUTE;
    }

    @Override
    public MissingRequiredAttribute asMissingRequiredAttribute() {
      return this;
    }

    /**
     * Returns the name of the missing required attribute.
     */
    public String getName() {
      return name;
    }

    @Override
    public String toString() {
      return "Required attribute missing: " + name;
    }

  }

  /**
   * A result indicating that an attribute update attempts to remove a required attribute.
   */
  public static final class RemovingRequiredAttribute extends AttributeValidationResult {

    private final String name;

    RemovingRequiredAttribute(String name) {
      this.name = name;
    }

    @Override
    public Type getType() {
      return Type.REMOVING_REQUIRED_ATTRIBUTE;
    }

    @Override
    public RemovingRequiredAttribute asRemovingRequiredAttribute() {
      return this;
    }

    /**
     * Returns the name the of required attribute whose removal was attempted.
     */
    public String getName() {
      return name;
    }

    @Override
    public String toString() {
      return "Attempt to remove required attribute: " + name;
    }

  }

  /**
   * A result indicating that nothing invalid was encountered.
   */
  public static final AttributeValidationResult VALID = new AttributeValidationResult() {

    @Override
    public Type getType() {
      return Type.VALID;
    }

    @Override
    public String toString() {
      return "Valid";
    }

  };

  private AttributeValidationResult() {}

  /**
   * Returns the type of the validation result.
   */
  public abstract Type getType();

  /**
   * Returns this object if it is an AttributeNotAllowed, or null
   * otherwise.
   */
  public AttributeNotAllowed asAttributeNotAllowed() {
    return null;
  }

  /**
   * Returns this object if it is an InvalidAttributeValue, or null
   * otherwise.
   */
  public InvalidAttributeValue asInvalidAttributeValue() {
    return null;
  }

  /**
   * Returns this object if it is an MissingRequiredAttribute, or
   * null otherwise.
   */
  public MissingRequiredAttribute asMissingRequiredAttribute() {
    return null;
  }

  /**
   * Returns this object if it is an RemovingRequiredAttribute, or
   * null otherwise.
   */
  public RemovingRequiredAttribute asRemovingRequiredAttribute() {
    return null;
  }

}