text:
module ModuleSpecs
  class NameEncoding
    class Cß
    end
    def name
      Cß.name
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpUnit">
    <phpunit_settings>
      <PhpUnitSettings load_method="PHPUNIT_PHAR" custom_loader_path="" phpunit_phar_path="$USER_HOME$/bin/phpunit.phar" />
    </phpunit_settings>
  </component>
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>CSS</id>
          </State>
          <State>
            <id>Code style issuesJavaScript</id>
          </State>
          <State>
            <id>Control flow issuesJavaScript</id>
          </State>
          <State>
            <id>Error handlingJavaScript</id>
          </State>
          <State>
            <id>General</id>
          </State>
          <State>
            <id>HAML</id>
          </State>
          <State>
            <id>JavaScript</id>
          </State>
          <State>
            <id>JavaScript validity issuesJavaScript</id>
          </State>
          <State>
            <id>PHP</id>
          </State>
          <State>
            <id>Potentially confusing code constructsJavaScript</id>
          </State>
          <State>
            <id>Probable bugsCSS</id>
          </State>
          <State>
            <id>Probable bugsJavaScript</id>
          </State>
          <State>
            <id>Probable bugsPHP</id>
          </State>
          <State>
            <id>UndefinedPHP</id>
          </State>
          <State>
            <id>XPath</id>
          </State>
        </expanded-state>
        <selected-state>
          <State>
            <id>InconsistentLineSeparators</id>
          </State>
        </selected-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="SvnConfiguration">
    <configuration>$USER_HOME$/.subversion</configuration>
  </component>
  <component name="masterDetails">
    <states>
      <state key="Copyright.UI">
        <settings>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
    </states>
  </component>
</project>


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

namespace Metaco.Trader.ViewModel
{
    public enum StatusState
    {
        Loading,
        Error,
        Success
    }
    public class StatusMainViewModel : PWViewModelBase
    {
        public StatusMainViewModel()
        {
            MessengerInstance.Register<StatusMessage>(this, OnStatusCommand);
        }

        void OnStatusCommand(StatusMessage message)
        {
            State = message.Status;
            if (message.Message != null)
                Message = message.Message;
        }

        private StatusState? _State;
        public StatusState? State
        {
            get
            {
                return _State;
            }
            set
            {
                if (value != _State)
                {
                    _State = value;
                    OnPropertyChanged(() => this.State);
                }
            }
        }

        private string _Message;
        public string Message
        {
            get
            {
                return _Message;
            }
            set
            {
                if (value != _Message)
                {
                    _Message = value;
                    OnPropertyChanged(() => this.Message);
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace FclEx
{
    public static class QueryableExtensions
    {
        public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate, bool condition)
        {
            return condition ? source.Where(predicate) : source;
        }

        public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, Expression<Func<T, int, bool>> predicate, bool condition)
        {
            return condition ? source.Where(predicate) : source;
        }
    }
}


text:
package com.studio.bookings.service;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.users.User;
import com.studio.bookings.entity.AccessControlList;
import com.studio.bookings.entity.Account;
import com.studio.bookings.enums.Permission;
import com.studio.bookings.enums.UserType;
import com.studio.bookings.util.Constants;

@Api(
	    name = "booking",
	    version = "v1",
	    scopes = {Constants.EMAIL_SCOPE},
	    clientIds = {Constants.WEB_CLIENT_ID},
	    audiences = {Constants.ANDROID_AUDIENCE}
	)

public class AccessControlListService extends BaseService {

	Permission aclPermission = Permission.ACL;

	@ApiMethod(name = "calendar.addAcl", path="calendar.addAcl", httpMethod = "post")
    public AccessControlList insertAccessControlList(
    		@Named("permission") String permission,
    		@Named("canView") String canView,
    		@Named("canViewAll") String canViewAll,
    		@Named("canInsert") String canInsert,
    		@Named("canUpdate") String canUpdate,
    		@Named("canDelete") String canDelete,
    		@Named("userType") String userType,
    		@Named("account") Long accountId,
			User user) {
		AccessControlList acl = null;
    	if(user != null) {
    		// TODO THROW UNAUTHORIZED EXCEPTION
    		if (this.allowInsert(accountId, aclPermission.toString(), user).get(0)) {
				acl = new AccessControlList(
						permission, canView, canViewAll, canInsert, canUpdate,
						canDelete, userType);
				aclDao.save(acl);
    		}
    	}
    	return acl;
	}

    @ApiMethod(name = "calendar.findAcl", path="calendar.findAcl", httpMethod = "get")
	public AccessControlList findAccessControlList(
			@Named("acl") Long aclId,
			@Named("account") Long accountId,
			User user) {

    	AccessControlList acl = null;
    	if(user != null) {
    		// TODO THROW UNAUTHORIZED EXCEPTION
    		if (this.allowView(accountId, aclPermission.toString(), user).get(0)) {
    			acl = aclDao.retrieve(aclId);
    		}
    	}
    	return acl;
	}

    @ApiMethod(name = "calendar.updateAcl", path="calendar.updateAcl", httpMethod = "post")
	public AccessControlList updateAccessControlList(
			@Named("acl") Long aclId,
			@Named("permission") String permission,
    		@Named("canView") String canView,
    		@Named("canViewAll") String canViewAll,
    		@Named("canInsert") String canInsert,
    		@Named("canUpdate") String canUpdate,
    		@Named("canDelete") String canDelete,
    		@Named("userType") String userType,
    		@Named("account") Long accountId,
    		User user) {

		AccessControlList aclFetched = aclDao.retrieve(aclId);
    	if(user != null) {
    		// TODO THROW UNAUTHORIZED EXCEPTION
    		if (this.allowUpdate(accountId, aclPermission.toString(), user).get(0)) {
				aclFetched.setPermission(Permission.valueOf(permission));
				aclFetched.setCanView(Boolean.valueOf(canView));
				aclFetched.setCanViewAll(Boolean.valueOf(canViewAll));
				aclFetched.setCanInsert(Boolean.valueOf(canInsert));
				aclFetched.setCanUpdate(Boolean.valueOf(canUpdate));
				aclFetched.setCanDelete(Boolean.valueOf(canDelete));
				aclFetched.setUserType(UserType.valueOf(userType));
				aclFetched.setCanDelete(Boolean.valueOf(canDelete));
				aclDao.save(aclFetched);
    		}
    	}
		return aclFetched;
	}

	@ApiMethod(name = "calendar.deleteAcl", path="calendar.deleteAcl", httpMethod = "post")
	public void deleteAccessControlList (
			@Named("aclList") Long aclId,
			@Named("account") Long accountId,
			User user) {

    	if(user != null) {
    		if (this.allowDelete(accountId, aclPermission.toString(), user).get(0)) {
    			aclDao.delete(aclId);
    		}
    	}
	}

	@ApiMethod(name = "calendar.listAcl", path="calendar.listAcl", httpMethod = "post")
    public List<AccessControlList> listAccessControlList(@Named("account") Long accountId, User user) {
		List<AccessControlList> aclList = null;
		if(user != null) {
    		// TODO THROW UNAUTHORIZED EXCEPTION
    		if (this.allowView(accountId, aclPermission.toString(), user).get(0)) {
    			aclList = aclDao.list();
    		}
		}
		return aclList;
    }

	private AccessControlList getByUserTypeAndPermission(UserType userType, Permission permission) {
		return aclDao.twoFilterQuery("userType", userType.toString(), "permission", permission.toString());
    }

	private UserType getUserType(Account account, User user) throws Exception {
    	UserType userType = personDao.oneFilterAncestorQuery("userId", user.getUserId(), account).getUserType();
    	if (userType == null) {
    		throw new NotFoundException("User doesn't have a user type for this account");
    	}
    	return userType;
	}

	@ApiMethod(name = "calendar.isCanView", path="calendar.isCanView", httpMethod = "get")
    public List<Boolean> allowView(
    		@Named("account") Long accountId,
    		@Named("permission") String permission,
    		User user) {
    	Account accountFetched = accountDao.retrieve(accountId);
    	UserType ut = null;
		try {
			ut = this.getUserType(accountFetched, user);
    	} catch (Exception e) {
    		ut = UserType.ATTENDEE;
    	}
    	List<Boolean> result = new ArrayList<Boolean>();
    	result.add(getByUserTypeAndPermission(ut, Permission.valueOf(permission)).getCanView());
        return result;
    }

	@ApiMethod(name = "calendar.isCanViewAll", path="calendar.isCanViewAll", httpMethod = "get")
    public List<Boolean> allowViewAll(
    		@Named("account") Long accountId,
    		@Named("permission") String permission,
    		User user) {
		Account accountFetched = accountDao.retrieve(accountId);
		UserType ut = null;
		try {
			ut = this.getUserType(accountFetched, user);
    	} catch (Exception e) {
    		ut = UserType.ATTENDEE;
    	}
    	List<Boolean> result = new ArrayList<Boolean>();
        result.add(this.getByUserTypeAndPermission(ut, Permission.valueOf(permission)).getCanViewAll());
        return result;
    }

	@ApiMethod(name = "calendar.isCanInsert", path="calendar.isCanInsert", httpMethod = "get")
    public List<Boolean> allowInsert(
    		@Named("account") Long accountId,
    		@Named("permission") String permission,
    		User user) {
		Account accountFetched = accountDao.retrieve(accountId);
		UserType ut = null;
		try {
			ut = this.getUserType(accountFetched, user);
    	} catch (Exception e) {
    		ut = UserType.ATTENDEE;
    	}
    	List<Boolean> result = new ArrayList<Boolean>();
    	result.add(this.getByUserTypeAndPermission(ut, Permission.valueOf(permission)).getCanInsert());
        return result;
    }

	@ApiMethod(name = "calendar.isCanUpdate", path="calendar.isCanUpdate", httpMethod = "get")
    public List<Boolean> allowUpdate(
    		@Named("account") Long accountId,
    		@Named("permission") String permission,
    		User user)  {
    	Account accountFetched = accountDao.retrieve(accountId);
		UserType ut = null;
		try {
			ut = this.getUserType(accountFetched, user);
    	} catch (Exception e) {
    		ut = UserType.ATTENDEE;
    	}
    	List<Boolean> result = new ArrayList<Boolean>();
    	result.add(this.getByUserTypeAndPermission(ut, Permission.valueOf(permission)).getCanUpdate());
    	return result;
    }

	@ApiMethod(name = "calendar.isCanDelete", path="calendar.isCanDelete", httpMethod = "get")
    public List<Boolean> allowDelete(
    		@Named("account") Long accountId,
    		@Named("permission") String permission,
    		User user)  {
		Account accountFetched = accountDao.retrieve(accountId);
		UserType ut = null;
		try {
			ut = this.getUserType(accountFetched, user);
    	} catch (Exception e) {
    		ut = UserType.ATTENDEE;
    	}
    	List<Boolean> result = new ArrayList<Boolean>();
    	result.add(this.getByUserTypeAndPermission(ut, Permission.valueOf(permission)).getCanDelete());
    	return result;
    }

}


text:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from chunk import chunkData
from padding import padData
from xor import xorData

class CBCMode(object):
    '''
    This class is used to implment CBC mode using python cryptography. The
    chunkData, padData, and xorData are custom classes that are used to build
    functionality that python cryptography would normally handle in the
    backend. Educational purposes only.
    '''
    def __init__(self, key, iv):
        '''
        This constructor initilizes the key and initialization vector. The key
        and the IV should be the same length, either 16, 24, or 32 bytes long.
        '''
        self.key = key
        self.iv = iv

    # Input validation for the key
    @property
    def key(self):
        return self._key

    @key.setter
    def key(self, key):
        if (len(key) not in [16, 24, 32]):
            raise Exception('The key must be 16, 24, or 32 bytes long.')
        self._key = key

    # Input validation for the IV
    @property
    def iv(self):
        return self._iv

    @iv.setter
    def iv(self, iv):
        if (len(iv) not in [16, 24, 32]):
            raise Exception('The iv must be 16, 24, or 32 bytes long.')
        self._iv = iv

    def pad(self, data):
        '''
        This constructor takes in the string that needs to be padded.
        Calls the custom pad class in the block/padding.py and returns the
        padded string.
        '''
        padding = padData(data)
        paddedData = padding.padString()
        return paddedData

    def unPad(self, data):
        '''
        This constructor takes in the padded string that needs to be unpadded
        by the reciever of the message.
        '''
        try:
            unPadding = padData(data)
            unPaddedData = unPadding.unPadString()
            return unPaddedData
        except ValueError:
            return data

    def preProcess(self, data):
        '''
        The preProcess constructor takes the plaintext. Then pads and chunks if
        needed. Returns a list.
        '''
        if (len(data) == 0):
            raise ValueError('Plaintext string can not be empty')
        elif (len(data) < 16):
            paddedList = [self.pad(data)]
            return paddedList
        elif (len(data) == 16):
            dataList = [data]
            return dataList
        elif(len(data) % 16 == 0):
            divList = chunkData(data)
            return divList.getChunk()
        else:
            chunk = chunkData(data)
            chunkedData = chunk.getChunk()
            shortBlock = self.pad(chunkedData.pop(-1))
            chunkedData.append(shortBlock)
            return chunkedData

    def postProcess(self, data):
        '''
        The postProcess constructor is used to validate and chunk the
        ciphertext. Returns a list.
        '''
        if (len(data) == 0 or len(data) < 16):
            raise ValueError('Invalid ciphertext byte length.')
        else:
            chunk = chunkData(data)
            return chunk.getChunk()

    def encrypt(self, plaintext):
        '''
        This encrypt constructor takes the plaintext string, sends it to the
        preProcess class to be padded and chunked. The blocks are then
        encrypted using python cryptography library ECB mode. The chaining
        of ciphertexts is done manually.
        '''
        # Send the plaintext string to be padded and chunked
        plaintext = self.preProcess(plaintext)

        # Initilize the python cryptography ECB mode
        backend = default_backend()
        cipher = Cipher(algorithms.AES(self.key), modes.ECB(),
                backend = backend)
        encryptor = cipher.encryptor()

        # Loop through the elements, special treatment for block 1
        # https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
        ciphertextList = []
        for i in range(0, len(plaintext)):
            if (i == 0):
                xor = xorData(self.iv, plaintext[i])
                initialXor = xor.getXor()
                firstElement = encryptor.update(initialXor)
                ciphertextList.append(firstElement)
            elif (i >= 1):
                xor = xorData(ciphertextList[i-1], plaintext[i])
                nElementXor = xor.getXor()
                nEncryption = encryptor.update(nElementXor)
                ciphertextList.append(nEncryption)
        return ''.join(ciphertextList)

    def decrypt(self, ciphertext):
        '''
        This decrypt constructor takes the ciphertext string, sends it to the
        postProcess class to be chunked. The blocks are sent to the python
        cryptography ECB mode for decryption. The first block is then xored
        with the IV. The remaining blocks are xored with the previous
        ciphertext in the list. The last element in the plaintextList is
        then unpadded.
        '''
        # Send the ciphertext string to be chunked
        ciphertext = self.postProcess(ciphertext)

        # Initilize the python cryptography ECB mode
        backend = default_backend()
        cipher = Cipher(algorithms.AES(self.key), modes.ECB(),
                backend = backend)
        decryptor = cipher.decryptor()

        # Loop through the ciphertext list, special treatment for block 1
        plaintextList = []
        for i in range(0, len(ciphertext)):
            if (i == 0):
                firstElement = decryptor.update(ciphertext[i])
                xor = xorData(self.iv, firstElement)
                firstPlaintext = xor.getXor()
                plaintextList.append(firstPlaintext)
            elif (i >= 1):
                nElement = decryptor.update(ciphertext[i])
                xor = xorData(ciphertext[i-1], nElement)
                nPlaintext = xor.getXor()
                plaintextList.append(nPlaintext)
        paddedElement = self.unPad(plaintextList.pop(-1))
        plaintextList.append(paddedElement)
        return ''.join(plaintextList)


text:
//Switch to the appropriate trace level
#define TRACE_LEVEL ETH_TRACE_LEVEL

//Dependencies
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "core/net.h"
#include "core/nic.h"
#include "core/ethernet.h"
#include "core/socket.h"
#include "core/raw_socket.h"
#include "core/tcp_timer.h"
#include "ipv4/arp.h"
#include "ipv4/ipv4.h"
#include "ipv6/ipv6.h"
#include "snmp/mib2_module.h"
#include "snmp/mib2_impl.h"
#include "debug.h"

//Check TCP/IP stack configuration
#if (ETH_SUPPORT == ENABLED)

//Unspecified MAC address
const MacAddr MAC_UNSPECIFIED_ADDR = {{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}};
//Broadcast MAC address
const MacAddr MAC_BROADCAST_ADDR = {{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}};

//Padding bytes
const uint8_t ethPadding[64] =
{
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

//A lookup table can be used to speed up CRC calculation
#if (ETH_FAST_CRC_SUPPORT == ENABLED)

static const uint32_t crc32Table[256] =
{
   0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
   0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
   0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
   0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
   0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
   0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
   0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
   0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
   0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
   0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
   0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
   0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
   0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
   0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
   0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
   0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
   0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
   0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
   0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
   0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
   0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
   0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
   0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
   0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
   0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
   0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
   0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
   0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
   0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
   0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
   0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
   0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
   0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
   0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
   0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
   0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
   0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
   0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
   0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
   0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
   0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
   0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
   0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
   0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
   0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
   0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
   0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
   0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
   0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
   0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
   0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
   0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
   0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
   0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
   0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
   0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
   0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
   0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
   0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
   0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
   0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
   0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
   0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
   0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};

#endif

/**
 * @brief Ethernet related initialization
 * @param[in] interface Underlying network interface
 * @return Error code
 **/

error_t ethInit(NetInterface *interface)
{
   //Create a mutex to prevent simultaneous access to the MAC filter table
   if(!osCreateMutex(&interface->macFilterMutex))
   {
      //Failed to create mutex
      return ERROR_OUT_OF_RESOURCES;
   }

   //Clear the MAC filter table contents
   memset(interface->macFilter, 0, sizeof(interface->macFilter));
   //No entry in the filter table
   interface->macFilterSize = 0;

   //Successful initialization
   return NO_ERROR;
}

/**
 * @brief Process an incoming Ethernet frame
 * @param[in] interface Underlying network interface
 * @param[in] ethFrame Incoming Ethernet frame to process
 * @param[in] length Total frame length
 **/

void ethProcessFrame(NetInterface *interface, EthHeader *ethFrame, size_t length)
{
#if (IPV6_SUPPORT == ENABLED)
   NetBuffer1 buffer;
#endif
   uint32_t crc;

   //Ensure the length of the incoming frame is valid
   if(length < ETH_MIN_FRAME_SIZE)
      return;

#if (MIB2_SUPPORT == ENABLED)
   //Total number of octets received on the interface
   MIB2_LOCK();
   MIB2_INC_COUNTER32(interface->mibIfEntry->ifInOctets, length);
   MIB2_UNLOCK();
#endif

   //Debug message
   TRACE_DEBUG("Ethernet frame received (%" PRIuSIZE " bytes)...\r\n", length);
   //Dump Ethernet header contents for debugging purpose
   ethDumpHeader(ethFrame);

   //CRC verification not supported by hardware?
   if(!interface->nicDriver->autoCrcCheck)
   {
      //The value of the residue is 0x2144DF1C when no CRC errors are detected
      if(ethCalcCrc(ethFrame, length) != 0x2144DF1C)
      {
         //Debug message
         TRACE_WARNING("Wrong CRC detected!\r\n");

#if (MIB2_SUPPORT == ENABLED)
         //Number of inbound packets that contained errors
         MIB2_LOCK();
         MIB2_INC_COUNTER32(interface->mibIfEntry->ifInErrors, 1);
         MIB2_UNLOCK();
#endif
         //Discard the received frame
         return;
      }
   }

   //Retrieve frame CRC
   memcpy(&crc, (uint8_t *) ethFrame + length - ETH_CRC_SIZE, ETH_CRC_SIZE);
   //Reseed the pseudo-random number generator
   netInitRand(crc);

   //Frame filtering based on destination MAC address
   if(ethCheckDestAddr(interface, &ethFrame->destAddr))
   {
#if (MIB2_SUPPORT == ENABLED)
      //Number of inbound packets which were chosen to be discarded
      //even though no errors had been detected
      MIB2_LOCK();
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifInDiscards, 1);
      MIB2_UNLOCK();
#endif
      //Discard the received frame
      return;
   }

#if (MIB2_SUPPORT == ENABLED)
   //Enter critical section
   MIB2_LOCK();

   //Check whether the destination address is a group address
   if(macIsMulticastAddr(&ethFrame->destAddr))
   {
      //Number of non-unicast packets delivered to a higher-layer protocol
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifInNUcastPkts, 1);
   }
   else
   {
      //Number of unicast packets delivered to a higher-layer protocol
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifInUcastPkts, 1);
   }

   //Leave critical section
   MIB2_UNLOCK();
#endif

#if (RAW_SOCKET_SUPPORT == ENABLED)
   //Allow raw sockets to process Ethernet packets
   rawSocketProcessEthPacket(interface, ethFrame, length - ETH_CRC_SIZE);
#endif

   //Calculate the length of the data payload
   length -= sizeof(EthHeader) + ETH_CRC_SIZE;

   //Check Ethernet type field
   switch(ntohs(ethFrame->type))
   {
#if (IPV4_SUPPORT == ENABLED)
   //ARP packet received?
   case ETH_TYPE_ARP:
      //Process incoming ARP packet
      arpProcessPacket(interface, (ArpPacket *) ethFrame->data, length);
      break;
   //IPv4 packet received?
   case ETH_TYPE_IPV4:
      //Process incoming IPv4 packet
      ipv4ProcessPacket(interface, (Ipv4Header *) ethFrame->data, length);
      break;
#endif
#if (IPV6_SUPPORT == ENABLED)
   //IPv6 packet received?
   case ETH_TYPE_IPV6:
      //The incoming Ethernet frame fits in a single chunk
      buffer.chunkCount = 1;
      buffer.maxChunkCount = 1;
      buffer.chunk[0].address = ethFrame->data;
      buffer.chunk[0].length = length;
      buffer.chunk[0].size = 0;
      //Process incoming IPv6 packet
      ipv6ProcessPacket(interface, (NetBuffer *) &buffer);
      break;
#endif
   //Unknown packet received?
   default:
      //Debug message
      TRACE_WARNING("Unknown Ethernet type!\r\n");

#if (MIB2_SUPPORT == ENABLED)
      //Number of packets received via the interface which were
      //discarded because of an unknown or unsupported protocol
      MIB2_LOCK();
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifInUnknownProtos , 1);
      MIB2_UNLOCK();
#endif
      break;
   }
}

/**
 * @brief Send an Ethernet frame
 * @param[in] interface Underlying network interface
 * @param[in] destAddr MAC address of the destination host
 * @param[in] buffer Multi-part buffer containing the payload
 * @param[in] offset Offset to the first payload byte
 * @param[in] type Ethernet type
 * @return Error code
 **/

error_t ethSendFrame(NetInterface *interface, const MacAddr *destAddr,
   NetBuffer *buffer, size_t offset, uint16_t type)
{
   error_t error;
   size_t length;
   uint32_t crc;
   EthHeader *header;

   //Is there enough space for the Ethernet header?
   if(offset < sizeof(EthHeader))
      return ERROR_INVALID_PARAMETER;

   //Make room for the Ethernet header
   offset -= sizeof(EthHeader);
   //Retrieve the length of the frame
   length = netBufferGetLength(buffer) - offset;

   //Position to the beginning of the frame
   header = netBufferAt(buffer, offset);

   //Format Ethernet header
   header->destAddr = *destAddr;
   header->srcAddr = interface->macAddr;
   header->type = htons(type);

   //Automatic padding not supported by hardware?
   if(!interface->nicDriver->autoPadding)
   {
      //The host controller should manually add padding
      //to the packet before transmitting it
      if(length < (ETH_MIN_FRAME_SIZE - ETH_CRC_SIZE))
      {
         //Add padding as necessary
         size_t n = (ETH_MIN_FRAME_SIZE - ETH_CRC_SIZE) - length;

         //Append padding bytes
         error = netBufferAppend(buffer, ethPadding, n);
         //Any error to report?
         if(error) return error;

         //Adjust frame length
         length += n;
      }
   }
   //CRC generation not supported by hardware?
   if(!interface->nicDriver->autoCrcGen)
   {
      //Compute CRC over the header and payload
      crc = ethCalcCrcEx(buffer, 0, length);
      //Convert from host byte order to little-endian byte order
      crc = htole32(crc);

      //Append the calculated CRC value
      error = netBufferAppend(buffer, &crc, sizeof(crc));
      //Any error to report?
      if(error) return error;

      //Adjust frame length
      length += sizeof(crc);
   }

#if (MIB2_SUPPORT == ENABLED)
   //Enter critical section
   MIB2_LOCK();

   //Total number of octets transmitted out of the interface
   MIB2_INC_COUNTER32(interface->mibIfEntry->ifOutOctets, length);

   //Check whether the destination address is a group address
   if(macIsMulticastAddr(&header->destAddr))
   {
      //The total number of non-unicast packets that higher-level
      //protocols requested be transmitted
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifOutNUcastPkts, 1);
   }
   else
   {
      //The total number of unicast packets that higher-level
      //protocols requested be transmitted
      MIB2_INC_COUNTER32(interface->mibIfEntry->ifOutUcastPkts, 1);
   }

   //Leave critical section
   MIB2_UNLOCK();
#endif

   //Debug message
   TRACE_DEBUG("Sending Ethernet frame (%" PRIuSIZE " bytes)...\r\n", length);
   //Dump Ethernet header contents for debugging purpose
   ethDumpHeader(header);

   //Send the resulting packet over the specified link
   return nicSendPacket(interface, buffer, offset);
}

/**
 * @brief Destination MAC address filtering
 * @param[in] interface Underlying network interface
 * @param[in] macAddr Destination MAC address to be checked
 * @return Error code
 **/

error_t ethCheckDestAddr(NetInterface *interface, const MacAddr *macAddr)
{
   uint_t i;

   //Filter out any invalid addresses
   error_t error = ERROR_INVALID_ADDRESS;

   //Host address?
   if(macCompAddr(macAddr, &interface->macAddr))
   {
      error = NO_ERROR;
   }
   //Broadcast address?
   else if(macCompAddr(macAddr, &MAC_BROADCAST_ADDR))
   {
      error = NO_ERROR;
   }
   //Multicast address?
   else
   {
      //Acquire exclusive access to the MAC filter table
      osAcquireMutex(&interface->macFilterMutex);

      //Loop through the MAC filter table
      for(i = 0; i < interface->macFilterSize; i++)
      {
         //Check whether the destination MAC address matches
         //a relevant multicast address
         if(macCompAddr(&interface->macFilter[i].addr, macAddr))
         {
            //The MAC address is acceptable
            error = NO_ERROR;
            //Stop immediately
            break;
         }
      }

      //Release exclusive access to the MAC filter table
      osReleaseMutex(&interface->macFilterMutex);
   }

   //Return status code
   return error;
}

/**
 * @brief Add a multicast address to the MAC filter table
 * @param[in] interface Underlying network interface
 * @param[in] macAddr Multicast MAC address to accept
 * @return Error code
 **/

error_t ethAcceptMulticastAddr(NetInterface *interface, const MacAddr *macAddr)
{
   uint_t i;

   //Acquire exclusive access to the MAC filter table
   osAcquireMutex(&interface->macFilterMutex);

   //Loop through filter table entries
   for(i = 0; i < interface->macFilterSize; i++)
   {
      //Check whether the table already contains the specified MAC address
      if(macCompAddr(&interface->macFilter[i].addr, macAddr))
      {
         //Increment the reference count
         interface->macFilter[i].refCount++;
         //Release exclusive access to the MAC filter table
         osReleaseMutex(&interface->macFilterMutex);
         //No error to report
         return NO_ERROR;
      }
   }

   //The MAC filter table is full?
   if(i >= MAC_FILTER_MAX_SIZE)
   {
      //Release exclusive access to the MAC filter table
      osReleaseMutex(&interface->macFilterMutex);
      //A new entry cannot be added
      return ERROR_FAILURE;
   }

   //Add a new entry to the table
   interface->macFilter[i].addr = *macAddr;
   //Initialize the reference count
   interface->macFilter[i].refCount = 1;
   //Adjust the size of the MAC filter table
   interface->macFilterSize++;

   //Force the Ethernet controller to update its MAC filter table
   nicSetMacFilter(interface);

   //Release exclusive access to the MAC filter table
   osReleaseMutex(&interface->macFilterMutex);
   //No error to report
   return NO_ERROR;
}

/**
 * @brief Remove a multicast address from the MAC filter table
 * @param[in] interface Underlying network interface
 * @param[in] macAddr Multicast MAC address to drop
 * @return Error code
 **/

error_t ethDropMulticastAddr(NetInterface *interface, const MacAddr *macAddr)
{
   uint_t i;
   uint_t j;

   //Acquire exclusive access to the MAC filter table
   osAcquireMutex(&interface->macFilterMutex);

   //Loop through filter table entries
   for(i = 0; i < interface->macFilterSize; i++)
   {
      //Specified MAC address found?
      if(macCompAddr(&interface->macFilter[i].addr, macAddr))
      {
         //Decrement the reference count
         interface->macFilter[i].refCount--;

         //Remove the entry if the reference count drops to zero
         if(interface->macFilter[i].refCount < 1)
         {
            //Adjust the size of the MAC filter table
            interface->macFilterSize--;

            //Remove the corresponding entry
            for(j = i; j < interface->macFilterSize; j++)
               interface->macFilter[j] = interface->macFilter[j + 1];

            //Force the Ethernet controller to update its MAC filter table
            nicSetMacFilter(interface);
         }

         //Release exclusive access to the MAC filter table
         osReleaseMutex(&interface->macFilterMutex);
         //No error to report
         return NO_ERROR;
      }
   }

   //Release exclusive access to the MAC filter table
   osReleaseMutex(&interface->macFilterMutex);
   //The specified MAC address does not exist
   return ERROR_FAILURE;
}

/**
 * @brief Ethernet CRC calculation
 * @param[in] data Pointer to the data over which to calculate the CRC
 * @param[in] length Number of bytes to process
 * @return Resulting CRC value
 **/

uint32_t ethCalcCrc(const void *data, size_t length)
{
//A lookup table can be used to speed up CRC calculation
#if (ETH_FAST_CRC_SUPPORT == ENABLED)
   uint_t i;

   //Point to the data over which to calculate the CRC
   const uint8_t *p = (uint8_t *) data;
   //CRC preset value
   uint32_t crc = 0xFFFFFFFF;

   //Loop through data
   for(i = 0; i < length; i++)
   {
      //The message is processed byte by byte
      crc = (crc >> 8) ^ crc32Table[(crc & 0xFF) ^ p[i]];
   }

   //Return 1's complement value
   return ~crc;

//Bit by bit CRC calculation
#else
   uint_t i;
   uint_t j;

   //Point to the data over which to calculate the CRC
   const uint8_t *p = (uint8_t *) data;
   //CRC preset value
   uint32_t crc = 0xFFFFFFFF;

   //Loop through data
   for(i = 0; i < length; i++)
   {
      //Update CRC value
      crc ^= p[i];
      //The message is processed bit by bit
      for(j = 0; j < 8; j++)
      {
         if(crc & 0x00000001)
            crc = (crc >> 1) ^ 0xEDB88320;
         else
            crc = crc >> 1;
      }
   }

   //Return 1's complement value
   return ~crc;
#endif
}

/**
 * @brief Calculate CRC over a multi-part buffer
 * @param[in] buffer Pointer to the multi-part buffer
 * @param[in] offset Offset from the beginning of the buffer
 * @param[in] length Number of bytes to process
 * @return Resulting CRC value
 **/

uint32_t ethCalcCrcEx(const NetBuffer *buffer, size_t offset, size_t length)
{
   uint_t i;
   uint_t n;
   uint32_t crc;
   uint8_t *p;
#if (ETH_FAST_CRC_SUPPORT == DISABLED)
   uint_t k;
#endif

   //CRC preset value
   crc = 0xFFFFFFFF;

   //Loop through data chunks
   for(i = 0; i < buffer->chunkCount && length > 0; i++)
   {
      //Is there any data to process in the current chunk?
      if(offset < buffer->chunk[i].length)
      {
         //Point to the first data byte
         p = (uint8_t *) buffer->chunk[i].address + offset;
         //Compute the number of bytes to process
         n = MIN(buffer->chunk[i].length - offset, length);
         //Adjust byte counter
         length -= n;

         //Process current chunk
         while(n > 0)
         {
#if (ETH_FAST_CRC_SUPPORT == ENABLED)
            //The message is processed byte by byte
            crc = (crc >> 8) ^ crc32Table[(crc & 0xFF) ^ *p];
#else
            //Update CRC value
            crc ^= *p;

            //The message is processed bit by bit
            for(k = 0; k < 8; k++)
            {
               if(crc & 0x00000001)
                  crc = (crc >> 1) ^ 0xEDB88320;
               else
                  crc = crc >> 1;
            }
#endif
            //Next byte
            p++;
            n--;
         }

         //Process the next block from the start
         offset = 0;
      }
      else
      {
         //Skip the current chunk
         offset -= buffer->chunk[i].length;
      }
   }

   //Return 1's complement value
   return ~crc;
}

/**
 * @brief Allocate a buffer to hold an Ethernet frame
 * @param[in] length Desired payload length
 * @param[out] offset Offset to the first byte of the payload
 * @return The function returns a pointer to the newly allocated
 *   buffer. If the system is out of resources, NULL is returned
 **/

NetBuffer *ethAllocBuffer(size_t length, size_t *offset)
{
   NetBuffer *buffer;

   //Allocate a buffer to hold the Ethernet header and the payload
   buffer = netBufferAlloc(length + sizeof(EthHeader));
   //Failed to allocate buffer?
   if(!buffer) return NULL;

   //Offset to the first byte of the payload
   *offset = sizeof(EthHeader);

   //Return a pointer to the freshly allocated buffer
   return buffer;
}

/**
 * @brief Convert a string representation of an MAC address to a binary MAC address
 * @param[in] str NULL-terminated string representing the MAC address
 * @param[out] macAddr Binary representation of the MAC address
 * @return Error code
 **/

error_t macStringToAddr(const char_t *str, MacAddr *macAddr)
{
   error_t error;
   int_t i = 0;
   int_t value = -1;

   //Parse input string
   while(1)
   {
      //Hexadecimal digit found?
      if(isxdigit((uint8_t) *str))
      {
         //First digit to be decoded?
         if(value < 0) value = 0;
         //Update the value of the current byte
         if(isdigit((uint8_t) *str))
            value = (value * 16) + (*str - '0');
         else if(isupper((uint8_t) *str))
            value = (value * 16) + (*str - 'A' + 10);
         else
            value = (value * 16) + (*str - 'a' + 10);
         //Check resulting value
         if(value > 0xFF)
         {
            //The conversion failed
            error = ERROR_INVALID_SYNTAX;
            break;
         }
      }
      //Dash or colon separator found?
      else if((*str == '-' || *str == ':') && i < 6)
      {
         //Each separator must be preceded by a valid number
         if(value < 0)
         {
            //The conversion failed
            error = ERROR_INVALID_SYNTAX;
            break;
         }

         //Save the current byte
         macAddr->b[i++] = value;
         //Prepare to decode the next byte
         value = -1;
      }
      //End of string detected?
      else if(*str == '\0' && i == 5)
      {
         //The NULL character must be preceded by a valid number
         if(value < 0)
         {
            //The conversion failed
            error = ERROR_INVALID_SYNTAX;
         }
         else
         {
            //Save the last byte of the MAC address
            macAddr->b[i] = value;
            //The conversion succeeded
            error = NO_ERROR;
         }

         //We are done
         break;
      }
      //Invalid character...
      else
      {
         //The conversion failed
         error = ERROR_INVALID_SYNTAX;
         break;
      }

      //Point to the next character
      str++;
   }

   //Return status code
   return error;
}

/**
 * @brief Convert a MAC address to a dash delimited string
 * @param[in] macAddr Pointer to the MAC address
 * @param[out] str NULL-terminated string representing the MAC address
 * @return Pointer to the formatted string
 **/

char_t *macAddrToString(const MacAddr *macAddr, char_t *str)
{
   static char_t buffer[18];

   //The str parameter is optional
   if(!str) str = buffer;

   //Format MAC address
   sprintf(str, "%02" PRIX8 "-%02" PRIX8 "-%02" PRIX8 "-%02" PRIX8 "-%02" PRIX8 "-%02" PRIX8,
      macAddr->b[0], macAddr->b[1], macAddr->b[2], macAddr->b[3], macAddr->b[4], macAddr->b[5]);

   //Return a pointer to the formatted string
   return str;
}

/**
 * @brief Dump Ethernet header for debugging purpose
 * @param[in] ethHeader Pointer to the Ethernet header
 **/

void ethDumpHeader(const EthHeader *ethHeader)
{
   //Dump Ethernet header contents
   TRACE_DEBUG("  Dest Addr = %s\r\n", macAddrToString(&ethHeader->destAddr, NULL));
   TRACE_DEBUG("  Src Addr = %s\r\n", macAddrToString(&ethHeader->srcAddr, NULL));
   TRACE_DEBUG("  Type = 0x%04" PRIX16 "\r\n", ntohs(ethHeader->type));
}

#endif


text:
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

# ls
alias ls='ls -F'

# Git
alias gs='git status'
alias gp='git push'
alias gu='git up'
alias ga='git add'
alias gc='git commit'
alias go='git checkout'
alias gl='git log'
alias gf='git fetch origin'
alias gm='git merge FETCH_HEAD'
alias pull='git pull'

# Editor
alias a='atom .'

# Mac OS X
alias o='open .'

# Commands starting with % for pasting from web
alias %=' '
alias $=' '

# Kill
alias ka9='killall -9'
alias k9='kill -9'

# Homebrew
alias brewu='brew update  && brew upgrade --all && brew cleanup && brew prune && brew doctor'

# Update Aliases
alias ae='atom ~/.zsh/aliases.zsh' #alias edit
alias ar='source ~/.zsh/aliases.zsh'  #alias reload
alias gar="killall -HUP -u \"$USER\" zsh"  #global alias reload

alias zshconfig="atom ~/.zshrc"
alias zshrc="atom ~/.zshrc"

# Sketch Plugin development
alias sketch-plugin-observe='fswatch *.sketchplugin | (while read; do cp -av *.sketchplugin ~/Library/Application\ Support/com.bohemiancoding.sketch3/Plugins | echo "> Copied: $(date +%H:%M:%S)"; done)'


text:
package com.whd.wifikeyview;

import com.whd.wifikeyview.network.NetworkListener;
import com.whd.wifikeyview.network.NetworkParser.Network;
import com.whd.wifikeyview.network.NetworkParser.SupplicantKey;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

//TODO https://github.com/culmor30/android-fragments-example/blob/master/src/com/culmor30/fragmentsTesting/FragmentsTestingActivity.java
public class ShowPassword implements NetworkListener {

	private Context mContext;
	private Context activity;

	public ShowPassword(Context context) {
		activity = context;

		try {
			mContext = context.createPackageContext
				("com.whd.wifikeyview", Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException nnfe) {
			nnfe.printStackTrace();
			throw (new RuntimeException("Package name not found"));
		}
	}

	@Override
	public void onParserDone(final Network network) {
		if (network == null) {
			WiFiKeyView.verboseLog(this, "onParserDone(Network)", "Network was null!!");
			return;
		}

		TableLayout showPasswordTable = new TableLayout(mContext);
		showPasswordTable.setStretchAllColumns(true);

		int backgroundColor = 0;
		int defValue = isColorDark(backgroundColor) ? Color.WHITE : Color.BLACK;
		int color = WiFiKeyView.getSharedPreferences().getInt("showpassworddialogtextcolor", defValue);

		// Read all network entries and add those with data
		for (SupplicantKey key : SupplicantKey.values()) {

			// The SSID should be in the title and not in our table
			if (key == SupplicantKey.SSID) {
				continue;
			}

			// Get the value and generate an TableRow if needed
			String value = network.get(key);
			if ( (value != null) && (!value.equals("")) ) {
				showPasswordTable.addView(
						generateTableRow(mContext.getString(key.getString()), value, color)
				);
			}
		}

		// Get PSK and password
		String psk = network.get(SupplicantKey.PSK);
		String password = network.get(SupplicantKey.PASSWORD);

		// Copy PSK to clip board if preference is set
		if (WiFiKeyView.doCopyPSK() && (psk != null) && (!psk.equals("")) ) {
			copyToClipboard(psk);
		}

		// Copy password to clip board if preference is set
		if (WiFiKeyView.doCopyPassword() && (password != null) && (!password.equals("")) ) {
			copyToClipboard(password);
		}

		// Show results to the user
		AlertDialog dialog = new AlertDialog.Builder(activity, android.R.style.Theme_Holo_Dialog)
				.setTitle(network.get(SupplicantKey.SSID))
				.setView(showPasswordTable)
				.setPositiveButton(mContext.getString(R.string.copy), new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						// Get psk and password
						String psk = network.get(SupplicantKey.PSK);
						String password = network.get(SupplicantKey.PASSWORD);

						// Copy the right one to the clipboard
						if ( (psk != null) && (!psk.equals("")) ) {
							copyToClipboard(psk);
						} else if ( (password != null) && (!password.equals("")) ) {
							copyToClipboard(password);
						}
					}
				})
				.setNegativeButton(mContext.getString(R.string.cancel), new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})
				.create();

		dialog.show();
	}

	@SuppressWarnings("deprecation")
	private void copyToClipboard(String text) {
		// Get reference to the clipboardmanager, we do not know what version we have
		Object clipboardManager = mContext.getSystemService(Context.CLIPBOARD_SERVICE);

		// If it is an instance of the ClipboardManager in content package, cast it
		if (clipboardManager instanceof android.content.ClipboardManager) {
			((android.content.ClipboardManager) clipboardManager).setPrimaryClip(ClipData.newPlainText("", text));

		// Otherwise it is the one in text package
		} else {
			((android.text.ClipboardManager) clipboardManager).setText(text);
		}

		// Visual feedback
		Toast.makeText(mContext, mContext.getString(R.string.password_copied), Toast.LENGTH_SHORT).show();
	}

	// TODO
	// Custom strings?
	@SuppressWarnings("unused")
	private void share() {
		// Create intent for sharing and set data
		Intent share = new Intent();
		share.setAction(Intent.ACTION_SEND);
		share.putExtra(Intent.EXTRA_TEXT, "SSID: " /*+ ssid + "\n"*/ +  mContext.getString(R.string.password) + " "/* + password*/);
		share.setType("text/plain");

		// Send the intent
		mContext.startActivity(Intent.createChooser(share, mContext.getString(R.string.share_password_to)));
	}

	/**
	 * Display a row from the supplicant file in a human readable way
	 *
	 * @param key
	 * 	: The key for the entry
	 * @param value
	 * 	: The value for the entry
	 * @return
	 * 	: A TableRow object to be displayed
	 */
	private TableRow generateTableRow(String key, String value, int color) {
		// Generate row layout
		TableRow row = new TableRow(mContext);
		row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		// Add the key to the layout
		LinearLayout ll_key = new LinearLayout(mContext);
		TextView tv_key = new TextView(mContext);
		tv_key.setText(key);
		tv_key.setPadding(15, 0, 0, 0);
		tv_key.setTextColor(color);

		ll_key.addView(tv_key);
		ll_key.setOrientation(LinearLayout.VERTICAL);
		ll_key.setWeightSum(1.0f);
		row.addView(ll_key);

		// Add the value to the layout
		LinearLayout ll_value = new LinearLayout(mContext);
		TextView tv_value = new TextView(mContext);
		tv_value.setText(value);
		tv_value.setPadding(0, 0, 15, 0);
		tv_value.setTextColor(color);
		tv_value.setGravity(Gravity.RIGHT);

		ll_value.addView(tv_value);
		ll_value.setOrientation(LinearLayout.VERTICAL);
		ll_value.setWeightSum(1.0f);
		row.addView(ll_value);

		return row;
	}

	/**
	 * http://stackoverflow.com/a/24261119/1470496
	 * @param color
	 * @return
	 */
	public boolean isColorDark(int color){
	    double darkness = 1-(0.299*Color.red(color) + 0.587*Color.green(color) + 0.114*Color.blue(color))/255;
	    if(darkness<0.5){
	        return false; // It's a light color
	    }else{
	        return true; // It's a dark color
	    }
	}
}


text:
package com.android.systemui.recents.model;

import java.util.ArrayList;
import java.util.HashMap;

/** Represents a grouping of tasks witihin a stack. */
public class TaskGrouping {

    int affiliation;
    long latestActiveTimeInGroup;

    Task.TaskKey mFrontMostTaskKey;
    ArrayList<Task.TaskKey> mTaskKeys = new ArrayList<Task.TaskKey>();
    HashMap<Task.TaskKey, Integer> mTaskKeyIndices = new HashMap<Task.TaskKey, Integer>();

    /** Creates a group with a specified affiliation. */
    public TaskGrouping(int affiliation) {
        this.affiliation = affiliation;
    }

    /** Adds a new task to this group. */
    void addTask(Task t) {
        mTaskKeys.add(t.key);
        if (t.key.lastActiveTime > latestActiveTimeInGroup) {
            latestActiveTimeInGroup = t.key.lastActiveTime;
        }
        t.setGroup(this);
        updateTaskIndices();
    }

    /** Removes a task from this group. */
    void removeTask(Task t) {
        mTaskKeys.remove(t.key);
        latestActiveTimeInGroup = 0;
        int taskCount = mTaskKeys.size();
        for (int i = 0; i < taskCount; i++) {
            long lastActiveTime = mTaskKeys.get(i).lastActiveTime;
            if (lastActiveTime > latestActiveTimeInGroup) {
                latestActiveTimeInGroup = lastActiveTime;
            }
        }
        t.setGroup(null);
        updateTaskIndices();
    }

    /** Returns the key of the next task in the group. */
    public Task.TaskKey getNextTaskInGroup(Task t) {
        int i = indexOf(t);
        if ((i + 1) < getTaskCount()) {
            return mTaskKeys.get(i + 1);
        }
        return null;
    }

    /** Returns the key of the previous task in the group. */
    public Task.TaskKey getPrevTaskInGroup(Task t) {
        int i = indexOf(t);
        if ((i - 1) >= 0) {
            return mTaskKeys.get(i - 1);
        }
        return null;
    }

    /** Gets the front task */
    public boolean isFrontMostTask(Task t) {
        return (t.key == mFrontMostTaskKey);
    }

    /** Finds the index of a given task in a group. */
    public int indexOf(Task t) {
        return mTaskKeyIndices.get(t.key);
    }

    /** Returns whether a task is in this grouping. */
    public boolean containsTask(Task t) {
        return mTaskKeyIndices.containsKey(t.key);
    }

    /** Returns whether one task is above another in the group.  If they are not in the same group,
     * this returns false. */
    public boolean isTaskAboveTask(Task t, Task below) {
        return mTaskKeyIndices.containsKey(t.key) && mTaskKeyIndices.containsKey(below.key) &&
                mTaskKeyIndices.get(t.key) > mTaskKeyIndices.get(below.key);
    }

    /** Returns the number of tasks in this group. */
    public int getTaskCount() { return mTaskKeys.size(); }

    /** Updates the mapping of tasks to indices. */
    private void updateTaskIndices() {
        if (mTaskKeys.isEmpty()) {
            mFrontMostTaskKey = null;
            mTaskKeyIndices.clear();
            return;
        }

        mFrontMostTaskKey = mTaskKeys.get(mTaskKeys.size() - 1);
        mTaskKeyIndices.clear();
        int taskCount = mTaskKeys.size();
        for (int i = 0; i < taskCount; i++) {
            Task.TaskKey k = mTaskKeys.get(i);
            mTaskKeyIndices.put(k, i);
        }
    }
}


text:
const path = require('path');
const matman = require('../../packages/matman');
const {BrowserRunner} = require('../../packages/matman-runner-puppeteer');

module.exports = async pageDriverOpts => {
  const pageDriver = await matman.launch(new BrowserRunner(), pageDriverOpts);

  await pageDriver.setDeviceConfig({
    userAgent:
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36 mycustomua',
    viewport: {
      width: 1250,
      height: 400,
    },
  });

  await pageDriver.setScreenshotConfig(true);

  // 设置 cookie
  await pageDriver.setCookieConfig('mykey1=myvalue1; mykey2=puppeteer_async');

  await pageDriver.setPageUrl('https://www.baidu.com');

  // 第一步:开始操作之前
  await pageDriver.addAction('init', async page => {
    // page 为 puppeteer 的 Page 类对象
    await page.waitFor('#su');
  });

  // 第二步:搜索输入框输入: matman
  await pageDriver.addAction('input_key_word', async page => {
    // page 为 puppeteer 的 Page 类对象
    await page.type('#kw', 'matman');
  });

  // 第三步:点击搜索按钮,获得搜索结果
  await pageDriver.addAction('click_to_search', async page => {
    // page 为 puppeteer 的 Page 类对象
    await page.click('#su');
    await page.waitFor('#content_left');
  });

  return await pageDriver.evaluate(
    path.resolve(__dirname, './crawlers/get-page-info-for-search.js'),
  );
};

// module
//   .exports({
//     show: true,
//     doNotCloseBrowser: true,
//     useRecorder: false,
//   })
//   .then(function (result) {
//     console.log(JSON.stringify(result));
//   })
//   .catch(function (error) {
//     console.error('failed:', error);
//   });


text:
import * as React from 'react';
import {
  Paper,
} from 'material-ui';
import { Form } from 'formsy-react';
import * as moment from 'moment';
import i from '../i18n';
import {
  get,
  put,
} from './api';
import UserMenu from './UserMenu';
import UserSide from './UserSide';
import UserPhoto from './UserPhoto';
import UserRequired from './UserRequired';
import UserOptional from './UserOptional';

import SaveError from '../Dialogs/SaveError';
import SaveSuccess from '../Dialogs/SaveSuccess';
import NetworkError from '../Dialogs/NetworkError';
import Unauthorized from '../Dialogs/Unauthorized';

export default class UserEdit extends React.Component<any, any> {
  state = {
    user: null,
    canSubmit: false,
    saveError: false,
    saveSuccess: false,
    networkErr: false,
    unauthorized: false,
  };

  componentDidMount() {
    get()
      .then((res) => {
        if (res && res['err']) return this.setState({ networkErr: true });
        this.setState({ user: res['data'] });
      })
      .catch(err => this.setState({ networkErr: true }));
  }

  submit = (user) => {
    this.setState({ canSubmit: false });
    put(user)
      .then((res) => {
        if (res && res['err']) return this.setState({ saveError: true });
        this.setState({ saveSuccess: true });
      })
      .catch(err => this.setState({ networkErr: true }));
  }

  onValid = () => this.setState({ canSubmit: true });

  onInvalid = () => this.setState({ canSubmit: false });

  saveErrorClose = () => this.setState({ saveError: false });

  saveSuccessClose = () => this.setState({ saveSuccess: false });

  networkErrClose = () => this.setState({ networkErr: false });

  render() {
    return (

        <UserMenu />

          <UserSide />

            <UserPhoto user={this.state.user}/>
            <Form
              onValid={this.onValid}
              onInvalid={this.onInvalid}
              onSubmit={this.submit}
            >
              <UserRequired user={this.state.user} />
              <UserOptional user={this.state.user} />
              <button
                className="submit"
                disabled={!this.state.canSubmit}
              >
                {i('Save')}
              </button>
            </Form>

        <Unauthorized
          open={this.state.unauthorized}
        />
        <SaveError
          open={this.state.saveError}
          close={this.saveErrorClose}
        />
        <SaveSuccess
          open={this.state.saveSuccess}
          close={this.saveSuccessClose}
        />
        <NetworkError
          open={this.state.networkErr}
          close={this.networkErrClose}
        />

    );
  }
}


text: skljfhsdfhgskjhfkjhsdgfjhsgdfjhgsdfkjhgsdkjhfgskdf


text:
package com.github.mkroli

import scala.language.postfixOps

package object dns4s {
  def maxLong(bits: Int) = BigInt(2).pow(bits) - 1 toLong

  def maxInt(bits: Int) = maxLong(bits).toInt

  private val hexChars = ('0' to '9') ++ ('A' to 'Z') ++ ('a' to 'z') toSet

  def bytes(s: String) = s.filter(hexChars).sliding(2, 2).map(BigInt(_, 16).toByte).toList
}


text:
package org.jscsi.target.scsi.cdb;

import java.nio.ByteBuffer;

import org.jscsi.target.util.BitManip;
import org.jscsi.target.util.ReadWrite;

/**
 * This class represents Command Descriptor Blocks for the READ (10)
 *  SCSI command.
 *

 * The READ (10) command requests that the device server to read the specified logical block(s) and
 * transfer them to the data-in buffer.
 *

 * Each logical block read includes user data and, if the medium is formatted with protection information enabled,
 * protection information. Each logical block transferred includes user data and may include protection information,
 * based on the RDPROTECT field and the medium format.
 *
 * @author Andreas Ergenzinger
 */
public final class Read10Cdb extends ReadCdb {

    /**
     * The value of the RDPROTECT field determines which checks on the protection information read from the medium the
     * target shall perform before returning status for the command associated with this command descriptor block.
     *

     * Since the jSCSI Target simulates a logical unit formatted without any protection information (that can be
     * checked), the value of this field is inconsequential.
     */
    private final int readProtect;

    /**
     * This variable represents the value of the DPO bit. Since the jSCSI Target does not support advanced caching
     * strategies, the value of this variable is ignored.
     *

     * A disable page out (DPO) bit set to zero specifies that the retention priority shall be determined by the
     * RETENTION PRIORITY fields in the Caching mode page (see 6.4.5). A DPO bit set to one specifies that the device
     * server shall assign the logical blocks accessed by this command the lowest retention priority for being fetched
     * into or retained by the cache. A DPO bit set to one overrides any retention priority specified in the Caching
     * mode page. All other aspects of the algorithm implementing the cache replacement strategy are not defined by this
     * standard.
     *

     * NOTE 11 - The DPO bit is used to control replacement of logical blocks in the cache when the application client
     * has information on the future usage of the logical blocks. If the DPO bit is set to one, then the application
     * client is specifying that the logical blocks accessed by the command are not likely to be accessed again in the
     * near future and should not be put in the cache nor retained by the cache. If the DPO bit is set to zero, then the
     * application client is specifying that the logical blocks accessed by this command are likely to be accessed again
     * in the near future.
     */
    private final boolean disablePageOut;

    /**
     * The FUA ({@link #forceUnitAccess}) and FUA_NV ( {@link #forceUnitAccessNonVolatileCache}) bits together determine
     * from exactly the requested data shall be retrieved (cache, non-volatile cache, or medium) and whether or not the
     * returned data has to be transferred to the medium before sending the response.
     *

     *

     *

     * FUA
     * FUA_NV
     * Description
     *

     *

     * 0
     * 0
     * The device server may read the logical blocks from volatile cache, non-volatile cache, and/or the medium.
     *

     *

     * 0
     * 1
     * If the NV_SUP bit is set to one in the Extended INQUIRY Data VPD page (see SPC-4), then the device server
     * shall read the logical blocks from non-volatile cache or the medium. If a non-volatile cache is present and a
     * volatile cache contains a more recent version of a logical block, then the device server shall write the logical
     * block to:

     * a) non-volatile cache; and/or

     * b) the medium,

     * before reading it. If the NV_SUP bit is set to zero in the Extended INQUIRY Data VPD page (see SPC-4), then the
     * device server may read the logical blocks from volatile cache, non-volatile cache, and/or the medium.
     *

     *

     * 1
     * 0 or 1
     * The device server may read the logical blocks from volatile cache, non-volatile cache, and/or the medium.
     *

     *

     */
    private final boolean forceUnitAccess;

    /**
     * The FUA ({@link #forceUnitAccess}) and FUA_NV ( {@link #forceUnitAccessNonVolatileCache}) bits together determine
     * from exactly the requested data shall be retrieved (cache, non-volatile cache, or medium) and whether or not the
     * returned data has to be transferred to the medium before sending the response.
     *
     * @see #forceUnitAccess
     */
    private final boolean forceUnitAccessNonVolatileCache;

    /**
     * The GROUP NUMBER field can specify a particular grouping function, which is a function that collects information
     * about attributes associated with commands (i.e., information about commands with the same group value are
     * collected into the specified group).
     *

     * The collection of this information is outside the scope of the SCSI standard (as of SBC3R25) and also not part of
     * the iSCSI specification, so the value of this field will be ignored.
     *

     * Support for the grouping function is indicated in the GROUP_SUP bit in the Extended INQUIRY Data VPD page (see
     * SPC-4).
     *

     *
     */
    private final int groupNumber;

    public Read10Cdb (final ByteBuffer buffer) {
        super(buffer);// OPERATION CODE + CONTROL

        // RDPROTECT
        byte b = buffer.get(1);
        readProtect = (b >> 5) & 7;

        // DPO
        disablePageOut = BitManip.getBit(b, 4);

        // FUA
        forceUnitAccess = BitManip.getBit(b, 3);

        // FUA_NV
        forceUnitAccessNonVolatileCache = BitManip.getBit(b, 1);

        // GROUP NUMBER
        b = buffer.get(6);
        groupNumber = b & 31;
    }

    @Override
    protected long deserializeLogicalBlockAddress (ByteBuffer buffer) {
        return ReadWrite.readUnsignedInt(buffer, 2);
    }

    @Override
    protected int deserializeTransferLength (ByteBuffer buffer) {
        return ReadWrite.readTwoByteInt(buffer, 7);
    }

    public int getReadProtect () {
        return readProtect;
    }

    public boolean disablePageOut () {
        return disablePageOut;
    }

    public boolean getForceUnitAccess () {
        return forceUnitAccess;
    }

    public boolean getForceUnitAccessNonVolatile () {
        return forceUnitAccessNonVolatileCache;
    }

    public int getGroupNumber () {
        return groupNumber;
    }

    @Override
    protected int getLogicalBlockAddressFieldIndex () {
        return 2;
    }

    @Override
    protected int getTransferLengthFieldIndex () {
        return 7;
    }
}


text:
<?php

interface ParserInterface {

	public function init();
	public function finish();

	public function log (&$record);
	public function toString();

	// Output array of numbers to disk
	public function save($fileprefix);
}

?>


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sakaiproject.sitemanage</groupId>
        <artifactId>sitemanage</artifactId>
        <version>11-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <name>sakai-site-manage-group-section-role-helper</name>
    <groupId>org.sakaiproject.sitemanage</groupId>
    <artifactId>sakai-site-manage-group-section-role-helper</artifactId>
    <organization>
        <name>The Sakai Foundation</name>
        <url>http://sakaiproject.org/</url>
    </organization>
    <inceptionYear>2003</inceptionYear>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-component-manager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.sitemanage</groupId>
            <artifactId>sakai-site-manage-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.sitemanage</groupId>
            <artifactId>sakai-site-manage-util</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.rsf</groupId>
            <artifactId>sakai-rsf-web-evolvers</artifactId>
            <version>${project.version}</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.rsf</groupId>
            <artifactId>sakai-rsf-core</artifactId>
            <version>${project.version}</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.rsf</groupId>
            <artifactId>sakai-rsf-web-templates</artifactId>
            <version>${project.version}</version>
            <type>war</type>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
		</dependency>
        <dependency>
			<groupId>net.sf.opencsv</groupId>
			<artifactId>opencsv</artifactId>
		</dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
         <dependency>
            <groupId>org.sakaiproject.edu-services.course-management</groupId>
            <artifactId>coursemanagement-api</artifactId>
        </dependency>
    </dependencies>
</project>


text:
""" Command line interface.
"""
# Copyright ©  2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, unicode_literals, print_function

import re

import click
from bunch import Bunch

from . import config

# Default name of the app, and its app directory
__app_name__ = 'gh'
config.APP_NAME = __app_name__

# The `click` custom context settings
CONTEXT_SETTINGS = dict(
    obj=Bunch(cfg=None, quiet=False, verbose=False),  # namespace for custom stuff
    help_option_names=['-h', '--help'],
    auto_envvar_prefix=__app_name__.upper().replace('-', '_'),
)

# `--license` option decorator
def license_option(*param_decls, **attrs):
    """``--license`` option that prints license information and then exits."""
    def decorator(func):
        "decorator inner wrapper"
        def callback(ctx, _dummy, value):
            "click option callback"
            if not value or ctx.resilient_parsing:
                return

            from . import __doc__ as license_text
            license_text = re.sub(r"``([^`]+?)``", lambda m: click.style(m.group(1), bold=True), license_text)
            click.echo(license_text)
            ctx.exit()

        attrs.setdefault('is_flag', True)
        attrs.setdefault('expose_value', False)
        attrs.setdefault('is_eager', True)
        attrs.setdefault('help', 'Show the license and exit.')
        attrs['callback'] = callback
        return click.option(*(param_decls or ('--license',)), **attrs)(func)

    return decorator

# Main command (root)
@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(message=config.VERSION_INFO)
@license_option()
@click.option('-q', '--quiet', is_flag=True, default=False, help='Be quiet (show only errors).')
@click.option('-v', '--verbose', is_flag=True, default=False, help='Create extra verbose output.')
@click.option('-c', '--config', "config_paths", metavar='FILE',
              multiple=True, type=click.Path(), help='Load given configuration file(s).')
@click.pass_context
def cli(ctx, quiet=False, verbose=False, config_paths=None):  # pylint: disable=unused-argument
    """GitHub Commander command line tool."""
    config.Configuration.from_context(ctx, config_paths)
    ctx.obj.quiet = quiet
    ctx.obj.verbose = verbose

# Import sub-commands to define them AFTER `cli` is defined
config.cli = cli
from . import commands as _  # noqa pylint: disable=unused-import

if __name__ == "__main__":  # imported via "python -m"?
    __package__ = 'gh_commander'  # pylint: disable=redefined-builtin
    cli()  # pylint: disable=no-value-for-parameter


text:
@import ontoplay.models.ontologyModel.OwlIndividual
@import java.util.ArrayList

@(individuals : ArrayList[OwlIndividual])

<div class='individual-panel form-group'>
	<select name='individual-select' class='individual-select form-control'>
		<option value='off'>Select a value</option>
	@individuals.map{i=>
		<option value='@i.getUri()'>@i.getLocalName()</option>
	}
	</select>
</div>


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54a.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-54a.tmpl.c
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using malloc() and set data pointer to a small buffer
 * GoodSource: Allocate using malloc() and set data pointer to a large buffer
 * Sink: memmove
 *    BadSink : Copy int64_t array to data using memmove
 * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

/* bad function declaration */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54b_badSink(int64_t * data);

void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54_bad()
{
    int64_t * data;
    data = NULL;
    /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
    data = (int64_t *)malloc(50*sizeof(int64_t));
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54b_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declaration */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54b_goodG2BSink(int64_t * data);

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    int64_t * data;
    data = NULL;
    /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
    data = (int64_t *)malloc(100*sizeof(int64_t));
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54b_goodG2BSink(data);
}

void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memmove_54_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
namespace MoodBox
{

// Settings
#define PUBLISHER_NAME						"Live Communication Tools LLC"

#define APP_NAME							"MoodBox"
#define APP_TITLE							QT_TRANSLATE_NOOP("@default", "AppTitle")
#define APP_TITLE1							QT_TRANSLATE_NOOP("@default", "AppTitle%1")

#define APP_ICON                                                ":/MoodBox/Resources/moodbox_icon.png"

#define DEFAULT_USERPIC						":/MoodBox/Resources/default_userpic.png"

// Separators
#define LOCATION_SEPARATOR					","
#define PATH_SEPARATOR						"/"
#define URL_SEPARATOR						"/"
#define SPACE								" "

// Pictures
#define PICTURES_EXTENSION					"png"
#define PICTURES_CONTENTTYPE				"image/"PICTURES_EXTENSION

#define SUPPORTED_PICTURE_FORMATS			"*.jpg *.jpeg *.png *.gif *.bmp *.svg"

#define ALTERNATE_IMAGE_FORMAT				"jpeg"
#define ALTERNATE_IMAGE_QUALITY				93

// Clipart

}

#endif // COMMON_H


text:
package org.apache.camel.component.platform.http.vertx;

import java.math.BigInteger;
import java.time.Duration;
import java.util.List;

import org.apache.camel.support.jsse.SSLContextParameters;

/**
 * HTTP server configuration
 */
public class VertxPlatformHttpServerConfiguration {
    public static final String DEFAULT_BIND_HOST = "0.0.0.0";
    public static final int DEFAULT_BIND_PORT = 8080;
    public static final String DEFAULT_PATH = "/";

    private String bindHost = DEFAULT_BIND_HOST;
    private int bindPort = DEFAULT_BIND_PORT;
    private String path = DEFAULT_PATH;
    private BigInteger maxBodySize;

    private SSLContextParameters sslContextParameters;
    private boolean useGlobalSslContextParameters;

    private BodyHandler bodyHandler = new BodyHandler();
    private Cors cors = new Cors();

    public int getPort() {
        return getBindPort();
    }

    public void setPort(int port) {
        setBindPort(port);
    }

    public void setHost(String host) {
        setBindHost(host);
    }

    public String getHost() {
        return getBindHost();
    }

    public String getBindHost() {
        return bindHost;
    }

    public void setBindHost(String bindHost) {
        this.bindHost = bindHost;
    }

    public int getBindPort() {
        return bindPort;
    }

    public void setBindPort(int bindPort) {
        this.bindPort = bindPort;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public BigInteger getMaxBodySize() {
        return maxBodySize;
    }

    public void setMaxBodySize(BigInteger maxBodySize) {
        this.maxBodySize = maxBodySize;
    }

    public SSLContextParameters getSslContextParameters() {
        return sslContextParameters;
    }

    public void setSslContextParameters(SSLContextParameters sslContextParameters) {
        this.sslContextParameters = sslContextParameters;
    }

    public boolean isUseGlobalSslContextParameters() {
        return useGlobalSslContextParameters;
    }

    public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
        this.useGlobalSslContextParameters = useGlobalSslContextParameters;
    }

    public Cors getCors() {
        return cors;
    }

    public void setCors(Cors corsConfiguration) {
        this.cors = corsConfiguration;
    }

    public BodyHandler getBodyHandler() {
        return bodyHandler;
    }

    public void setBodyHandler(BodyHandler bodyHandler) {
        this.bodyHandler = bodyHandler;
    }

    public static class Cors {
        private boolean enabled;
        private List<String> origins;
        private List<String> methods;
        private List<String> headers;
        private List<String> exposedHeaders;
        private Duration accessControlMaxAge;

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }

        public List<String> getOrigins() {
            return origins;
        }

        public void setOrigins(List<String> origins) {
            this.origins = origins;
        }

        public List<String> getMethods() {
            return methods;
        }

        public void setMethods(List<String> methods) {
            this.methods = methods;
        }

        public List<String> getHeaders() {
            return headers;
        }

        public List<String> getExposedHeaders() {
            return exposedHeaders;
        }

        public void setExposedHeaders(List<String> exposedHeaders) {
            this.exposedHeaders = exposedHeaders;
        }

        public void setHeaders(List<String> headers) {
            this.headers = headers;
        }

        public Duration getAccessControlMaxAge() {
            return accessControlMaxAge;
        }

        public void setAccessControlMaxAge(Duration accessControlMaxAge) {
            this.accessControlMaxAge = accessControlMaxAge;
        }
    }

    public static class BodyHandler {
        private boolean handleFileUploads;
        private String uploadsDirectory = "file-uploads";
        private boolean mergeFormAttributes = true;
        private boolean deleteUploadedFilesOnEnd;
        private boolean preallocateBodyBuffer = true;

        public boolean isHandleFileUploads() {
            return handleFileUploads;
        }

        public void setHandleFileUploads(boolean handleFileUploads) {
            this.handleFileUploads = handleFileUploads;
        }

        public String getUploadsDirectory() {
            return uploadsDirectory;
        }

        public void setUploadsDirectory(String uploadsDirectory) {
            this.uploadsDirectory = uploadsDirectory;
        }

        public boolean isMergeFormAttributes() {
            return mergeFormAttributes;
        }

        public void setMergeFormAttributes(boolean mergeFormAttributes) {
            this.mergeFormAttributes = mergeFormAttributes;
        }

        public boolean isDeleteUploadedFilesOnEnd() {
            return deleteUploadedFilesOnEnd;
        }

        public void setDeleteUploadedFilesOnEnd(boolean deleteUploadedFilesOnEnd) {
            this.deleteUploadedFilesOnEnd = deleteUploadedFilesOnEnd;
        }

        public boolean isPreallocateBodyBuffer() {
            return preallocateBodyBuffer;
        }

        public void setPreallocateBodyBuffer(boolean preallocateBodyBuffer) {
            this.preallocateBodyBuffer = preallocateBodyBuffer;
        }
    }
}


text:
import React from 'react';
import {render} from '@testing-library/react';

import App from './App';

test('renders title', () => {
  const {getByText} = render(<App/>);
  const linkElement = getByText(/SPAT/i);
  expect(linkElement).toBeInTheDocument();
});


text:
package appeng.api.recipes;

import net.minecraft.item.ItemStack;
import appeng.api.exceptions.MissingIngredientError;
import appeng.api.exceptions.RegistrationError;

public interface IIngredient {

	/**
	 * Acquire a single input stack for the current recipe, if more then one ItemStack is possible a
	 * RegistrationError exception will be thrown, ignore these and let the system handle the error.
	 *
	 * @return a single ItemStack for the recipe handler.
	 *
	 * @throws RegistrationError
	 * @throws MissingIngredientError
	 */
	ItemStack getItemStack() throws RegistrationError, MissingIngredientError;

	/**
	 * Acquire a list of all the input stacks for the current recipe, this is for handlers that support
	 * multiple inputs per slot.
	 *
	 * @return an array of ItemStacks for the recipe handler.
	 * @throws RegistrationError
	 * @throws MissingIngredientError
	 */
	ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError;

	/**
	 * If you wish to support air, you must test before getting the ItemStack, or ItemStackSet
	 *
	 * @return true if this slot contains no ItemStack, this is passed as "_"
	 */
	public boolean isAir();

	/**
	 * @return The Name Space of the item. Prefer getItemStack or getItemStackSet
	 */
	public String getNameSpace();

	/**
	 * @return The Name of the item. Prefer getItemStack or getItemStackSet
	 */
	public String getItemName();

	/**
	 * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet
	 */
	public int getDamageValue();

	/**
	 * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet
	 */
	public int getQty();

	/**
	 * Bakes the lists in for faster runtime lookups.
	 * @throws MissingIngredientError
	 * @throws RegistrationError
	 */
	void bake() throws RegistrationError, MissingIngredientError;

}


text:
import { Field, TextInput, Chip, Button } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import React, { useState } from 'react';
import { useSubscription } from 'use-subscription';

import { useToastMessageDispatch } from '../../contexts/ToastMessagesContext';
import { useTranslation } from '../../contexts/TranslationContext';
import { AsyncStatePhase } from '../../hooks/useAsyncState';
import { useEndpointData } from '../../hooks/useEndpointData';
import { formsSubscription } from '../../views/omnichannel/additionalForms';
import { FormSkeleton } from './Skeleton';

const Tags = ({ tags = [], handler = () => {}, error = '' }) => {
	const { value: tagsResult = [], phase: stateTags } = useEndpointData('livechat/tags.list');
	const t = useTranslation();
	const forms = useSubscription(formsSubscription);

	const { useCurrentChatTags = () => {} } = forms;
	const Tags = useCurrentChatTags();

	const dispatchToastMessage = useToastMessageDispatch();

	const [tagValue, handleTagValue] = useState('');

	const removeTag = (tag) => {
		const tagsFiltered = tags.filter((tagArray) => tagArray !== tag);
		handler(tagsFiltered);
	};

	const handleTagTextSubmit = useMutableCallback(() => {
		if (!tagValue || tagValue.trim() === '') {
			dispatchToastMessage({ type: 'error', message: t('Enter_a_tag') });
			handleTagValue('');
			return;
		}
		if (tags.includes(tagValue)) {
			dispatchToastMessage({ type: 'error', message: t('Tag_already_exists') });
			return;
		}
		handler([...tags, tagValue]);
		handleTagValue('');
	});

	if ([stateTags].includes(AsyncStatePhase.LOADING)) {
		return <FormSkeleton />;
	}

	const { tags: tagsList } = tagsResult;

	return (
		<>
			<Field.Label mb='x4'>{t('Tags')}</Field.Label>
			{Tags && tagsList && tagsList.length > 0 ? (
				<Field.Row>
					<Tags value={tags} handler={handler} />
				</Field.Row>
			) : (
				<>
					<Field.Row>
						<TextInput
							error={error}
							value={tagValue}
							onChange={(event) => handleTagValue(event.target.value)}
							flexGrow={1}
							placeholder={t('Enter_a_tag')}
						/>
						<Button disabled={!tagValue} mis='x8' title={t('add')} onClick={handleTagTextSubmit}>
							{t('Add')}
						</Button>
					</Field.Row>
					<Field.Row justifyContent='flex-start'>
						{tags.map((tag, i) => (
							<Chip key={i} onClick={() => removeTag(tag)} mie='x8'>
								{tag}
							</Chip>
						))}
					</Field.Row>
				</>
			)}
		</>
	);
};

export default Tags;


text:
namespace Merchello.Core.EntityCollections
{
    using System;

    using Merchello.Core.Models.EntityBase;
    using Merchello.Core.Persistence.Querying;

    using Umbraco.Core.Persistence;

    /// <summary>
    /// The cached entity collection provider base.
    /// </summary>
    /// <typeparam name="T">
    /// The type of entity
    /// </typeparam>
    public abstract class CachedEntityCollectionProviderBase<T> : EntityCollectionProviderBase<T>, ICachedEntityCollectionProvider
        where T : class, IEntity
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CachedEntityCollectionProviderBase{T}"/> class.
        /// </summary>
        /// <param name="merchelloContext">
        /// The merchello context.
        /// </param>
        /// <param name="collectionKey">
        /// The collection key.
        /// </param>
        protected CachedEntityCollectionProviderBase(IMerchelloContext merchelloContext, Guid collectionKey)
            : base(merchelloContext, collectionKey)
        {
        }

        /// <summary>
        /// The get paged entity keys.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="Page{Guid}"/>.
        /// </returns>
        /// <remarks>
        /// All we're doing here is keeping a bit of control in case we need to do some processing before or after
        /// later on.
        /// </remarks>
        public Page<Guid> GetPagedEntityKeys(long page, long itemsPerPage, string sortBy = "", SortDirection sortDirection = SortDirection.Ascending)
        {
            return this.PerformGetPagedEntityKeys(page, itemsPerPage, sortBy, sortDirection);
        }

        /// <summary>
        /// The get paged entity keys.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="Page{Guid}"/>.
        /// </returns>
        protected abstract Page<Guid> PerformGetPagedEntityKeys(
            long page,
            long itemsPerPage,
            string sortBy = "",
            SortDirection sortDirection = SortDirection.Ascending);
    }
}