text:
package org.knopflerfish.bundle.component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.osgi.framework.*;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import org.osgi.service.component.ComponentConstants;
import org.osgi.service.component.runtime.ServiceComponentRuntime;

/**
 * Service Component Runtime
 */
class SCR implements SynchronousBundleListener
{
  final BundleContext bc;
  final CMHandler cmHandler;

  private final Set<Bundle> lazy = Collections.synchronizedSet(new HashSet<Bundle>());
  private final Hashtable<Bundle, Component[]> bundleComponents = new Hashtable<Bundle, Component[]>();
  private final Hashtable<String, Component[]> components = new Hashtable<String, Component[]>();
  private final Hashtable<String, Component[]> serviceComponents = new Hashtable<String, Component[]>();
  private final Hashtable<BundleContext, ComponentServiceListener> compListeners = new Hashtable<BundleContext, ComponentServiceListener>();
  private final HashMap<Thread, List<PostponedBind>> postponedBind = new HashMap<Thread, List<PostponedBind>>();
  private final HashMap<Thread, Integer> ppRef = new HashMap<Thread, Integer>();
  private long nextId = 0;

  /**
   *
   */
  SCR(BundleContext bc) {
    this.bc = bc;
    cmHandler = new CMHandler(this);
  }

  /**
   * Start SCR.
   *
   */
  void start() {
    cmHandler.start();
    bc.addBundleListener(this);
    postponeCheckin();
    try {
      final Bundle [] bundles = bc.getBundles();
      for (final Bundle bundle : bundles) {
        if ((bundle.getState() & (Bundle.ACTIVE | Bundle.STARTING)) != 0) {
          processBundle(bundle);
        }
      }
    } finally {
      postponeCheckout();
    }
    bc.registerService(ServiceComponentRuntime.class.getName(),
                       new ServiceComponentRuntimeImpl(this), null);
    bc.registerService(org.apache.felix.scr.ScrService.class.getName(),
                       new ScrServiceImpl(this), null);
  }

  /**
   * Stop SCR.
   *
   */
  void stop() {
    bc.removeBundleListener(this);
    cmHandler.stop();
    final Bundle [] b = bundleComponents.keySet().toArray(new Bundle[bundleComponents.size()]);
    for (final Bundle element : b) {
      removeBundle(element, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
    }
  }

  //
  // BundleListener method
  //

  /**
   * Process bundle components when it starts.
   */
  public void bundleChanged(BundleEvent event) {
    postponeCheckin();
    try {
      final Bundle bundle = event.getBundle();

      switch (event.getType()) {
      case BundleEvent.LAZY_ACTIVATION:
        lazy.add(bundle);
        processBundle(bundle);
        break;
      case BundleEvent.STARTED:
        if (!lazy.remove(bundle)) {
          processBundle(bundle);
        }
        break;
      case BundleEvent.STOPPING:
        lazy.remove(bundle);
        removeBundle(bundle, ComponentConstants.DEACTIVATION_REASON_BUNDLE_STOPPED);
        break;
      }
    } finally {
      postponeCheckout();
    }
  }

  //
  // Package methods
  //

  /**
   * Get next available component id
   *
   * @return Long component id.
   */
  synchronized Long getNextComponentId() {
    return new Long(nextId++);
  }

  /**
   * Check if bundle has service components and process them.
   *
   * @param b Bundle to check
   */
  void processBundle(Bundle b) {
    final String sc = b.getHeaders().get(ComponentConstants.SERVICE_COMPONENT);
    Activator.logDebug("Process header " + ComponentConstants.SERVICE_COMPONENT +
                       " for bundle#" + b.getBundleId() + ": " + sc);
    if (sc != null) {
      final ArrayList<String> entries = splitwords(sc);
      if (entries.size() == 0) {
        Activator.logError(b, "Header " + ComponentConstants.SERVICE_COMPONENT + " empty.", null);
        return;
      }
      XmlPullParser p;
      try {
        final XmlPullParserFactory f = XmlPullParserFactory.newInstance();
        f.setNamespaceAware(true);
        p = f.newPullParser();
      } catch (final XmlPullParserException xppe) {
        Activator.logError("Could not fina a XML parser", xppe);
        return;
      }
      final ArrayList<ComponentDescription> cds = new ArrayList<ComponentDescription>();
      for (String me : entries) {
        final int pos = me.lastIndexOf('/');
        final String path = pos > 0 ? me.substring(0, pos) : "/";
        final Enumeration<URL> e = b.findEntries(path, me.substring(pos+1), false);
        if (null != e) {
          while (e.hasMoreElements()) {
            final URL u = e.nextElement();
            InputStream is = null;
            try {
              is = u.openStream();
            } catch (final IOException ioe) {
              Activator.logError(b, "Failed to open: " + u, ioe);
              return;
            }
            try {
              p.setInput(is, null);
              Activator.logDebug("Parse component description: " + u);
              while (true) {
                try {
                  final ComponentDescription cd = ComponentDescription.parseComponent(b, p);
                  Activator.logDebug("Got component description: " + cd);
                  if (cd != null) {
                    cds.add(cd);
                  } else {
                    break;
                  }
                } catch (final XmlPullParserException pe) {
                  Activator.logError(b, "Componenent description in '" + u +"'. " +
                                     "Got " + pe, pe);
                }
              }
            } catch (final Exception exc) {
              Activator.logError(b, "Failed to read componenent description '" + u +"'.", exc);
            } finally {
              try {
                is.close();
              } catch (final IOException ioe) {
                Activator.logError(b, "Failed to close: " + u, ioe);
              }
            }
          }
        } else {
          Activator.logError(b, "Resource not found: " + me, null);
        }
      }
      if (cds.size() > 0) {
        final Component [] carray = new Component [cds.size()];
        for (int i = 0; i < carray.length; i++) {
          final ComponentDescription cd = cds.get(i);
          Component c;
          if (cd.isImmediate()) {
            c = new ImmediateComponent(this, cd);
          } else if (cd.getFactory() != null) {
            c = new FactoryComponent(this, cd);
          } else {
            c = new DelayedComponent(this, cd);
          }
          carray[i] = c;
          addComponentArray(components, cd.getName(), c);
          final String [] s = cd.getServices();
          if (s != null) {
            for (final String element : s) {
              addComponentArray(serviceComponents, element, c);
            }
          }
        }
        bundleComponents.put(b, carray);
        for (final Component element : carray) {
          if (element.compDesc.isEnabled()) {
            element.enable();
          }
        }
      }
    }
  }

  /**
   * Remove service resources for bundle
   *
   * @param b Bundle to check
   */
  void removeBundle(Bundle b, int reason) {
    Activator.logDebug("Remove " + b +" from SCR");
    final Component [] ca = bundleComponents.remove(b);
    if (ca != null) {
      for (final Component component : ca) {
        component.disable(reason, null);
        final ComponentDescription cd = component.compDesc;
        removeComponentArray(components, cd.getName(), component);
        final String [] services = cd.getServices();
        if (services != null) {
          for (final String service : services) {
            removeComponentArray(serviceComponents, service, component);
          }
        }
      }
    }
    ComponentServiceListener csl = compListeners.remove(b.getBundleContext());
    if (csl != null) {
      csl.close();
    }
  }

  /**
   * Disabled named component or all components owned by
   * specified bundle.
   *
   * @param name Component to disable or null if we want all
   * @param b Bundle owning component
   */
  void disableComponent(String name, Bundle b) {
    final Component [] ca = bundleComponents.get(b);
    if (ca != null) {
      for (final Component element : ca) {
        if (name == null || name.equals(element.compDesc.getName())) {
          element.disable(ComponentConstants.DEACTIVATION_REASON_DISABLED, null);
        }
      }
    }
  }

  /**
   * Enabled named component or all components owned by
   * specified bundle.
   *
   * @param name Component to enable or null if we want all
   * @param b Bundle owning component
   */
  void enableComponent(String name, Bundle b) {
    final Component [] ca = bundleComponents.get(b);
    if (ca != null) {
      for (final Component element : ca) {
        if (name == null || name.equals(element.compDesc.getName())) {
          element.enable();
        }
      }
    }
  }

  /**
   * Get all components.
   */
  List<Component> getAllComponents() {
    final ArrayList<Component> res = new ArrayList<Component>();
    while (true) {
      try {
        for (Component[] e : components.values()) {
          for (final Component element : e) {
            res.add(element);
          }
        }
        return res;
      } catch (final ConcurrentModificationException ignore) { }
      res.clear();
    }
  }

  /**
   * Get components with specified name.
   */
  Component [] getComponent(String name) {
    return components.get(name);
  }

  /**
   * Check if component is part of a circular reference chain.
   *
   * @param component Component to check
   * @param path Stack of referenced components
   * @return If circle found return message showing circle,
   *         otherwise return null.
   */
  String checkCircularReferences(Component component,
                                 ArrayList<Component> path) {
    final int len = path.size();
    if (len > 0 && path.get(0) == component) {
      final StringBuilder sb = new StringBuilder("Found circular component chain: ");
      for (final Component element : path) {
        sb.append((element).compDesc.getName());
        sb.append("->");
      }
      sb.append(component.compDesc.getName());
      return sb.toString();
    } else if (!component.isSatisfied() && !path.contains(component)) {
      // We have not checked component before and it is inactive
      final Reference [] rs = component.getRawReferences();
      if (rs != null) {
        path.add(component);
        for (int i = 0; i < rs.length; i++) {
          // Loop through all mandatory references
          if (!rs[i].isRefOptional()) {
            final Component [] cs = serviceComponents.get(rs[i].refDesc.interfaceName);
            if (cs != null) {
              Filter targetFilter = rs[i].getCurrentTarget();
              boolean prototype_required =  ReferenceDescription.SCOPE_PROTOTYPE_REQUIRED.equals(rs[i].getScope());
              // Loop through all found components
              for (final Component c : cs) {
                if ((targetFilter == null || targetFilter.match(c.getProperties())) &&
                    (!prototype_required || Constants.SCOPE_PROTOTYPE.equals(c.getScope()))) {
                  final String res = checkCircularReferences(c, path);
                  if (res != null) {
                    return res;
                  }
                }
              }
            }
          }
        }
        path.remove(len);
      }
    }
    return null;
  }

  /**
   * Save binds that where circular binds.
   */
  void postponeBind(ComponentContextImpl cci, ReferenceListener rl, ServiceReference<?> sr) {
    if (rl.isDynamic() && rl.isOptional()) {
      final Thread ct = Thread.currentThread();
      synchronized (ppRef) {
        List<PostponedBind> ppBinds = postponedBind.get(ct);
        if (ppBinds == null) {
          ppBinds = new ArrayList<PostponedBind>();
          postponedBind.put(ct, ppBinds);
        }
        ppBinds.add(new PostponedBind(cci, rl, sr));
      }
      Activator.logDebug("Postpone bind service " + Activator.srInfo(sr) + " to " + cci);
    } else {
      Activator.logDebug("Not dynamic, skip postpone bind service " + Activator.srInfo(sr) + " to " + cci);
    }
  }

  /**
   * Save binds that where circular binds.
   */
  void clearPostponeBind(ComponentContextImpl cci, ReferenceListener rl, ServiceReference<?> sr) {
    if (rl.isDynamic() && rl.isOptional()) {
      synchronized (ppRef) {
        for (final List<PostponedBind> list : postponedBind.values()) {
          for (final Iterator<PostponedBind> j = list.iterator(); j.hasNext(); ) {
            final PostponedBind pb = j.next();
            if (pb.cci == cci && pb.rl == rl && pb.sr == sr) {
              j.remove();
              Activator.logDebug("Cleared postponed bind " + Activator.srInfo(sr)
                                 + " to " + cci);
            }
          }
        }
      }
    }
  }

  /**
   * Check-in thread for saving postponed binds.
   */
  void postponeCheckin() {
    synchronized (ppRef) {
      final Thread ct = Thread.currentThread();
      Integer refCount = ppRef.get(ct);
      if (refCount != null) {
        refCount = new Integer(refCount.intValue() + 1);
      } else {
        refCount = new Integer(1);
      }
      ppRef.put(ct, refCount);
    }
  }

  /**
   * Check-out thread for saving postponed binds.
   */
  void postponeCheckout() {
    final Thread ct = Thread.currentThread();
    List<PostponedBind> ppBinds;
    synchronized (ppRef) {
      final Integer refCount = ppRef.get(ct);
      if (refCount != null) {
        final int i = refCount.intValue() - 1;
        if (i > 0) {
          ppRef.put(ct, new Integer(i));
          return;
        }
      } else {
        Activator.logError("Ref. count for postpone failed",
                           new Throwable());
      }
      ppBinds = postponedBind.remove(ct);
    }
    if (ppBinds != null) {
      for (final PostponedBind postponedBind2 : ppBinds) {
        postponedBind2.retry();
      }
    }
    synchronized (ppRef) {
      ppBinds = postponedBind.remove(ct);
      ppRef.remove(ct);
    }
    // We don't retry failed rebinds again
    if (ppBinds != null) {
      for (final PostponedBind postponedBind2 : ppBinds) {
        Activator.logInfo("Skip, retried postponed bind: " +
                          postponedBind2.toString());
      }
    }
  }

  /**
   * Get all components for a bundle
   */
  Component [] getComponents(Bundle b) {
    return bundleComponents.get(b);
  }

  ComponentServiceListener getComponentServiceListener(BundleContext bc)
  {
    ComponentServiceListener res = compListeners.get(bc);
    if (res == null) {
      res = new ComponentServiceListener(bc);
      compListeners.put(bc, res);
    }
    return res;
  }

  //
  // Private methods
  //

  /**
   * Add component inside an array in a map.
   *
   */
  private static void addComponentArray(Map<String, Component[]> map, String key, Component c) {
    final Component [] a = map.get(key);
    if (a == null) {
      map.put(key, new Component [] {c});
    } else {
      final Component [] n = new Component[a.length + 1];
      System.arraycopy(a, 0, n, 0, a.length);
      n[a.length] = c;
      map.put(key, n);
    }
  }

  /**
   * Remove component inside an array in a map. Remove array if empty.
   *
   */
  private static void removeComponentArray(Map<String, Component[]> map, String key, Component c) {
    final Component [] a = map.get(key);
    if (a != null) {
      if (a.length == 1) {
        if (a[0] == c) {
          map.remove(key);
        }
      } else {
        final Component [] n = new Component[a.length - 1];
        int offset = 0;
        for (int i = 0; i < n.length; i++) {
          if (a[i + offset] == c) {
            offset = 1;
          }
          n[i] = a[i + offset];
        }
        if (offset == 1 || a[n.length] == c) {
          map.put(key, n);
        }
      }
    }
  }

  /**
   * Split a string into words separated by specified separator characters.
   * All whitespace characters will also be removed unless inside a quote.
   * <p>
   * Citation character (") may be used to group words with embedded
   * whitespace and separator characters.
   * </p>
   *
   * @param s          String to split.
   * @param separators Character to use for splitting. Any of the
   *                   characters in the separator string are considered
   *                   to be separator between words and will be removed
   *                   from the result. If no words are found, return an
   *                   array of length zero.
   */
  private static ArrayList<String> splitwords(String s) {
    boolean bCit = false;            // true when inside citation chars.
    final ArrayList<String> res = new ArrayList<String>();
    int first = -1;
    int last = -1;

    for (int i = 0; i < s.length(); i++) {
      final char c = s.charAt(i);
      if (bCit || c != ',') {
        if (first >= 0) {
          if (c == '"') {
            bCit = !bCit;
          } else if (bCit || !Character.isWhitespace(c)) {
            last = i;
          }
        } else if (!Character.isWhitespace(c)) {
          first = c == '"' ? i+1 : i;
          last = i;
        }
      } else {
        res.add(s.substring(first, last+1));
        first = -1;
      }
    }
    if (first >= 0) {
      res.add(s.substring(first, last+1));
    }
    return res;
  }

}


text:
class Player;
class BadGuy;

//idle is in between turns
//waiting is skip a turn
//moving and fighting are
enum class CreatureState{IDLE, WAITING, MOVING, FIGHTING};

class Creature
{
public:
	Creature();
	~Creature();
	void update(CreatureState turnState,
		const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player);

	void draw(DPE::SpriteBatch& m_spriteBatch);

	int getEvade() const { return m_evade; }
	int getHealth() const { return m_health; }
	int getMaxHealth() const { return m_maxHealth; }

	glm::vec2 getPosition() const { return m_position; }

	void applyDamage(const int& damage);

	const int TILE_SIZE = 128;

	Armor getArmor() const { return m_armor; }
	Weapon getWeapon() const { return m_weapon; }

protected:

	void performTurn(CreatureState turnState,
		const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player);

	virtual void onAttack(const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player) {
		std::cout << "oof" << std::endl;
	}

	virtual void onMove(const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player);

	virtual void onBeginSequence(const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player) {
		std::cout << "oof" << std::endl;
	}

	virtual void onBeginTurn(const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player) {
		std::cout << "oof" << std::endl;
	}

	virtual void onIdle(const float& progressThroughTurn,
		const int& turnsSinceStart,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		std::vector<BadGuy*>& badGuys,
		Player& player) {
	}

	void setTarget(const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entMap,
		glm::vec2 target);

	void moveTowardsTile(const glm::vec2& nodePosOne,
		const glm::vec2& nodePosTwo,
		const std::vector<std::vector<int>>& map,
		std::vector<std::vector<int>>& entmap,
		int fractionBetweenTwo);
	//returns true when arrived to next tile
	//bool moveToNextTile(std::vector<Node>& path, const std::vector<std::vector<int>>& map, std::vector<std::vector<int>>& entmap, float deltaTime);
	//uses raw positions and uses Bresenham
	bool seesPoint(const std::vector<std::vector<int>>& map, const std::vector<std::vector<int>>& entmap, glm::vec2 end);

	glm::vec2 m_position = glm::vec2(0.0f, 0.0f);

	//used for animation
	glm::vec2 m_nextPosition = glm::vec2(0.0f);

	int m_direction = 0; // 2 = left, 1 = right

	DPE::TileSheet m_tileSheet;
	DPE::ColorRGBA8 m_color;

	std::vector<Node> m_path;

	PathFinder m_pathFinder;

	//frames in between animations
	double m_animSpeed = 5;

	float m_animTime = 0.0;

	int m_evade = 0;

	int m_health = 10;

	int m_maxHealth = 10;

	bool m_shouldWait = false;

	int m_animTile = 0;

	Armor m_armor;
	Weapon m_weapon;

	BresenhamAlgorithm visionThing;
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RapidPliant.App
{
    public static class AppBoostrapper
    {
        public static void Run<TApplication>()
            where TApplication : RapidPliantAppliction, new()
        {
            var app = new TApplication();
            app.Run();
        }
    }
}


text:
 	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                         initWithImage:img
                                         style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(onBack:)];
	self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;

#####ScrollView莫名其妙不能在viewController划到顶怎么办?

	self.automaticallyAdjustsScrollViewInsets = NO;

#####想在代码里改在xib里添加的layoutAttributes,但是怎么用代码找啊?
像拉button一样的拉你的约束.nslayoutattribute也是可以拉线的.

#####怎么像safari一样滑动的时候隐藏navigationbar?
	navigationController.hidesBarsOnSwipe = Yes

#####导航条返回键带的title太讨厌了,怎么让它消失!
	[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                     forBarMetrics:UIBarMetricsDefault];

#####本来我的statusbar是lightcontent的,结果用UIImagePickerController会导致我的statusbar的样式变成黑色,怎么办?

	- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
	{
    	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
	}

#####怎么把我的navigationbar弄成透明的而不是带模糊的效果?
	[self.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
	self.navigationBar.shadowImage = [UIImage new];
	self.navigationBar.translucent = YES;

#####怎么改变uitextfield placeholder的颜色和位置?

1. 重写方法

		- (void) drawPlaceholderInRect:(CGRect)rect
		{
    		[[UIColor blueColor] setFill];
    		[self.placeholder drawInRect:rect withFont:self.font 	lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
		}

2. KVC

 		UIColor *color = [UIColor whiteColor];
    	_userName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"用户名" attributes:@{NSForegroundColorAttributeName: color}];

		[_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

#####应该使用FOUNDATION_EXPORT还是#define来定义常量?
一般iOS我们定义常量的方法有两种,来看下面例子
我的.h文件

	FOUNDATION_EXPORT NSString * const kMyConstantString;
	FOUNDATION_EXPORT NSString * const kMyConstantString2;
.m文件是这样定义的

	NSString * const kMyConstantString = @"Hello";
	NSString * const kMyConstantString2 = @"World";
还有一种是常用的#define方法了

	#define kMyConstantString @"Hello"

有什么区别呢?
使用第一种方法在检测字符串的值是否相等的时候更快.对于第一种你可以直接使用`(stringInstance == MyFirstConstant)`来比较,而`define`则使用的是这种`.([stringInstance isEqualToString:MyFirstConstant])`
哪个效率高,显而易见了.第一种直接比较的是指针地址,而第二个则是一一比较字符串的每一个字符是否相等.

#####static inline function是干嘛的?
如果你的.m文件需要频繁调用一个函数,可以用static inline来声明,这相当于把函数体当做一个大号的宏定义.不过这也不是百分之百有效,到底能不能把函数体转换为大号宏定义来用要看编译器心情,它要是觉得你的方法太复杂,他就不转了.他直接调用函数.
类似这种简单函数他肯定是乐意的.

	static inline CGRect ScaleRect(CGRect rect, float n)

#####


text:
package main

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"net/http"
	"regexp"
	"strings"
	"time"
)

const (
	openState = "open"
	// closeState = "close"
)

type Close struct{}

func (b *Close) closeIndices(host string, indices []clusterIndex, candidates []retention, now time.Time) {
	re := regexp.MustCompile("\\d{4}.\\d{2}.\\d{2}")

	for _, index := range indices {
		if index.State == openState {
			for _, candidate := range candidates {
				if strings.HasPrefix(index.Name, candidate.IndexPrefix) {
					match := re.FindString(index.Name)

					if match != "" {
						t, err := time.Parse("2006.01.02", match)

						if err != nil {
							log.Panic(err)
						}

						threshold := now.AddDate(0, 0, candidate.IndexRetention*-1)

						if t.Before(threshold) {
							fmt.Println("Closing " + index.Name)
							b.flushIndex(host, index)
							b.closeIndex(host, index)
						}
					}

				}

			}
		}
	}
}

func (b *Close) flushIndex(host string, index clusterIndex) {
	url := fmt.Sprintf("%s/%s/_flush", host, index.Name)

	resp, err := http.Post(url, "application/json", nil)
	defer resp.Body.Close()

	if err != nil {
		log.Panic(err)
	}

	if resp.StatusCode != 200 {
		log.Panic(fmt.Sprintf("Response code is %d", resp.StatusCode))
	}
}

func (b *Close) closeIndex(host string, index clusterIndex) {
	url := fmt.Sprintf("%s/%s/_close", host, index.Name)

	resp, err := http.Post(url, "application/json", nil)
	defer resp.Body.Close()

	if err != nil {
		log.Panic(err)
	}

	if resp.StatusCode != 200 {
		log.Panic(fmt.Sprintf("Response code is %d", resp.StatusCode))
	}
}

func (b *Close) Invoke(host string, candidates []retention) {
	indices := ListIndices(host)
	b.closeIndices(host, indices, candidates, time.Now())
}


text:
import * as Redux from 'redux';
import { connect } from 'react-redux';
import { default as ScrumBoard, OwnProps, StateProps, DispatchProps } from '../components/ScrumBoard';
import { AppState, Action, BoardId } from '../../shared/models';
import ScrumBoardDispatcher from '../../shared/dispatchers/ScrumBoardDispatcher';
import store from '../store';

const mapStateToProps = (state: AppState, ownProps: OwnProps): StateProps => ({
    board: state.boards.filter(board => {
        return board.id.value === ownProps.match.params.valueOfBoardId
    })[0]
})

const mapDispatchToProps = (dispatch: Redux.Dispatch<Action<any>>, ownProps: OwnProps): DispatchProps => ({
    scrumBoardDispatcher: new ScrumBoardDispatcher(
        dispatch, store.getState, BoardId.create(ownProps.match.params.valueOfBoardId))
});

export default connect<StateProps, DispatchProps, OwnProps>(
    mapStateToProps,
    mapDispatchToProps
)(ScrumBoard);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Docums Mycol. 31(no. 124): 4 (2002)

#### Original name
Inocybe griseotarda Poirier

### Remarks
null


text:
require_dependency "subscribem/application_controller"

module Subscribem
  #The book doesn't explicitly say that it should inherit from
  #Subscribem::ApplicationController but all others under account do
  class Account::UsersController < Subscribem::ApplicationController
    def new
      @user = Subscribem::User.new
    end

    def create
      account = Subscribem::Account.find_by!(:subdomain => request.subdomain)
      user = account.users.create(user_params)
      force_authentication!(account, user)
      flash[:success] = "You have signed up successfully."
      redirect_to root_path
    end

    private
      def user_params
        params.require(:user).permit(:email, :password, :password_confirmation)
      end
  end
end


text:
/*
Implement copy on write string class in c++
*/

/*
Because we want to implement copy on write class, we define copy constructor, assignment operator.
In real application, we should disallow copy constructor and assignment operator.
*/

#include<iostream>
using namespace std;

class CopyOWString {
public:
    CopyOWString(const char* str) { newStr(str); }
    CopyOWString(CopyOWString& cowStr) { incRef(cowStr); }
    ~CopyOWString() { decRef(); }

    char* getStr(){return strcontent;}
    int* getCount(){return referencecount;}

    CopyOWString& operator = (const char* str);
    CopyOWString& operator = (CopyOWString& cowStr);

private:
    void incRef(CopyOWString& cowStr);
    void decRef();
    void newStr(const char* str);

    char* strcontent;
    int* referencecount;
};

/*
Increase the reference count to string
*/
void CopyOWString::incRef(CopyOWString& cowStr) {
    referencecount = cowStr.referencecount;
    strcontent = cowStr.strcontent;
    (*referencecount)++;
}

/*
Decrease the reference count to string
*/
void CopyOWString::decRef() {
    (*referencecount)--;
    if (*referencecount <= 0) {
        delete []strcontent;
        delete referencecount;
    }
}

void CopyOWString::newStr(const char* str) {
    strcontent= new char[strlen(str) + 1];
    strcpy(strcontent, str);
    referencecount = new int(1);
}

CopyOWString& CopyOWString::operator = (CopyOWString& cowStr) {
    if (this != &cowStr) {
        decRef();
        incRef(cowStr);
    }
    return *this;
}

CopyOWString& CopyOWString::operator = (const char* str) {
    decRef();
    newStr(str);
    return *this;
}

int main() {

    CopyOWString a("abc");
    cout<<*a.getStr()<<endl;
    cout<<*a.getCount()<<endl;
    CopyOWString b(a);
    cout<<*a.getCount()<<endl;
    a.~CopyOWString();
    cout<<*a.getCount()<<endl;
    return 0;
}


text:
/*
 * NodeTV - app.js
 * Author: Gordon Hall
 *
 * Released under MIT license - see LICENSE
 */

(function() {

	// init vars
	var config
	  , version = '0.1.0a'
	// get modules
	  , fs = require('fs')
	  , git = require('gitty')
	// get os module
	  , os = require('os')
	  , qs = require('querystring')
	// get middleware
	  , express = require('express')
	  , app = express.createServer()
	  , http = require('http')
	  , jade = require('jade')
	// create socket connection
	  , io = require('socket.io').listen(app)
	  , port = 1337
	  , nslookup = require('dns').lookup
	  , netIp
	  , launched_apps = {};

	// console output colors
	var red = '\u001b[31m'
	  , blue = '\u001b[34m'
	  , reset = '\u001b[0m';

	var ipFlag = false;
	console.log('Starting NodeTV...');
	console.log('Resolving network IP...');
	resolveIp(os.hostname());

	function resolveIp(hostname) {
		// determine network ip from hostname
		nslookup(hostname, function(err, addr, fam) {
			// if failed
			if (err) {
				// if there is a domain in the hostname
				if (os.hostname().split('.').length === 3) {
					// let the user know
					console.log(red + '!!! ' + reset + 'NodeTV has detected a potential issue while resolving your IP, applying workaround...');
					ipFlag = true;
					// try again without it
					var hostNoDomain = os.hostname().split('.')[0] + '.' + os.hostname().split('.')[2];
					resolveIp(hostNoDomain);
				} else {
					// otherwise tell the user something's up
					console.log(red + 'There was a problem resolving the network IP from the server\'s hostname.' + reset);
					// and quit
					process.exit();
				}
			} else {
				if (ipFlag) {
					console.log(red + '!!! ' + reset + 'NodeTV applied a workaround for an issue and may exhibit unexpected behavior.');
				}
				// all is good give NodeTV the resolved IP
				netIp = addr;
				// once IP is resolved, start the server
				// this nslookup fixes an issue for devices that are unable
				// to resolve a hostname over LAN, like Android
				init();
			}
		});
	}

	function init() {
		// load modules
		require('./remote.js')(io);

		// config server
		app.configure(function() {

			// set view directory and engine
			app.set('views', __dirname + '/views');
			app.set('view engine', 'jade');

			// methodOverride checks req.body.method for the HTTP method override
			// bodyParser parses the request body and populates req.body
			app.use(express.methodOverride());
			app.use(express.bodyParser());

			// use cookie parser
			app.use(express.cookieParser());

			// set public directory for static files
			app.use(express.static(__dirname + '/public'));

			// use router for non-static files
			app.use(app.router);

		});

		// dev env
		app.configure('development', function(){
			app.use(express.errorHandler({
				dumpExceptions: true,
				showStack: true
			}));
		});

		// prod env
		app.configure('production', function(){
			app.use(express.errorHandler());
		});

		/*
		 * http routes
		 */

		// render app
		app.get('/', function(req, res) {
			res.render('index', {
				layout : 'layout',
				netIp : 'http://' + netIp,
				version : version
			});
		});

		// give client the app list
		app.get('/applist', function(req, res) {
			// generate a temporary unique id for each app
			var appId = function() {
				var chars = 'abcdefghijklmnopqrstuvwxyz1234567890'
				  , id = '';
				for (var i = 0; i < 10; i++) {
					id += chars.charAt((Math.random() * chars.length - 1).toFixed());
				}
				return id;
			};

			// get app list, create array, and send to client
			fs.readdir(__dirname + '/apps', function(err, files) {
				if (err || !files.length) {
					// if an error is thrown log it and tell the client
					console.log(err || red + '!!! ' + reset + 'No apps installed. Failed.');
					res.writeHead(500);
					res.write('Error reading app directory or no apps are installed.');
					res.end();
				} else {
					// otherwise lets serve up some apps
					var applist = [];
					// construct app object from manifest file
					files.forEach(function(val, key) {
						var appname = val
						// get manifest path
						  , manifest = __dirname + '/apps/' + appname + '/manifest.json'
						  , appconfig = JSON.parse(fs.readFileSync(manifest));
						// resolve paths to public route
						appconfig.icon = '/apps/' + appname + appconfig.icon;
						// do the same for each script
						appconfig.scripts.forEach(function(val, key) {
							appconfig.scripts[key] = '/apps/' + appname + val;
						});
						// give id
						appconfig.id = appname + ':' + appId();
						// add to list
						applist.push(appconfig);
					});

					res.writeHead(200);
					res.write(JSON.stringify(applist));
					res.end();
				}
			});
		});

		// resolve static content for apps
		app.get('/apps/:appname/:directory/:file', function(req, res) {
			// get params
			var params = req.params
			  , appname = params.appname
			  , dir = params.directory
			  , file = params.file
			  , path = __dirname + '/apps/' + appname + '/' + dir + '/' + file;
			// determine if file is valid
			fs.exists(path, function(valid) {
				if (valid) {
					// read the file
					var asset = fs.readFileSync(path);
					// and serve it up
					res.writeHead(200);
					res.end(asset);
				} else {
					// fail
					res.writeHead(404);
					res.write('File not found.');
					res.end();
				}
			});
		});

		// app launcher/ui server
		app.post('/launch/:appname', function(req, res) {
		    var appname = req.params.appname
              , app_dir = __dirname + '/apps/' + appname
              , appconfig
              , manifest = app_dir + '/manifest.json';
            // sanity check
            if (fs.existsSync(manifest)) {
                appconfig = JSON.parse(fs.readFileSync(manifest));
                // determine if the view should be rendered or sent
                var splitup = appconfig.home.split('.')
                  , last = splitup.length - 1;
                // render jade template
                if (splitup[last] == 'jade') {
                    res.render(app_dir + appconfig.home, {
                        layout: false
                    });
                // render static html
                } else if (splitup[last] == 'html') {
                    res.writeHead(200);
                    fs.readFile(app_dir + appconfig.home, function(err, data) {
                        res.write(data);
                        res.end();
                    });
                }
                // require server side code
                if (appconfig.init && !(launched_apps[appname])) {
                    require(app_dir + appconfig.init)(app);
                    launched_apps[appname] = true
                }
            } else {
                res.writeHead(404);
                res.end();
            }
		});

		// get mounted drives
		app.get('/getMountedDisks', function(req, res) {
		    // determine os type
		    var platform = os.platform()
		      , disks = []
		      , paths = {
		      		'darwin' : '/Volumes',
		      		'linux' : '/mnt'
		      };
		    // find and parse mounted disks
		    fs.readdir(paths[platform], function(err, data) {
		    	if (err) {
		    		res.writeHead(500);
		    		res.end();
		    	} else {
		    		data.forEach(function(val, key) {
		    			var disk = {
		    				name : val,
		    				path : paths[platform] + '/' + val
		    			};
		    			disks.push(disk);
		    		});
		    		res.write(JSON.stringify(disks));
		    		res.end();
		    	}
		    });
		});

		// finds subdirectories of the passed path and returns them in an array
		app.get('/listDirectories', function(req, res) {
			// get the path var
			var path = qs.parse(req.url.split('?')[1]).path
			  , dirs = [];
			// if the path is good then get it's dirs
			if (fs.existsSync(path)) {
				fs.readdir(path, function(err, files) {
					files.forEach(function(val,key) {
						if (fs.lstatSync(path + '/' + val).isDirectory() && val.charAt(0) !== '.') {
							dirs.push(val);
						}
					});
					res.write(JSON.stringify(dirs));
					res.end();
				});
			// otherwise fail
			} else {
				res.writeHead(500);
				res.write('Invalid path.');
				res.end();
			}
		});

		// index library
		app.post('/indexLibrary', function(req, res) {
			var path = qs.parse(req.url.split('?')[1]).path;
		    // scan path for movies, music, and pictures
		    require('./indexlib.js')(path, io, function(data) {
		        // respond with library
		        res.write(JSON.stringify(data));
		        res.end();
		    }, function(err) {
		        res.writeHead(500);
		        res.end();
		    });
		});

		// send the media request by the path
		app.get('/play', function(req, res) {
		    var path = qs.parse(req.url.split('?')[1]).path;
		    // retrieve media and respond with it
		});

		/*
		 * start server
		 */

		app.listen(port, function() {
			console.log('NodeTV running at ' + netIp + ':' + port);
		});
	}

})();


text:
package com.sissi.pipeline.in.iq.bytestreams;

import com.sissi.pipeline.in.ClassMatcher;
import com.sissi.protocol.Protocol;
import com.sissi.protocol.iq.bytestreams.Bytestreams;

/**
 * <query xmlns='http://jabber.org/protocol/bytestreams'><streamhost-used jid='streamhostproxy.example.net'/></query>
 *
 * @author kim 2013年12月24日
 */
public class BytestreamsUsedMatcher extends ClassMatcher {

	public BytestreamsUsedMatcher() {
		super(Bytestreams.class);
	}

	public boolean match(Protocol protocol) {
		return super.match(protocol) && protocol.cast(Bytestreams.class).used();
	}
}


text:
package nio.mapping;

import java.io.File;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import nio.base.BufferAutoRegisteringFactory;
import nio.base.IBufferFactory;
import nio.base.INio;

/**
 * Pametovo namapovany arraylist pre jeden objekt, ktory ma
 * konstantnu velkost.
 *
 * @author Lukas Sekerak
 * @param <T>
 */
public class StaticArrayList<T extends INio> extends SimpleArrayList<T>
{

	public StaticArrayList(File file,
			int elementsize,
			int DelimPoPrvkov,
			IBufferFactory factory) throws IOException {
		super(file, elementsize, DelimPoPrvkov);
		map.setFactory(factory);
	}

	public StaticArrayList(File file,
			int elementsize,
			int DelimPoPrvkov,
			IBufferFactory factory,
			int initialSize) throws IOException {
		this(file, elementsize, DelimPoPrvkov, factory);
		Initialize(initialSize);
	}

	public boolean add(T v) {
		add();
		set(size() - 1, v);
		return true;
	}
	public synchronized int add2(T v) {
		add();
		int size = size() - 1;
		set(size, v);
		return size;
	}
	public synchronized void get(int index, T value) {
		value.nioRead(getBuffer(index));
	}

	public T set(int index, T value) {
		value.nioWrite(getBuffer(index));
		return value;
	}

	@Override
	public void add(int arg0, T arg1) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean addAll(Collection<? extends T> arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean addAll(int arg0, Collection<? extends T> arg1) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean containsAll(Collection<?> arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean removeAll(Collection<?> arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean retainAll(Collection<?> arg0) {
		throw new UnsupportedOperationException();
	}
	@SuppressWarnings("hiding")
	@Override
	public <T> T[] toArray(T[] arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public T get(int index) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean contains(Object arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public int indexOf(Object arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean isEmpty() {
		return size() == 0;
	}
	@Override
	public Iterator<T> iterator() {
		throw new UnsupportedOperationException();
	}
	@Override
	public int lastIndexOf(Object arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public ListIterator<T> listIterator() {
		throw new UnsupportedOperationException();
	}
	@Override
	public ListIterator<T> listIterator(int arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public boolean remove(Object arg0) {
		throw new UnsupportedOperationException();
	}
	@Override
	public T remove(int index) {
		super.delete(index);
		return null;
	}
	@Override
	public List<T> subList(int arg0, int arg1) {
		throw new UnsupportedOperationException();
	}
	@Override
	public Object[] toArray() {
		throw new UnsupportedOperationException();
	}
	@Override
	public void clear() {
		throw new UnsupportedOperationException();
	}

	public static void main(String[] args) {
		class Cislo implements INio
		{
			public int	a;

			@Override
			public void nioWrite(MappedByteBuffer buffer) {
				buffer.putInt(a);
			}
			@Override
			public void nioRead(MappedByteBuffer buffer) {
				a = buffer.getInt();
			}
			public Cislo(int v) {
				a = v;
			}
		}
		StaticArrayList<Cislo> test = null;
		IBufferFactory factory = new BufferAutoRegisteringFactory();

		try {
			test = new StaticArrayList<Cislo>(new File("test.db"), 100000, 1000000, factory);
			for (int i = 0; i < test.size(); i++) {
				test.set(i, new Cislo(i));
			}
			Cislo cislo = new Cislo(5);
			for (int i = 0; i < test.size(); i++) {
				test.get(i, cislo);
			}
			System.out.println();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}


text:
-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Dec 10, 2015 at 10:24 PM
-- Server version: 5.6.21
-- PHP Version: 5.6.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `ntaskmanager`
--

-- --------------------------------------------------------

--
-- Table structure for table `centers`
--

CREATE TABLE IF NOT EXISTS `centers` (
`id` int(11) NOT NULL,
  `center_name` varchar(100) NOT NULL,
  `location` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `centers`
--

INSERT INTO `centers` (`id`, `center_name`, `location`) VALUES
(1, 'Berekuso Health Center', 'Eastern region-Berekuso township');

-- --------------------------------------------------------

--
-- Table structure for table `nurses`
--

CREATE TABLE IF NOT EXISTS `nurses` (
`id` int(11) NOT NULL,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `centerId` int(11) NOT NULL,
  `userid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `report_log`
--

CREATE TABLE IF NOT EXISTS `report_log` (
  `id` int(11) NOT NULL,
  `report message` varchar(500) NOT NULL,
  `datetime` datetime NOT NULL,
  `task_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `supervisors`
--

CREATE TABLE IF NOT EXISTS `supervisors` (
`id` int(11) NOT NULL,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `userid` int(11) NOT NULL,
  `centerid` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `supervisors`
--

INSERT INTO `supervisors` (`id`, `firstname`, `lastname`, `userid`, `centerid`) VALUES
(1, 'Eric', 'Appiah', 2, 1);

-- --------------------------------------------------------

--
-- Table structure for table `tasks`
--

CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL,
  `title` varchar(200) NOT NULL,
  `description` varchar(200) NOT NULL,
  `postdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `enddate` date NOT NULL,
  `assigned` int(1) NOT NULL,
  `nid` int(11) NOT NULL,
  `sid` int(11) NOT NULL,
  `status` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tasks`
--

INSERT INTO `tasks` (`id`, `title`, `description`, `postdate`, `enddate`, `assigned`, `nid`, `sid`, `status`) VALUES
(3, 'asdasdadasda', 'sdadsdasdas', '2015-12-10 17:26:33', '2015-12-26', 0, 0, 1, 'uncompleted');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `permission` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `password`, `permission`) VALUES
(1, 'admin', 'admin', 0),
(2, 'eric.appiah', 'ericappiah', 1);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `centers`
--
ALTER TABLE `centers`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `nurses`
--
ALTER TABLE `nurses`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `supervisors`
--
ALTER TABLE `supervisors`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `tasks`
--
ALTER TABLE `tasks`
 ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `centers`
--
ALTER TABLE `centers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `nurses`
--
ALTER TABLE `nurses`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `supervisors`
--
ALTER TABLE `supervisors`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `tasks`
--
ALTER TABLE `tasks`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text: Some Dev Tools I use


text:
#pragma once

#include "DFGCommon.h"

#if ENABLE(FTL_JIT)

#include "CCallHelpers.h"
#include <wtf/ThreadSafeRefCounted.h>

namespace JSC { namespace FTL {

class State;
struct OSRExit;

// This is an object that stores some interesting data about an OSR exit. It's expected that you will
// scrape this data from this object by the time compilation finishes.
struct OSRExitHandle : public ThreadSafeRefCounted<OSRExitHandle> {
    OSRExitHandle(unsigned index, OSRExit& exit)
        : index(index)
        , exit(exit)
    {
    }

    unsigned index;
    OSRExit& exit;

    // This is the label at which the OSR exit jump lives. This will get populated once the OSR exit
    // emits its jump. This happens immediately when you call OSRExit::appendOSRExit(). It happens at
    // some time during late path emission if you do OSRExit::appendOSRExitLater().
    CCallHelpers::Label label;

    // This emits the exit thunk and populates 'label'.
    void emitExitThunk(State&, CCallHelpers&);
};

} } // namespace JSC::FTL

#endif // ENABLE(FTL_JIT)


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('stories', '0005_auto_20141221_1953'),
    ]

    operations = [
        migrations.AlterField(
            model_name='story',
            name='date_of_visit',
            field=models.DateField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
    ]


text:
import logging

from collections import OrderedDict

from django.conf import settings
from django.core.cache import cache
from django.shortcuts import render

from apiclient.errors import Error as GoogleAPIError
from oauth2client.client import Error as Oauth2Error
from OpenSSL.crypto import Error as OpenSSLError

from kitsune.announcements.models import Announcement
from kitsune.announcements.forms import AnnouncementForm
from kitsune.lib.sumo_locales import LOCALES
from kitsune.products.models import Product
from kitsune.sumo.googleanalytics import visitors_by_locale
from kitsune.wiki.events import (
    ApproveRevisionInLocaleEvent, ReadyRevisionEvent,
    ReviewableRevisionInLocaleEvent)

log = logging.getLogger('k.dashboards')

def render_readouts(request, readouts, template, locale=None, extra_data=None, product=None):
    """Render a readouts, possibly with overview page.

    Use the given template, pass the template the given readouts, limit the
    considered data to the given locale, and pass along anything in the
    `extra_data` dict to the template in addition to the standard data.

    """
    current_locale = locale or request.LANGUAGE_CODE
    on_default_locale = request.LANGUAGE_CODE == settings.WIKI_DEFAULT_LANGUAGE

    default_kwargs = {
        'locale': settings.WIKI_DEFAULT_LANGUAGE,
    }
    locale_kwargs = {
        'locale': request.LANGUAGE_CODE,
    }
    ready_kwargs = {}

    if product is not None:
        default_kwargs['product'] = product.slug
        locale_kwargs['product'] = product.slug
        ready_kwargs['product'] = product.slug

    data = {
        'readouts': OrderedDict((slug, class_(request, locale=locale,
                                              product=product))
                                for slug, class_ in readouts.iteritems()
                                if class_.should_show_to(request)),
        'default_locale': settings.WIKI_DEFAULT_LANGUAGE,
        'default_locale_name': LOCALES[settings.WIKI_DEFAULT_LANGUAGE].native,
        'current_locale': current_locale,
        'current_locale_name': LOCALES[current_locale].native,
        'request_locale_name': LOCALES[request.LANGUAGE_CODE].native,
        'is_watching_default_approved':
            ApproveRevisionInLocaleEvent.is_notifying(request.user, **default_kwargs),
        'is_watching_other_approved': (
            None if on_default_locale
            else ApproveRevisionInLocaleEvent.is_notifying(request.user, **locale_kwargs)),
        'is_watching_default_locale': (
            ReviewableRevisionInLocaleEvent.is_notifying(request.user, **default_kwargs)),
        'is_watching_other_locale': (
            None if on_default_locale
            else ReviewableRevisionInLocaleEvent.is_notifying(request.user, **locale_kwargs)),
        'is_watching_default_ready': ReadyRevisionEvent.is_notifying(request.user, **ready_kwargs),
        'on_default_locale': on_default_locale,
        'announce_form': AnnouncementForm(),
        'announcements': Announcement.get_for_locale_name(current_locale),
        'product': product,
        'products': Product.objects.filter(visible=True),
    }
    if extra_data:
        data.update(extra_data)
    return render(request, 'dashboards/' + template, data)

# Cache it all day to avoid calling Google Analytics over and over.
CACHE_TIMEOUT = 24 * 60 * 60  # 24 hours

def get_locales_by_visit(start_date, end_date):
    """Get a list of (locale, visits) tuples sorted descending by visits."""

    cache_key = 'locales_sorted_by_visits:{start}:{end}'.format(
        start=start_date, end=end_date)

    sorted_locales = cache.get(cache_key)
    if sorted_locales is None:
        try:
            results = visitors_by_locale(start_date, end_date)
            locales_and_visits = results.items()
            sorted_locales = list(reversed(sorted(
                locales_and_visits, key=lambda x: x[1])))
            cache.add(cache_key, sorted_locales, CACHE_TIMEOUT)
        except (GoogleAPIError, Oauth2Error, OpenSSLError):
            # Just return all locales with 0s for visits.
            log.exception('Something went wrong getting visitors by locale '
                          'from Google Analytics. Nobody got a 500 though.')
            sorted_locales = [(l, 0) for l in settings.SUMO_LANGUAGES]

    return sorted_locales


text:
function Directory() {
    this._name = null;
    this._parent = null;

    // getName public function
    // Gets the Directory's name.
    // @return - The name of the Directory as a string.
    this.getName = function() {
        return this._name;
    };

    // _removeFromParent protected function
    // Removes the Directory from the parent Directory.
    this._removeFromParent = function() {
        delete this._parent._children[this._name];
    };
};

// Folder class
// Object used to represent a system folder.
// @field protected - _name: The name of the Folder.
// @field protected - _children: Hash of Directories by name that this Folder will hold.
// @throws - An error if name is empty or null.
function Folder(name) {
    this._name = null;
    this._children = [];

    // __setName private function
    // Verifies and sets the name of this folder.
    // @param - name: The name to set this Folder to.
    // @throws - An error if name is empty or null.
    this.__setName = function(name) {
        if(name === undefined) { //For inheritence
            return;
        }

        if(!name) {
            throw 'Folder name must not be empty.';
        }

        this._name = name;
    };
    this.__setName(name);

    // getPath public function
    // Gets the full path of this Folder.
    // @return - The full path as a string.
    this.getPath = function() {
        return(this._parent.getPath() + this._name + '/');
    };

    // getChildren public function
    // Gets the children of the Folder.
    // @return - An array of the children Directories.
    this.getChildren = function() {
        var childArr = [];
        var dirNames = Object.keys(this._children);
        for(var i=0; i<dirNames.length; i++){
            childArr.push(this._children[dirNames[i]]);
        }
        return childArr;
    };

    // sortedChildNames public function
    // Builds a sorted list of formatted child names.
    // @returns - A list of the formatted child names.
    this.sortedChildNames = function(){
        var childNames = Object.keys(this._children);
        var objList = [];
        for(var i=0; i<childNames.length; i++){
            objList.push(this._children[childNames[i]]);
        }

        objList.sort(function(childA,childB){
            var nameA = childA._name;
            var nameB = childB._name;

            if(nameA < nameB) {
                return -1;
            }
            if(nameA > nameB) {
                return 1;
            }
            return 0;
        });

        var sortedNames = [];
        for(var i=0; i<objList.length; i++) {
            if(objList[i] instanceof Folder){
                sortedNames.push(objList[i]._name + '/');
            }
            else
            {
                sortedNames.push(objList[i]._name);
            }
        }

        return sortedNames;
    };

    // addChild public function
    // Adds the specified Directory to this folder.
    // @param - newChild: The Directory to add to this folder.
    // @throws - An error if newChild already exists.
    this.addChild = function(newChild) {
        if(this._children[newChild._name]) {
            throw(this._name + ' already contains a directory named ' + newChild._name);
        }
        this._children[newChild._name] = newChild;
        newChild._parent = this;
    };

    // remove public function
    // Removes the Folder from the system.
    this.remove = function() {
        this._removeChildren();
        this._removeFromParent();
    };

    // _removeChildren protected function
    // Removes the Folder's children from the system.
    this._removeChildren = function() {
        var childKeys = Object.keys(this._children);
        for(var i=0; i<childKeys.length; i++) {
            this._children[childKeys[i]].remove();
        }
    };

    // getChild public function
    // Retrieves the specified child of the Folder.
    // @param - childName: The string name of the child being retrieved.
    // @return - The specified child Directory if it exists, else null.
    this.getChild = function(childName) {
        if(!childName) {
            return null;
        }

        var child = this._children[childName];
        if(!child){
            return null;
        }

        return child;
    };

    // getFolder public function
    // Retrieves the specified Folder of this Folder.
    // @param - folderName: The string name of the child folder begin retrieved.
    // @return - The specified Folder if it exists, else null
    this.getFolder = function(folderName) {
        var folder = this.getChild(folderName);

        if(!folder || !(folder instanceof Folder)) {
            return null;
        }

        return folder;
    };
};

Folder.prototype = new Directory();

// Root class
// Object used to represent a root system folder.
// @field protected - name: Always null.
function Root() {
    this._name = null;

    // getPath public function
    // Gets the full path of this Root.
    // @return - The full path as a string.
    this.getPath = function() {
        return('/');
    };

    // remove public function
    // Removes the Root from the system.
    this.remove = function() {
        this._removeChildren();
    };
};

Root.prototype = new Folder();

// File class
// Object used to represent a file directory.
// @field protected - _name: Name of file with extension.
// @field protected - _parent: Folder that contains this file.
// @field private - __extension: The extension that signifies what type of file this is.
// @field public - data: The machine data for the file.
// @throws - An error if name is empty
//      or contains just an extension.
function File(name, data) {
    this._name = null;
    this._parent = null;
    this.__extension = null;
    this.data = data;

    // __setName private function
    // Verifies and sets the name of this file and extension.
    // @param - fullName: The full name to set this File to.
    // @throws - An error if name is empty
    //      or contains just an extension.
    this.__setName = function(fullName) {
        if(fullName === undefined) { //For inheritence
            return;
        }

        if(!fullName) {
            throw 'File name must not be empty.';
        }

        var parsedName = fullName.split('.');
        if(parsedName[0] === '') {
            throw 'File name cannot be just an extension.';
        }

        var tempExt = parsedName.pop();
        if(parsedName.length === 0 || tempExt === '') {
            this.__extension = null;
        }
        else {
            this.__extension = tempExt;
        }

        this._name = fullName;
    };
    this.__setName(name);

    // getPath public function
    // Gets the full path of this File.
    // @return - The full path as a string.
    this.getPath = function() {
        return(this._parent.getPath() + this._name);
    };

    // remove public function
    // Removes the File from the system.
    this.remove = function() {
        this._removeFromParent();
    };
};

File.prototype = new Directory();


text:
package io.vertx.ext.auth.test.oauth2;

import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.JWTOptions;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authentication.TokenCredentials;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import io.vertx.ext.auth.impl.http.SimpleHttpClient;
import io.vertx.ext.auth.oauth2.OAuth2Auth;
import io.vertx.ext.auth.oauth2.OAuth2FlowType;
import io.vertx.ext.auth.oauth2.OAuth2Options;
import io.vertx.ext.auth.oauth2.Oauth2Credentials;
import io.vertx.ext.auth.oauth2.authorization.ScopeAuthorization;
import io.vertx.ext.auth.oauth2.impl.OAuth2AuthProviderImpl;
import io.vertx.ext.auth.oauth2.providers.AzureADAuth;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.UnsupportedEncodingException;

@RunWith(VertxUnitRunner.class)
public class OAuth2OBODiscoveryTest {

  @Rule
  public RunTestOnContext rule = new RunTestOnContext();

  private static final JsonObject fixture = new JsonObject(
    "{" +
      "  \"access_token\": \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\"," +
      "  \"token_type\": \"bearer\"," +
      "  \"expires_in\": 3600" +
      "}");

  protected OAuth2Auth oauth2;
  private HttpServer server;

  @Before
  public void setUp(TestContext should) {
    final Async setup = should.async();

    // mock AzureAD
    AzureADAuth.discover(
      rule.vertx(),
      new OAuth2Options()
        .setFlow(OAuth2FlowType.AAD_OBO)
        .setClientId("client-id")
        .setClientSecret("client-secret")
        .setTenant("common")
        .setJWTOptions(
          new JWTOptions()
            .addAudience("api://resource")))

      .onFailure(should::fail)
      .onSuccess(oauth2 -> {
        this.oauth2 = oauth2;

        server = rule.vertx().createHttpServer().requestHandler(req -> {
          if (req.method() == HttpMethod.POST && "/resource/oauth2/token".equals(req.path())) {
            should.assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
            req.setExpectMultipart(true).bodyHandler(buffer -> {
              try {
                JsonObject payload = SimpleHttpClient.queryToJson(buffer);
                // according to the docs Azure expects the following values:
                should.assertEquals("urn:ietf:params:oauth:grant-type:jwt-bearer", payload.getString("grant_type"));
                should.assertEquals("head.body.signature", payload.getValue("assertion"));
                // client-id and client-secret are passed in the authorization header
                should.assertEquals("on_behalf_of", payload.getValue("requested_token_use"));
                should.assertEquals("a b", payload.getValue("scope"));
              } catch (UnsupportedEncodingException e) {
                should.fail(e);
              }
              req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
            });
          } else {
            req.response().setStatusCode(400).end();
          }
        }).listen(8080, ready -> {
          if (ready.failed()) {
            throw new RuntimeException(ready.cause());
          }

          // hack the config to go to the mock
          ((OAuth2AuthProviderImpl) this.oauth2).getConfig()
            .setTokenPath("http://localhost:" + ready.result().actualPort() + "/resource/oauth2/token")
            .setAuthorizationPath("http://localhost:" + ready.result().actualPort() + "/resource/oauth2/authorize");

          // ready
          setup.complete();
        });
      });
  }

  @After
  public void tearDown(TestContext should) throws Exception {
    final Async tearDown = should.async();
    server.close()
      .onFailure(should::fail)
      .onSuccess(v -> tearDown.complete());
  }

  @Test
  public void getToken(TestContext should) {
    final Async test = should.async();

    // Given that we want to trade an existing token for a new one (On-Behalf-Of) we **must** user OAuth2Credentials
    oauth2.authenticate(new Oauth2Credentials().setAssertion("head.body.signature").addScope("a").addScope("b"), res -> {
      if (res.failed()) {
        should.fail(res.cause());
      } else {
        User token = res.result();
        should.assertNotNull(token);
        should.assertNotNull(token.principal());

        // mock the token
        // with a dump from the official docs:
        token.attributes()
          .put("accessToken", new JsonObject(
            "{\n" +
            "  \"aud\": \"ef1da9d4-ff77-4c3e-a005-840c3f830745\",\n" +
            "  \"iss\": \"https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/\",\n" +
            "  \"iat\": 1537233106,\n" +
            "  \"nbf\": 1537233106,\n" +
            "  \"exp\": 1537237006,\n" +
            "  \"acr\": \"1\",\n" +
            "  \"aio\": \"AXQAi/8IAAAAFm+E/QTG+gFnVxLjWdw8K+61AGrSOuMMF6ebaMj7XO3IbmD3fGmrOyD+NvZyGn2VaT/kDKXw4MIhrgGVq6Bn8wLXoT1LkIZ+FzQVkJPPLQOV4KcXqSlCVPDS/DiCDgE222TImMvWNaEMaUOTsIGvTQ==\",\n" +
            "  \"amr\": [\n" +
            "    \"wia\"\n" +
            "  ],\n" +
            "  \"appid\": \"75dbe77f-10a3-4e59-85fd-8c127544f17c\",\n" +
            "  \"appidacr\": \"0\",\n" +
            "  \"email\": \"AbeLi@microsoft.com\",\n" +
            "  \"family_name\": \"Lincoln\",\n" +
            "  \"given_name\": \"Abe (MSFT)\",\n" +
            "  \"idp\": \"https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd0122247/\",\n" +
            "  \"ipaddr\": \"222.222.222.22\",\n" +
            "  \"name\": \"abeli\",\n" +
            "  \"oid\": \"02223b6b-aa1d-42d4-9ec0-1b2bb9194438\",\n" +
            "  \"rh\": \"I\",\n" +
            "  \"scp\": \"user_impersonation\",\n" +
            "  \"sub\": \"l3_roISQU222bULS9yi2k0XpqpOiMz5H3ZACo1GeXA\",\n" +
            "  \"tid\": \"fa15d692-e9c7-4460-a743-29f2956fd429\",\n" +
            "  \"unique_name\": \"abeli@microsoft.com\",\n" +
            "  \"uti\": \"FVsGxYXI30-TuikuuUoFAA\",\n" +
            "  \"ver\": \"1.0\"\n" +
            "}"));

        ScopeAuthorization.create(" ", "scp").getAuthorizations(token, authz1 -> {
          should.assertTrue(authz1.succeeded());
          should.assertTrue(PermissionBasedAuthorization.create("user_impersonation").match(token));
          test.complete();
        });
      }
    });
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<title>add News</title>

<form action="<?php echo $this->route->url('add');?>" method="post" class="messages">

      title
      <input type="text" name="title" placeholder="title" />

      content
      <textarea name="content" placeholder="content"></textarea>

      <input type="submit" value="Submit" style="background:#00a3eb;color:#fff;" />
      <input type="reset" value="Reset" />

</form>


text:
package minium.actions;

/**
 * Keyboard interactions can be performed using this interactable interface. It "hides"
 * keyboard interactions under its methods. It mimics most of keyboard actions in
 * org.openqa.selenium.interactions.Actions.
 *
 * @author rui.figueira
 *
 * @param <T> this {@link Interactable} for chainable calls
 */
public interface KeyboardInteractable<T extends Interactable<?>> extends Interactable<T> {

    /**
     * Clears all input text in the first matched field.
     *
     * @return this {@link Interactable}
     */
    public T clear();

    /**
     * Performs a modifier key press. Does not release the modifier key - subsequent interactions
     * may assume it's kept pressed. Note that the modifier key is never released implicitly -
     * either keyUp(theKey) or sendKeys(Keys.NULL) must be called to
     * release the modifier.
     *
     * @param keys either {@code Keys.SHIFT}, {@code Keys.ALT} or {@code Keys.CONTROL}.
     *  If the provided key is none of those, {@link IllegalArgumentException} is thrown
     * @return this {@link Interactable}
     */
    public T keyDown(Keys keys);

    /**
     * Performs a modifier key press after focusing on an element.
     *
     * @param keys either {@code Keys.SHIFT}, {@code Keys.ALT} or {@code Keys.CONTROL}.
     *  If the provided key is none of those, {@link IllegalArgumentException} is thrown
     * @return this {@link Interactable}
     */
    public T keyUp(Keys keys);

    /**
     * Sends keys to this element.
     *
     * @param keys keys to send
     * @return this {@link Interactable}
     */
    public T sendKeys(CharSequence ... keys);

    /**
     * Sends keys to this element.
     *
     * @param keys keys to send
     * @return this {@link Interactable}
     */
    public T sendKeys(CharSequence keys);

    /**
     * Same as {@link #sendKeys(CharSequence)}
     *
     * @param text text to type
     * @return this {@link Interactable}
     */
    public T type(CharSequence text);

    /**
     * Same as {@link #clear()} followed by {@link #sendKeys(CharSequence)}
     *
     * @param text text to type
     * @return this {@link Interactable}
     */
    public T fill(CharSequence text);
}


text:
namespace Cxns {

::ClientReturnedRecord ClientReturnedRecord::toCpp() {
    return ::ClientReturnedRecord(
        transform<int64_t, int64_t>()(RecordId),
        transform<std::string, Platform::String^>()(Content),
        transform<std::experimental::optional<std::string>, Platform::String^>()(Misc));
}

ClientReturnedRecord^ ClientReturnedRecord::fromCpp(const ::ClientReturnedRecord& value) {
    ClientReturnedRecord^ ret = ref new ClientReturnedRecord();
    ret->RecordId = transform<int64_t, int64_t>()(value.record_id);
    ret->Content = transform<std::string, Platform::String^>()(value.content);
    ret->Misc = transform<std::experimental::optional<std::string>, Platform::String^>()(value.misc);
    return ret;
}

}  // namespace Cxns


text:
<?php

namespace QCloudSDK\Core;

use Pimple\Container;

abstract class AbstractFacade
{
    /**
     * @var Container
     */
    private $container;
    /**
     * @var array
     */
    protected $map = [];
    /**
     * @var array
     */
    private $instances = [];

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function __get($name)
    {
        if(!isset($this->instances[$name])){
            if(!isset($this->map[$name])) throw new \RuntimeException('Undefined item key in facade.');
            $targetClass = $this->map[$name];
            $this->instances[$name] = new $targetClass($this->container['config']);
        }
        return $this->instances[$name];
    }
}


text:
'use strict';

import path from 'path';

/**
 * Base Class
 * @param  {Object} http
 * @return {Class}
 */
export default class {
  /**
   * constructor
   * @param  {Object} http []
   * @return {}      []
   */
  constructor(...args){
    this.init(...args);
  }
  /**
   * init
   * @param  {Object} http []
   * @return {}      []
   */
  init(){
  }
  /**
   * invoke method, support __before & __after magic methods
   * @param  {String} method []
   * @param  {mixed} data []
   * @return {Promise}    []
   */
  async invoke(method, ...data){
    if (this.__before) {
      await think.co(this.__before(this));
    }
    // Check whether method exists
    if (!this[method]){
      return Promise.reject(new Error(think.locale('METHOD_NOT_EXIST', method)));
    }
    let result = await think.co(this[method](...data));
    if (this.__after) {
      await think.co(this.__after(this));
    }
    return result;
  }
  /**
   * get file basename
   * @param  {String} filepath []
   * @return {String}          []
   */
  basename(filepath = this.__filename){
    return path.basename(filepath, '.js');
  }
  /**
   * parse module from filepath
   * @param  {String} filepath []
   * @return {String}          []
   */
  parseModuleFromPath(filepath = this.__filename){
    if (!filepath){
      return '';
    }
    if (think.mode !== think.mode_module){
      return '';
    }
    let prefix = think.APP_PATH + think.sep;
    let pos = filepath.indexOf(prefix);
    if (pos === -1){
      return '';
    }
    let nextPos = filepath.indexOf(think.sep, pos + prefix.length);
    if (nextPos === -1){
      return '';
    }
    let module = filepath.slice(pos + prefix.length, nextPos);
    if (think.module.indexOf(module) > -1){
      return module;
    }
    return '';
  }
}


text:
Rails.application.routes.draw do
  post 'calendar/create'

  resources :reservations
  resources :contacts

  resources :home, only: :index do
    collection { get :photos }
  end

  root to: 'home#index'
end


text:
export default class Main extends Daisy.Component {
    render() {
        return `
<input type="checkbox" class="toggle-all">

                <template :include={{this.body}}/>

`;
    }
}


text:
namespace Google.Cloud.Container.V1.Snippets
{
    // [START container_v1_generated_ClusterManager_SetNetworkPolicy_async_flattened2]
    using Google.Cloud.Container.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedClusterManagerClientSnippets
    {
        /// <summary>Snippet for SetNetworkPolicyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task SetNetworkPolicy2Async()
        {
            // Create client
            ClusterManagerClient clusterManagerClient = await ClusterManagerClient.CreateAsync();
            // Initialize request argument(s)
            string name = "";
            NetworkPolicy networkPolicy = new NetworkPolicy();
            // Make the request
            Operation response = await clusterManagerClient.SetNetworkPolicyAsync(name, networkPolicy);
        }
    }
    // [END container_v1_generated_ClusterManager_SetNetworkPolicy_async_flattened2]
}


text:
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.

package jodd.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Http connection. Created by {@link HttpConnectionProvider}.
 */
public interface HttpConnection {

	/**
	 * Returns connection output stream.
	 */
	public OutputStream getOutputStream() throws IOException;

	/**
	 * Returns connection input stream.
	 */
	public InputStream getInputStream() throws IOException;

	/**
	 * Closes connection. Ignores all exceptions.
	 */
	public void close();

	/**
	 * Sets the timeout for connections, in milliseconds. With this option set to a non-zero timeout,
	 * connection will block for only this amount of time. If the timeout expires, an Exception is raised.
	 * The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
	 */
	void setTimeout(int milliseconds);

}


text:
CREATE OR REPLACE FUNCTION multiply_numbers(number2 integer, number1 integer) RETURNS integer
    AS $$
begin
        return number2 * number1;
end;
$$
    LANGUAGE plpgsql;


text:
<?xml version="1.0" encoding="utf-8"?>

Logging Out of a Site

How to log out of a site. If you have set the site to remember your login credentials, logging out will forget your login credentials.

Click the Logout link that is typically located in the top right corner of each page.

Tip: To exit a site without logging out, simply close your Web browser. This does not cancel the Remember Login setting.


text:
Desarrollo de Aplicaciones Cliente-Servidor
=

```shell
mvn clean package
```


text:
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
require 'rest-client'
require 'json'

#
# == Elastic Search Shard Allocation Status
#
class ESShardAllocationStatus < Sensu::Plugin::Check::CLI
  option :scheme,
         description: 'URI scheme',
         long: '--scheme SCHEME',
         default: 'http'

  option :server,
         description: 'Elasticsearch server',
         short: '-s SERVER',
         long: '--server SERVER',
         default: 'localhost'

  option :port,
         description: 'Port',
         short: '-p PORT',
         long: '--port PORT',
         default: '9200'

  def get_es_resource(resource)
    r = RestClient::Resource.new("#{config[:scheme]}://#{config[:server]}:#{config[:port]}/#{resource}", timeout: 45)
    JSON.parse(r.get)
  rescue Errno::ECONNREFUSED
    warning 'Connection refused'
  rescue RestClient::RequestTimeout
    warning 'Connection timed out'
  end

  def master?
    state = get_es_resource('/_cluster/state?filter_routing_table=true&filter_metadata=true&filter_indices=true&filter_blocks=true&filter_nodes=true')
    local = get_es_resource('/_nodes/_local')
    local['nodes'].keys.first == state['master_node']
  end

  def get_status(type)
    settings = get_es_resource('/_cluster/settings')
    # Get the status for the given type, or default to 'all'
    # which is the ES default
    begin
      settings[type]['cluster']['routing']['allocation']['enable'].downcase
    rescue
      'all'
    end
  end

  # #YELLOW
  # method has too many lines
  def run
    if master?
      transient   = get_status('transient')
      persistent  = get_status('persistent')

      if transient == persistent
        ok "Persistent and transient allocation match:  #{persistent}"
      else
        critical "Persistent(#{persistent}) and transient(#{transient}) \
        shard allocation do not match."
      end
    else
      ok 'Not the master'
    end
  end
end


text:
/* */
var test = require("tape");
var random = require("./index");
test('random(points)', function(t) {
  var points = random('points');
  t.equal(points.type, 'FeatureCollection', 'is a featurecollection');
  t.equal(points.features.length, 1, 'right number of features');
  t.equal(points.features[0].geometry.type, 'Point', 'feature type correct');
  t.end();
});
test('random(polygons)', function(t) {
  var points = random('polygons');
  t.equal(points.type, 'FeatureCollection', 'is a featurecollection');
  t.equal(points.features.length, 1, 'right number of features');
  t.equal(points.features[0].geometry.type, 'Polygon', 'feature type correct');
  t.end();
});
test('random(polygons, 10)', function(t) {
  var points = random('polygons', 10);
  t.equal(points.type, 'FeatureCollection', 'is a featurecollection');
  t.equal(points.features.length, 10, 'right number of features');
  t.equal(points.features[0].geometry.type, 'Polygon', 'feature type correct');
  t.end();
});
test('random(polygons, 1, {num_vertices})', function(t) {
  var points = random('polygons', 10, {num_vertices: 23});
  t.equal(points.type, 'FeatureCollection', 'is a featurecollection');
  t.equal(points.features.length, 10, 'right number of features');
  t.equal(points.features[0].geometry.coordinates[0].length, 24, 'num vertices');
  t.end();
});
test('random(points, 10, {bbox})', function(t) {
  var points = random('points', 10, {bbox: [0, 0, 0, 0]});
  t.equal(points.type, 'FeatureCollection', 'is a featurecollection');
  t.equal(points.features.length, 10, 'right number of features');
  t.equal(points.features[0].geometry.type, 'Point', 'feature type correct');
  t.deepEqual(points.features[0].geometry.coordinates, [0, 0], 'feature type correct');
  t.end();
});


text:
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/redshift/model/UsageLimitFeatureType.h>
#include <aws/redshift/model/UsageLimitLimitType.h>
#include <aws/redshift/model/UsageLimitPeriod.h>
#include <aws/redshift/model/UsageLimitBreachAction.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/redshift/model/ResponseMetadata.h>
#include <aws/redshift/model/Tag.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{
  /**
   *
Describes a usage limit object for a cluster.

See Also:
   AWS
   * API Reference

   */
  class AWS_REDSHIFT_API ModifyUsageLimitResult
  {
  public:
    ModifyUsageLimitResult();
    ModifyUsageLimitResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    ModifyUsageLimitResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
The identifier of the usage limit.

     */
    inline const Aws::String& GetUsageLimitId() const{ return m_usageLimitId; }

    /**
     *
The identifier of the usage limit.

     */
    inline void SetUsageLimitId(const Aws::String& value) { m_usageLimitId = value; }

    /**
     *
The identifier of the usage limit.

     */
    inline void SetUsageLimitId(Aws::String&& value) { m_usageLimitId = std::move(value); }

    /**
     *
The identifier of the usage limit.

     */
    inline void SetUsageLimitId(const char* value) { m_usageLimitId.assign(value); }

    /**
     *
The identifier of the usage limit.

     */
    inline ModifyUsageLimitResult& WithUsageLimitId(const Aws::String& value) { SetUsageLimitId(value); return *this;}

    /**
     *
The identifier of the usage limit.

     */
    inline ModifyUsageLimitResult& WithUsageLimitId(Aws::String&& value) { SetUsageLimitId(std::move(value)); return *this;}

    /**
     *
The identifier of the usage limit.

     */
    inline ModifyUsageLimitResult& WithUsageLimitId(const char* value) { SetUsageLimitId(value); return *this;}

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline const Aws::String& GetClusterIdentifier() const{ return m_clusterIdentifier; }

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline void SetClusterIdentifier(const Aws::String& value) { m_clusterIdentifier = value; }

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline void SetClusterIdentifier(Aws::String&& value) { m_clusterIdentifier = std::move(value); }

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline void SetClusterIdentifier(const char* value) { m_clusterIdentifier.assign(value); }

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline ModifyUsageLimitResult& WithClusterIdentifier(const Aws::String& value) { SetClusterIdentifier(value); return *this;}

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline ModifyUsageLimitResult& WithClusterIdentifier(Aws::String&& value) { SetClusterIdentifier(std::move(value)); return *this;}

    /**
     *
The identifier of the cluster with a usage limit.

     */
    inline ModifyUsageLimitResult& WithClusterIdentifier(const char* value) { SetClusterIdentifier(value); return *this;}

    /**
     *
The Amazon Redshift feature to which the limit applies.

     */
    inline const UsageLimitFeatureType& GetFeatureType() const{ return m_featureType; }

    /**
     *
The Amazon Redshift feature to which the limit applies.

     */
    inline void SetFeatureType(const UsageLimitFeatureType& value) { m_featureType = value; }

    /**
     *
The Amazon Redshift feature to which the limit applies.

     */
    inline void SetFeatureType(UsageLimitFeatureType&& value) { m_featureType = std::move(value); }

    /**
     *
The Amazon Redshift feature to which the limit applies.

     */
    inline ModifyUsageLimitResult& WithFeatureType(const UsageLimitFeatureType& value) { SetFeatureType(value); return *this;}

    /**
     *
The Amazon Redshift feature to which the limit applies.

     */
    inline ModifyUsageLimitResult& WithFeatureType(UsageLimitFeatureType&& value) { SetFeatureType(std::move(value)); return *this;}

    /**
     *
The type of limit. Depending on the feature type, this can be based on a time
     * duration or data size.

     */
    inline const UsageLimitLimitType& GetLimitType() const{ return m_limitType; }

    /**
     *
The type of limit. Depending on the feature type, this can be based on a time
     * duration or data size.

     */
    inline void SetLimitType(const UsageLimitLimitType& value) { m_limitType = value; }

    /**
     *
The type of limit. Depending on the feature type, this can be based on a time
     * duration or data size.

     */
    inline void SetLimitType(UsageLimitLimitType&& value) { m_limitType = std::move(value); }

    /**
     *
The type of limit. Depending on the feature type, this can be based on a time
     * duration or data size.

     */
    inline ModifyUsageLimitResult& WithLimitType(const UsageLimitLimitType& value) { SetLimitType(value); return *this;}

    /**
     *
The type of limit. Depending on the feature type, this can be based on a time
     * duration or data size.

     */
    inline ModifyUsageLimitResult& WithLimitType(UsageLimitLimitType&& value) { SetLimitType(std::move(value)); return *this;}

    /**
     *
The limit amount. If time-based, this amount is in minutes. If data-based,
     * this amount is in terabytes (TB).

     */
    inline long long GetAmount() const{ return m_amount; }

    /**
     *
The limit amount. If time-based, this amount is in minutes. If data-based,
     * this amount is in terabytes (TB).

     */
    inline void SetAmount(long long value) { m_amount = value; }

    /**
     *
The limit amount. If time-based, this amount is in minutes. If data-based,
     * this amount is in terabytes (TB).

     */
    inline ModifyUsageLimitResult& WithAmount(long long value) { SetAmount(value); return *this;}

    /**
     *
The time period that the amount applies to. A weekly period
     * begins on Sunday. The default is monthly.

     */
    inline const UsageLimitPeriod& GetPeriod() const{ return m_period; }

    /**
     *
The time period that the amount applies to. A weekly period
     * begins on Sunday. The default is monthly.

     */
    inline void SetPeriod(const UsageLimitPeriod& value) { m_period = value; }

    /**
     *
The time period that the amount applies to. A weekly period
     * begins on Sunday. The default is monthly.

     */
    inline void SetPeriod(UsageLimitPeriod&& value) { m_period = std::move(value); }

    /**
     *
The time period that the amount applies to. A weekly period
     * begins on Sunday. The default is monthly.

     */
    inline ModifyUsageLimitResult& WithPeriod(const UsageLimitPeriod& value) { SetPeriod(value); return *this;}

    /**
     *
The time period that the amount applies to. A weekly period
     * begins on Sunday. The default is monthly.

     */
    inline ModifyUsageLimitResult& WithPeriod(UsageLimitPeriod&& value) { SetPeriod(std::move(value)); return *this;}

    /**
     *
The action that Amazon Redshift takes when the limit is reached. Possible
     * values are:

 log - To log an event in a system table.
     * The default is log.

 emit-metric - To emit CloudWatch
     * metrics.

 disable - To disable the feature until the
     * next usage period begins.

     */
    inline const UsageLimitBreachAction& GetBreachAction() const{ return m_breachAction; }

    /**
     *
The action that Amazon Redshift takes when the limit is reached. Possible
     * values are:

 log - To log an event in a system table.
     * The default is log.

 emit-metric - To emit CloudWatch
     * metrics.

 disable - To disable the feature until the
     * next usage period begins.

     */
    inline void SetBreachAction(const UsageLimitBreachAction& value) { m_breachAction = value; }

    /**
     *
The action that Amazon Redshift takes when the limit is reached. Possible
     * values are:

 log - To log an event in a system table.
     * The default is log.

 emit-metric - To emit CloudWatch
     * metrics.

 disable - To disable the feature until the
     * next usage period begins.

     */
    inline void SetBreachAction(UsageLimitBreachAction&& value) { m_breachAction = std::move(value); }

    /**
     *
The action that Amazon Redshift takes when the limit is reached. Possible
     * values are:

 log - To log an event in a system table.
     * The default is log.

 emit-metric - To emit CloudWatch
     * metrics.

 disable - To disable the feature until the
     * next usage period begins.

     */
    inline ModifyUsageLimitResult& WithBreachAction(const UsageLimitBreachAction& value) { SetBreachAction(value); return *this;}

    /**
     *
The action that Amazon Redshift takes when the limit is reached. Possible
     * values are:

 log - To log an event in a system table.
     * The default is log.

 emit-metric - To emit CloudWatch
     * metrics.

 disable - To disable the feature until the
     * next usage period begins.

     */
    inline ModifyUsageLimitResult& WithBreachAction(UsageLimitBreachAction&& value) { SetBreachAction(std::move(value)); return *this;}

    /**
     *
A list of tag instances.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
A list of tag instances.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tags = value; }

    /**
     *
A list of tag instances.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tags = std::move(value); }

    /**
     *
A list of tag instances.

     */
    inline ModifyUsageLimitResult& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
A list of tag instances.

     */
    inline ModifyUsageLimitResult& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
A list of tag instances.

     */
    inline ModifyUsageLimitResult& AddTags(const Tag& value) { m_tags.push_back(value); return *this; }

    /**
     *
A list of tag instances.

     */
    inline ModifyUsageLimitResult& AddTags(Tag&& value) { m_tags.push_back(std::move(value)); return *this; }

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline ModifyUsageLimitResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline ModifyUsageLimitResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    Aws::String m_usageLimitId;

    Aws::String m_clusterIdentifier;

    UsageLimitFeatureType m_featureType;

    UsageLimitLimitType m_limitType;

    long long m_amount;

    UsageLimitPeriod m_period;

    UsageLimitBreachAction m_breachAction;

    Aws::Vector<Tag> m_tags;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace Redshift
} // namespace Aws


text:
package com.arpnetworking.play.metrics;

import com.arpnetworking.metrics.MetricsFactory;
import com.arpnetworking.steno.Logger;
import com.arpnetworking.steno.LoggerFactory;
import com.google.common.base.Strings;
import play.libs.F;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

/**
 * Simple action wrapper that wraps each call in a metrics timer.
 *
 * TODO(vkoskela): Add to shared library with Play dependency (tsd-core?) [MAI-?]
 *
 * @author Ville Koskela (vkoskela at groupon dot com)
 */
public class MetricsActionWrapper extends Action.Simple {

    /**
     * Public constructor.
     *
     * @param metricsFactory Instance of MetricsFactory.
     * @param action The Action to wrap.
     */
    public MetricsActionWrapper(final MetricsFactory metricsFactory, final Action<?> action) {
        _metricsFactory = metricsFactory;
        this.delegate = action;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    // CHECKSTYLE.OFF: IllegalThrow
    public F.Promise<Result> call(final Http.Context context) throws Throwable {
        // CHECKSTYLE.ON: IllegalThrow

        // TODO(vkoskela): Add sampled metrics action wrapper [MAI-340]
        /*
        final Metrics metrics = getMetrics(context);
        final Timer timer = metrics.createTimer(createTimerName(context));
        return delegate.call(context).map(new F.Function<Result, Result>() {
            @Override
            // CHECKSTYLE.OFF: IllegalThrow
            public Result apply(final Result result) throws Throwable {
                // CHECKSTYLE.ON: IllegalThrow
                timer.stop();
                metrics.close();
                return result;
            }
        });*/
        return delegate.call(context);
        // TODO(vkoskela): Add success/failure counter by mapping on return code. [MAI-279]
    }

    /**
     * Create the name of the timer from a Http.Context.
     *
     * @param context Context of the HTTP request/response.
     * @return Name of the timer for the request/response.
     */
    protected String createTimerName(final Http.Context context) {
        // TODO(vkoskela): Use routes information to replace variable path parts with variable names. [MAI-280]
        final Http.Request r = context.request();
        final StringBuilder metricNameBuilder = new StringBuilder("RestService/");
        metricNameBuilder.append(r.method());

        if (!Strings.isNullOrEmpty(r.path())) {
            if (!r.path().startsWith("/")) {
                metricNameBuilder.append("/");
            }
            metricNameBuilder.append(r.path());
        }

        return metricNameBuilder.toString();
    }

    /*
    private Metrics getMetrics(final Http.Context context) {
        Metrics metrics = (Metrics) context.args.get(METRICS_KEY);
        if (metrics == null) {
            metrics = _metricsFactory.create();
            context.args.put(METRICS_KEY, metrics);
        } else {
            LOGGER.warn()
                    .setMessage("Found metrics in request context; possible issue")
                    .addData("metrics", metrics)
                    .log();
        }
        return metrics;
    }
    */

    private final MetricsFactory _metricsFactory;

    private static final String METRICS_KEY = "metrics";
    private static final Logger LOGGER = LoggerFactory.getLogger(MetricsActionWrapper.class);
}