text:
package org.apache.camel.component.jdbc;

import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

/**
 * Unit test based on user forum request about this component
 */
public class JdbcAnotherRouteTest extends AbstractJdbcTestSupport {

    @EndpointInject("mock:result")
    private MockEndpoint mock;

    @Test
    public void testTimerInvoked() throws Exception {
        mock.expectedMinimumMessageCount(1);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                // trigger every second
                from("timer://kickoff?period=1000").
                    setBody(constant("select * from customer")).
                    to("jdbc:testdb").
                    to("mock:result");
            }
        };
    }
}


text:
package squidpony.squidgrid.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import squidpony.squidmath.Bresenham;
import squidpony.squidmath.Coord3D;
import squidpony.squidmath.RNG;

/**
 * Provides utilities for working with colors as well as caching operations for
 * color creation.
 *
 * All returned SColor objects are cached so multiple requests for the same
 * SColor will not create duplicate long term objects.
 *
 * @author Eben Howard - http://squidpony.com - howard@squidpony.com
 */
public class SColorFactory {

    private static final TreeMap<String, SColor> nameLookup = new TreeMap<>();
    private static final TreeMap<Integer, SColor> valueLookup = new TreeMap<>();
    private static RNG rng = new RNG();
    private static Map<Integer, SColor> colorBag = new HashMap<>();
    private static Map<String, ArrayList<SColor>> palettes = new HashMap<>();
    private static int floor = 1;//what multiple to floor rgb values to in order to reduce total colors

    /**
     * Prevents any instances from being created.
     */
    private SColorFactory() {
    }

    /**
     * Returns the SColor Constant who's name is the one provided. If one cannot
     * be found then null is returned.
     *
     * This method constructs a list of the SColor constants the first time it
     * is called.
     *
     * @param s
     * @return
     */
    public static SColor colorForName(String s) {
        if (nameLookup.isEmpty()) {
            for (SColor sc : SColor.FULL_PALETTE) {
                nameLookup.put(sc.getName(), sc);
            }
        }

        return nameLookup.get(s);
    }

    /**
     * Returns the SColor who's value matches the one passed in. If no SColor
     * Constant matches that value then a cached or new SColor is returned that
     * matches the provided value.
     *
     * This method constructs a list of the SColor constants the first time it
     * is called.
     *
     * @param rgb
     * @return
     */
    public static SColor colorForValue(int rgb) {
        if (valueLookup.isEmpty()) {
            for (SColor sc : SColor.FULL_PALETTE) {
                valueLookup.put(sc.getRGB(), sc);
            }
        }

        return valueLookup.containsKey(rgb) ? valueLookup.get(rgb) : asSColor(rgb);
    }

    /**
     * Returns the number of SColor objects currently cached.
     *
     * @return
     */
    public static int quantityCached() {
        return colorBag.size();
    }

    /**
     * Utility method to blend the two colors by the amount passed in as the
     * coefficient.
     *
     * @param a
     * @param b
     * @param coef
     * @return
     */
    private static int blend(int a, int b, double coef) {
        coef = Math.min(1, coef);
        coef = Math.max(0, coef);
        return (int) (a + (b - a) * coef);
    }

    /**
     * Returns an SColor that is the given distance from the first color to the
     * second color.
     *
     * @param color1 The first color
     * @param color2 The second color
     * @param coef The percent towards the second color, as 0.0 to 1.0
     * @return
     */
    public static SColor blend(SColor color1, SColor color2, double coef) {
        return asSColor(blend(color1.getAlpha(), color2.getAlpha(), coef),
                blend(color1.getRed(), color2.getRed(), coef),
                blend(color1.getGreen(), color2.getGreen(), coef),
                blend(color1.getBlue(), color2.getBlue(), coef));
    }

    /**
     * Returns an SColor that is randomly chosen from the color line between the
     * two provided colors from the two provided points.
     *
     * @param color1
     * @param color2
     * @param min The minimum percent towards the second color, as 0.0 to 1.0
     * @param max The maximum percent towards the second color, as 0.0 to 1.0
     * @return
     */
    public static SColor randomBlend(SColor color1, SColor color2, double min, double max) {
        return blend(color1, color2, rng.between(min, max));
    }

    /**
     * Adds the two colors together.
     *
     * @param color1
     * @param color2
     * @return
     */
    public static SColor add(SColor color1, SColor color2) {
        return asSColor(color1.getAlpha() + color2.getAlpha(), color1.getRed() + color2.getRed(), color1.getGreen() + color2.getGreen(), color1.getBlue() + color2.getBlue());
    }

    /**
     * Uses the second color as a light source, meaning that each of the red,
     * green, and blue values of the first color are multiplied by the lighting
     * color's percentage of full value (255).
     *
     * @param color
     * @param light
     * @return
     */
    public static SColor lightWith(SColor color, SColor light) {
        return asSColor((int) (color.getAlpha() * light.getAlpha() / 255f), (int) (color.getRed() * light.getRed() / 255f), (int) (color.getGreen() * light.getGreen() / 255f), (int) (color.getBlue() * light.getBlue() / 255f));
    }

    /**
     * Clears the backing cache.
     *
     * Should only be used if an extreme number of colors are being created and
     * then not reused, such as when blending different colors in different
     * areas that will not be revisited.
     */
    public static void emptyCache() {
        colorBag = new HashMap<>();
    }

    /**
     * Sets the value at which each of the red, green, and blue values will be
     * set to the nearest lower multiple of.
     *
     * For example, a floor value of 5 would mean that each of those values
     * would be considered the nearest lower multiple of 5 when building the
     * colors.
     *
     * If the value passed in is less than 1, then the flooring value is set at
     * 1.
     *
     * @param value
     */
    public static void setFloor(int value) {
        floor = Math.max(1, value);
    }

    /**
     * Returns the cached color that matches the desired rgb value.
     *
     * If the color is not already in the cache, it is created and added to the
     * cache.
     *
     * This method does not check to see if the value is already available as a
     * SColor constant. If such functionality is desired then please use
     * colorForValue(int rgb) instead.
     *
     * @param argb
     * @return
     */
    public static SColor asSColor(int argb) {
        int working = argb;
        if (floor != 1) {//need to convert to floored values
            int a = (argb >> 24) & 0xff;
            a -= a % floor;
            int r = (argb >> 16) & 0xff;
            r -= r % floor;
            int g = (argb >> 8) & 0xff;
            g -= g % floor;
            int b = argb & 0xff;
            b -= b % floor;

            //put back together
            working = ((a & 0xFF) << 24)
                    | ((r & 0xFF) << 16)
                    | ((g & 0xFF) << 8)
                    | (b & 0xFF);
        }

        if (colorBag.containsKey(working)) {
            return colorBag.get(working);
        } else {
            SColor color = new SColor(working);
            colorBag.put(working, color);
            return color;
        }
    }

    /**
     * Returns an SColor that is opaque.
     *
     * @param r
     * @param g
     * @param b
     * @return
     */
    public static SColor asSColor(int r, int g, int b) {
        return asSColor(255, r, g, b);
    }

    /**
     * Returns an SColor with the given values, with those values clamped
     * between 0 and 255.
     *
     * @param a
     * @param r
     * @param g
     * @param b
     * @return
     */
    public static SColor asSColor(int a, int r, int g, int b) {
        a = Math.min(a, 255);
        a = Math.max(a, 0);
        r = Math.min(r, 255);
        r = Math.max(r, 0);
        g = Math.min(g, 255);
        g = Math.max(g, 0);
        b = Math.min(b, 255);
        b = Math.max(b, 0);
        return asSColor(a * 256 * 256 * 256 + r * 256 * 256 + g * 256 + b);
    }

    /**
     * Returns an SColor representation of the provided Color. If there is a
     * named SColor constant that matches the value, then that constant is
     * returned.
     *
     * @param color
     * @return
     */
    public static SColor asSColor(Color color) {
        return colorForValue(color.getRGB());
    }

    /**
     * Returns an SColor that is a slightly dimmer version of the provided
     * color.
     *
     * @param color
     * @return
     */
    public static SColor dim(SColor color) {
        return blend(color, SColor.BLACK, 0.1);
    }

    /**
     * Returns an SColor that is a somewhat dimmer version of the provided
     * color.
     *
     * @param color
     * @return
     */
    public static SColor dimmer(SColor color) {
        return blend(color, SColor.BLACK, 0.3);
    }

    /**
     * Returns an SColor that is a lot darker version of the provided color.
     *
     * @param color
     * @return
     */
    public static SColor dimmest(SColor color) {
        return blend(color, SColor.BLACK, 0.7);
    }

    /**
     * Returns an SColor that is a slightly lighter version of the provided
     * color.
     *
     * @param color
     * @return
     */
    public static SColor light(SColor color) {
        return blend(color, SColor.WHITE, 0.1);
    }

    /**
     * Returns an SColor that is a somewhat lighter version of the provided
     * color.
     *
     * @param color
     * @return
     */
    public static SColor lighter(SColor color) {
        return blend(color, SColor.WHITE, 0.3);
    }

    /**
     * Returns an SColor that is a lot lighter version of the provided color.
     *
     * @param color
     * @return
     */
    public static SColor lightest(SColor color) {
        return blend(color, SColor.WHITE, 0.6);
    }

    /**
     * Returns an SColor that is the fully desaturated (greyscale) version of
     * the provided color.
     *
     * @param color
     * @return
     */
    public static SColor desaturated(SColor color) {
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        int average = (int) (r * 0.299 + g * 0.587 + b * 0.114);

        return asSColor(average, average, average);
    }

    /**
     * Returns an SColor that is the version of the provided color desaturated
     * the given amount.
     *
     * @param color
     * @param percent The percent to desaturate, from 0.0 for none to 1.0 for
     * fully desaturated
     * @return
     */
    public static SColor desaturate(SColor color, double percent) {
        return blend(color, desaturated(color), percent);
    }

    /**
     * Returns a list of colors starting at the first color and moving to the
     * second color. The end point colors are included in the list.
     *
     * @param color1
     * @param color2
     * @return
     */
    public static ArrayList<SColor> asGradient(SColor color1, SColor color2) {
        String name = paletteNamer(color1, color2);
        if (palettes.containsKey(name)) {
            return palettes.get(name);
        }

        //get the gradient
        Queue<Coord3D> gradient = Bresenham.line3D(scolorToCoord3D(color1), scolorToCoord3D(color2));
        ArrayList<SColor> ret = new ArrayList<>();
        for (Coord3D coord : gradient) {
            ret.add(coord3DToSColor(coord));
        }

        palettes.put(name, ret);
        return ret;
    }

    /**
     * Returns the palette associate with the provided name, or null if there is
     * no such palette.
     *
     * @param name
     * @return
     */
    public static ArrayList<SColor> palette(String name) {
        return palettes.get(name);
    }
    /**
     * Returns the palette associate with the provided name, or null if there is
     * no such palette.
     *
     * @param name
     * @return
     *
     * @deprecated Prefer palette
     */
    public static ArrayList<SColor> pallet(String name) {
        return palettes.get(name);
    }

    /**
     * Returns the SColor that is the provided percent towards the end of the
     * palette. Bounds are checked so as long as there is at least one color in
     * the palette, values below 0 will return the first element and values
     * above 1 will return the last element;
     *
     * If there is no palette keyed to the provided name, null is returned.
     *
     * @param name
     * @param percent
     * @return
     */
    public static SColor fromPalette(String name, float percent) {
        ArrayList<SColor> list = palettes.get(name);
        if (list == null) {
            return null;
        }

        int index = Math.round(list.size() * percent);//find the index that's the given percent into the gradient
        index = Math.min(index, list.size() - 1);
        index = Math.max(index, 0);
        return list.get(index);
    }
    /**
     * Returns the SColor that is the provided percent towards the end of the
     * palette. Bounds are checked so as long as there is at least one color in
     * the palette, values below 0 will return the first element and values
     * above 1 will return the last element;
     *
     * If there is no palette keyed to the provided name, null is returned.
     *
     * @param name
     * @param percent
     * @return
     *
     * @deprecated Prefer fromPalette
     */
    public static SColor fromPallet(String name, float percent) {
        ArrayList<SColor> list = palettes.get(name);
        if (list == null) {
            return null;
        }

        int index = Math.round(list.size() * percent);//find the index that's the given percent into the gradient
        index = Math.min(index, list.size() - 1);
        index = Math.max(index, 0);
        return list.get(index);
    }

    /**
     * Presents a pop-up JColorChooser dialog showing all of the SColor
     * constants along with examples of what the various dimming and lightening
     * methods change them to..
     *
     * @param parent The component which is the parent of this dialog
     * @return the SColor that is chosen in the dialog
     */
    public static SColor showSColorChooser(Component parent) {
        final JColorChooser chooser = new JColorChooser();
        chooser.setChooserPanels(new AbstractColorChooserPanel[]{new SColorChooserPanel()});

        JDialog dialog = JColorChooser.createDialog(parent, "Choose A Color", true, chooser, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pickedColor = asSColor(chooser.getColor().getRGB());
            }
        }, null);
        dialog.setLocationRelativeTo(parent);
        dialog.setVisible(true);

        return pickedColor;
    }
    private static SColor pickedColor;//needed for the color chooser

    /**
     * Places the palette into the cache, along with each of the member colors.
     *
     * @param name
     * @param palette
     */
    public static void addPalette(String name, ArrayList<SColor> palette) {
        ArrayList<SColor> temp = new ArrayList<>();

        //make sure all the colors in the palette are also in the general color cache
        for (SColor sc : palette) {
            temp.add(asSColor(sc.getRGB()));
        }

        palettes.put(name, temp);
    }
    /**
     * Places the palette into the cache, along with each of the member colors.
     *
     * @param name
     * @param palette
     *
     * @deprecated Prefer addPalette
     */
    public static void addPallet(String name, ArrayList<SColor> palette) {
        ArrayList<SColor> temp = new ArrayList<>();

        //make sure all the colors in the palette are also in the general color cache
        for (SColor sc : palette) {
            temp.add(asSColor(sc.getRGB()));
        }

        palettes.put(name, temp);
    }

    /**
     * Converts the provided color into a three dimensional coordinate point for
     * use in the Bresenham algorithms.
     *
     * @param color
     * @return
     */
    private static Coord3D scolorToCoord3D(SColor color) {
        return new Coord3D(color.getRed(), color.getGreen(), color.getBlue());
    }

    /**
     * Converts the provided three dimensional coordinate into a color for use
     * in the Bresenham algorithms.
     *
     * @param coord
     * @return
     */
    private static SColor coord3DToSColor(Coord3D coord) {
        return asSColor(coord.x, coord.y, coord.z);
    }

    private static String paletteNamer(SColor color1, SColor color2) {
        return color1.getName() + " to " + color2.getName();
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
// Created by Administrator on 3/6/2016.
//

#ifndef NATIVEOPERATIONS_ND4JMALLOC_H
#define NATIVEOPERATIONS_ND4JMALLOC_H
#include <cstdlib>
#endif //NATIVEOPERATIONS_ND4JMALLOC_H


text:
package com.sap.mlt.xliff12.impl.rfc4646;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

abstract class SubtagSet implements Serializable, Cloneable, Iterable<Subtag>,
		Comparable<SubtagSet> {

	private static final long serialVersionUID = 1L;

	private Subtag primary;

	protected SubtagSet(Subtag primary) {
		this.primary = primary;
	}

	public String toString() {
		StringBuilder buf = new StringBuilder();
		for (Subtag subtag : this) {
			if (buf.length() > 0)
				buf.append('-');
			buf.append(subtag.getName());
		}
		return buf.toString();
	}

	public Iterator<Subtag> iterator() {
		return new SubtagIterator(primary);
	}

	public boolean contains(Subtag subtag) {
		for (Subtag tag : this)
			if (tag.equals(subtag))
				return true;
		return false;
	}

	public boolean contains(String tag) {
		return contains(tag, Subtag.Type.SIMPLE);
	}

	public boolean contains(String tag, Subtag.Type type) {
		return contains(new Subtag(type, tag));
	}

	public int length() {
		return toString().length();
	}

	public boolean isValid() {
		for (Subtag subtag : this)
			if (!subtag.isValid())
				return false;
		return true;
	}

	@SuppressWarnings("unused")
	public int count() {
		int n = 0;
		for (Subtag tag : this)
			n++;
		return n;
	}

	public Subtag get(int index) {
		if (index < 0 || index >= count())
			throw new IndexOutOfBoundsException();
		Subtag tag = primary;
		for (int n = 1; n <= index; n++)
			tag = tag.getNext();
		return tag;
	}

	static class SubtagIterator implements Iterator<Subtag> {
		private Subtag current;

		SubtagIterator(Subtag current) {
			this.current = current;
		}

		public boolean hasNext() {
			return current != null;
		}

		public Subtag next() {
			Subtag tag = current;
			current = tag.getNext();
			return tag;
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		for (Subtag tag : this)
			result = prime * result + tag.hashCode();
		return result;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final SubtagSet other = (SubtagSet) obj;
		if (count() != other.count()) {
			return false;
		}
		Iterator<Subtag> i1 = iterator();
		Iterator<Subtag> i2 = other.iterator();
		while (i1.hasNext()) {
			Subtag subtag1 = i1.next();
			Subtag subtag2 = i2.next();
			if (!subtag1.toString().equals(subtag2.toString())) {
				return false;
			}
		}
		return true;
	}

	public Subtag[] toArray() {
		List<Subtag> tags = new LinkedList<Subtag>();
		for (Subtag tag : this)
			tags.add(tag);
		return tags.toArray(new Subtag[tags.size()]);
	}

	public List<Subtag> asList() {
		return Arrays.asList(toArray());
	}

	public int compareTo(SubtagSet o) {
		Iterator<Subtag> i = iterator();
		Iterator<Subtag> e = o.iterator();
		for (; i.hasNext() && e.hasNext();) {
			Subtag inext = i.next();
			Subtag enext = e.next();
			int c = inext.compareTo(enext);
			if (c != 0)
				return c;
		}
		if (e.hasNext() && !i.hasNext())
			return -1;
		if (i.hasNext() && !e.hasNext())
			return 1;
		return 0;
	}

	@Override
	protected SubtagSet clone() {
		try {
			SubtagSet clone = (SubtagSet) super.clone();
			clone.primary = clone.primary.clone();
			return clone;
		} catch (CloneNotSupportedException e) {
			throw new AssertionError(e);
		}
	}

	protected Subtag getPrimary() {
		return primary;
	}
}


text:
void lowered_privilege_function(unsigned char *ptr)
{
	char buffer[50];
	seteuid(0);
	strcpy(buffer, ptr);
}
int main(int argc, char *argv[])
{
	if(argc > 1)
		lowered_privilege_function(argv[1]);
}


text:
import { Routes, RouterModule } from '@angular/router';

import { AuthGuard } from '../auth/auth.guard';

import { Inventory10IndexComponent } from './inventory10-index.component';
import { Inventory10ViewComponent } from './inventory10-view.component';

const routes: Routes = [
    { path: 'inventory10', component: Inventory10IndexComponent, canActivate: [AuthGuard] },
    { path: 'inventory10/view/:id', component: Inventory10ViewComponent, canActivate: [AuthGuard] },
];

export const routing = RouterModule.forChild(routes);


text:
package org.apache.hadoop.mapred;

import java.io.IOException;
import java.util.List;

import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.mapred.CleanupQueue.PathDeletionContext;
import org.apache.hadoop.mapred.JvmManager.JvmEnv;
import org.apache.hadoop.util.ProcessTree;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;

/**
 * The default implementation for controlling tasks.
 *
 * This class provides an implementation for launching and killing
 * tasks that need to be run as the tasktracker itself. Hence,
 * many of the initializing or cleanup methods are not required here.
 *
 * <br/>
 *
 *  NOTE: This class is internal only class and not intended for users!!
 */
public class DefaultTaskController extends TaskController {

  private static final Log LOG =
      LogFactory.getLog(DefaultTaskController.class);
  /**
   * Launch a new JVM for the task.
   *
   * This method launches the new JVM for the task by executing the
   * the JVM command using the {@link Shell.ShellCommandExecutor}
   */
  void launchTaskJVM(TaskController.TaskControllerContext context)
                                      throws IOException {
    initializeTask(context);

    JvmEnv env = context.env;
    List<String> wrappedCommand =
      TaskLog.captureOutAndError(env.setup, env.vargs, env.stdout, env.stderr,
          env.logSize, true);
    ShellCommandExecutor shexec =
        new ShellCommandExecutor(wrappedCommand.toArray(new String[0]),
                                  env.workDir, env.env);
    // set the ShellCommandExecutor for later use.
    context.shExec = shexec;
    shexec.execute();
  }

  /**
   * Initialize the task environment.
   *
   * Since tasks are launched as the tasktracker user itself, this
   * method has no action to perform.
   */
  void initializeTask(TaskController.TaskControllerContext context) {
    // The default task controller does not need to set up
    // any permissions for proper execution.
    // So this is a dummy method.
    return;
  }

  /*
   * No need to do anything as we don't need to do as we dont need anything
   * extra from what TaskTracker has done.
   */
  @Override
  void initializeJob(JobInitializationContext context) {
  }

  @Override
  void terminateTask(TaskControllerContext context) {
    ShellCommandExecutor shexec = context.shExec;
    if (shexec != null) {
      Process process = shexec.getProcess();
      if (Shell.WINDOWS) {
        // Currently we don't use setsid on WINDOWS.
        //So kill the process alone.
        if (process != null) {
          process.destroy();
        }
      }
      else { // In addition to the task JVM, kill its subprocesses also.
        String pid = context.pid;
        if (pid != null) {
          if(ProcessTree.isSetsidAvailable) {
            ProcessTree.terminateProcessGroup(pid);
          }else {
            ProcessTree.terminateProcess(pid);
          }
        }
      }
    }
  }

  @Override
  void killTask(TaskControllerContext context) {
    ShellCommandExecutor shexec = context.shExec;
    if (shexec != null) {
      if (Shell.WINDOWS) {
        //We don't do send kill process signal in case of windows as
        //already we have done a process.destroy() in termintateTaskJVM()
        return;
      }
      String pid = context.pid;
      if (pid != null) {
        if(ProcessTree.isSetsidAvailable) {
          ProcessTree.killProcessGroup(pid);
        }else {
          ProcessTree.killProcess(pid);
        }
      }
    }
  }

  /**
   * Enables the task for cleanup by changing permissions of the specified path
   * in the local filesystem
   */
  @Override
  void enableTaskForCleanup(PathDeletionContext context)
         throws IOException {
    enablePathForCleanup(context);
  }

  /**
   * Enables the job for cleanup by changing permissions of the specified path
   * in the local filesystem
   */
  @Override
  void enableJobForCleanup(PathDeletionContext context)
         throws IOException {
    enablePathForCleanup(context);
  }

  /**
   * Enables the path for cleanup by changing permissions of the specified path
   * in the local filesystem
   */
  private void enablePathForCleanup(PathDeletionContext context)
         throws IOException {
    try {
      FileUtil.chmod(context.fullPath, "u+rwx", true);
    } catch(InterruptedException e) {
      LOG.warn("Interrupted while setting permissions for " + context.fullPath +
          " for deletion.");
    } catch(IOException ioe) {
      LOG.warn("Unable to change permissions of " + context.fullPath);
    }
  }

  @Override
  public void initializeDistributedCacheFile(DistributedCacheFileContext context)
      throws IOException {
    Path localizedUniqueDir = context.getLocalizedUniqueDir();
    try {
      // Setting recursive execute permission on localized dir
      LOG.info("Doing chmod on localdir :" + localizedUniqueDir);
      FileUtil.chmod(localizedUniqueDir.toString(), "+x", true);
    } catch (InterruptedException ie) {
      LOG.warn("Exception in doing chmod on" + localizedUniqueDir, ie);
      throw new IOException(ie);
    }
  }

  @Override
  public void initializeUser(InitializationContext context) {
    // Do nothing.
  }

}


text:
"""
@file    SPATControl.py
@author  Craig Rafter
@date    15/08/2016

class for fixed time signal control

"""
import signalControl, readJunctionData, traci
import numpy as np
from copy import copy
from collections import defaultdict

class SPATControl(signalControl.signalControl):
    def __init__(self, junctionData, minGreenTime=10, maxGreenTime=60, extendTime=1, packetRate = 0.2, mode='FT'):
        super(SPATControl, self).__init__()
        self.junctionData = junctionData
        self.firstCalled = self.getCurrentSUMOtime()
        self.lastCalled = self.getCurrentSUMOtime()
        self.lastStageIndex = 0
        traci.trafficlights.setRedYellowGreenState(self.junctionData.id,
            self.junctionData.stages[self.lastStageIndex].controlString)

        self.mode = mode
        assert mode in ['FT', 'VA'], 'Mode not valid'
        self.minGreenTime = minGreenTime
        self.maxGreenTime = maxGreenTime
        self.extendTimePerStep = 0.001*extendTime*traci.simulation.getDeltaT()
        self.stageTime = 0.0
        self.controlledLanes = traci.trafficlights.getControlledLanes(self.junctionData.id)
        self.laneInductors = self._getLaneInductors()
        self.packetRate = int(1000*packetRate)
        phase = self.junctionData.stages[self.lastStageIndex].controlString
        changeTimes = self._getChangeTimes()
        position = traci.junction.getPosition(self.junctionData.id)
        self.newSPaT = (position, phase, changeTimes)
        self.oldSPaT = (position, phase, changeTimes)

    def process(self):
        if not self.getCurrentSUMOtime() % self.packetRate:
            phase = self.junctionData.stages[self.lastStageIndex].controlString
            changeTimes = self._getChangeTimes()
            position = traci.junction.getPosition(self.junctionData.id)
            self.oldSPaT = copy(self.newSPaT)
            self.newSPaT = (position, phase, changeTimes)
        else:
            self.CAMactive = False

        # Get actuation information and make actuation decision
        if self.mode == 'VA':
            activeLanes = self._getActiveLanes()
            meanDetectTimePerLane = np.zeros(len(activeLanes))
            for i, lane in enumerate(activeLanes):
                detectTimes = []
                for loop in self.laneInductors[lane]:
                    detectTimes.append(traci.inductionloop.getTimeSinceDetection(loop))
                meanDetectTimePerLane[i] = np.mean(detectTimes)

            # Set adaptive time limit
            if np.any(meanDetectTimePerLane < 2):
                extend = self.extendTimePerStep
            else:
                extend = 0.0

            self.stageTime = max(self.stageTime, self.minGreenTime) + extend
            self.stageTime = min(self.stageTime, self.maxGreenTime)
        else:
            self.stageTime = self.junctionData.stages[self.lastStageIndex].period

        # Process light state
        if self.transitionObject.active:
            # If the transition object is active i.e. processing a transition
            pass
        elif (self.getCurrentSUMOtime() - self.firstCalled) < (self.junctionData.offset*1000):
            # Process offset first
            pass
        elif (self.getCurrentSUMOtime() - self.lastCalled) < self.stageTime*1000:
            # Before the period of the next stage
            pass
        else:
            # Not active, not in offset, stage not finished
            if len(self.junctionData.stages) != (self.lastStageIndex)+1:
                # Loop from final stage to first stage
                self.transitionObject.newTransition(
                    self.junctionData.id,
                    self.junctionData.stages[self.lastStageIndex].controlString,
                    self.junctionData.stages[self.lastStageIndex+1].controlString)
                self.lastStageIndex += 1
            else:
                # Proceed to next stage
                self.transitionObject.newTransition(
                    self.junctionData.id,
                    self.junctionData.stages[self.lastStageIndex].controlString,
                    self.junctionData.stages[0].controlString)
                self.lastStageIndex = 0

            # print(0.001*(self.getCurrentSUMOtime() - self.lastCalled))
            self.lastCalled = self.getCurrentSUMOtime()
            self.stageTime = 0.0

        super(SPATControl, self).process()

    def _getActiveLanes(self):
        # Get the current control string to find the green lights
        stageCtrlString = self.junctionData.stages[self.lastStageIndex].controlString
        activeLanes = []
        for i, phase in enumerate(stageCtrlString):
            if phase == 'G':
                activeLanes.append(self.controlledLanes[i])
        # Get a list of the unique
        activeLanes = list(np.unique(np.array(activeLanes)))
        return activeLanes

    def _getLaneInductors(self):
        laneInductors = defaultdict(list)

        for loop in traci.inductionloop.getIDList():
            loopLane = traci.inductionloop.getLaneID(loop)
            if loopLane in self.controlledLanes:
                laneInductors[loopLane].append(loop)

        return laneInductors

    def _getChangeTimes(self):
        elapsedTime = 0.001*(self.getCurrentSUMOtime() - self.lastCalled)
        Tremaining = self.stageTime - elapsedTime

        Nstages = len(self.junctionData.stages)
        Nlanes = len(self.junctionData.stages[0].controlString)
        changeTimes = [-1 for i in range(Nlanes)]
        orderedStages = [i%Nstages for i in range(self.lastStageIndex, self.lastStageIndex+Nstages)]

        for scale, stage in enumerate(orderedStages):
            stageCtrlString = self.junctionData.stages[stage].controlString
            for i, phase in enumerate(stageCtrlString):
                if phase == 'G' and changeTimes[i] < 0:
                    if scale > 0:
                        changeTimes[i] = Tremaining + (scale-1)*self.maxGreenTime
                    else:
                        changeTimes[i] = 0

        return changeTimes

    def getSPaTData(self):
        return self.oldSPaT


text:
package com.gpm.mbean.site;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.util.UUID;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;

import com.gpm.login.ThirdPartyLoginServlet;
import com.gpm.manager.UserAccountManager;
import com.gpm.manager.exception.UserAccountException;
import com.gpm.model.UserAccount;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {
  private static final long serialVersionUID = 1L;

  private static String VERSION;

  // URI to redirect to after successfully logging in
  private URI redirect;

  // Details for a user logging in with GPM account
  private String email;

  // UUID of currently logged in user
  private UUID user;

  public String login() {
    try {
      UserAccount account = UserAccountManager.findByEmail(email);
      if (account != null) {
        user = account.getUuid();
      }
    } catch (UserAccountException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (redirect != null) {
      return redirect.getPath() + "?faces-redirect=true";
    } else {
      return "/index.xhtml?faces-redirect=true";
    }
  }

  public void loginFacebook(final String facebookIdent) {
    try {
      UserAccount account = UserAccountManager.findByFacebookIdent(facebookIdent);
      if (account != null) {
        user = account.getUuid();
      }
    } catch (UserAccountException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    redirect = null;
    email = null;
    user = null;
    return "/index.xhtml?faces-redirect=true";
  }

  public boolean isLoggedIn() {
    return user != null;
  }

  public boolean isAdministrator() {
    if (isLoggedIn()) {
      UserAccount account = null;
      try {
        account = UserAccountManager.findByUuid(user.toString());
      } catch (UserAccountException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return account != null && account.isAdministrator();
    }
    return false;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(final String email) {
    this.email = email;
  }

  public URI getRedirect() {
    return redirect;
  }

  public void setRedirect(final URI redirect) {
    this.redirect = redirect;
  }

  public UUID getUserUuid() {
    return user;
  }

  public String getFacebookLoginUrl() {
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    return ThirdPartyLoginServlet.getFacebookLoginUrl((HttpServletRequest) context.getRequest());
  }

  public String getGoogleLoginUrl() {
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    return ThirdPartyLoginServlet.getGoogleLoginUrl((HttpServletRequest) context.getRequest());
  }

  public String getVersion() {
    if (VERSION == null) {
      InputStream in = this.getClass().getClassLoader().getResourceAsStream("VERSION");
      try {
        VERSION = IOUtils.toString(in);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return VERSION;
  }
}


text:
const outputPath = '../georgesandbox-master/sandboxstatic/plugins/testPlugin';

/// / Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractLess = new ExtractTextPlugin({
  filename: "./css/plugin.css",
  // disable: process.env.NODE_ENV === "development"
});

module.exports = (options) => ({
  // In production, we skip all hot-reloading stuff
  entry: [
    path.join(process.cwd(), 'app/sandboxBootstrap.js'),
  ],

  output: {
    path: path.resolve(process.cwd(), outputPath),
    publicPath: '/',
    filename: 'bundle.js',
    libraryTarget: 'var',
    library: 'plugin2'
  },

  externals: {
    'babel-polyfill': 'window',
    jquery: '$',
    backbone: 'Backbone',
    underscore: '_',
    moment: 'moment'
  },

  module: {
    loaders: [

      {
        test: /\.js$/, // Transform all .js files required somewhere with Babel
        loader: 'babel-loader',
        exclude: /node_modules/,
      },

      {test: /\.tsx?$/, loader: "awesome-typescript-loader"},

      {
        test: /\.less$/,

        use: extractLess.extract({
          use: [{
            loader: "css-loader"
          }, {
            loader: "less-loader"
          }],
          // use style-loader in development
          fallback: "style-loader"
        })
      },

      {
        // Do not transform vendor's CSS with CSS-modules
        // The point is that they remain in global scope.
        // Since we require these CSS files in our JS or CSS files,
        // they will be a part of our compilation either way.
        // So, no need for ExtractTextPlugin here.
        test: /\.css$/,
        include: /node_modules/,
        loaders: ['style-loader', 'css-loader'],
      },

      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader',
      }, {
        test: /\.(jpg|png|gif)$/,
        loaders: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            query: {
              progressive: true,
              optimizationLevel: 7,
              interlaced: false,
              pngquant: {
                quality: '65-90',
                speed: 4,
              },
            },
          },
        ],
      }, {
        test: /\.html$/,
        loader: 'html-loader',
      }, {
        test: /\.json$/,
        loader: 'json-loader',
      }, {
        test: /\.(mp4|webm)$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
        },
      }],
  },

  // devtool: 'inline-source-map',
  devtool: 'source-map',

  resolve: {
    modules: ['app', 'node_modules'],
    extensions: [
      '.js',
      '.jsx',
      '.react.js',
      '.d.ts', '.ts', '.tsx',
      '.less'
    ],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
  },

  plugins: [
    // new BundleAnalyzerPlugin({
    //            analyzerMode: 'static'
    //        }),
    extractLess,
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new webpack.NamedModulesPlugin(),

    new HtmlWebpackPlugin({
      template: 'app/index.html',
      filename: 'ignore-me',
      inject: true
      // minify: {
      //   removeComments: true,
      //   collapseWhitespace: true,
      //   removeRedundantAttributes: true,
      //   useShortDoctype: true,
      //   removeEmptyAttributes: true,
      //   removeStyleLinkTypeAttributes: true,
      //   keepClosingSlash: true,
      //   minifyJS: true,
      //   minifyCSS: true,
      //   minifyURLs: true,
      // },
      // inject: true,
    })

    // new webpack.optimize.CommonsChunkPlugin({
    //   name: 'vendor',
    //   children: true,
    //   minChunks: 2,
    //   async: true,
    // }),

    // Minify and optimize the index.html
    // new HtmlWebpackPlugin({
    //   template: 'app/index.html',
    //   minify: {
    //     removeComments: true,
    //     collapseWhitespace: true,
    //     removeRedundantAttributes: true,
    //     useShortDoctype: true,
    //     removeEmptyAttributes: true,
    //     removeStyleLinkTypeAttributes: true,
    //     keepClosingSlash: true,
    //     minifyJS: true,
    //     minifyCSS: true,
    //     minifyURLs: true,
    //   },
    //   inject: true,
    // }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    // new OfflinePlugin({
    //   relativePaths: false,
    //   publicPath: '/',
    //
    //   // No need to cache .htaccess. See http://mxs.is/googmp,
    //   // this is applied before any match in `caches` section
    //   excludes: ['.htaccess'],
    //
    //   caches: {
    //     main: [':rest:'],
    //
    //     // All chunks marked as `additional`, loaded after main section
    //     // and do not prevent SW to install. Change to `optional` if
    //     // do not want them to be preloaded at all (cached only when first loaded)
    //     additional: ['*.chunk.js'],
    //   },

    // Removes warning for about `additional` section usage
    //   safeToUseOptionalCaches: true,
    //
    //   AppCache: false,
    // }),
  ],

  // performance: {
  //   assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
  // },
});


text:
    <title>Font Awesome Icons</title>

Font Awesome Examples

    Lots of easy ways to use Font Awesome

        Basic Icons

            View LESS

                 fa-camera-retro

                You can place Font Awesome icons just about anywhere using the CSS Prefix fa and the icon's
                name. Font Awesome is designed to be used with inline elements (we like the <i> tag
                for
                brevity, but using a <span> is more semantically correct).

<i class="fa fa-camera-retro"></i> fa-camera-retro

                        If you change the font-size of the icon's container, the icon gets bigger. Same things goes for
                        color,
                        drop shadow, and anything else that gets inherited using CSS.

        Larger Icons

            View LESS

 fa-lg

 fa-2x

 fa-3x

 fa-4x

 fa-5x

                To increase icon sizes relative to their container, use the fa-lg (33% increase), fa-2x,
                fa-3x, fa-4x, or fa-5x classes.

<i class="fa fa-camera-retro fa-lg"></i>
                fa-lg
                <i class="fa fa-camera-retro fa-2x"></i> fa-2x
                <i class="fa fa-camera-retro fa-3x"></i> fa-3x
                <i class="fa fa-camera-retro fa-4x"></i> fa-4x
                <i class="fa fa-camera-retro fa-5x"></i> fa-5x

                        If your icons are getting chopped off on top and bottom, make sure you have
                        sufficient line-height.

        Fixed Width Icons

            View LESS

                  Home
                  Library
                  Applications
                  Settings

                Use fa-fw to set icons at a fixed width. Great to use when different icon widths throw off
                alignment.
                Especially useful in things like nav lists & list groups.

<div class="list-group">
                <a class="list-group-item"
                href="#"><i class="fa fa-home fa-fw"></i>&nbsp; Home</a>
                <a class="list-group-item"
                href="#"><i class="fa fa-book fa-fw"></i>&nbsp; Library</a>
                <a class="list-group-item"
                href="#"><i class="fa fa-pencil fa-fw"></i>&nbsp; Applications</a>
                <a class="list-group-item"
                href="#"><i class="fa fa-cog fa-fw"></i>&nbsp; Settings</a>
                </div>

        List Icons

            View LESS

List icons

can be used

as bullets

in lists

Use fa-ul and fa-li to easily replace default bullets in unordered lists.

<ul class="fa-ul">
                <li><i class="fa-li fa fa-check-square"></i>List icons</li>
                <li><i class="fa-li fa fa-check-square"></i>can be used</li>
                <li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
                <li><i class="fa-li fa fa-square"></i>in lists</li>
                </ul>

        Bordered & Pulled Icons

            View LESS

                …tomorrow we will run faster, stretch out our arms farther… And then one fine morning—
                So we beat on, boats against the current, borne back ceaselessly into the past.

                Use fa-border and pull-right or pull-left for easy pull quotes or
                article icons.

<i class="fa fa-quote-left fa-3x pull-left fa-border"></i>
                ...tomorrow we will run faster, stretch out our arms farther...
                And then one fine morning— So we beat on, boats against the
                current, borne back ceaselessly into the past.

        Spinning Icons

            View LESS

                <button class="btn btn-default btn-lg"></button>
                <button class="btn btn-default btn-lg"></button>
                <button class="btn btn-default btn-lg"></button>
                <button class="btn btn-default btn-lg"></button>

                Use the fa-spin class to get any icon to rotate. Works well with fa-spinner,
                fa-refresh, and fa-cog.

<i class="fa fa-spinner fa-spin"></i>
                <i class="fa fa-circle-o-notch fa-spin"></i>
                <i class="fa fa-refresh fa-spin"></i>
                <i class="fa fa-cog fa-spin"></i>

                 CSS3 animations aren't supported in IE8 - IE9.

        Rotated & Flipped

            View LESS

                  normal

                  fa-rotate-90

                  fa-rotate-180

                  fa-rotate-270

                  fa-flip-horizontal

                  fa-flip-vertical

                To arbitrarily rotate and flip icons, use the fa-rotate-* and fa-flip-*
                classes.

<i class="fa fa-shield"></i>
                normal<br>
                <i class="fa fa-shield fa-rotate-90"></i>
                fa-rotate-90<br>
                <i class="fa fa-shield fa-rotate-180"></i>
                fa-rotate-180<br>
                <i class="fa fa-shield fa-rotate-270"></i>
                fa-rotate-270<br>
                <i class="fa fa-shield fa-flip-horizontal"></i> fa-flip-horizontal<br>
                <i class="fa fa-shield fa-flip-vertical"></i> icon-flip-vertical

        Stacked Icons

            View LESS

                fa-twitter on fa-square-o

                fa-flag on fa-circle

                fa-terminal on fa-square

                fa-ban on fa-camera

                To stack multiple icons, use the fa-stack class on the parent, the fa-stack-1x
                for the regularly sized icon, and fa-stack-2x for the larger icon. fa-inverse
                can be used as an alternative icon color. You can even throw larger icon classes
                on the parent
                to get further control of sizing.

<span class="fa-stack fa-lg">
                <i class="fa fa-square-o fa-stack-2x"></i>
                <i class="fa fa-twitter fa-stack-1x"></i>
                </span>
                fa-twitter on fa-square-o<br>
                <span class="fa-stack fa-lg">
                <i class="fa fa-circle fa-stack-2x"></i>
                <i class="fa fa-flag fa-stack-1x fa-inverse"></i>
                </span>
                fa-flag on fa-circle<br>
                <span class="fa-stack fa-lg">
                <i class="fa fa-square fa-stack-2x"></i>
                <i class="fa fa-terminal fa-stack-1x fa-inverse"></i>
                </span>
                fa-terminal on fa-square<br>
                <span class="fa-stack fa-lg">
                <i class="fa fa-camera fa-stack-1x"></i>
                <i class="fa fa-ban fa-stack-2x text-danger"></i>
                </span>
                fa-ban on fa-camera

Bootstrap 3 Examples

                     Delete

                     Settings

                     Font Awesome
Version 4.2.0

                    <input type="text" placeholder="Email address" class="form-control">

                    <input type="password" placeholder="Password" class="form-control">

                     User

 Edit

 Delete

 Ban

 Make admin

                Font Awesome works great with the full range of Bootstrap components.

<a class="btn btn-danger" href="#">
                <i class="fa fa-trash-o fa-lg"></i> Delete</a>
                <a class="btn btn-default btn-sm" href="#">
                <i class="fa fa-cog"></i> Settings</a>

                <a class="btn btn-lg btn-success" href="#">
                <i class="fa fa-flag fa-2x pull-left"></i> Font Awesome<br>Version 4.2.0</a>

                <div class="btn-group">
                <a class="btn btn-default"
                href="#"><i class="fa fa-align-left"></i></a>
                <a class="btn btn-default"
                href="#"><i class="fa fa-align-center"></i></a>
                <a class="btn btn-default"
                href="#"><i class="fa fa-align-right"></i></a>
                <a class="btn btn-default"
                href="#"><i class="fa fa-align-justify"></i></a>
                </div>

                <div class="input-group margin-bottom-sm">
                <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
                <input class="form-control"
                type="text" placeholder="Email address">
                </div>
                <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
                <input class="form-control"
                type="password" placeholder="Password">
                </div>

                <div class="btn-group open">
                <a class="btn btn-primary"
                href="#"><i class="fa fa-user fa-fw"></i> User</a>
                <a class="btn btn-primary dropdown-toggle"
                data-toggle="dropdown" href="#">
                <span class="fa fa-caret-down"></span></a>
                <ul class="dropdown-menu">
                <li><a href="#"><i class="fa fa-pencil fa-fw"></i> Edit</a></li>
                <li><a href="#"><i class="fa fa-trash-o fa-fw"></i> Delete</a></li>
                <li><a href="#"><i class="fa fa-ban fa-fw"></i> Ban</a></li>
                <li class="divider"></li>
                <li><a href="#"><i class="i"></i> Make admin</a></li>
                </ul>
                </div>

Custom CSS

Anything you can do with CSS font styles, you can do with Font Awesome.

Star Ratings (inspired by CSS Tricks)


text:
public class ShutdownReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        mainActivity.saveLocalData();
        mainActivity.stopActivity();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>com.sunfishempire.bananasalloy</id>
    <name>BananasAlloy</name>
    <version>1.0</version>
    <publisher>vuinguyen</publisher>
    <url>http://sunfishempire.com</url>
    <description>not specified</description>
    <copyright>2013 by vuinguyen</copyright>
    <icon>appicon.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
    <guid>dd7f86c6-13ca-4582-bcd9-b9e88fab8034</guid>
    <property name="ti.ui.defaultunit" type="string">system</property>
    <iphone>
        <orientations device="iphone">
            <orientation>Ti.UI.PORTRAIT</orientation>
        </orientations>
        <orientations device="ipad">
            <orientation>Ti.UI.PORTRAIT</orientation>
            <orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
            <orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
            <orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
        </orientations>
    </iphone>
    <android xmlns:android="http://schemas.android.com/apk/res/android"/>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules/>
    <deployment-targets>
        <target device="blackberry">false</target>
        <target device="android">true</target>
        <target device="ipad">true</target>
        <target device="iphone">true</target>
        <target device="mobileweb">true</target>
    </deployment-targets>
    <sdk-version>3.0.2.GA</sdk-version>
    <plugins>
        <plugin version="1.0">ti.alloy</plugin>
    </plugins>
</ti:app>


text:
package org.apache.activemq.apollo.util.path

import java.util.regex.Pattern
import java.lang.String

/**
  * Holds the delimiters used to parse paths.
  *
  * @author Hiram Chirino
  */
sealed trait Part {
  def matches(p: Part) = true
}

object RootPart extends Part {
  override def matches(p: Part) = p match {
    case RootPart => true
    case _ => false
  }
}

object AnyChildPart extends Part
object AnyDescendantPart extends Part

case class RegexChildPart(regex:Pattern) extends Part

case class LiteralPart(value: String) extends Part {
  override def matches(p: Part) = p match {
    case LiteralPart(v) => v == value
    case _ => true
  }
  override def toString = value
}


text:
(function() {
	'use strict';

	angular.module('pinpointApp').directive('cpuLoadChartDirective', ['$timeout',
        function ($timeout) {
            return {
                template: '

',
                replace: true,
                restrict: 'E',
                scope: {
                    namespace: '@' // string value
                },
                link: function postLink(scope, element, attrs) {

                    // define variables
                    var sId, oChart;

                    // define variables of methods
                    var setIdAutomatically, setWidthHeight, render, showCursorAt, resize;

                    /**
                     * set id automatically
                     */
                    setIdAutomatically = function () {
                        sId = 'multipleValueAxesId-' + scope.namespace;
                        element.attr('id', sId);
                    };

                    /**
                     * set width height
                     * @param w
                     * @param h
                     */
                    setWidthHeight = function (w, h) {
                        if (w) element.css('width', w);
                        if (h) element.css('height', h);
                    };

                    /**
                     * render
                     * @param chartData
                     */
                    render = function (chartData) {
                        var options = {
                            "type": "serial",
                            "theme": "light",
                            "autoMargins": false,
                            "marginTop": 10,
                            "marginLeft": 70,
                            "marginRight": 70,
                            "marginBottom": 30,
                            "legend": {
                                "useGraphSettings": true,
                                "autoMargins": true,
                                "align" : "right",
                                "position": "top",
                                "valueWidth": 70
                            },
                            "usePrefixes": true,
                            "dataProvider": chartData,
                            "valueAxes": [
                                {
                                    "id": "v1",
                                    "gridAlpha": 0,
                                    "axisAlpha": 1,
                                    "position": "left",
                                    "title": "Cpu Usage (%)",
                                    "maximum" : 100,
                                    "minimum" : 0
                                },
                            ],
                            "graphs": [
                                {
                                    "valueAxis": "v1",
                                    "balloonText": "[[value]]%",
                                    "legendValueText": "[[value]]%",
                                    "lineColor": "rgb(31, 119, 180)",
                                    "fillColor": "rgb(31, 119, 180)",
                                    "title": "JVM",
                                    "valueField": "jvmCpuLoad",
                                    "fillAlphas": 0.4,
                                    "connect": false
                                },
                                {
                                    "valueAxis": "v1",
                                    "balloonText": "[[value]]%",
                                    "legendValueText": "[[value]]%",
                                    "lineColor": "rgb(174, 199, 232)",
                                    "fillColor": "rgb(174, 199, 232)",
                                    "title": "System",
                                    "valueField": "systemCpuLoad",
                                    "fillAlphas": 0.4,
                                    "connect": false
                                },
                                {
                                    "valueAxis": "v1",
                                    "showBalloon": false,
                                    "lineColor": "#FF6600",
                                    "title": "Max",
                                    "valueField": "maxCpuLoad",
                                    "fillAlphas": 0,
                                    "visibleInLegend": false
                                }
                            ],
                            "chartCursor": {
                                "categoryBalloonAlpha": 0.7,
                                "fullWidth": true,
                                "cursorAlpha": 0.1
                            },
                            "categoryField": "time",
                            "categoryAxis": {
                                "axisColor": "#DADADA",
                                "startOnAxis": true,
                                "gridPosition": "start",
                                "labelFunction": function (valueText, serialDataItem, categoryAxis) {
                                	return moment(valueText).format("HH:mm:ss");
                                }
                            }
                        };
                        $timeout(function () {
                            oChart = AmCharts.makeChart(sId, options);
                            oChart.chartCursor.addListener('changed', function (event) {
                                scope.$emit('cpuLoadChartDirective.cursorChanged.' + scope.namespace, event);
                            });
                        });
                    };

                    /**
                     * show cursor at
                     * @param category
                     */
                    showCursorAt = function (category) {
                        if (category) {
                            if (angular.isNumber(category)) {
                                category = oChart.dataProvider[category].time;
                            }
                            oChart.chartCursor.showCursorAt(category);
                        } else {
                            oChart.chartCursor.hideCursor();
                        }
                    };

                    /**
                     * resize
                     */
                    resize = function () {
                        if (oChart) {
                            oChart.validateNow();
                            oChart.validateSize();
                        }
                    };

                    /**
                     * scope event on cpuLoadChartDirective.initAndRenderWithData.namespace
                     */
                    scope.$on('cpuLoadChartDirective.initAndRenderWithData.' + scope.namespace, function (event, data, w, h) {
                        setIdAutomatically();
                        setWidthHeight(w, h);
                        render(data);
                    });

                    /**
                     * scope event on cpuLoadChartDirective.showCursorAt.namespace
                     */
                    scope.$on('cpuLoadChartDirective.showCursorAt.' + scope.namespace, function (event, category) {
                        showCursorAt(category)
                    });

                    /**
                     * scope event on cpuLoadChartDirective.resize.namespace
                     */
                    scope.$on('cpuLoadChartDirective.resize.' + scope.namespace, function (event) {
                        resize();
                    });
                }
            };
        }
    ]);
})();


text:
using std::set;
using std::string;
using std::vector;

namespace cc {

class OutputSurfaceCallbacks :
  public WebKit::WebGraphicsContext3D::WebGraphicsSwapBuffersCompleteCallbackCHROMIUM,
  public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
 public:
   explicit OutputSurfaceCallbacks(OutputSurfaceClient* client)
     : client_(client) {}

   // WK:WGC3D::WGSwapBuffersCompleteCallbackCHROMIUM implementation.
   virtual void onSwapBuffersComplete() {
     client_->OnSwapBuffersComplete();
   }

   // WK:WGC3D::WGContextLostCallback implementation.
   virtual void onContextLost() {
     client_->DidLoseOutputSurface();
   }

 private:
  OutputSurfaceClient* client_;
};

OutputSurface::OutputSurface(
    scoped_ptr<WebKit::WebGraphicsContext3D> context3d)
    : client_(NULL),
      context3d_(context3d.Pass()),
      has_gl_discard_backbuffer_(false) {
}

OutputSurface::OutputSurface(
    scoped_ptr<cc::SoftwareOutputDevice> software_device)
    : client_(NULL),
      software_device_(software_device.Pass()),
      has_gl_discard_backbuffer_(false) {
}

OutputSurface::OutputSurface(
    scoped_ptr<WebKit::WebGraphicsContext3D> context3d,
    scoped_ptr<cc::SoftwareOutputDevice> software_device)
    : client_(NULL),
      context3d_(context3d.Pass()),
      software_device_(software_device.Pass()),
      has_gl_discard_backbuffer_(false) {
}

OutputSurface::~OutputSurface() {
}

bool OutputSurface::BindToClient(
    cc::OutputSurfaceClient* client) {
  DCHECK(client);
  client_ = client;
  if (!context3d_)
    return true;
  if (!context3d_->makeContextCurrent())
    return false;

  string extensions_string = UTF16ToASCII(context3d_->getString(GL_EXTENSIONS));
  vector<string> extensions_list;
  base::SplitString(extensions_string, ' ', &extensions_list);
  set<string> extensions(extensions_list.begin(), extensions_list.end());

  has_gl_discard_backbuffer_ =
      extensions.count("GL_CHROMIUM_discard_backbuffer") > 0;

  callbacks_.reset(new OutputSurfaceCallbacks(client_));
  context3d_->setSwapBuffersCompleteCallbackCHROMIUM(callbacks_.get());
  context3d_->setContextLostCallback(callbacks_.get());

  return true;
}

void OutputSurface::SendFrameToParentCompositor(CompositorFrame* frame) {
  NOTIMPLEMENTED();
}

void OutputSurface::EnsureBackbuffer() {
  DCHECK(context3d_);
  if (has_gl_discard_backbuffer_)
    context3d_->ensureBackbufferCHROMIUM();
}

void OutputSurface::DiscardBackbuffer() {
  DCHECK(context3d_);
  if (has_gl_discard_backbuffer_)
    context3d_->discardBackbufferCHROMIUM();
}

void OutputSurface::Reshape(gfx::Size size) {
  DCHECK(context3d_);
  context3d_->reshape(size.width(), size.height());
}

void OutputSurface::BindFramebuffer() {
  DCHECK(context3d_);
  context3d_->bindFramebuffer(GL_FRAMEBUFFER, 0);
}

void OutputSurface::SwapBuffers(const LatencyInfo& latency_info) {
  DCHECK(context3d_);
  // Note that currently this has the same effect as SwapBuffers; we should
  // consider exposing a different entry point on WebGraphicsContext3D.
  context3d_->prepareTexture();
}

void OutputSurface::PostSubBuffer(gfx::Rect rect,
                                  const LatencyInfo& latency_info) {
  DCHECK(context3d_);
  context3d_->postSubBufferCHROMIUM(
      rect.x(), rect.y(), rect.width(), rect.height());
}

}  // namespace cc


text:
<?php
/* @var $this EmployeeDemoController */
/* @var $model EmployeeDemo */

$this->breadcrumbs=array(
	'Employee Demos'=>array('index'),
	$model->id,
);

$this->menu=array(
	array('label'=>'List EmployeeDemo', 'url'=>array('index')),
	array('label'=>'Create EmployeeDemo', 'url'=>array('create')),
	array('label'=>'Update EmployeeDemo', 'url'=>array('update', 'id'=>$model->id)),
	array('label'=>'Delete EmployeeDemo', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage EmployeeDemo', 'url'=>array('admin')),
);
?>

View EmployeeDemo #<?php echo $model->id; ?>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(
		'id',
		'employee_id',
		'subject',
		'test_id',
		'test_result',
		'demo_class',
		'demo_datetime',
	),
)); ?>


text:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load static from staticfiles %}

{% block head %}
    <link href="{% static 'css/studies.css' %}" media="screen" rel="stylesheet" type="text/css"/>

    <link rel="stylesheet" href="{% static "css/select2.min.css" %}" />
    <title>{% block title %}Add a new image{% endblock %}</title>
{% endblock %}

{% block content %}

Upload a map to decode it with Neurosynth

Welcome to NeuroVault - a  public web repository for statistical
                        maps of the brain. After filling in the minimum
                        information outlined below (only the fields with an
                        asterisk [*] are compulsory), your map
                        will be sent back to Neurosynth.org for
                        decoding. Remember that your map needs to be unthresholded and in MNI152
                        space for decoding to work correctly!.
                        By uploading your map you agree to make it publicly available under CC0 license.
			You can always come back to NeuroVault.org to
			inspect, modify, and/or delete your maps. If you wish to use Neurosynth decoding, but keep
			your maps private, consider creating a a private collection.

        <form  class="form-horizontal" method="post"  enctype="multipart/form-data">
    		{% crispy form %}
	</form>

    {% include "statmaps/_contrast_lookup.html" %}

{% endblock %}


text:
package com.modwiz.cloakedchristmas;

import com.modwiz.cloakedchristmas.proxy.ClientProxy;
import com.modwiz.cloakedchristmas.proxy.CommonProxy;
import com.modwiz.cloakedchristmas.proxy.ServerProxy;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Mod(modid = CloakedChristmas.MOD_ID)
public class CloakedChristmas {
    public static final String MOD_ID = "cloakedchristmas";
    public static final Logger LOGGER = LogManager.getLogger(MOD_ID);

    @SidedProxy(clientSide = ClientProxy.CLASSPATH, serverSide = ServerProxy.CLASSPATH)
    public static CommonProxy PROXY;

    private void onPreInitializationEvent(FMLPreInitializationEvent event) {
        PROXY.onPreInitialization(event);
    }
}


text:
namespace llvm {
namespace pdb {

class LinePrinter;

class TypedefDumper : public PDBSymDumper {
public:
  TypedefDumper(LinePrinter &P);

  void start(const PDBSymbolTypeTypedef &Symbol);

  void dump(const PDBSymbolTypeArray &Symbol) override;
  void dump(const PDBSymbolTypeBuiltin &Symbol) override;
  void dump(const PDBSymbolTypeEnum &Symbol) override;
  void dump(const PDBSymbolTypeFunctionSig &Symbol) override;
  void dump(const PDBSymbolTypePointer &Symbol) override;
  void dump(const PDBSymbolTypeUDT &Symbol) override;

private:
  LinePrinter &Printer;
};
}
}

#endif


text:
Searching for a word or phrase which meets certain criteria is a common need in many applications. An effective search should correctly identify every candidate either as a match or not a match. Moreover, an effective search should be efficient.

Given an English dictionary to search, create a program that will find all words in the dictionary which match the following criteria:

1. The target word is exactly 7 letters long.
2. The target word contains all the vowels [aeiou] exactly once.
3. Two of the letters in the target word are not vowels.

So if '.' represents any single non-vowel character, possible matched words would be:

- aeiou..
- aeio.u.
- aei.ou.
- ae.iou.
- a.eiou.
- .aeiou.
- aeio..u
- aei.o.u
- ae.io.u
- etc.

## Your Assignment

Find a good English dictionary online which you can download and which has at least 150,000 words. Then write a program to parse every word in this dictionary and determine if it meets the above criteria. Finally, use your program to find at least 5 English words which match this criteria.

You may write your program in any programming language you choose. You can also use any design methodology you feel suits the problem: object-oriented, procedural, scripting, functional, etc.

Your code should should contain good naming, appropriate comments, and display good design. Efficiency of your algorithm should be one consideration. If there are two different solutions which both produce correct answers, but one of them runs in one tenth the time, then the faster solution is a better one.


text:
from oslo_log import log as logging
import webob
from webob import exc

from cinder.api import extensions
from cinder.api.openstack import wsgi
from cinder import exception
from cinder.i18n import _, _LI
from cinder import volume

LOG = logging.getLogger(__name__)
authorize = extensions.extension_authorizer('volume', 'volume_unmanage')

class VolumeUnmanageController(wsgi.Controller):
    def __init__(self, *args, **kwargs):
        super(VolumeUnmanageController, self).__init__(*args, **kwargs)
        self.volume_api = volume.API()

    @wsgi.response(202)
    @wsgi.action('os-unmanage')
    def unmanage(self, req, id, body):
        """Stop managing a volume.

        This action is very much like a delete, except that a different
        method (unmanage) is called on the Cinder driver.  This has the effect
        of removing the volume from Cinder management without actually
        removing the backend storage object associated with it.

        There are no required parameters.

        A Not Found error is returned if the specified volume does not exist.

        A Bad Request error is returned if the specified volume is still
        attached to an instance.
        """
        context = req.environ['cinder.context']
        authorize(context)

        LOG.info(_LI("Unmanage volume with id: %s"), id, context=context)

        try:
            vol = self.volume_api.get(context, id)
            self.volume_api.delete(context, vol, unmanage_only=True)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)
        except exception.VolumeAttached:
            msg = _("Volume cannot be deleted while in attached state")
            raise exc.HTTPBadRequest(explanation=msg)
        return webob.Response(status_int=202)

class Volume_unmanage(extensions.ExtensionDescriptor):
    """Enable volume unmanage operation."""

    name = "VolumeUnmanage"
    alias = "os-volume-unmanage"
    namespace = "http://docs.openstack.org/volume/ext/volume-unmanage/api/v1.1"
    updated = "2012-05-31T00:00:00+00:00"

    def get_controller_extensions(self):
        controller = VolumeUnmanageController()
        extension = extensions.ControllerExtension(self, 'volumes', controller)
        return [extension]


text:
using System;
using Xunit;

namespace NOptional.Tests
{
    public class ObjectConstruction
    {
        private const string TestValue = "Hello world";

        [Fact]
        public void EmptyFactoryReturnedNone()
        {
            var none = Optional<object>.Empty;

            Assert.False(none.IsPresent);
        }

        [Fact]
        public void NoneByExtensionMethod()
        {
            string someValue = null;

            var optional = someValue.AsOption();

            Assert.False(optional.IsPresent);
        }

        [Fact]
        public void OfFromValue()
        {
            var optional = Optional<string>.Of(TestValue);

            Assert.True(optional.IsPresent);
        }

        [Fact]
        public void SomeByExtensionMethod()
        {
            var optional = TestValue.AsOption();

            Assert.True(optional.IsPresent);
        }

        [Fact]
        public void OfNullableFromNull()
        {
            var none = Optional<string>.OfNullable(null);

            Assert.False(none.IsPresent);
        }

        [Fact]
        public void OfNullableFromValue()
        {
            var optional = Optional<string>.OfNullable(TestValue);

            Assert.True(optional.IsPresent);
        }

        [Fact]
        public void OfFromNullThrowsException()
        {
            Assert.Throws<ArgumentNullException>(() =>
            {
                var optional = Optional<string>.Of(null);
            });
        }
    }
}


text:
    {{ badgeTitle }}

    <ng-content></ng-content>


text:
This exercise should focus on teaching about the special types of arguments to `defun`: `&key`, `&rest`, `&optional`.

## Learning objectives

- Know how to take optional arguments using `&optional`
- Know how to use `&rest` to take an arbitrary number of arguments
- Know how to take keyword arguments using `&key`
- Know how to set default values for optional / keyword arguments
- Be able to use `supplied-p` parameters with optional / keyword
  arguments

## Out of scope

- Anonymous functions using `lambda`
- Local functions using `flet`, `labels`, etc.
- Recursion / self-referential functions
- The somewhat arcane `&aux` keyword
- The `&allow-other-keys` keyword
- Multiple value returns with `values`
- Early returns with `return-from`
- Methods / generic functions
- Higher-order functions
- Macros

The concept file for `named-parameters` can (and perhaps should) mention `&allow-other-keys`.

## Concepts

- `named-parameters`
- `rest-parameters`
- `default-parameters`

## Prerequisites

- `functions`
- `expressions`
- `integers`
- `arithmetic`
- `conditionals`

## Resources to refer to

- [Practical Common
  Lisp](http://www.gigamonkeys.com/book/functions.html)
- [Common Lisp Hyperspec](http://www.lispworks.com/documentation/HyperSpec/Body/m_defun.htm)

### Hints

- [Common Lisp
  Cookbook](https://lispcookbook.github.io/cl-cookbook/functions.html)


text:
/*
 * mpcHandler.c
 *
 * Created: 10.2.2015 10:46:19
 *  Author: Tomas Baca
 */

#include "mpcHandler.h"

/* -------------------------------------------------------------------- */
/*	Variables for data reception from STM u-controller					*/
/* -------------------------------------------------------------------- */

char stmRxBuffer[STM_BUFFER_SIZE];

int16_t payloadSize = 0;
int16_t bytesReceived;

char stmMessageReceived = 0;
char receivingMessage = 0;
char receiverState = 0;
char crcIn = 0;

/* -------------------------------------------------------------------- */
/*	This structure holds all states estimated by the kalman filter		*/
/* -------------------------------------------------------------------- */

volatile kalmanStates_t kalmanStates;

/* -------------------------------------------------------------------- */
/*	This structure holds setpoints for MPC								*/
/* -------------------------------------------------------------------- */

volatile mpcSetpoints_t mpcSetpoints;

/* -------------------------------------------------------------------- */
/*	These variables hold actions from MPC								*/
/* -------------------------------------------------------------------- */

volatile int16_t mpcElevatorOutput = 0;
volatile int16_t mpcAileronOutput = 0;

/* -------------------------------------------------------------------- */
/*	Initialize the local copy of kalman states to ZERO					*/
/* -------------------------------------------------------------------- */
void initializeKalmanStates() {

	kalmanStates.elevator.position = 0;
	kalmanStates.elevator.velocity = 0;
	kalmanStates.elevator.acceleration = 0;
	kalmanStates.elevator.acceleration_input = 0;
	kalmanStates.elevator.acceleration_error = 0;

	kalmanStates.aileron.position = 0;
	kalmanStates.aileron.velocity = 0;
	kalmanStates.aileron.acceleration = 0;
	kalmanStates.aileron.acceleration_input = 0;
	kalmanStates.aileron.acceleration_error = 0;
}

/* -------------------------------------------------------------------- */
/*	Fetch the incoming char into a buffer, completes the message		*/
/* -------------------------------------------------------------------- */
int8_t stmParseChar(char inChar, stmMessageHandler_t * messageHandler) {

	if (receivingMessage) {

		// expecting to receive the payload size
		if (receiverState == 0) {

			// check the message length
			if (inChar >= 0 && inChar < STM_BUFFER_SIZE) {

				payloadSize = inChar;
				receiverState = 1;
				crcIn += inChar;

			// the receiving message is over the buffer size
			} else {

				receivingMessage = 0;
				receiverState = 0;
			}

		// expecting to receive the payload
		} else if (receiverState == 1) {

			// put the char in the buffer
			stmRxBuffer[bytesReceived++] = inChar;
			// add crc
			crcIn += inChar;

			// if the message should end, change state
			if (bytesReceived >= payloadSize)
			receiverState = 2;

		// expecting to receive the crc
		} else if (receiverState == 2) {

			if (crcIn == inChar) {

				stmMessageReceived = 1;
				receivingMessage = 0;
			} else {

				receivingMessage = 0;
				receiverState = 0;
			}
		}

	} else {

		// this character precedes every message
		if (inChar == 'a') {

			crcIn = inChar;

			receivingMessage = 1;
			receiverState = 0;
			bytesReceived = 0;
		}
	}

	if (stmMessageReceived) {

		messageHandler->messageBuffer = stmRxBuffer+1;
		messageHandler->messageId = stmRxBuffer[0];
		stmMessageReceived = 0;
		return 1;
	}

	return 0;
}

float readFloat(char * message, int * indexFrom) {

	float tempFloat;

	char * ukazatel = (char*) &tempFloat;
	*(ukazatel++) = message[(*indexFrom)++];
	*(ukazatel++) = message[(*indexFrom)++];
	*(ukazatel++) = message[(*indexFrom)++];
	*(ukazatel++) = message[(*indexFrom)++];

	return tempFloat;
}

int16_t readInt16(char * message, int * indexFrom) {

	int16_t tempInt;

	char * ukazatel = (char*) &tempInt;
	*(ukazatel++) = message[(*indexFrom)++];
	*(ukazatel++) = message[(*indexFrom)++];

	return tempInt;
}

uint32_t readUint32(char * message, int * indexFrom) {

	uint32_t tempInt;

	char * ukazatel = (char*) &tempInt;
	uint8_t i;
	for (i = 0; i < 4; i++) {
		*(ukazatel++) = message[(*indexFrom)++];
	}

	return tempInt;
}

char readChar(char * message, int * indexFrom) {

	char tempChar = message[(*indexFrom)++];

	return tempChar;
}

void sendFloat(UsartBuffer * usartBuffer, const float var, char * crc) {

	char * ukazatel = (char*) &var;

	usartBufferPutByte(usartBuffer, *(ukazatel), 10);
	*crc += *(ukazatel);

	usartBufferPutByte(usartBuffer, *(ukazatel+1), 10);
	*crc += *(ukazatel+1);

	usartBufferPutByte(usartBuffer, *(ukazatel+2), 10);
	*crc += *(ukazatel+2);

	usartBufferPutByte(usartBuffer, *(ukazatel+3), 10);
	*crc += *(ukazatel+3);
}

void sendInt16(UsartBuffer * usartBuffer, const int16_t var, char * crc) {

	char * ukazatel = (char*) &var;

	usartBufferPutByte(usartBuffer, *(ukazatel), 10);
	*crc += *(ukazatel);

	usartBufferPutByte(usartBuffer, *(ukazatel+1), 10);
	*crc += *(ukazatel+1);
}

void sendChar(UsartBuffer * usartBuffer, const char var, char * crc) {

	usartBufferPutByte(usartBuffer, var, 10);
	*crc += var;
}

/* -------------------------------------------------------------------- */
/*	Send actual measurement and system input values to STM				*/
/* -------------------------------------------------------------------- */
void stmSendMeasurement(float elevSpeed, float aileSpeed, int16_t elevInput, int16_t aileInput) {

	char crc = 0;

	sendChar(usart_buffer_stm, 'a', &crc);		// this character initiates the transmission

	sendChar(usart_buffer_stm, 1+12, &crc);		// this will be the size of the message
	sendChar(usart_buffer_stm, '1', &crc);		// id of the message

	// sends the payload
	sendFloat(usart_buffer_stm, elevSpeed, &crc);
	sendFloat(usart_buffer_stm, aileSpeed, &crc);
	sendInt16(usart_buffer_stm, elevInput, &crc);
	sendInt16(usart_buffer_stm, aileInput, &crc);

	// at last send the crc, ends the transmission
	sendChar(usart_buffer_stm, crc, &crc);
}

/* -------------------------------------------------------------------- */
/*	Send point setpoint to STM											*/
/* -------------------------------------------------------------------- */
void stmSendSetpoint(float elevatorSetpoint, float aileronSetpoint) {

	char crc = 0;

	sendChar(usart_buffer_stm, 'a', &crc);		// this character initiates the transmission

	sendChar(usart_buffer_stm, 1 + 2*4, &crc);		// this will be the size of the message
	sendChar(usart_buffer_stm, 's', &crc);		// id of the message

	// sends the payload
	sendFloat(usart_buffer_stm, elevatorSetpoint, &crc);
	sendFloat(usart_buffer_stm, aileronSetpoint, &crc);

	// at last send the crc, ends the transmission
	sendChar(usart_buffer_stm, crc, &crc);
}

/* -------------------------------------------------------------------- */
/*	Send dual setpoints to STM (start and end of horizon)				*/
/* -------------------------------------------------------------------- */
void stmSendTrajectory(float elevatorTrajectory[5], float aileronTrajectory[5]) {

	char crc = 0;

	sendChar(usart_buffer_stm, 'a', &crc);		// this character initiates the transmission

	sendChar(usart_buffer_stm, 1 + 5*4 + 5*4, &crc);	// this will be the size of the message
	sendChar(usart_buffer_stm, 't', &crc);		// id of the message

	int i;

	// send the elevator trajectory
	for (i = 0; i < 5; i++) {

		sendFloat(usart_buffer_stm, elevatorTrajectory[i], &crc);
	}

	// send the aileron trajectory
	for (i = 0; i < 5; i++) {

		sendFloat(usart_buffer_stm, aileronTrajectory[i], &crc);
	}

	// at last send the crc, ends the transmission
	sendChar(usart_buffer_stm, crc, &crc);
}

/* -------------------------------------------------------------------- */
/*	Send request for reset the kalman states							*/
/* -------------------------------------------------------------------- */
void stmResetKalman(float initElevator, float initAileron) {

	char crc = 0;

	sendChar(usart_buffer_stm, 'a', &crc);		// this character initiates the transmission
	sendChar(usart_buffer_stm, 1 + 2*4, &crc);		// this will be the size of the message

	sendChar(usart_buffer_stm, '2', &crc);		// id of the message

	sendFloat(usart_buffer_stm, initElevator, &crc);
	sendFloat(usart_buffer_stm, initAileron, &crc);

	// at last send the crc, ends the transmission
	sendChar(usart_buffer_stm, crc, &crc);
}

/* -------------------------------------------------------------------- */
/*	Override the current kalman's integrated position					*/
/* -------------------------------------------------------------------- */
void stmSetKalmanPosition(float elevatorPos, float aileronPos) {

	char crc = 0;

	sendChar(usart_buffer_stm, 'a', &crc);		// this character initiates the transmission
	sendChar(usart_buffer_stm, 1 + 2*4, &crc);		// this will be the size of the message

	sendChar(usart_buffer_stm, '3', &crc);		// id of the message

	sendFloat(usart_buffer_stm, elevatorPos, &crc);
	sendFloat(usart_buffer_stm, aileronPos, &crc);

	// at last send the crc, ends the transmission
	sendChar(usart_buffer_stm, crc, &crc);
}


text:
@interface UIColor (MackNotas)

+ (UIColor *)colorWithR:(CGFloat)r G:(CGFloat)g B:(CGFloat)b andAlpha:(CGFloat)alpha;
+ (UIColor *)colorFromHex:(NSInteger)hex;
+ (UIColor *)vermelhoMainBackground;
+ (UIColor *)cinzaBtnLoginDisable;
+ (UIColor *)verdeFaltas;
+ (UIColor *)blueGreen;
+ (UIColor *)placeholder;
+ (UIColor *)infoColor;
+ (UIColor *)verboseColor;
+ (UIColor *)debugColor;
+ (UIColor *)warnColor;
@end


text:
'use strict';

const expect = require('chai').expect;
const InstallationChecker = require('../../../lib/models/installation-checker');
const path = require('path');

describe('Installation Checker', function() {
  let installationChecker;

  function fixturePath(pathToFile) {
    return path.resolve(path.join(__dirname, '..', '..', 'fixtures'), pathToFile);
  }

  function checkInstallations() {
    installationChecker.checkInstallations();
  }

  describe('bower', function() {

    it('works when installation directory exist', function() {
      let project = {
        root: fixturePath('installation-checker/valid-bower-installation'),
        bowerDirectory: fixturePath('installation-checker/valid-bower-installation/bower_components'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.not.throw(/No dependencies installed/);
    });

    it('fails when installation directory doesn\'t exist', function() {
      let project = {
        root: fixturePath('installation-checker/invalid-bower-installation'),
        bowerDirectory: fixturePath('installation-checker/invalid-bower-installation/bower_components'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.throw(/^SilentError: InstallationChecker: Unable to parse: .*bower.json/);
    });

  });

  describe('npm', function() {

    it('works when installation directory exist', function() {
      let project = {
        root: fixturePath('installation-checker/valid-npm-installation'),
        nodeModulesPath: fixturePath('installation-checker/valid-npm-installation/node_modules'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.not.throw(/No dependencies installed/);
    });

    it('fails when installation directory doesn\'t exist', function() {
      let project = {
        root: fixturePath('installation-checker/invalid-npm-installation'),
        nodeModulesPath: fixturePath('installation-checker/invalid-npm-installation/node_modules'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.throw(/^SilentError: InstallationChecker: Unable to parse: .*package.json/);
    });

  });

  describe('npm and bower', function() {

    it('fails reporting both dependencies', function() {
      let project = {
        root: fixturePath('installation-checker/invalid-bower-and-npm'),
        bowerDirectory: fixturePath('installation-checker/invalid-bower-and-npm/bower_components'),
        nodeModulesPath: fixturePath('installation-checker/invalid-bower-and-npm/node_modules'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.throw(/^SilentError: InstallationChecker: Unable to parse: .*package.json/);
    });

    it('ignores directories without bower.js and package.json files', function() {
      let project = {
        root: fixturePath('installation-checker/empty'),
        bowerDirectory: fixturePath('installation-checker/empty/bower_components'),
        nodeModulesPath: fixturePath('installation-checker/empty/node_modules'),
      };
      installationChecker = new InstallationChecker({ project });

      expect(checkInstallations).to.not.throw('/No dependencies installed/');
    });

  });
});


text:
\documentclass[t]{beamer}
%NewComand definitions
\usepackage{xparse}
\usepackage{fontspec}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{unicode-math}
\usepackage{listings}

\NewDocumentCommand\FV{}{\alert<2>}
\NewDocumentCommand\GV{}{\alert<3>}
\NewDocumentCommand\alphaconversion{}{\Rightarrow_α}
\NewDocumentCommand\betareduction{}{\Rightarrow_β}

\begin{document}

\begin{frame}{Aufgabe 02a}

  \begin{gather*}
    (λf\underbrace{x.fx}_{GV = \{x\}} )(\underbrace{λzy.xy}_{FV=\{x\}})x \\
    \uncover<2->{
      \alphaconversion (λf \underbrace{x'.fx'}_{GV=\{x'\}})(\underbrace{λzy.xy}_{FV=\{x\}})x \\
    }
    \uncover<3->{
      \betareduction (λx'. \underbrace{(λzy.xy)x'}_{GV=\{y,z\}}) \underbrace{x}_{FV=\{x\}} \\
    }
    \uncover<4->{
      \betareduction (λz\underbrace{y.xy}_{GV=\{y\}}) \underbrace{x}_{FV=\{x\}} \\
    }
    \uncover<5->{
      \betareduction (λy.xy)
    }
  \end{gather*}
\end{frame}

\begin{frame}{Aufgabe 2b}
  \frametitle{Aufgabe 2b}
  \lstinputlisting[language=Haskell]{A2b.hs}
$\langle G\rangle =  ( ( λgxy.\langle ite\rangle  (\langle iszero\rangle  y)$ \\
$        ( \langle ite\rangle  (\langle iszero\rangle  (\langle pred\rangle  y))$ \\
$          ( g (\langle succ\rangle  x)          (\langle pred\rangle  y))$ \\
$          ( g (\langle succ\rangle  (\langle succ\rangle  x)) (\langle pred\rangle  (\langle pred\rangle  y)))$ \\
$        )    $
$      ) $
\end{frame}
\end{document}


text:
<?php

namespace KoolKode\Lexer;

/**
 * An iterator that is applied during serialization of token containers.
 *
 * @author Martin Schröder
 */
class SerializedTokenIterator extends \ArrayIterator
{
	public function __debugInfo()
	{
		return [
			'index' => $this->key(),
			'count' => $this->count()
		];
	}

	/**
	 * Consume the next token within the iteration (the iterator moves to
	 * the next element and the token is returned).
	 *
	 * @return AbstractToken
	 *
	 * @throws \OutOfBoundsException When the end of the iteration has been reached.
	 */
	public function consume()
	{
		if(!$this->valid())
		{
			throw new \OutOfBoundsException('No more serialized token data available');
		}

		$token = $this->current();
		$this->next();

		return $token;
	}

	/**
	 * Consume the next token and cast it's text content into an integer that
	 * is returned (the iterator moves to the next element).
	 *
	 * @return integer
	 *
	 * @throws \OutOfBoundsException When the end of the iteration has been reached.
	 * @throws \UnexpectedValueException When the consumed token is not of type integer.
	 */
	public function consumeInteger()
	{
		$value = $this->consume();

		if(!is_numeric($value))
		{
			throw new \UnexpectedValueException('Expecting integer, given ' . gettype($value));
		}

		return (int)$value;
	}
}


text:
import random
import string

import fixedlist

KEYS = 300
VALUES = 250

def main():
    fixedlist.set_redis(redis_host='0.0.0.0', redis_port=6380)

    # Ints
    for i in xrange(0, KEYS):
        list_key = 'test_list_%s' % i
        fixedlist.varnish(list_key)
        for i in range(0, VALUES):
            fixedlist.add(list_key, [i, i+1])
            assert len(fixedlist.get(list_key)) <= 200

    # Strings
    for i in xrange(0, KEYS):
        list_key = 'test_list_%s' % i
        fixedlist.varnish(list_key)
        for i in range(0, VALUES):
            fixedlist.add(list_key, [randomword(6), randomword(6)])
            assert len(fixedlist.get(list_key)) <= 200

def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length))

if __name__ == '__main__':
    main()


text:
<?php

namespace Zend\View\Helper;

use Zend\Authentication\AuthenticationServiceInterface;
use Zend\View\Exception;

/**
 * View helper plugin to fetch the authenticated identity.
 */
class Identity extends AbstractHelper
{
    /**
     * AuthenticationService instance
     *
     * @var AuthenticationServiceInterface
     */
    protected $authenticationService;

    /**
     * Retrieve the current identity, if any.
     *
     * If none available, returns null.
     *
     * @throws Exception\RuntimeException
     * @return mixed|null
     */
    public function __invoke()
    {
        if (!$this->authenticationService instanceof AuthenticationServiceInterface) {
            throw new Exception\RuntimeException('No AuthenticationServiceInterface instance provided');
        }

        if (!$this->authenticationService->hasIdentity()) {
            return;
        }

        return $this->authenticationService->getIdentity();
    }

    /**
     * Set AuthenticationService instance
     *
     * @param AuthenticationServiceInterface $authenticationService
     * @return Identity
     */
    public function setAuthenticationService(AuthenticationServiceInterface $authenticationService)
    {
        $this->authenticationService = $authenticationService;
        return $this;
    }

    /**
     * Get AuthenticationService instance
     *
     * @return AuthenticationServiceInterface
     */
    public function getAuthenticationService()
    {
        return $this->authenticationService;
    }
}


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

<title>com.hourglassapps.cpi_ii.stem.stempel.egothor</title>
<meta name="date" content="2015-04-26">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.hourglassapps.cpi_ii.stem.stempel.egothor

Classes

Compile

Diff

DiffIt

Gener

Lift

MultiTrie

MultiTrie2

Optimizer

Optimizer2

Reduce

Row

Trie


text:
const char *CLI_ALGORITHM_NAMES[NO_CLI_ALGOS] = {"kmeans"};
cli_function CLI_ALGORITHM_FUNCTIONS[NO_CLI_ALGOS] = {kmeans_task};


text:
const constants = require('./constants.js');
const authenticate = require('./functions/authenticate.js');
const getId = require('./functions/getId.js');
const getMetadata = require('./functions/getMetadata.js');
const error = require('./functions/error.js');
const displayProjectInfo = require('./functions/displayProjectInfo.js');
const checkNewVersion = require('./functions/checkNewVersion.js');
const findInProject = require('./functions/findInProject.js');

/**
 * Display info about a Google Apps Script project
 *
 * @param {String} identifier - Id of the project we want info about.
 * @returns {void}
 */
module.exports = async (identifier) => {
    let auth;
    try {
        const checkedVersion = await checkNewVersion();
        const projectRoot = await findInProject('.', constants.META_DIR);
        auth = await authenticate([]);

        let id;
        if (identifier) {
            id = identifier;
        } else if (projectRoot.found) {
            id = await getId(projectRoot.folder);
        } else {
            throw {
                message: `Can't seem to find a Google Apps Script project here`,
                print: true,
            };
        }

        const metadata = await getMetadata(auth, id);
        displayProjectInfo(metadata);
        process.exit(0);
    } catch (err) {
        await error.log(err, auth);
        process.exit(1);
    }
};


text:
import java.io.File;
import java.security.PrivilegedAction;

/**
 * This is a sample PrivilegedAction implementation, designed to be
 * used with the JaasAzn class.
 */
public class SampleAction implements PrivilegedAction {

    /**
     * This sample PrivilegedAction performs the following operations:
     *

     *
 Access the System property java.home
     *
 Access the System property user.home
     *
 Access the file foo.txt
     *

     *
     * @return null in all cases.
     *
     * @exception SecurityException if the caller does not have permission
     *          to perform any of the operations listed above.
     */
    public Object run() {
        System.out.println("\nYour java.home property value is: "
                            +System.getProperty("java.home"));

        System.out.println("\nYour user.home property value is: "
                            +System.getProperty("user.home"));

        File f = new File("foo.txt");
        System.out.print("\nfoo.txt does ");
        if (!f.exists())
            System.out.print("not ");
        System.out.println("exist in the current working directory.");
        return null;
    }
}