text:
package nes

import (
	"encoding/gob"
	"log"
)

type Mapper7 struct {
	*Cartridge
	prgBank int
}

func NewMapper7(cartridge *Cartridge) Mapper {
	return &Mapper7{cartridge, 0}
}

func (m *Mapper7) Save(encoder *gob.Encoder) error {
	encoder.Encode(m.prgBank)
	return nil
}

func (m *Mapper7) Load(decoder *gob.Decoder) error {
	decoder.Decode(&m.prgBank)
	return nil
}

func (m *Mapper7) Step() {
}

func (m *Mapper7) Read(address uint16) byte {
	switch {
	case address < 0x2000:
		return m.CHR[address]
	case address >= 0x8000:
		index := m.prgBank*0x8000 + int(address-0x8000)
		return m.PRG[index]
	case address >= 0x6000:
		index := int(address) - 0x6000
		return m.SRAM[index]
	default:
		log.Fatalf("unhandled mapper7 read at address: 0x%04X", address)
	}
	return 0
}

func (m *Mapper7) Write(address uint16, value byte) {
	switch {
	case address < 0x2000:
		m.CHR[address] = value
	case address >= 0x8000:
		m.prgBank = int(value & 7)
		switch value & 0x10 {
		case 0x00:
			m.Cartridge.Mirror = MirrorSingle0
		case 0x10:
			m.Cartridge.Mirror = MirrorSingle1
		}
	case address >= 0x6000:
		index := int(address) - 0x6000
		m.SRAM[index] = value
	default:
		log.Fatalf("unhandled mapper7 write at address: 0x%04X", address)
	}
}


text:
package org.vaadin.spring.sample.security.ui;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.VaadinComponent;
import org.vaadin.spring.mvp.MvpPresenterView;
import org.vaadin.spring.navigator.SpringViewProvider;
import org.vaadin.spring.security.Security;

import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.themes.ValoTheme;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

@UIScope
@VaadinComponent
@SuppressWarnings("serial")
public class MainLayout extends VerticalLayout implements ViewDisplay, ClickListener, ViewChangeListener {

	private Panel viewContainer;

	private HorizontalLayout navbar;

	private Button btnHome;
	private Button btnSocial;
	private Button btnLogout;

	@Autowired
	Security security;

	@Autowired
	SpringViewProvider springViewProvider;

	@PostConstruct
	public void postConstuct() {
		setSizeFull();

		navbar = new HorizontalLayout();
		navbar.setWidth("100%");
		navbar.setMargin(true);
		navbar.setDefaultComponentAlignment(Alignment.MIDDLE_RIGHT);
		addComponent(navbar);

		final Label brand = new Label("Vaadin4Spring Security Social Demo");
		brand.addStyleName(ValoTheme.LABEL_H2);
		brand.addStyleName(ValoTheme.LABEL_NO_MARGIN);
		navbar.addComponent(brand);
		navbar.setComponentAlignment(brand, Alignment.MIDDLE_LEFT);
		navbar.setExpandRatio(brand, 1);

		btnHome = new Button("Home", FontAwesome.HOME);
		btnHome.addStyleName(ValoTheme.BUTTON_BORDERLESS);
		btnHome.setData(ViewToken.HOME);
		btnHome.addClickListener(this);
		navbar.addComponent(btnHome);

		btnSocial = new Button("Social connections", FontAwesome.SHARE_SQUARE);
		btnSocial.addStyleName(ValoTheme.BUTTON_BORDERLESS);
		btnSocial.setData(ViewToken.SOCIAL);
		btnSocial.addClickListener(this);
		navbar.addComponent(btnSocial);

		btnLogout = new Button("Logout", FontAwesome.SIGN_OUT);
		btnLogout.setData("-");
		btnLogout.addStyleName(ValoTheme.BUTTON_BORDERLESS);
		navbar.addComponent(btnLogout);
		btnLogout.addClickListener(new ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				UI.getCurrent().getSession().close();
				Page.getCurrent().setLocation("/logout");

			}
		});

		viewContainer = new Panel();
		viewContainer.setSizeFull();
		addComponent(viewContainer);
		setExpandRatio(viewContainer, 1);

	}

	@Override
	public void showView(View view) {

		if (view instanceof MvpPresenterView) {
			viewContainer.setContent(((MvpPresenterView) view).getViewComponent());
		}

	}

	@Override
	public void buttonClick(ClickEvent event) {

		/* This method in class should be public
		 * private boolean isViewBeanNameValidForCurrentUI(String beanName)
		 *
		 *  workaround
		 *
		 *  This should be implemented in custom Navigator class.
		 */
		if ( springViewProvider.getView((String) event.getButton().getData()) == null ) {
			/*
			 * For this demo, notify user that has no access.
			 * Easily, this can be modified to hide adminLink
			 */
			//notify user
			Notification.show("Access is alowed only for admin users.", Type.ERROR_MESSAGE);
		} else {
			UI.getCurrent().getNavigator().navigateTo((String) event.getButton().getData());
		}

	}

	@Override
	public boolean beforeViewChange(ViewChangeEvent event) {
		return true;
	}

	@Override
	public void afterViewChange(ViewChangeEvent event) {
		for (int i=0; i<navbar.getComponentCount(); i++) {

			if (navbar.getComponent(i) instanceof Button) {
				final Button btn = (Button) navbar.getComponent(i);
				btn.removeStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);

				String view = (String) btn.getData();

				if (event.getViewName().equals(view)) {
					btn.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
				}
			}
		}

	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.plivo.api.models.complianceapplication;

import com.plivo.api.models.base.Submitter;
import retrofit2.Call;

public class ComplianceApplicationSubmitter extends Submitter<ComplianceApplicationCreateResponse> {

    public ComplianceApplicationSubmitter(String id) {
        super(id);
    }

    @Override
    protected Call<ComplianceApplicationCreateResponse> obtainCall() {
        return client().getApiService().complianceApplicationSubmit(client().getAuthId(), id,this);
    }
}


text:
using Windows.Foundation.Metadata;
using Windows.UI.Xaml;

namespace DJNanoShow.Triggers
{
    public class IsTypePresentStateTrigger : StateTriggerBase
    {
        public static readonly DependencyProperty TypeNameProperty =
            DependencyProperty.Register("TypeName", typeof(string), typeof(IsTypePresentStateTrigger),
            new PropertyMetadata(null, OnTypeNamePropertyChanged));

        public string TypeName
        {
            get { return (string)GetValue(TypeNameProperty); }
            set { SetValue(TypeNameProperty, value); }
        }

        private static void OnTypeNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var trigger = d as IsTypePresentStateTrigger;

            var triggerResult = false;
            var val = e.NewValue as string;

            if (!string.IsNullOrWhiteSpace(val))
            {
                triggerResult = ApiInformation.IsTypePresent(val);
            }
            trigger.SetActive(triggerResult);
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: M4rk0
 * Date: 8/16/2016
 * Time: 5:03 PM
 */

namespace App\OAuth2Models;

use App\MateyModels\AbstractManager;
use AuthBucket\OAuth2\Model\RefreshTokenManagerInterface;

class RefreshTokenManager extends AbstractManager implements RefreshTokenManagerInterface
{

}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace DelimitedDataDeserializer
{
	public static class ValidationExtensions
	{
		public static bool IsValid<T>(this Tuple<ICollection<ValidationResult>, T> source)
		{
			return source.Item1.Count() == 0;
		}

		public static bool IsValid<T>(this IEnumerable<Tuple<ICollection<ValidationResult>, T>> source)
		{
			return source.All(x => x.Item1.Count() == 0);
		}

		public static int ValidationResultCount<T>(this Tuple<ICollection<ValidationResult>, T> source)
		{
			return source.Item1.Count;
		}

		public static TList Append<TList, TValue>(this TList list, TValue item) where TList : class, ICollection<TValue>
		{
			if (list == null) throw new ArgumentNullException("list");
			list.Add(item);
			return list;
		}

		public static Tuple<ICollection<ValidationResult>, T> AddValidationResult<T>(this Tuple<ICollection<ValidationResult>, T> source, string format, params object[] args)
		{
			source.Item1.Add(new ValidationResult(string.Format(format, args)));
			return source;
		}

		public static Tuple<ICollection<ValidationResult>, T> AsValidatedResult<T>(this Tuple<ICollection<ValidationResult>, T> source)
		{
			ICollection<ValidationResult> validationResults = new Collection<ValidationResult>();
			ValidationContext validationContext = new ValidationContext(source.Item2, null, null);
			Validator.TryValidateObject(source.Item2, validationContext, validationResults, true);

			foreach (var validationResult in validationResults)
				source.Item1.Add(validationResult);

			return source;
		}
	}
}


text:
import * as admin from 'firebase-admin';
import {ensureUsers} from './user';
import {ensureData} from './data';

const main = async () => {
  try {
    admin.initializeApp();
    await ensureUsers();
    await ensureData();
    process.exit();
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
};
main();


text:
package org.apache.abdera.ext.rss;

import javax.xml.namespace.QName;

import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
import org.apache.abdera.model.Generator;

public class RssGenerator extends ElementWrapper implements Generator {

    public RssGenerator(Element internal) {
        super(internal);
    }

    public RssGenerator(Factory factory, QName qname) {
        super(factory, qname);
    }

    public IRI getResolvedUri() {
        return null;
    }

    public IRI getUri() {
        return null;
    }

    public String getVersion() {
        return null;
    }

    public Generator setUri(String uri) {
        throw new UnsupportedOperationException("Modifications are not allowed");
    }

    public Generator setVersion(String version) {
        throw new UnsupportedOperationException("Modifications are not allowed");
    }

}


text:
package com.youlongnet.lulu.ui.frg;

import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.youlongnet.lulu.R;
import com.youlongnet.lulu.net.luluRequst.AddAddressRequest;
import com.youlongnet.lulu.net.luluRequst.AlertPullRequest;
import com.youlongnet.lulu.net.luluRequst.BaseResponse;
import com.youlongnet.lulu.net.luluRequst.WeatherRequest;
import com.youlongnet.lulu.net.queue.Net;
import com.youlongnet.lulu.net.utils.NetHelper;
import com.youlongnet.lulu.ui.base.BaseFragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import butterknife.InjectView;
import butterknife.OnClick;

public class GuidFragment extends BaseFragment {

    @InjectView(R.id.tv_content)
    TextView mTvContent;

    @Override
    public int setLayout() {
        return R.layout.frg_guid;
    }

    @Override
    public void initData(View view) {

    }

    @OnClick({R.id.postString, R.id.postJsonString, R.id.get1, R.id.get2, R.id.example})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.postString:
                postString();
                break;
            case R.id.postJsonString:
                postJsonString();
                break;
            case R.id.get1:
                get1();
                break;
            case R.id.get2:
                get2();
                break;
            case R.id.example:
                example();
                break;
        }
    }

    @Override
    protected void onRealPause() {
        super.onRealPause();
    }

    private void example() {
        AddAddressRequest request = new AddAddressRequest(mContext);
        AddAddressRequest.RequestBean param = new AddAddressRequest.RequestBean();
        param.frist_name = "ywh";
        param.last_name = "lyao";
        param.address = "罗湖区莲塘";
        param.key = "123456";
        param.note = "我是测试接口";
        param.time = "2015年4月27日";
        param.phone_number = "1565978564";
        param.tax_id = "1314520";
        param.user_id = "54321";
        request.setParameter(param)
                .setCache(true)
                .setDebug(true)
                .setLoop(3000);
        request.setCallbacks(new NetHelper.NetCallback<String>() {
            @Override
            public void onCompleted(VolleyError e, String s) {
                if (s != null)
                    System.out.println(s);
                if (e != null) {
                    Toast.makeText(mContext, e.networkResponse.statusCode + "", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void get1() {
        mTvContent.setText("");
        Net.with(mContext)
                .load("http://www.weather.com.cn/data/sk/101010100.html")
                .setMethod("get")
                .setDebug(true)
                .setCache(true)
                .setSpliceParam(false)
                .setLoop(3000)
                .setCallback(new NetHelper.NetCallback<WeatherRequest.WeatherRes>() {
                    @Override
                    public void onCompleted(VolleyError e, WeatherRequest.WeatherRes weatherRes) {
                        if (weatherRes != null) {
                            mTvContent.setText(weatherRes.weatherinfo.getCity() + " " + weatherRes.weatherinfo.getTemp());
                        }
                        if (e != null) {
                            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void get2() {
        mTvContent.setText("");
        WeatherRequest request = new WeatherRequest(mContext);
        request.setDebug(true)
                .setCache(true);
        request.setCallbacks(new NetHelper.NetCallback<WeatherRequest.WeatherRes>() {
            @Override
            public void onCompleted(VolleyError e, WeatherRequest.WeatherRes weatherRes) {
                if (weatherRes != null) {
                    mTvContent.setText(weatherRes.weatherinfo.getCity() + " " + weatherRes.weatherinfo.getTemp());
                }
                if (e != null) {
                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void postJsonString() {
        mTvContent.setText("");
        AlertPullRequest request = new AlertPullRequest(mContext);
        /*构建参数*/
        AlertPullRequest.AlertInfoReq req = new AlertPullRequest.AlertInfoReq();
        AlertPullRequest.Settings settings = new AlertPullRequest.Settings();
        Collections.addAll(settings.alerts,
                new AlertPullRequest.SettingItem("0", "OKCoin.cn", true, 1200, 0),
                new AlertPullRequest.SettingItem("1", "OKCoin.com", false, 1900, 300));
        req.setting = settings;

        request.setParameter(req)
                .setCache(true)
                .setDebug(true);
        //链式加载泛型无法起到限制作用
        request.setCallbacks(new NetHelper.NetCallback<AlertPullRequest.AlertInfoRes>() {
            @Override
            public void onCompleted(VolleyError e, AlertPullRequest.AlertInfoRes alertInfoRes) {
                if (alertInfoRes != null) {
                    mTvContent.append("errorCode:" + alertInfoRes.errorCode + " " + "info:" + alertInfoRes.info + " " + "result:" + alertInfoRes.result);
                }
                if (e != null) {
                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void postString() {
        mTvContent.setText("");
        Map<String, String> param = new HashMap<>();
        param.put("type", "1");
        param.put("sub_type", "3");

        Net.with(mContext).
                load("http://lulutest.19196.com/1.0/hall.getHallLink")
                .setParameter(param)
                .setDebug(true)
                .setTag("circleFrg")
                .cancelAll()
                .setCache(true)
                .setCallback(new NetHelper.NetCallback<BaseResponse.SlideView>() {

                    @Override
                    public void onCompleted(VolleyError e, BaseResponse.SlideView response) {
                        if (response != null) {
                            ArrayList<String> images = new ArrayList<>();
                            for (BaseResponse.SlideItemInfo info : response.data) {
                                mTvContent.append(info.hall_image + "\n");
                            }
                        }
                        if (e != null) {
                            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}


text:
KEYSTORE=proxyserver.jks
if [ -r ${KEYSTORE} ]
then
    echo "${KEYSTORE} exists; please rename or delete it before creating a replacement"
    exit 1
fi

DNAME="cn=JMeter Proxy (DO NOT TRUST)"
VALIDITY=${1:-1}
# Must agree with property proxy.cert.keystorepass
STOREPASSWORD=password
# Must agree with proxy.cert.keypassword
KEYPASSWORD=password

## generate the keystore with the certificate
keytool -genkeypair -alias jmeter -keystore ${KEYSTORE} -keypass ${KEYPASSWORD} -storepass ${STOREPASSWORD} -validity "${VALIDITY}" -keyalg RSA -dname "${DNAME}"

## show the contents
keytool -list -v -keystore ${KEYSTORE} -storepass ${STOREPASSWORD}


text:
"""Client utilities common to all platforms."""

import os
import platform
import subprocess
import threading
import time

import logging

from grr.lib import config_lib

def HandleAlarm(process):
  try:
    logging.info("Killing child process due to timeout")
    process.kill()
  # There is a race condition here where the process terminates
  # just before it would be killed. We ignore the exception
  # in that case as the process is already gone.
  except OSError:
    pass

def Execute(cmd,
            args,
            time_limit=-1,
            bypass_whitelist=False,
            daemon=False,
            use_client_context=False,
            cwd=None):
  """Executes commands on the client.

  This function is the only place where commands will be executed
  by the GRR client. This makes sure that all issued commands are compared to a
  white list and no malicious commands are issued on the client machine.

  Args:
    cmd: The command to be executed.
    args: List of arguments.
    time_limit: Time in seconds the process is allowed to run.
    bypass_whitelist: Allow execution of things that are not in the whitelist.
        Note that this should only ever be called on a binary that passes the
        VerifySignedBlob check.
    daemon: Start the new process in the background.
    use_client_context: Run this script in the client's context. Defaults to
                        system context.
    cwd: Current working directory for the command.

  Returns:
    A tuple of stdout, stderr, return value and time taken.
  """
  if not bypass_whitelist and not IsExecutionWhitelisted(cmd, args):
    # Whitelist doesn't contain this cmd/arg pair
    logging.info("Execution disallowed by whitelist: %s %s.", cmd,
                 " ".join(args))
    return ("", "Execution disallowed by whitelist.", -1, -1)

  if daemon:
    pid = os.fork()
    if pid == 0:
      # This is the child, it will run the daemon process. We call os.setsid
      # here to become the session leader of this new session and the process
      # group leader of the new process group so we don't get killed when the
      # main process exits.
      try:
        os.setsid()
      except OSError:
        # This only works if the process is running as root.
        pass
      _Execute(
          cmd, args, time_limit, use_client_context=use_client_context, cwd=cwd)
      os._exit(0)  # pylint: disable=protected-access
  else:
    return _Execute(
        cmd, args, time_limit, use_client_context=use_client_context, cwd=cwd)

def _Execute(cmd, args, time_limit=-1, use_client_context=False, cwd=None):
  """Executes cmd."""
  run = [cmd]
  run.extend(args)
  env = os.environ.copy()
  if use_client_context:
    env.pop("LD_LIBRARY_PATH", None)
    env.pop("PYTHON_PATH", None)
    context = "client"
  else:
    context = "system"
  logging.info("Executing %s in %s context.", " ".join(run), context)
  p = subprocess.Popen(
      run,
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
      stderr=subprocess.PIPE,
      env=env,
      cwd=cwd)

  alarm = None
  if time_limit > 0:
    alarm = threading.Timer(time_limit, HandleAlarm, (p,))
    alarm.setDaemon(True)
    alarm.start()

  stdout, stderr, exit_status = "", "", -1
  start_time = time.time()
  try:
    stdout, stderr = p.communicate()
    exit_status = p.returncode
  except IOError:
    # If we end up here, the time limit was exceeded
    pass
  finally:
    if alarm:
      alarm.cancel()

  return (stdout, stderr, exit_status, time.time() - start_time)

def IsExecutionWhitelisted(cmd, args):
  """Check if a binary and args is whitelisted.

  Args:
    cmd: Canonical path to the binary.
    args: List of arguments to be passed to the binary.

  Returns:
    Bool, True if it is whitelisted.

  These whitelists could also go in the platform specific client files
  client_utils_<platform>.py. We chose to leave them here instead of putting
  them in global arrays to discourage people coding other modules from adding
  new commands to the whitelist before running them.
  The idea is to have a single place that lists every command we can run during
  normal operation (obviously doesn't catch the special cases where we bypass
  the list).
  """
  if platform.system() == "Windows":
    whitelist = [
        ("driverquery.exe", ["/v"]),
        ("ipconfig.exe", ["/all"]),
        ("tasklist.exe", ["/SVC"]),
        ("tasklist.exe", ["/v"]),
    ]
  elif platform.system() == "Linux":
    whitelist = [
        ("/bin/df", []),
        ("/bin/echo", ["1"]),
        ("/bin/rpm", ["-qa"]),
        ("/bin/sleep", ["10"]),
        ("/sbin/auditctl", ["-l"]),
        ("/sbin/ifconfig", ["-a"]),
        ("/sbin/iptables", ["-L", "-n", "-v"]),
        ("/sbin/lsmod", []),
        ("/usr/bin/dpkg", ["--list"]),
        ("/usr/bin/last", []),
        ("/usr/bin/yum", ["list", "installed", "-q"]),
        ("/usr/bin/yum", ["repolist", "-v", "-q"]),
        ("/usr/bin/who", []),
        ("/usr/sbin/dmidecode", ["-q"]),
        ("/usr/sbin/sshd", ["-T"]),
    ]
  elif platform.system() == "Darwin":
    whitelist = [
        ("/bin/echo", ["1"]),
        ("/bin/launchctl", ["unload", config_lib.CONFIG["Client.plist_path"]]),
        ("/usr/bin/hdiutil", ["info"]),
        ("/usr/bin/last", []),
        ("/usr/bin/who", []),
        ("/usr/sbin/kextstat", []),
        ("/usr/sbin/system_profiler", ["-xml", "SPHardwareDataType"]),
    ]
  else:
    whitelist = []

  for (allowed_cmd, allowed_args) in whitelist:
    if cmd == allowed_cmd and args == allowed_args:
      return True

  return False


text:
package org.objectweb.asm.xml;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.FieldVisitor;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

/**
 * SAXFieldAdapter
 *
 * @author Eugene Kuleshov
 */
public class SAXFieldAdapter implements FieldVisitor {
    private final ContentHandler h;

    public SAXFieldAdapter(ContentHandler h, AttributesImpl att) {
        this.h = h;

        try {
            h.startElement("", "field", "field", att);
        } catch (SAXException ex) {
            throw new RuntimeException(ex.toString());
        }
    }

    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        return new SAXAnnotationAdapter(h,
                "annotation",
                visible ? 1 : -1,
                null,
                desc);
    }

    public void visitAttribute(Attribute attr) {
        // TODO Auto-generated method stub
    }

    public void visitEnd() {
        try {
            h.endElement("", "field", "field");
        } catch (SAXException ex) {
            throw new RuntimeException(ex.toString());
        }
    }

}


text:
- [Laravel 3.2.14](#3.2.14)
- [Upgrading From 3.2.13](#upgrade-3.2.14)
- [Laravel 3.2.13](#3.2.13)
- [Upgrading From 3.2.12](#upgrade-3.2.13)
- [Laravel 3.2.12](#3.2.12)
- [Upgrading From 3.2.11](#upgrade-3.2.12)
- [Laravel 3.2.11](#3.2.11)
- [Upgrading From 3.2.10](#upgrade-3.2.11)
- [Laravel 3.2.10](#3.2.10)
- [Upgrading From 3.2.9](#upgrade-3.2.10)
- [Laravel 3.2.9](#3.2.9)
- [Upgrading From 3.2.8](#upgrade-3.2.9)
- [Laravel 3.2.8](#3.2.8)
- [Upgrading From 3.2.7](#upgrade-3.2.8)
- [Laravel 3.2.7](#3.2.7)
- [Upgrading From 3.2.6](#upgrade-3.2.7)
- [Laravel 3.2.6](#3.2.6)
- [Upgrading From 3.2.5](#upgrade-3.2.6)
- [Laravel 3.2.5](#3.2.5)
- [Upgrading From 3.2.4](#upgrade-3.2.5)
- [Laravel 3.2.4](#3.2.4)
- [Upgrading From 3.2.3](#upgrade-3.2.4)
- [Laravel 3.2.3](#3.2.3)
- [Upgrading From 3.2.2](#upgrade-3.2.3)
- [Laravel 3.2.2](#3.2.2)
- [Upgrading From 3.2.1](#upgrade-3.2.2)
- [Laravel 3.2.1](#3.2.1)
- [Upgrading From 3.2](#upgrade-3.2.1)
- [Laravel 3.2](#3.2)
- [Upgrading From 3.1](#upgrade-3.2)
- [Laravel 3.1.9](#3.1.9)
- [Upgrading From 3.1.8](#upgrade-3.1.9)
- [Laravel 3.1.8](#3.1.8)
- [Upgrading From 3.1.7](#upgrade-3.1.8)
- [Laravel 3.1.7](#3.1.7)
- [Upgrading From 3.1.6](#upgrade-3.1.7)
- [Laravel 3.1.6](#3.1.6)
- [Upgrading From 3.1.5](#upgrade-3.1.6)
- [Laravel 3.1.5](#3.1.5)
- [Upgrading From 3.1.4](#upgrade-3.1.5)
- [Laravel 3.1.4](#3.1.4)
- [Upgrading From 3.1.3](#upgrade-3.1.4)
- [Laravel 3.1.3](#3.1.3)
- [Upgrading From 3.1.2](#uprade-3.1.3)
- [Laravel 3.1.2](#3.1.2)
- [Upgrading From 3.1.1](#upgrade-3.1.2)
- [Laravel 3.1.1](#3.1.1)
- [Upgrading From 3.1](#upgrade-3.1.1)
- [Laravel 3.1](#3.1)
- [Upgrading From 3.0](#upgrade-3.1)

## Laravel 3.2.14

- IoC can now resolve default parameters.
- Fix bug in Postgres insert_get_id when using FETCH_ASSOC.

### Upgrading From 3.2.13

- Replace the **laravel** folder.

## Laravel 3.2.13

- Upgraded Symfony HttpFoundation to 2.1.6.
- Various framework fixes.

### Upgrading From 3.2.12

- Replace the **laravel** folder.

## Laravel 3.2.12

- Clear sections on a complete render operation.

### Upgrading From 3.2.11

- Replace the **laravel** folder.

## Laravel 3.2.11

- Improve performance of Eloquent eager load matching.
- Check `gethostname` on environment detection.

### Upgrading From 3.2.10

- Replace the **laravel** folder.

## Laravel 3.2.10

- Fix bug in Eloquent model.

### Upgrading From 3.2.9

- Replace the **laravel** folder.

## Laravel 3.2.9

- Always log exceptions even when there are "logger" event listeners.
- Fix nasty view exception messages.

### Upgrading From 3.2.8

- Replace the **laravel** folder.

## Laravel 3.2.8

- Fix double slash bug in URLs when using languages and no "index.php".
- Fix possible security issue in Auth "remember me" cookies.

### Upgrading From 3.2.7

- Replace the **laravel** folder.

## Laravel 3.2.7

- Fix bug in Eloquent `to_array` method.
- Fix bug in displaying of generic error page.

### Upgrading From 3.2.6

- Replace the **laravel** folder.

## Laravel 3.2.6

- Revert Blade code back to 3.2.3 tag.

### Upgrading From 3.2.5

- Replace the **laravel** folder.

## Laravel 3.2.5

- Revert nested where code back to 3.2.3 tag.

### Upgrading From 3.2.4

- Replace the **laravel** folder.

## Laravel 3.2.4

- Speed up many to many eager loading mapping.
- Tweak the Eloquent::changed() method.
- Various bug fixes and improvements.

### Upgrading From 3.2.3

- Replace the **laravel** folder.

## Laravel 3.2.3

- Fixed eager loading bug in Eloquent.
- Added `laravel.resolving` event for all IoC resolutions.

### Upgrading From 3.2.2

- Replace the **laravel** folder.

## Laravel 3.2.2

- Overall improvement of Postgres support.
- Fix issue in SQL Server Schema grammar.
- Fix issue with eager loading and `first` or `find`.
- Fix bug causing parameters to not be passed to `IoC::resolve`.
- Allow the specification of hostnames in environment setup.
- Added `DB::last_query` method.
- Added `password` option to Auth configuration.

### Upgrading From 3.2.1

- Replace the **laravel** folder.

## Laravel 3.2.1

- Fixed bug in cookie retrieval when cookie is set on same request.
- Fixed bug in SQL Server grammar for primary keys.
- Fixed bug in Validator on PHP 5.4.
- If HTTP / HTTPS is not specified for generated links, current protocol is used.
- Fix bug in Eloquent auth driver.
- Added `format` method to message container.

### Upgrading From 3.2

- Replace the **laravel** folder.

## Laravel 3.2

- [Added `to_array` method to the base Eloquent model](/docs/database/eloquent#to-array).
- [Added `$hidden` static variable to the base Eloquent model](/docs/database/eloquent#to-array).
- [Added `sync` method to has\_many\_and\_belongs\_to Eloquent relationship](/docs/database/eloquent#sync-method).
- [Added `save` method to has\_many Eloquent relationship](/docs/database/eloquent#has-many-save).
- [Added `unless` structure to Blade template engine](/docs/views/templating#blade-unless).
- [Added Blade comments](/docs/views/templating#blade-comments).
- [Added simpler environment management](/docs/install#environments).
- Added `Blade::extend()` method to define custom blade compilers.
- Added `View::exists` method.
- Use [Memcached](http://php.net/manual/en/book.memcached.php) API instead of older [Memcache](http://php.net/manual/en/book.memcache.php) API.
- Added support for bundles outside of the bundle directory.
- Added support for DateTime database query bindings.
- Migrated to the Symfony HttpFoundation component for core request / response handling.
- Fixed the passing of strings into the `Input::except` method.
- Fixed replacement of optional parameters in `URL::transpose` method.
- Improved `update` handling on `Has_Many` and `Has_One` relationships.
- Improved View performance by only loading contents from file once.
- Fix handling of URLs beginning with hashes in `URL::to`.
- Fix the resolution of unset Eloquent attributes.
- Allows pivot table timestamps to be disabled.
- Made the `get_timestamp` Eloquent method static.
- `Request::secure` now takes `application.ssl` configuration option into consideration.
- Simplified the `paths.php` file.
- Only write file caches if number of minutes is greater than zero.
- Added `$default` parameter to Bundle::option method.
- Fixed bug present when using Eloquent models with Twig.
- Allow multiple views to be registered for a single composer.
- Added `Request::set_env` method.
- `Schema::drop` now accepts `$connection` as second parameter.
- Added `Input::merge` method.
- Added `Input::replace` method.
- Added saving, saved, updating, creating, deleting, and deleted events to Eloquent.
- Added new `Sectionable` interface to allow cache drivers to simulate namespacing.
- Added support for `HAVING` SQL clauses.
- Added `array_pluck` helper, similar to pluck method in Underscore.js.
- Allow the registration of custom cache and session drivers.
- Allow the specification of a separate asset base URL for using CDNs.
- Allow a `starter` Closure to be defined in `bundles.php` to be run on Bundle::start.
- Allow the registration of custom database drivers.
- New, driver based authentication system.
- Added Input::json() method for working with applications using Backbone.js or similar.
- Added Response::json method for creating JSON responses.
- Added Response::eloquent method for creating Eloquent responses.
- Fixed bug when using many-to-many relationships on non-default database connection.
- Added true reflection based IoC to container.
- Added `Request::route()->controller` and `Request::route()->controller_action`.
- Added `Event::queue`, `Event::flusher`, and `Event::flush` methods to Event class.
- Added `array_except` and `array_only` helpers, similar to `Input::except` and `Input::only` but for arbitrary arrays.

### Upgrading From 3.1

- Add new `asset_url` and `profiler` options to application configuration.
- Replace **auth** configuration file.

Add the following entry to the `aliases` array in `config/application.php`..

	'Profiler'   => 'Laravel\\Profiling\\Profiler',

Add the following code above `Blade::sharpen()` in `application/start.php`..

	if (Config::get('application.profiler'))
	{
	    Profiler::attach();
	}

- Upgrade the **paths.php** file.
- Replace the **laravel** folder.

## Laravel 3.1.9

- Fixes cookie session driver bug that caused infinite loop on some occasions.

### Upgrading From 3.1.8

- Replace the **laravel** folder.

## Laravel 3.1.8

- Fixes possible WSOD when using Blade's @include expression.

### Upgrading From 3.1.7

- Replace the **laravel** folder.

## Laravel 3.1.7

- Fixes custom validation language line loading from bundles.
- Fixes double-loading of classes when overriding the core.
- Classify migration names.

### Upgrading From 3.1.6

- Replace the **laravel** folder.

## Laravel 3.1.6

- Fixes many-to-many eager loading in Eloquent.

### Upgrading From 3.1.5

- Replace the **laravel** folder.

## Laravel 3.1.5

- Fixes bug that could allow secure cookies to be sent over HTTP.

### Upgrading From 3.1.4

- Replace the **laravel** folder.

## Laravel 3.1.4

- Fixes Response header casing bug.
- Fixes SQL "where in" (…) short-cut bug.

### Upgrading From 3.1.3

- Replace the **laravel** folder.

## Laravel 3.1.3

- Fixes **delete** method in Eloquent models.

### Upgrade From 3.1.2

- Replace the **laravel** folder.

## Laravel 3.1.2

- Fixes Eloquent query method constructor conflict.

### Upgrade From 3.1.1

- Replace the **laravel** folder.

## Laravel 3.1.1

- Fixes Eloquent model hydration bug involving custom setters.

### Upgrading From 3.1

- Replace the **laravel** folder.

## Laravel 3.1

- Added events to logger for more flexibility.
- Added **database.fetch** configuration option.
- Added controller factories for injecting any IoC.
- Added **link_to_action** HTML helpers.
- Added ability to set default value on Config::get.
- Added the ability to add pattern based filters.
- Improved session ID assignment.
- Added support for "unsigned" integers in schema builder.
- Added config, view, and lang loaders.
- Added more logic to **application/start.php** for more flexibility.
- Added foreign key support to schema builder.
- Postgres "unique" indexes are now added with ADD CONSTRAINT.
- Added "Event::until" method.
- Added "memory" cache and session drivers.
- Added Controller::detect method.
- Added Cache::forever method.
- Controller layouts now resolved in Laravel\Controller __construct.
- Rewrote Eloquent and included in core.
- Added "match" validation rule.
- Fixed table prefix bug.
- Added Form::macro method.
- Added HTML::macro method.
- Added Route::forward method.
- Prepend table name to default index names in schema.
- Added "forelse" to Blade.
- Added View::render_each.
- Able to specify full path to view (path: ).
- Added support for Blade template inheritance.
- Added "before" and "after" validation checks for dates.

### Upgrading From 3.0

#### Replace your **application/start.php** file.

The default **start.php** file has been expanded in order to give you more flexibility over the loading of your language, configuration, and view files. To upgrade your file, copy your current file and paste it at the bottom of a copy of the new Laravel 3.1 start file. Next, scroll up in the **start** file until you see the default Autoloader registrations (line 61 and line 76). Delete both of these sections since you just pasted your previous auto-loader registrations at the bottom of the file.

#### Remove the **display** option from your **errors** configuration file.

This option is now set at the beginning of your **application/start** file.

#### Call the parent controller's constructor from your controller.

Simply add a **parent::__construct();** to to any of your controllers that have a constructor.

#### Prefix Laravel migration created indexes with their table name.

If you have created indexes on tables using the Laravel migration system and you used to the default index naming scheme provided by Laravel, prefix the index names with their table name on your database. So, if the current index name is "id_unique" on the "users" table, make the index name "users_id_unique".

#### Add alias for Eloquent in your application configuration.

Add the following to the **aliases** array in your **application/config/application.php** file:

	'Eloquent' => 'Laravel\\Database\\Eloquent\\Model',
	'Blade' => 'Laravel\\Blade',

#### Update Eloquent many-to-many tables.

Eloquent now maintains **created_at** and **updated_at** column on many-to-many intermediate tables by default. Simply add these columns to your tables. Also, many-to-many tables are now the singular model names concatenated with an underscore. For example, if the relationship is between User and Role, the intermediate table name should be **role_user**.

#### Remove Eloquent bundle.

If you are using the Eloquent bundle with your installation, you can remove it from your bundles directory and your **application/bundles.php** file. Eloquent version 2 is included in the core in Laravel 3.1. Your models can also now extend simply **Eloquent** instead of **Eloquent\Model**.

#### Update your **config/strings.php** file.

English pluralization and singularization is now automatic. Just completely replace your **application/config/strings.php** file.

#### Add the **fetch** option to your database configuration file.

A new **fetch** option allows you to specify in which format you receive your database results. Just copy and paste the option from the new **application/config/database.php** file.

#### Add **database** option to your Redis configuration.

If you are using Redis, add the "database" option to your Redis connection configurations. The "database" value can be zero by default.

	'redis' => array(
		'default' => array(
			'host' => '127.0.0.1',
			'port' => 6379,
			'database' => 0
		),
	),


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>module RailsEmbedEditor - RDoc Documentation</title>

<link href="./fonts.css" rel="stylesheet">
<link href="./rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Methods

::config

    module RailsEmbedEditor

Constants

VERSION

Public Class Methods

          config(&block)

          click to toggle source

# File lib/rails_embed_editor.rb, line 8
def self.config(&block)
  if block_given?
    block.call(RailsEmbedEditor::Config)
  else
    RailsEmbedEditor::Config
  end
end

Validate

Generated by RDoc 4.1.1.

Based on Darkfish by Michael Granger.


text:
{{ define "main" }}

Some things I've made.

  {{ range .Data.Pages.ByWeight.Reverse }}
    {{ .Render "li"}}
  {{ end }}

{{ end }}


text:
angular.module('scroll-trigger')
.factory('thresholdFn', function($window) {
  return function(elem) {
    elem = elem || $window;
    if (elem == $window) {
      return elem.pageYOffset + elem.innerHeight;
    } else {
      return elem.scrollTop + elem.clientHeight;
    }
  };
});


text:
<resources xmlns:tools="http://schemas.android.com/tools" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="fui_progress_dialog_loading">Laden…</string>
    <string name="fui_sign_in_default">Inloggen</string>
    <string name="fui_tos_and_pp">Als u doorgaat, geeft u aan dat u onze %1$s en ons %2$s accepteert.</string>
    <string name="fui_tos_and_pp_footer">%1$s \u00A0 \u00A0 %2$s</string>
    <string name="fui_idp_name_google">Google</string>
    <string name="fui_idp_name_facebook">Facebook</string>
    <string name="fui_idp_name_twitter">Twitter</string>
    <string name="fui_idp_name_github">GitHub</string>
    <string name="fui_sign_in_with_google">Inloggen met Google</string>
    <string name="fui_sign_in_with_facebook">Inloggen met Facebook</string>
    <string name="fui_sign_in_with_twitter">Inloggen met Twitter</string>
    <string name="fui_sign_in_with_github">Inloggen met GitHub</string>
    <string name="fui_sign_in_with_email">Inloggen met e-mailadres</string>
    <string name="fui_sign_in_with_phone">Inloggen met telefoon</string>
    <string name="fui_sign_in_anonymously">Doorgaan als gast</string>
    <string name="fui_next_default">Volgende</string>
    <string name="fui_email_hint">E-mail</string>
    <string name="fui_phone_hint">Telefoonnummer</string>
    <string name="fui_password_hint">Wachtwoord</string>
    <string name="fui_required_field">Dit veld mag niet leeg zijn.</string>
    <string name="fui_invalid_email_address">Dit e-mailadres is niet juist</string>
    <string name="fui_missing_email_address">Voer uw e-mailadres in om verder te gaan</string>
    <string name="fui_progress_dialog_checking_accounts">Controleren op bestaande accounts…</string>
    <string name="fui_title_register_email">Aanmelden</string>
    <string name="fui_name_hint">Voor- en achternaam</string>
    <string name="fui_button_text_save">Opslaan</string>
    <string name="fui_progress_dialog_signing_up">Aanmelden…</string>
    <plurals name="fui_error_weak_password"> <item quantity="one">Uw wachtwoord is niet sterk genoeg. Gebruik ten minste %1$d teken en een combinatie van letters en cijfers.</item> <item quantity="other">Uw wachtwoord is niet sterk genoeg. Gebruik ten minste %1$d tekens en een combinatie van letters en cijfers.</item> </plurals>
    <string name="fui_email_account_creation_error">Registratie van e-mailaccount is mislukt</string>
    <string name="fui_terms_of_service">Servicevoorwaarden</string>
    <string name="fui_privacy_policy">Privacybeleid</string>
    <string name="fui_welcome_back_idp_header">U heeft al een account</string>
    <string name="fui_welcome_back_email_header">Welkom terug.</string>
    <string name="fui_welcome_back_idp_prompt">U heeft %1$s al gebruikt. Log in met %2$s om verder te gaan.</string>
    <string name="fui_welcome_back_password_prompt_body">U heeft al ingelogd met %1$s. Voer uw wachtwoord in voor dit account.</string>
    <string name="fui_progress_dialog_signing_in">Inloggen…</string>
    <string name="fui_trouble_signing_in">Problemen met inloggen?</string>
    <string name="fui_title_recover_password_activity">Wachtwoord herstellen</string>
    <string name="fui_title_confirm_recover_password">Controleer uw inbox</string>
    <string name="fui_password_recovery_body">Er wordt een e-mail naar dit adres verzonden met instructies om uw wachtwoord te resetten.</string>
    <string name="fui_button_text_send">Verzenden</string>
    <string name="fui_confirm_recovery_body">Volg de instructies die we naar %1$s hebben verzonden om uw wachtwoord te herstellen.</string>
    <string name="fui_progress_dialog_sending">Verzenden…</string>
    <string name="fui_error_email_does_not_exist">Dit e-mailadres komt niet overeen met een bestaand account</string>
    <string name="fui_error_unknown">Er is een onbekende fout opgetreden.</string>
    <string name="fui_error_invalid_password">Onjuist wachtwoord.</string>
    <string name="fui_accessibility_logo">App-logo</string>
    <string name="fui_verify_phone_number_title">Voer uw telefoonnummer in</string>
    <string name="fui_invalid_phone_number">Voer een geldig telefoonnummer in</string>
    <string name="fui_enter_confirmation_code">Voer de zescijferige code in die we hebben verzonden naar</string>
    <string name="fui_resend_code_in">Code opnieuw verzenden over 0:%02d</string>
    <string name="fui_verify_your_phone_title">Uw telefoonnummer verifiëren</string>
    <string name="fui_verifying">Verifiëren…</string>
    <string name="fui_incorrect_code_dialog_body">Onjuiste code. Probeer het opnieuw.</string>
    <string name="fui_error_too_many_attempts">Dit telefoonnummer is te vaak gebruikt</string>
    <string name="fui_error_quota_exceeded">Er is een probleem met de verificatie van uw telefoonnummer</string>
    <string name="fui_error_session_expired">Deze code is niet meer geldig</string>
    <string name="fui_sign_in_with_phone_number">Inloggen met telefoonnummer</string>
    <string name="fui_auto_verified">Telefoonnummer is automatisch geverifieerd</string>
    <string name="fui_resend_code">Code opnieuw verzenden</string>
    <string name="fui_verify_phone_number">Telefoonnummer verifiëren</string>
    <string name="fui_continue_phone_login">Doorgaan</string>
    <string name="fui_sms_terms_of_service">Als u op "%1$s" tikt, ontvangt u mogelijk een sms. Er kunnen sms- en datakosten in rekening worden gebracht.</string>
    <string name="fui_sms_terms_of_service_and_privacy_policy_extended">Als u op "%1$s" tikt, geeft u aan dat u onze %2$s en ons %3$s accepteert. Mogelijk ontvangt u een sms. Er kunnen sms- en datakosten in rekening worden gebracht.</string>
</resources>


text:
      {{ utils.back_link('Назад к списку заказов', 'order_history', order='-created') }}
      {{ title }}

# endblock

# block content

      #include 'cart/order_table.html'

    #include 'cart/order_buttons.html'

# endblock


text:
DecodeBuffer::DecodeBuffer(const unsigned char *data, unsigned int length)
{
    buffer = data;
    end = buffer + length;
    nextSrc = buffer;
    availableBitsInSrc = 8;
}

int DecodeBuffer::countLeadingZeros(unsigned &value, int endOkay)
{
    unsigned ix = 0;

    assert(availableBitsInSrc != 0);

    DBG("DecodeBuffer::countLeadingZeros: availableBitsInSrc = %d, *src = 0x%08x\n",
        availableBitsInSrc, *nextSrc);

    while (nextSrc < end)
    {
        unsigned mask = 1U << (availableBitsInSrc - 1);

        while (availableBitsInSrc)
        {
            if ((*nextSrc) & mask)
            {
                DBG("DecodeBuffer::countLeadingZeros: got %d\n", ix);

                // consume the 1 bit.
                availableBitsInSrc--;
                if (!availableBitsInSrc)
                {
                    availableBitsInSrc = 8;
                    nextSrc++;
                }
                value = ix;
                return 1;
            }
            ix++;
            mask >>= 1;
            availableBitsInSrc--;
        }
        nextSrc++;
        availableBitsInSrc = 8;
    }

    if (!endOkay)
    {
        CERR << "DecodeBuffer::countLeadingZeros: assertion failed." << ENDL;
        abort();
    }
    return 0;
}

int DecodeBuffer::decodeDirect(unsigned int &value,
                               unsigned int numBits,
                               int          endOkay)
{
    unsigned remainingBits = numBits;
    unsigned destShift = 0;

    value = 0;

    assert(numBits <= (sizeof(unsigned) * 8));
    assert(numBits != 0);

    DBG("DecodeBuffer::decodeDirect: %d bits,  availableBitsInSrc = %d, remaining = %d: ",
        numBits, availableBitsInSrc, end-nextSrc);

    while (remainingBits)
    {
        if (nextSrc >= end)
        {
            if (!endOkay)
            {
                CERR << "DecodeBuffer::decodeDirect: assertation failed" << ENDL;
            }
            return 0;
        }

        if (availableBitsInSrc > remainingBits)
        {
            // We must shift the bits into place.
            unsigned readBits = *nextSrc >> (availableBitsInSrc - remainingBits);

            value |= (readBits & PARTIAL_INT_MASK[remainingBits]) << destShift;
            availableBitsInSrc -= remainingBits;
            remainingBits = 0;
        }
        else
        {
            unsigned readBits = *nextSrc & PARTIAL_INT_MASK[availableBitsInSrc];
            value |= readBits << destShift;
            destShift += availableBitsInSrc;
            remainingBits -= availableBitsInSrc;

            nextSrc++;
            availableBitsInSrc = 8;
        }
    }

    DBG("value = 0x%08x\n", value);
    return 1;
}

int DecodeBuffer::decodeValue(unsigned int &value,
                              unsigned int numBits,
                              unsigned int blockSize,
                              int          endOkay)
{
    unsigned int remainingBits = numBits;
    unsigned int numBlocks = 0;
    unsigned int result = 0;

    DBG("DecodeBuffer::decodeValue: %d bits, %d blocksize\n",
           numBits, blockSize);

    assert(numBits <= (sizeof(unsigned) * 8));
    assert(numBits != 0);
    assert(blockSize <= numBits);

    if (blockSize == 0)
        blockSize = numBits;

    if ((blockSize == numBits) || (numBits < 3))
    {
        // No use for block compression.
        return decodeDirect(value, numBits, endOkay);
    }

    do
    {
        unsigned int bitsToRead = blockSize > remainingBits ? remainingBits : blockSize;
        unsigned int block;

        if (!decodeDirect(block, bitsToRead, endOkay))
        {
            return 0;
        }

        result = result | (block << (numBits - remainingBits));
        remainingBits -= bitsToRead;

        if (remainingBits)
        {
            unsigned marker;

            // Now read the marker bit.
            if (!decodeDirect(marker, 1, endOkay))
            {
                return 0;
            }

            if (!marker)
            {
                // The remainder of the value is all the same as the most significant bit
                // of the last block we read.
                unsigned lastBit = block & (1 << (bitsToRead - 1));

                DBG("decodeBuffer: got block compression (lastBit = %d, remainingBits = %d)\n",
                       lastBit ? 1 : 0, remainingBits);

                if (lastBit)
                {
                    // We need to build a mask of doom.
                    unsigned mask = PARTIAL_INT_MASK[remainingBits];

                    mask <<= (numBits - remainingBits);

                    DBG("Mask of ones = 0x%08x\n", mask);

                    result |= mask;
                }
                // No need to extend zeros.
                // Break out of outer loop, we're done.
                remainingBits = 0;
            }
        }

        if (++numBlocks >= 4)
        {
            blockSize = numBits;
        }
        else if (blockSize > 2)
        {
            blockSize >>= 1;
        }
    } while (remainingBits);

    DBG("decodeValue: value = 0x%08x\n", value);

    value = result;
    return 1;
}

// Simply returns a pointer to the correct spot in the internal
// buffer. If the caller needs this data to last beyond the lifetime
// of the internal buffer, they must copy the data.
const unsigned char *DecodeBuffer::decodeRawMem(unsigned int len)
{
    const unsigned char *retVal;

    // Force ourselves to a byte boundary.
    if (availableBitsInSrc != 8)
    {
        availableBitsInSrc = 8;
        nextSrc++;
    }

    retVal = nextSrc;

    if (end - nextSrc < (ptrdiff_t) len)
    {
        CERR << "DecodeBuffer::decodeRawMem called with " << len
            << " length with only " << end - nextSrc
            << " bytes remaining." << ENDL;
        abort();
    }

    nextSrc += len;
    return retVal;
}

int DecodeBuffer::decodeCachedValue(unsigned int &value,
                                    unsigned int numBits,
                                    IntCache     &cache,
                                    unsigned int blockSize,
                                    int          endOkay)
{
    unsigned int index;

    if (!countLeadingZeros(index, endOkay))
    {
        return 0;
    }

    if (index == 2)
    {
        unsigned int sameDiff;

        decodeDirect(sameDiff, 1);

        if (sameDiff)
        {
            value = cache.getLastDiff(PARTIAL_INT_MASK[numBits]);
            cache.insert(value, PARTIAL_INT_MASK[numBits]);
            return 1;
        }

        blockSize = cache.getBlockSize(numBits);

        if (!decodeValue(value, numBits, blockSize, endOkay))
        {
            return 0;
        }

        cache.insert(value, PARTIAL_INT_MASK[numBits]);
        return 1;
    }

    if (index > 2)
        index--;
    if (index > cache.getSize())
    {
        CERR << "Assertion 2 failed in DecodeCachedValue: index=" << index
            << ", cache size=" << cache.getSize() << ENDL;
        abort();
    }
    value = cache.get(index);
    return 1;
}

int DecodeBuffer::decodeCachedValue(unsigned char &value,
                                    unsigned int  numBits,
                                    CharCache     &cache,
                                    unsigned int  blockSize,
                                    int           endOkay)
{
    unsigned int index;

    if (!countLeadingZeros(index, endOkay))
    {
        return 0;
    }

    if (index == 2)
    {
        unsigned int val;

        if (decodeValue(val, numBits, blockSize, endOkay))
        {
            value = (unsigned char) val;
            cache.insert(value);
            return 1;
        }
        return 0;
    }
    if (index > 2)
        index--;
    if (index > cache.getSize())
    {
        CERR << "Assertion 4 failed in DecodeCachedValue: index=" << index
            << ", cache size=" << cache.getSize() << ENDL;
        abort();
    }
    value = cache.get(index);
    return 1;
}

int DecodeBuffer::decodeCachedValue(unsigned int &value, unsigned int numBits,
                                    PixelCache & cache,
                                    HuffmanCoder & escapeCoder0,
                                    HuffmanCoder & escapeCoder1, int endOkay)
{
    unsigned int index = 0;

    if (!countLeadingZeros(index, endOkay))
    {
        return 0;
    }

    if (index == 2)
    {
        value = 0;
        unsigned int pixelValue;

        if (!decodeDirect(pixelValue, 1, endOkay))
            return 0;
        unsigned int mask = 0x1;

        for (unsigned int x = 0; x < numBits;)
        {
            unsigned int runLength;

            if (pixelValue)
            {
                runLength = escapeCoder1.decode(*this) + 1;
                for (unsigned int i = runLength; i; i--)
                {
                    value |= mask;
                    mask <<= 1;
                }
                pixelValue = 0;
            }
            else
            {
                runLength = escapeCoder0.decode(*this) + 1;
                mask <<= runLength;
                pixelValue = 1;
            }
            x += runLength;
        }
        cache.insert(value);
        return 1;
    }
    if (index > 2)
        index--;
    if (index > cache.getSize())
    {
        CERR << "Assertion 6 failed in DecodeCachedValue: index=" << index
            << ", cache size=" << cache.getSize() << ENDL;
        abort();
    }
    value = cache.get(index);
    return 1;
}


text:
<?php

namespace PHPPremailer\Test;

require_once '../src/PremailerClient.php';

use \PHPUnit_Framework_TestCase;
use PHPPremailer\PremailerClient;
use PHPPremailer\PremailerResponse;

class PremailerTest extends PHPUnit_Framework_TestCase {

	const PREMAILER_TEST_URL = 'http://dialect.ca/premailer-tests/base.html';
	const URL_HTML_FILE      = 'data/url.html';
	const URL_TEXT_FILE      = 'data/url.txt';
	const ORIGINAL_FILE      = 'data/original.html';
	const HTML_HTML_FILE     = 'data/html.html';
	const HTML_TEXT_FILE     = 'data/html.txt';

	/**
	 * Original html file
	 *
	 * @var string
	 */
	private $original_file;

	/**
	 * Read original html file
	 *
	 * @return string
	 */
	private function get_original_file()
	{
		if($this->original_file === null)
			$this->original_file = file_get_contents(self::ORIGINAL_FILE);

		return $this->original_file;
	}

	public function test_basics()
	{
		$client = new PremailerClient();

		$this->assertEquals(null, $client->get_source_type());
		$this->assertEquals(null, $client->get_source_text());
		$this->assertEquals(PremailerClient::ADAPTER_HPRICOT, $client->get_adapter());
		$this->assertEquals('', $client->get_base_url());
		$this->assertEquals(PremailerClient::DEFAULT_LINE_LENGTH, $client->get_line_length());
		$this->assertEquals('', $client->get_link_query_string());
		$this->assertEquals(PremailerClient::DEFAULT_PRESERVE_STYLES, $client->get_preserve_styles());
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_IDS, $client->get_remove_ids());
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_CLASSES, $client->get_remove_classes());
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_COMMENTS, $client->get_remove_comments());
	}

	public function test_source()
	{
		$url = 'http://www.google.com';
		$html = '';
		$client = new PremailerClient();

		$client->set_source(null, $url);
		$this->assertEquals(null, $client->get_source_type());
		$this->assertEquals(null, $client->get_source_text());

		$client->set_source(PremailerClient::SOURCE_TYPE_URL, null);
		$this->assertEquals(null, $client->get_source_type());
		$this->assertEquals(null, $client->get_source_text());

		$client->set_source(null, null);
		$this->assertEquals(null, $client->get_source_type());
		$this->assertEquals(null, $client->get_source_text());

		$client->set_source(PremailerClient::SOURCE_TYPE_URL, $url);
		$this->assertEquals(PremailerClient::SOURCE_TYPE_URL, $client->get_source_type());
		$this->assertEquals($url, $client->get_source_text());

		$client->set_source(PremailerClient::SOURCE_TYPE_HTML, $this->get_original_file());
		$this->assertEquals(PremailerClient::SOURCE_TYPE_HTML, $client->get_source_type());
		$this->assertEquals($this->get_original_file(), $client->get_source_text());
	}

	/**
     * @expectedException        PHPPremailer\PremailerException
	 * @expectedExceptionMessage source_type must be one of Premailer::SOURCE_TYPE_URL or Premailer::SOURCE_TYPE_HTML
     */
	public function test_set_source_exception()
	{
		$client = new PremailerClient();

		$client->set_source('foo', 'bar');
	}

	public function test_adapter()
	{
		$client = new PremailerClient();

		$client->set_adapter();
		$this->assertEquals(PremailerClient::ADAPTER_HPRICOT, $client->get_adapter());

		$client->set_adapter(PremailerClient::ADAPTER_HPRICOT);
		$this->assertEquals(PremailerClient::ADAPTER_HPRICOT, $client->get_adapter());

		$client->set_adapter(PremailerClient::ADAPTER_NOKOGIRI);
		$this->assertEquals(PremailerClient::ADAPTER_NOKOGIRI, $client->get_adapter());
	}

	/**
     * @expectedException        PHPPremailer\PremailerException
	 * @expectedExceptionMessage $adapter must be one of Premailer::ADAPTER_HPRICOT or Premailer::ADAPTER_NOKOGIRI
     */
	public function test_set_adapter_exception()
	{
		$client = new PremailerClient();

		$client->set_adapter('foo');
	}

	public function test_send_html()
	{
		$client = new PremailerClient(PremailerClient::SOURCE_TYPE_HTML, $this->get_original_file());

		$response = $client->send()->get_response();
		$alt_response = new PremailerResponse($client->get_response_text());

		$this->assertEquals(PremailerResponse::STATUS_SUCCESS, $response->get_status());

		$this->assertEquals('Created', $response->get_message());
		$this->assertEquals('0.1', $response->get_version());

		$this->assertStringEqualsFile(self::HTML_HTML_FILE, $response->get_html(PremailerResponse::SSL_NOT_VERIFY));
		$this->assertStringEqualsFile(self::HTML_TEXT_FILE, $response->get_text(PremailerResponse::SSL_NOT_VERIFY));

		$options = $response->get_options();

		$this->assertEquals(PremailerClient::ADAPTER_HPRICOT, $options['adapter']);
		$this->assertEquals(false, isset($options['base_url']));
		$this->assertEquals((string) PremailerClient::DEFAULT_LINE_LENGTH, $options['line_length']);
		$this->assertEquals('', $options['link_query_string']);
		$this->assertEquals(PremailerClient::DEFAULT_PRESERVE_STYLES, $options['preserve_styles']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_IDS, $options['remove_ids']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_CLASSES, $options['remove_classes']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_COMMENTS, $options['remove_comments']);
	}

	public function test_send_url()
	{
		$client = new PremailerClient(PremailerClient::SOURCE_TYPE_URL, self::PREMAILER_TEST_URL);

		$response = $client->send()->get_response();
		$alt_response = new PremailerResponse($client->get_response_text());

		$this->assertEquals(PremailerResponse::STATUS_SUCCESS, $response->get_status());

		$this->assertEquals('Created', $response->get_message());
		$this->assertEquals('0.1', $response->get_version());

		$this->assertStringEqualsFile(self::URL_HTML_FILE, $response->get_html());
		$this->assertStringEqualsFile(self::URL_TEXT_FILE, $response->get_text());

		$options = $response->get_options();

		$this->assertEquals(PremailerClient::ADAPTER_HPRICOT, $options['adapter']);
		$this->assertEquals(false, isset($options['base_url']));
		$this->assertEquals((string) PremailerClient::DEFAULT_LINE_LENGTH, $options['line_length']);
		$this->assertEquals('', $options['link_query_string']);
		$this->assertEquals(PremailerClient::DEFAULT_PRESERVE_STYLES, $options['preserve_styles']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_IDS, $options['remove_ids']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_CLASSES, $options['remove_classes']);
		$this->assertEquals(PremailerClient::DEFAULT_REMOVE_COMMENTS, $options['remove_comments']);
	}

	/**
     * @expectedException        PHPPremailer\PremailerException
	 * @expectedExceptionMessage Either the url or html must be provided
     */
	public function test_send_exception()
	{
		$client = new PremailerClient();

		$client->send();
	}
}


text:
set -e

BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )"

OUTPUT_DIR=${OUTPUT_DIR:-$HOME/nmt_data/wmt16_de_en}
echo "Writing to ${OUTPUT_DIR}. To change this, set the OUTPUT_DIR environment variable."

OUTPUT_DIR_DATA="${OUTPUT_DIR}/data"

mkdir -p $OUTPUT_DIR_DATA

echo "Downloading Europarl v7. This may take a while..."
wget -nc -nv -O ${OUTPUT_DIR_DATA}/europarl-v7-de-en.tgz \
  http://www.statmt.org/europarl/v7/de-en.tgz

echo "Downloading Common Crawl corpus. This may take a while..."
wget -nc -nv -O ${OUTPUT_DIR_DATA}/common-crawl.tgz \
  http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz

echo "Downloading News Commentary v11. This may take a while..."
wget -nc -nv -O ${OUTPUT_DIR_DATA}/nc-v11.tgz \
  http://data.statmt.org/wmt16/translation-task/training-parallel-nc-v11.tgz

echo "Downloading dev/test sets"
wget -nc -nv -O  ${OUTPUT_DIR_DATA}/dev.tgz \
  http://data.statmt.org/wmt16/translation-task/dev.tgz
wget -nc -nv -O  ${OUTPUT_DIR_DATA}/test.tgz \
  http://data.statmt.org/wmt16/translation-task/test.tgz

# Extract everything
echo "Extracting all files..."
mkdir -p "${OUTPUT_DIR_DATA}/europarl-v7-de-en"
tar -xvzf "${OUTPUT_DIR_DATA}/europarl-v7-de-en.tgz" -C "${OUTPUT_DIR_DATA}/europarl-v7-de-en"
mkdir -p "${OUTPUT_DIR_DATA}/common-crawl"
tar -xvzf "${OUTPUT_DIR_DATA}/common-crawl.tgz" -C "${OUTPUT_DIR_DATA}/common-crawl"
mkdir -p "${OUTPUT_DIR_DATA}/nc-v11"
tar -xvzf "${OUTPUT_DIR_DATA}/nc-v11.tgz" -C "${OUTPUT_DIR_DATA}/nc-v11"
mkdir -p "${OUTPUT_DIR_DATA}/dev"
tar -xvzf "${OUTPUT_DIR_DATA}/dev.tgz" -C "${OUTPUT_DIR_DATA}/dev"
mkdir -p "${OUTPUT_DIR_DATA}/test"
tar -xvzf "${OUTPUT_DIR_DATA}/test.tgz" -C "${OUTPUT_DIR_DATA}/test"

# Concatenate Training data
cat "${OUTPUT_DIR_DATA}/europarl-v7-de-en/europarl-v7.de-en.en" \
  "${OUTPUT_DIR_DATA}/common-crawl/commoncrawl.de-en.en" \
  "${OUTPUT_DIR_DATA}/nc-v11/training-parallel-nc-v11/news-commentary-v11.de-en.en" \
  > "${OUTPUT_DIR}/train.en"
wc -l "${OUTPUT_DIR}/train.en"

cat "${OUTPUT_DIR_DATA}/europarl-v7-de-en/europarl-v7.de-en.de" \
  "${OUTPUT_DIR_DATA}/common-crawl/commoncrawl.de-en.de" \
  "${OUTPUT_DIR_DATA}/nc-v11/training-parallel-nc-v11/news-commentary-v11.de-en.de" \
  > "${OUTPUT_DIR}/train.de"
wc -l "${OUTPUT_DIR}/train.de"

# Clone Moses
if [ ! -d "${OUTPUT_DIR}/mosesdecoder" ]; then
  echo "Cloning moses for data processing"
  git clone https://github.com/moses-smt/mosesdecoder.git "${OUTPUT_DIR}/mosesdecoder"
fi

# Convert SGM files
# Convert newstest2014 data into raw text format
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/dev/dev/newstest2014-deen-src.de.sgm \
  > ${OUTPUT_DIR_DATA}/dev/dev/newstest2014.de
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/dev/dev/newstest2014-deen-ref.en.sgm \
  > ${OUTPUT_DIR_DATA}/dev/dev/newstest2014.en

# Convert newstest2015 data into raw text format
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/dev/dev/newstest2015-deen-src.de.sgm \
  > ${OUTPUT_DIR_DATA}/dev/dev/newstest2015.de
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/dev/dev/newstest2015-deen-ref.en.sgm \
  > ${OUTPUT_DIR_DATA}/dev/dev/newstest2015.en

# Convert newstest2016 data into raw text format
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/test/test/newstest2016-deen-src.de.sgm \
  > ${OUTPUT_DIR_DATA}/test/test/newstest2016.de
${OUTPUT_DIR}/mosesdecoder/scripts/ems/support/input-from-sgm.perl \
  < ${OUTPUT_DIR_DATA}/test/test/newstest2016-deen-ref.en.sgm \
  > ${OUTPUT_DIR_DATA}/test/test/newstest2016.en

# Copy dev/test data to output dir
cp ${OUTPUT_DIR_DATA}/dev/dev/newstest20*.de ${OUTPUT_DIR}
cp ${OUTPUT_DIR_DATA}/dev/dev/newstest20*.en ${OUTPUT_DIR}
cp ${OUTPUT_DIR_DATA}/test/test/newstest20*.de ${OUTPUT_DIR}
cp ${OUTPUT_DIR_DATA}/test/test/newstest20*.en ${OUTPUT_DIR}

# Tokenize data
for f in ${OUTPUT_DIR}/*.de; do
  echo "Tokenizing $f..."
  ${OUTPUT_DIR}/mosesdecoder/scripts/tokenizer/tokenizer.perl -q -l de -threads 8 < $f > ${f%.*}.tok.de
done

for f in ${OUTPUT_DIR}/*.en; do
  echo "Tokenizing $f..."
  ${OUTPUT_DIR}/mosesdecoder/scripts/tokenizer/tokenizer.perl -q -l en -threads 8 < $f > ${f%.*}.tok.en
done

# Clean all corpora
for f in ${OUTPUT_DIR}/*.en; do
  fbase=${f%.*}
  echo "Cleaning ${fbase}..."
  ${OUTPUT_DIR}/mosesdecoder/scripts/training/clean-corpus-n.perl $fbase de en "${fbase}.clean" 1 80
done

# Create character vocabulary (on tokenized data)
${BASE_DIR}/bin/tools/generate_char_vocab.py \
  < ${OUTPUT_DIR}/train.tok.clean.en \
  > ${OUTPUT_DIR}/vocab.tok.char.en
${BASE_DIR}/bin/tools/generate_char_vocab.py \
  < ${OUTPUT_DIR}/train.tok.clean.de \
  > ${OUTPUT_DIR}/vocab.tok.char.de

# Create character vocabulary (on non-tokenized data)
${BASE_DIR}/bin/tools/generate_char_vocab.py \
  < ${OUTPUT_DIR}/train.clean.en \
  > ${OUTPUT_DIR}/vocab.char.en
${BASE_DIR}/bin/tools/generate_char_vocab.py \
  < ${OUTPUT_DIR}/train.clean.de \
  > ${OUTPUT_DIR}/vocab.char.de

# Create vocabulary for EN data
$BASE_DIR/bin/tools/generate_vocab.py \
   --max_vocab_size 50000 \
  < ${OUTPUT_DIR}/train.tok.clean.en \
  > ${OUTPUT_DIR}/vocab.50k.en \

# Create vocabulary for DE data
$BASE_DIR/bin/tools/generate_vocab.py \
  --max_vocab_size 50000 \
  < ${OUTPUT_DIR}/train.tok.clean.de \
  > ${OUTPUT_DIR}/vocab.50k.de \

# Generate Subword Units (BPE)
# Clone Subword NMT
if [ ! -d "${OUTPUT_DIR}/subword-nmt" ]; then
  git clone https://github.com/rsennrich/subword-nmt.git "${OUTPUT_DIR}/subword-nmt"
fi

# Learn Shared BPE
for merge_ops in 32000; do
  echo "Learning BPE with merge_ops=${merge_ops}. This may take a while..."
  cat "${OUTPUT_DIR}/train.tok.clean.de" "${OUTPUT_DIR}/train.tok.clean.en" | \
    ${OUTPUT_DIR}/subword-nmt/learn_bpe.py -s $merge_ops > "${OUTPUT_DIR}/bpe.${merge_ops}"

  echo "Apply BPE with merge_ops=${merge_ops} to tokenized files..."
  for lang in en de; do
    for f in ${OUTPUT_DIR}/*.tok.${lang} ${OUTPUT_DIR}/*.tok.clean.${lang}; do
      outfile="${f%.*}.bpe.${merge_ops}.${lang}"
      ${OUTPUT_DIR}/subword-nmt/apply_bpe.py -c "${OUTPUT_DIR}/bpe.${merge_ops}" < $f > "${outfile}"
      echo ${outfile}
    done
  done

  # Create vocabulary file for BPE
  cat "${OUTPUT_DIR}/train.tok.clean.bpe.${merge_ops}.en" "${OUTPUT_DIR}/train.tok.clean.bpe.${merge_ops}.de" | \
    ${OUTPUT_DIR}/subword-nmt/get_vocab.py | cut -f1 -d ' ' > "${OUTPUT_DIR}/vocab.bpe.${merge_ops}"

done

echo "All done."


text:
from ..oauth import OAuth2, register_oauth

@register_oauth
class Linkedin(OAuth2):
    '''LinkedIn api

    https://developer.linkedin.com/apis
    '''
    auth_uri = 'https://www.linkedin.com/uas/oauth2/authorization'
    token_uri = 'https://www.linkedin.com/uas/oauth2/accessToken'


text:
from django.conf.urls import patterns, url

urlpatterns = patterns("spirit.views.admin.category",
    url(r'^$', 'category_list', name='admin-category'),
    url(r'^list/$', 'category_list', name='admin-category-list'),
    url(r'^create/$', 'category_create', name='admin-category-create'),
    url(r'^update/(?P<category_id>\d+)/$', 'category_update', name='admin-category-update'),
)


text:
package org.apache.ignite.internal.processors.query.stat;

import org.apache.ignite.IgniteException;

/** */
public class GatherStatisticCancelException extends IgniteException {
    /** */
    private static final long serialVersionUID = 0L;
}


text:
package org.insightech.er.db.sqltype;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.insightech.er.db.sqltype.SqlType.TypeKey;
import org.insightech.er.util.POIUtils;
import org.insightech.er.util.io.IOUtils;

public final class SqlTypeFactory {
	public static void load() throws IOException, ClassNotFoundException {
		InputStream in = null;

		try {
			in = SqlTypeFactory.class.getResourceAsStream("/SqlType.xls");

			HSSFWorkbook workBook = POIUtils.readExcelBook(in);

			HSSFSheet sheet = workBook.getSheetAt(0);

			Map<String, Map<SqlType, String>> dbAliasMap = new HashMap<String, Map<SqlType, String>>();
			Map<String, Map<TypeKey, SqlType>> dbSqlTypeMap = new HashMap<String, Map<TypeKey, SqlType>>();

			HSSFRow headerRow = sheet.getRow(0);

			for (int colNum = 4, endColNum = headerRow.getLastCellNum(); colNum < endColNum; colNum++) {
				String dbId = POIUtils.getCellValue(sheet, 0, colNum);

				Map<SqlType, String> aliasMap = new LinkedHashMap<SqlType, String>();
				dbAliasMap.put(dbId, aliasMap);

				Map<TypeKey, SqlType> sqlTypeMap = new LinkedHashMap<TypeKey, SqlType>();
				dbSqlTypeMap.put(dbId, sqlTypeMap);
			}

			SqlType.setDBAliasMap(dbAliasMap, dbSqlTypeMap);

			for (int rowNum = 1, endRowNum = sheet.getLastRowNum(); rowNum <= endRowNum; rowNum++) {
				HSSFRow row = sheet.getRow(rowNum);

				String sqlTypeId = POIUtils.getCellValue(sheet, rowNum, 0);
				if (StringUtils.isEmpty(sqlTypeId)) {
					break;
				}
				Class javaClass = Class.forName(POIUtils.getCellValue(sheet,
						rowNum, 1));
				boolean needArgs = POIUtils.getBooleanCellValue(sheet, rowNum,
						2);
				boolean fullTextIndexable = POIUtils.getBooleanCellValue(sheet,
						rowNum, 3);

				SqlType sqlType = new SqlType(sqlTypeId, javaClass, needArgs,
						fullTextIndexable);

				for (int colNum = 4, endColNum = row.getLastCellNum(); colNum < endColNum; colNum++) {

					String dbId = POIUtils.getCellValue(sheet, 0, colNum);

					if (StringUtils.isEmpty(dbId)) {
						dbId = POIUtils.getCellValue(sheet, 0, colNum - 1);
						String key = POIUtils.getCellValue(sheet, rowNum,
								colNum);
						if (StringUtils.isNotEmpty(key)) {
							sqlType.addToSqlTypeMap(key, dbId);
						}

					} else {
						Map<SqlType, String> aliasMap = dbAliasMap.get(dbId);

						if (POIUtils.getCellColor(sheet, rowNum, colNum) != HSSFColor.RED.index) {
							String alias = POIUtils.getCellValue(sheet, rowNum,
									colNum);

							if (StringUtils.isEmpty(alias)) {
								alias = sqlTypeId;
							}

							aliasMap.put(sqlType, alias);

							if (POIUtils.getCellColor(sheet, rowNum, colNum) == HSSFColor.SKY_BLUE.index) {
								sqlType.addToSqlTypeMap(alias, dbId);
							}
						}
					}
				}
			}

		} finally {
			IOUtils.closeQuietly(in);
		}

	}

	public static void main(String[] args) {
		SqlType.main(new String[0]);
	}

	private SqlTypeFactory() {
		// do nothing.
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>se.skuggla.trerad</id>
    <name>Pia4_TreRad</name>
    <version>1.0.0</version>
    <publisher>Malin Olofsson</publisher>
    <url>http://skuggla.se</url>
    <description>not specified</description>
    <copyright>2013 by Malin Olofsson</copyright>
    <icon>appicon.png</icon>
    <persistent-wifi>false</persistent-wifi>
    <prerendered-icon>false</prerendered-icon>
    <statusbar-style>default</statusbar-style>
    <statusbar-hidden>false</statusbar-hidden>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
    <guid>ec973cf3-debc-48b8-827a-6c947660cece</guid>
    <property name="ti.ui.defaultunit" type="string">system</property>
    <iphone>
        <orientations device="iphone">
            <orientation>Ti.UI.PORTRAIT</orientation>
        </orientations>
        <orientations device="ipad">
            <orientation>Ti.UI.PORTRAIT</orientation>
            <orientation>Ti.UI.UPSIDE_PORTRAIT</orientation>
            <orientation>Ti.UI.LANDSCAPE_LEFT</orientation>
            <orientation>Ti.UI.LANDSCAPE_RIGHT</orientation>
        </orientations>
    </iphone>
    <android xmlns:android="http://schemas.android.com/apk/res/android"/>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules>
        <module platform="android">facebook</module>
        <module platform="iphone">facebook</module>
    </modules>
    <deployment-targets>
        <target device="android">true</target>
        <target device="blackberry">false</target>
        <target device="ipad">false</target>
        <target device="iphone">true</target>
        <target device="mobileweb">false</target>
        <target device="tizen">false</target>
    </deployment-targets>
    <sdk-version>3.2.2.GA</sdk-version>
</ti:app>


text:
<?php
    class WorkoutDAO {
    	const GET_USER_WORKOUT_DAYS_SQL = "SELECT DISTINCT workouts.record FROM workouts LEFT JOIN cardio_workouts ON workouts.record = cardio_workouts.record WHERE workouts.user = %s";
    	const GET_USER_WORKOUTS_BY_EXERCISE_SQL = "SELECT * FROM workouts WHERE exercise = '%s' AND reps < 120 AND user = %s ORDER BY record DESC, set_number LIMIT 10";
    	const GET_USER_WORKOUTS_BY_DAY_SQL = "SELECT e.name as exname, w.*,c.comments FROM exercises e, workouts w LEFT JOIN comments c USING (record,user) WHERE w.day_number= '%s' AND w.user = %s AND w.exercise=e.id AND w.record >= SUBDATE(now(),INTERVAL '20' day) ORDER BY record, exercise, set_number";
    	const GET_USER_ROUTINE_BY_DAY_SQL = "SELECT exercises, cardio_exercises, routine FROM routine WHERE day_number='%s' AND user = %s";
    	const GET_NUMBER_OF_WORKOUTS_BY_DAY_SQL = "select day_number from workouts where user = %s and day_number in (%s)";
    	const RESET_ROUTINE_SQL = "delete from routine where user = %s and day_number in (%s)";
    	const GET_PRESET_ROUTINE_LIST_SQL = "select distinct name, set_number, reference from preconfig_routine";

    	public function getUserWorkoutDays($userId) {
    		$workoutDays = array();
    		$query = sprintf(self::GET_USER_WORKOUT_DAYS_SQL, $userId);
    		$result = @mysql_query($query);

    		if ($result) {
    			while ($row = mysql_fetch_array($result)) {
    				array_push($workoutDays, $row["record"]);
    			}
    		} else {
    			throw new Exception("DB : " . mysql_error());
    		}

    		return $workoutDays;
    	}

    	public function getUserWorkoutsByExercise($userId, $exercise) {
    	    $workouts = array();
    	    $data = DBUtils::escapeData(array($exercise, $userId));
            $query = vsprintf(self::GET_USER_WORKOUTS_BY_EXERCISE_SQL, $data);
            $result = @mysql_query($query);

            if ($result) {
                // we have data, let's parse it out
                while ($row = mysql_fetch_array($result)) {
                    $workout = new Workout();
                    $workout->id = $row["id"];
                    $workout->record = $row["record"];
                    $workout->exercise = $row["exercise"];
                    $workout->setNumber = $row["set_number"];
                    $workout->reps = $row["reps"];
                    $workout->weight = $row["weight"];
                    $workout->dayNumber = $row["day_number"];

                    array_push($workouts, $workout);
                }
            } else {
                throw new Exception("DB : " . mysql_error());
            }

            return $workouts;
    	}

    	public function getUserWorkoutsByDay($userId, $day) {
    		// parameter order for the sql statement - $day, $userId
    		$workouts = array();
    		$data = DBUtils::escapeData(array($day, $userId));
    		$query = vsprintf(self::GET_USER_WORKOUTS_BY_DAY_SQL, $data);
    		$result = @mysql_query($query);

    		if ($result) {
    			// we have data, let's parse it out
    			while ($row = mysql_fetch_array($result)) {
    				$workout = new Workout();
    				$workout->id = $row["id"];
    				$workout->record = $row["record"];
    				$workout->exercise = $row["exercise"];
    				$workout->exerciseName = $row["exname"];
    				$workout->setNumber = $row["set_number"];
    				$workout->reps = $row["reps"];
    				$workout->weight = $row["weight"];
    				$workout->dayNumber = $row["day_number"];

    				array_push($workouts, $workout);
    			}
    		} else {
                throw new Exception("Error getting the workouts by day - DB : " . mysql_error());
            }

            return $workouts;
    	}

    	public function getDefaultWeight($exerciseId, $history, $setReps, $setCount) {
    		// find the workouts in history that correspond to the requested exercise id
    		$previousInfo = array();
    		foreach($history as $workout) {
    			if ($workout->exercise == $exerciseId && $workout->reps < 100) {
    				array_push($previousInfo, $workout);
    				// there should be multiple records, get them all...
    			}
    		}

    		$defaultWeight = 0;
    		$previousTotal = 0;
    		foreach ($previousInfo as $workout) {
    			// add the weight to the total
    			$previousTotal += $workout->reps * $workout->weight;
    			// set the default weight to the highest value
    			if ($workout->weight > $defaultWeight) {
    				$defaultWeight = $workout->weight;
    			}
    		}

    		// if there is a previous total and it is greater than or equal to the max
    		// reps * the default weight * the number of sets and the are more than
    		// the set count workouts, increase the weight by 10
    		if ($previousTotal > 0 && $previousTotal >= ($setReps * $defaultWeight * count($previousInfo)) && count($previousInfo) > $setCount) {
    			$defaultWeight += 10;
    		}

    		return $defaultWeight;
    	}

    	function getRoutine($userId, $day) {
    		$routine = null;
    		// get the exercises that are defined for the day for the given user
    		$data = DBUtils::escapeData(array($day, $userId));
    		$query = vsprintf(self::GET_USER_ROUTINE_BY_DAY_SQL, $data);
    		$result = @mysql_query($query);

    		$exercises = "no data";
    		$cardioExercises = "no data";
    		$routineSets = "no data";

    		if ($result) {
    			if (mysql_num_rows($result)) {
    				$exercises = mysql_result($result, 0, 0);
    				$cardioExercises = mysql_result($result, 0, 1);
    				$routineSets = mysql_result($result, 0, 2);
    			}
    		} else {
    			throw new Exception("Error getting the user routine - DB : " . mysql_error());
    		}

    		if ($exercises != "no data") {
    			$routine = new Routine();
    			$routine->sets = explode(",", $routineSets);

    			$exerciseDao = new ExerciseDAO();
    			// get the muscle exercises...
    			$routine->exercises = $exerciseDao->getListOfExercises($exercises);

    			// get the cardio exercises...
    			$routine->cardio = $exerciseDao->getCardioListOfExercises($cardioExercises);
    		}

    		return $routine;
    	}

    	/**
    	 * Gets the number of workouts that have been logged for any of the days in the dayList for the
    	 * given userId.
    	 *
    	 * @param int $userId
    	 * @param array $dayList
    	 * @throws Exception if there is an error running the SQL
    	 */
    	function getNumberOfLoggedWorkoutsByDay($userId, $dayList) {
    	    $numberOfWorkouts = 0;

    	    // first need to put the dayList into a format where it can be put in the SQL statement (can't
    	    // use implode because we need to escape the pieces)
    	    foreach ($dayList as $dayId) {
    	        $listOfDays .= "'". mysql_real_escape_string($dayId) . "',";
    	    }
    	    // remove the last comma
    	    $listOfDays = substr($listOfDays, 0, -1);

    	    $data = array(mysql_real_escape_string($userId), $listOfDays);
    	    $query = vsprintf(self::GET_NUMBER_OF_WORKOUTS_BY_DAY_SQL, $data);
    	    $result = @mysql_query($query);
    	    if ($result) {
    	        $numberOfWorkouts = mysql_num_rows($result);
    	    } else {
    	        throw new Exception("Exception attempting to get the number of workouts by day - DB : " . mysql_error());
    	    }

    	    return $numberOfWorkouts;
    	}

    	/**
    	 * Resets the routine for the given user by deleting any configured routines for the days provided
    	 * in the list.
    	 *
    	 * @param int $userId The User ID to use to reset the routine
    	 * @param array $dayList An array of day numbers
    	 * @throws Exception If there is an error running the SQL
    	 */
    	function resetRoutine($userId, $dayList) {
    	    // first need to put the dayList into a format where it can be put in the SQL statement (can't
    	    // use implode because we need to escape the pieces)
    	    foreach ($dayList as $dayId) {
    	        $listOfDays .= "'". mysql_real_escape_string($dayId) . "',";
    	    }
    	    // remove the last comma
    	    $listOfDays = substr($listOfDays, 0, -1);

    	    $data = array(mysql_real_escape_string($userId), $listOfDays);
    	    $query = vsprintf(self::RESET_ROUTINE_SQL, $data);
    	    $result = @mysql_query($query);
    	    if (!$result) {
    	        throw new Exception("Exception attempting to reset the routine - DB : " . mysql_error());
    	    }
    	}

    	/**
    	 * Gets the list of preset routines that are available. Returns a map of
    	 *     [preset id]["name"] => preset name
    	 *     [preset id]["reference"] => preset reference
    	 *
    	 * @return A map of id => name for the preset routines.
    	 * @throws Exception if there is an error running the SQL
    	 */
    	function getPresetRoutineList() {
    	    $result = @mysql_query(self::GET_PRESET_ROUTINE_LIST_SQL);
    	    $routines = array();
    	    if ($result) {
    	        while ($row = mysql_fetch_array($result)) {
    	            $routines[$row["set_number"]]["name"] = $row["name"];
    	            $routines[$row["set_number"]]["reference"] = $row["reference"];
    	        }
    	    } else {
    	        throw new Exception("Exception attempting to get the preset routines - DB : " . mysql_error());
    	    }
    	    return $routines;
    	}
    }
?>


text:
Relay is a JavaScript framework for building data-driven React applications.

* **Declarative:** Never again communicate with your data store using an imperative API. Simply declare your data requirements using GraphQL and let Relay figure out how and when to fetch your data.
* **Colocation:** Queries live next to the views that rely on them, so you can easily reason about your app. Relay aggregates queries into efficient network requests to fetch only what you need.
* **Mutations:** Relay lets you mutate data on the client and server using GraphQL mutations, and offers automatic data consistency, optimistic updates, and error handling.

[See how to use Relay in your own project](https://relay.dev/docs/en/introduction-to-relay).

## Example

The [relay-examples](https://github.com/relayjs/relay-examples) repository contains an implementation of [TodoMVC](http://todomvc.com/). To try it out:

```
git clone https://github.com/relayjs/relay-examples.git
cd relay-examples/todo
yarn
yarn build
yarn start
```

Then, just point your browser at `http://localhost:3000`.

## Contribute

We actively welcome pull requests, learn how to [contribute](./.github/CONTRIBUTING.md).

## Users

We have a [community-maintained list](https://relay.dev/en/users) of people and projects using Relay in production.

## License

Relay is [MIT licensed](./LICENSE).

## Thanks

We'd like to thank [the contributors](https://github.com/facebook/relay/graphs/contributors) that helped make Relay in open source possible.

The open source project [`relay-hooks`](https://github.com/relay-tools/relay-hooks) allowed the community to experiment with Relay and React Hooks, and was a source of valuable feedback for us. The idea for the `useSubscription` hook originated in [an issue](https://github.com/relay-tools/relay-hooks/issues/5#issuecomment-603930570) on that repo. Thank you @morrys for driving this project and for playing such an important role in our open source community.

Thank you for helping make this possible!


text:
package net.hydromatic.optiq.impl.jdbc;

import org.eigenbase.rel.RelNode;
import org.eigenbase.rel.TableAccessRelBase;
import org.eigenbase.relopt.*;

import java.util.Collections;
import java.util.List;

/**
 * Relational expression representing a scan of a table in a JDBC data source.
 */
public class JdbcTableScan extends TableAccessRelBase implements JdbcRel {
  final JdbcTable jdbcTable;

  protected JdbcTableScan(
      RelOptCluster cluster,
      RelOptTable table,
      JdbcTable jdbcTable,
      JdbcConvention jdbcConvention) {
    super(cluster, cluster.traitSetOf(jdbcConvention), table);
    this.jdbcTable = jdbcTable;
    assert jdbcTable != null;
  }

  @Override
  public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
    assert inputs.isEmpty();
    return new JdbcTableScan(
        getCluster(), table, jdbcTable, (JdbcConvention) getConvention());
  }

  public JdbcImplementor.Result implement(JdbcImplementor implementor) {
    return implementor.result(jdbcTable.tableName(),
        Collections.singletonList(JdbcImplementor.Clause.FROM), this);
  }
}

// End JdbcTableScan.java


text:
import sys
import random
from test_base import *

class TestInvalidLock2(TestBase):

  def generate(self):
    # scrub tag and data
    self.clear_tag()

    for iteration in range(100):
      lock_count = 0
      for w in range(self.ways_p):
        if lock_count < 6:
          lock_this = random.randint(0,1)
          if lock_this:
            self.send_tagst(w, 0, valid=0, lock=1)
            lock_count += 1

      for n in range(1000):
        block_offset = random.randint(0,7)
        index = 0
        tag = random.randint(0,15)
        taddr = self.get_addr(tag,index,block_offset)

        store_not_load = random.randint(0,1)
        if store_not_load:
          self.send_sw(taddr)
        else:
          self.send_lw(taddr)

      for w in range(self.ways_p):
        self.flush_inv(w,0)

    self.tg.done()

#   main()
if __name__ == "__main__":
  t = TestInvalidLock2()
  t.generate()


text:
import logging
import xml.sax.xmlreader

from idl.matter_idl_types import Idl, ParseMetaData, Attribute
from typing import Optional, List

class IdlPostProcessor:
    """Defines a callback that will apply after an entire parsing
       is complete.
    """

    def FinalizeProcessing(self, idl: Idl):
        """Update idl with any post-processing directives."""
        pass

class ProcessingPath:
    """Maintains the current path of tags within xml processing.

    As processing descents into an xml like `<configurator><cluster>....`
    paths will have contents like ['configurator', 'cluster', ...].

    The main purpose for this is to log and keep track of what was visited
    and in general to report things like 'this path found but was not handled'.
    """

    def __init__(self, paths: List[str] = None):
        if paths is None:
            paths = []
        self.paths = paths

    def push(self, name: str):
        self.paths.append(name)

    def pop(self):
        self.paths.pop()

    def __str__(self):
        return '::'.join(self.paths)

    def __repr__(self):
        return 'ProcessingPath(%r)' % self.paths

class Context:
    """
    Contains a processing state during XML reading.

    The purpose of this is to allow elements to interact with each other, share
    data and defer processing.

    Usage:
      - globally shared data:
         > locator: parsing location, for error reporting
         > path: current ProcessingPath for any logging of where we are located
      - shared data:
         > global attributes are parsed by one handler, but used by others
      - post-processing support:
         > can register AddIdlPostProcessor to perform some processing once
           a full parsing pass has been done

    More data may be added in time if it involves separate XML parse handlers
    needing to interact with each other.
    """

    def __init__(self, locator: Optional[xml.sax.xmlreader.Locator] = None):
        self.path = ProcessingPath()
        self.locator = locator
        self._not_handled = set()
        self._idl_post_processors = []

        # Map of code -> attribute
        self._global_attributes = {}

    def GetCurrentLocationMeta(self) -> ParseMetaData:
        if not self.locator:
            return None

        return ParseMetaData(line=self.locator.getLineNumber(), column=self.locator.getColumnNumber())

    def GetGlobalAttribute(self, code):
        if code in self._global_attributes:
            return self._global_attributes[code]

        raise Exception(
            'Global attribute 0x%X (%d) not found. You probably need to load global-attributes.xml' % (code, code))

    def AddGlobalAttribute(self, attribute: Attribute):
        # NOTE: this may get added several times as both 'client' and 'server'
        #       however matter should not differentiate between the two
        code = attribute.definition.code
        logging.info('Adding global attribute 0x%X (%d): %s' % (code, code, attribute.definition.name))

        self._global_attributes[code] = attribute

    def MarkTagNotHandled(self):
        path = str(self.path)
        if path not in self._not_handled:
            logging.warning("TAG %s was not handled/recognized" % path)
            self._not_handled.add(path)

    def AddIdlPostProcessor(self, processor: IdlPostProcessor):
        self._idl_post_processors.append(processor)

    def PostProcess(self, idl: Idl):
        for p in self._idl_post_processors:
            p.FinalizeProcessing(idl)

        self._idl_post_processors = []


text:
package com.iniesta.ftests.stream.taxi;

import java.util.Properties;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.TimestampExtractor;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer082;

import com.iniesta.ftests.stream.taxi.AverageTaxiRide.AverageCalculator;

public class TaxiKafkaAverage {

	protected final static int maxEventDelay = 60;

	@SuppressWarnings("serial")
	public static void main(String[] args) throws Exception {
		ParameterTool parameter = ParameterTool.fromArgs(args);

		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

		Properties props = new Properties();
		props.setProperty("zookeeper.connect", parameter.get("zookeeper.connect", "localhost:2181"));
		props.setProperty("bootstrap.servers", parameter.get("bootstrap.servers", "localhost:9092"));
		props.setProperty("group.id", parameter.get("group.id", "group1"));

		DataStream<TaxiRide> rides = env.addSource(new FlinkKafkaConsumer082<>("cleansedRides", new TaxiRideSchema(), props))
				.assignTimestamps(new TimestampExtractor<TaxiRide>() {

					long current;

					@Override
					public long getCurrentWatermark() {
						return current;
					}

					@Override
					public long extractWatermark(TaxiRide ride, long currentTimestamp) {
						current =  current - (maxEventDelay*1000);
						return -1;
					}

					@Override
					public long extractTimestamp(TaxiRide ride, long currentTimestamp) {
						return ride.time.getMillis();
					}
				});

		DataStream<Tuple2<Long, Float>> rideSpeeds = rides.keyBy("rideId").flatMap(new AverageCalculator());

		rideSpeeds.print();

		env.execute("Average Taxi Ride");
	}
}


text:
> at Big Ruby 2013, by Joshua Timberman

#### Changing a single line in a file

* managing whole file resources (template, cookbook\_file, remote\_file)

* to edit single line, 'ruby\_block' resource (not preferred generally if do-able via noun-ish resources)

```
ruby_block "edit /etc/hosts" do
  block do
    rc = Chef::Util::FileEdit.new("/etc/hosts")
    rc.search_file_replace_line(
      /^127\.0\.0\.1 localhost$/,
      "127.0.0.1 #{new_fqdn} #{new_hostname} locahost"
    )
    rc.write_file
  end
end
```

* 'Chef::Util::FileEdit' got multiple more helpful methods, some are
> search\_file\_replace\_line(regex, newline)  : if matched, replace whole line with newline
> search\_file\_replace(regex, replace)       : if matched, replace all occurences
> search\_file\_delete\_line(regex)            : if matched, remove line
> search\_file\_delete(regex)                 : if matched, delete all occurences
> insert\_line\_after\_match(regex, newline)   : if matched, insert newline after matching line
> insert\_line\_if\_no\_match(regex, newline)   : if not matched, insert newline at end of file
> write\_file                                : write the new file content, flush

* cookbook "line", resource provider for managing single lines; 'http://ckbk.it/line'

---

#### Chef's built-in version matching

> Platforms, Cookbooks, Software/packages

Match versions that are dotted numeric notations upto 3 places.
Provides first-class version matching, allows X.Y.Z version string.
* [Documentation on Cookbook Version](http://docs.opscode.com/essentials_cookbook_versions_constraints.html)

* How to use it
> require 'chef/version\_contraint' library
> initialize a Chef::VersionContraint object with the constraint
> send 'include?' method with version to match

* Constraint Operator
```
=   : equal
>   : greater than
<   : less than
>=  : greater than or equal
<=  : less than or equal
~>  : approximately greater than (pessimistic)
```

* Some code

```
require 'chef/version_constraint'

required_version = Chef::VersionContraint.new(">= 10.7.0")
required_version.include?("10.6.0") ## false
required_version.include?("10.7.3") ## true
required_version.include?(node['platform_version'])
```

---

#### REPL for Chef

* 'shef' till Chef.10; 'chef-shell' from Chef.11

* built on IRB; 3 modes/contexts
> main: access node attributes, interact with chef-server, do IRB stuff
> attributes: context of Cookbooks' attributes file, follow same order
> recipe: context of recipe where all resources, DSL methods are available

```
## lot of commands, many available work with chef-server API
$ chef-shell
chef> help
...

## loading config from a client for a specific chef-server
$ chef-shell -z
chef> Chef::Config[:chef_server_url]
...
chef> node.run_list
...

chef> attributes_mode
chef:attributes> default['shef'] = 'Fun'
chef:attributes> node.default['shef'] = 'Woo'  ## in older version can't just say node['']

chef> recipe_mode
chef> package "vim"
... ## return resource object
chef> package "git"
...
chef> resources
... ## returns list of resources
chef> run_chef
... ## applies resource
chef> search(:node, "role:workstation")
... can search like from server in recipe
chef> data_bag_item(:users, "jtimberman")
... access data-bag-items similarly

$ pry
(main):0 > require 'chef'
(main):0 > require 'chef/shell/ext'
(main):0 > Shell::Extensions.extend_context_object(self)
(main):0 > Chef::Config.from_file("/etc/chef/client.rb")
(main):0 > node.all
... listing all nodes

## can use this similarly from knife-plugins, libraries, applications

```

---

#### The Resource Collection

* Chef loads recipes looking for resources and adds them to ResourceCollection, then walks through it taking actions.

example recipe

```
package 'apache2'

template '/etc/apache2/apache2.conf' do
  mode 0644
  owner 'www-data'
  group 'www-data'
  notifies :restart, 'service[apache2]'
end

service 'apache2' do
  supports :reload => true, :status => true
  action [:enable, :start]
end
```

paste recipe in chef-shell then use the resources()

```
chef:recipe> resources
["package[apache2]", "template[/etc/apache2/apache2.conf]", "service[apache2]"]
```

* run\_context.resource\_collection
> * the run\_context loads and tracks context of Chef run
> * resource collection is part of run context
> * resource collection can be accessed directly with 'run\_context.resource\_collection'

```
chef:recipe> run_context.resource_collection
## here 'resource_by_name' is hash of all resources
## they have numeric index, the order in which action gets applied

chef:recipe> run_context.resource_collection.each do |r|
               puts "#{r} is a #{r.resource_name}"
             end
...

```
---

#### Anatomy of loading and execuing a recipe

* Chef.11 onwards have 'chef-apply', started from [gist](https://gist.github.com/danielsdeleo/2920702).

```
require 'chef/client'
require 'chef/providers'
require 'chef/resources'

Chef::Config[:solo] = true
client = Chef::Client.new

client.node = Chef::Node.build("apply-node")
client.run_ohai
client.build_node

run_context = Chef::RunContext.new(
      client.node, {}, client.events
    )

recipe = Chef::Recipe.new(
      "(chef-apply cookbook)",
      "(chef-apply recipe)",
      run_context
    )
recipe.from_file(recipe_path)

runner = Chef::Runner.new(run_context)
runner.converge
```

* **NEVER DO THIS**, but 'chef-apply' takes STDIN

start chef-apply over a listener

```
while true
do
nc -l 8787 | sudo chef-apply -s
done
```

then from anywhere via telnet, run insecure $#!t

```
telnet $IP_OF_NC8787 8787
package "git"
^]
^D
```

---

#### FAQ:Testing

* Chef-10.14 onwards 'why-run' mode is dry-run
* Test-Kitchen
* ChefSpec

---
---