text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Templating;

use Symfony\Bundle\FrameworkBundle\Templating\PhpEngine;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;

class PhpEngineTest extends TestCase
{
    public function testEvaluateAddsAppGlobal()
    {
        $container = $this->getContainer();
        $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader');
        $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, $app = new GlobalVariables($container));
        $globals = $engine->getGlobals();
        $this->assertSame($app, $globals['app']);
    }

    public function testEvaluateWithoutAvailableRequest()
    {
        $container = new Container();
        $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader');
        $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, new GlobalVariables($container));

        $container->set('request', null);

        $globals = $engine->getGlobals();
        $this->assertEmpty($globals['app']->getRequest());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetInvalidHelper()
    {
        $container = $this->getContainer();
        $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader');
        $engine = new PhpEngine(new TemplateNameParser(), $container, $loader);

        $engine->get('non-existing-helper');
    }

    /**
     * Creates a Container with a Session-containing Request service.
     *
     * @return Container
     */
    protected function getContainer()
    {
        $container = new Container();
        $request = new Request();
        $session = new Session(new MockArraySessionStorage());

        $request->setSession($session);
        $container->set('request', $request);

        return $container;
    }
}


text:
package com.taptrack.tcmptappy.ui.modules.sendtcmpmessage.vistas.prettysheet;

import com.taptrack.tcmptappy.ui.modules.sendtcmpmessage.vistas.prettysheet.commanddetail.CommandDetailViewAdapter;

import java.util.List;

public interface PrettySheetAdapter {
    public static final int NONE = -1;

    public List<CommandFamilyItem> getCommandFamilyOptions();
    public List<CommandItem> getCommandsForFamily(int family);
    public CommandItem getCommandItem(int itemId);
    public CommandDetailViewAdapter getDetailAdapterForItem(int itemId);
}

redpajama_set_name: RedPajamaGithub


text:
Template.financeDashboard.helpers({
  weeklyIncome: function() {
    var finishedLoop = setIncome("Weekly");
    return finishedLoop;
  },
  weeklyExpense: function() {
    var finishedLoop = setExpense("Weekly");
    return finishedLoop;
  },
  weeklyTotal: function() {
    var totalAmount;
    var finishedLoopIncome = setIncome("Weekly");
    var finishedLoopExpense = setExpense("Weekly");

    totalAmount = finishedLoopIncome - finishedLoopExpense;
    if (totalAmount > -1) {
      totalAmount = "£"+totalAmount+"";
    } else {
      totalAmount = "£"+totalAmount+"";
    }
    return totalAmount;
  },
  monthlyIncome: function() {
    var finishedLoop = setIncome("Monthly");
    return finishedLoop;
  },
  monthlyExpense: function() {
    var finishedLoop = setExpense("Monthly");
    return finishedLoop;
  },
  monthlyTotal: function() {
    var totalAmount;
    var finishedLoopIncome = setIncome("Monthly");
    var finishedLoopExpense = setExpense("Monthly");

    totalAmount = finishedLoopIncome - finishedLoopExpense;
    if (totalAmount > -1) {
      totalAmount = "£"+totalAmount+"";
    } else {
      totalAmount = "£"+totalAmount+"";
    }
    return totalAmount;
  },
  annualIncome: function() {
    var finishedLoop = setIncome("Annually");
    return finishedLoop;
  },
  annualExpense: function() {
    var finishedLoop = setExpense("Annually");
    return finishedLoop;
  },
  annualTotal: function() {
    var totalAmount;
    var finishedLoopIncome = setIncome("Annually");
    var finishedLoopExpense = setExpense("Annually");

    totalAmount = finishedLoopIncome - finishedLoopExpense;
    if (totalAmount > -1) {
      totalAmount = "£"+totalAmount+"";
    } else {
      totalAmount = "£"+totalAmount+"";
    }
    return totalAmount;
  }
});
Template.financeDashboard.rendered=function() {
  var timingIncome = setIncome("Monthly");
  var timingExpense = setExpense('Monthly');
  var ctxw = document.getElementById("financeGraphMonthly").getContext("2d");
  var data = {
    labels : ["Monthly Income","Monthly Expense"],
    datasets : [
      {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        pointColor : "rgba(220,220,220,1)",
        pointStrokeColor : "#fff",
        data : [timingIncome,timingExpense]
      }
    ]
  }
  var myNewChart = new Chart(ctxw).Bar(data,null);
}

var setIncome = function(timing) {
  var finishedLoop = financesLoop(
    Finances.find({userId: Meteor.userId(), financeType: "Income"}).fetch(),
    0,
    timing
  );
  return finishedLoop;
}

var setExpense = function(timing) {
  var finishedLoop = financesLoop(
    Finances.find({userId: Meteor.userId(), financeType: "Expense"}).fetch(),
    0,
    timing
  );
  return finishedLoop;
}

var financesLoop = function(userFinances, totalIncome, timingLoop) {
  $(userFinances).each(function() {
    var current = this, newAmount;
    if (timingLoop == "Weekly") {
      newAmount = financesCheckWeekly(current);
    } else if (timingLoop == "Monthly") {
      newAmount = financesCheckMonthly(current);
    } else if (timingLoop == "Annually") {
      newAmount = financesCheckAnnually(current);
    }

    totalIncome = parseInt(totalIncome + newAmount);
  });
  return totalIncome;
}

var financesCheckWeekly = function(current) {
  var newAmount = 0;
  if (current.timing == "One-Off") {
    newAmount = 0;
  } else if (current.timing == "Weekly") {
    newAmount = (parseInt(current.amount));
  } else if (current.timing == "Monthly") {
    newAmount = Math.round((parseInt(current.amount) * 12) / 52);
  } else if (current.timing == "Annualy") {
    newAmount = Math.round(parseInt(current.amount) / 52);
  }

  return newAmount;
}

var financesCheckMonthly = function(current) {
  var newAmount = 0;
  if (current.timing == "One-Off") {
    newAmount = 0;
  } else if (current.timing == "Weekly") {
    newAmount = Math.round((parseInt(current.amount) * 52)/12);
  } else if (current.timing == "Monthly") {
    newAmount = parseInt(current.amount);
  } else if (current.timing == "Annualy") {
    newAmount = Math.round(parseInt(current.amount) / 12);
  }

  return newAmount;
}

var financesCheckAnnually = function(current) {
  var newAmount = 0;
  if (current.timing == "One-Off") {
    newAmount = 0;
  } else if (current.timing == "Weekly") {
    newAmount = parseInt(current.amount) * 52;
  } else if (current.timing == "Monthly") {
    newAmount = parseInt(current.amount) * 12;
  } else if (current.timing == "Annualy") {
    newAmount = parseInt(current.amount);
  }

  return newAmount;
}


text:
var constants = {
  // 401
  UNAUTHORIZED: 'unauthorized',

  // 403
  FORBIDDEN: 'permission denied',

  // 404
  NOT_FOUND: 'not found',

  // 500
  SERVER_ERROR: 'internal server error',

  // custom
  INVALID_ARGUMENT: 'invalid argument',
  INVALID_APP_KEY: 'invalid app key',
  INVALID_USERNAME: 'invalid username',
  UNAUTHORIZED_APP: 'unauthorized app',
  USERNAME_EXISTS: 'username already exists',
  EMAIL_EXISTS: 'email already exists',
  EMAIL_NOT_CONFIRMED: 'email not confirmed',
  ACCOUNT_IS_LOCKED: 'account is locked',
  INVALID_LOGIN_OR_PASSWORD: 'invalid login or password',
  INCORRECT_CURRENT_PASSWORD: 'incorrect current password',
  UNABLE_TO_LOGIN_BY_PASSWORD: 'unable to login by password',
  NOT_ALLOWED_TO_CREATE_USER: 'not allowed to create user',
  NOT_ALLOWED_TO_REGISTER: 'not allowed to register',
  NOT_BIND_TO_APP: 'not bind to current app',
  BIND_TO_APP: 'already bind to current app'
};

export default constants;


text:
package simulator

import (
	"strings"

	"github.com/vmware/govmomi/simulator/esx"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/types"
)

// Create Datacenter Folders.
// Every Datacenter has 4 inventory Folders: Vm, Host, Datastore and Network.
// The ESX folder child types are limited to 1 type.
// The VC folders have additional child types, including nested folders.
func createDatacenterFolders(dc *mo.Datacenter, isVC bool) {
	folders := []struct {
		ref   *types.ManagedObjectReference
		name  string
		types []string
	}{
		{&dc.VmFolder, "vm", []string{"VirtualMachine", "VirtualApp", "Folder"}},
		{&dc.HostFolder, "host", []string{"ComputeResource", "Folder"}},
		{&dc.DatastoreFolder, "datastore", []string{"Datastore", "StoragePod", "Folder"}},
		{&dc.NetworkFolder, "network", []string{"Network", "DistributedVirtualSwitch", "Folder"}},
	}

	for _, f := range folders {
		folder := &Folder{}
		folder.Name = f.name

		if isVC {
			folder.ChildType = f.types
			e := Map.PutEntity(dc, folder)

			// propagate the generated morefs to Datacenter
			ref := e.Reference()
			f.ref.Type = ref.Type
			f.ref.Value = ref.Value
		} else {
			folder.ChildType = f.types[:1]
			folder.Self = *f.ref
			Map.PutEntity(dc, folder)
		}
	}

	net := Map.Get(dc.NetworkFolder).(*Folder)

	for _, ref := range esx.Datacenter.Network {
		// Add VM Network by default to each Datacenter
		network := &mo.Network{}
		network.Self = ref
		network.Name = strings.Split(ref.Value, "-")[1]
		network.Entity().Name = network.Name
		if isVC {
			network.Self.Value = "" // we want a different moid per-DC
		}

		net.putChild(network)
	}
}


text:
USE TelerikAcademy

-- 4. Write a SQL query to find all information about all departments (use "TelerikAcademy" database).
SELECT * FROM Departments

-- 5. Write a SQL query to find all department names.
SELECT Name AS [Depertment Name]
FROM Departments

-- 6. Write a SQL query to find the salary of each employee.
SELECT Salary AS [Employee Salary]
FROM Employees

-- 7. Write a SQL to find the full name of each employee.
SELECT FirstName + ' ' + MiddleName + '.' + ' ' + LastName AS [Full Name]
FROM Employees
------second way------
SELECT COALESCE(FirstName + ' ', '') + COALESCE(MiddleName + '. ', '') + COALESCE(LastName,'') AS [Full Name]
FROM Employees

-- 8. Write a SQL query to find the email addresses of each employee (by his first and last name). Consider that the mail domain is telerik.com.
-- Emails should look like "John.Doe@telerik.com". The produced column should be named "Full Email Addresses".

 SELECT FirstName + '.' + LastName + '@telerik.com' AS [Full Name]
FROM Employees
------second way------
SELECT COALESCE(FirstName + '.', '') + COALESCE(LastName,'') + COALESCE('@telerik.com', '')  AS [Full Email Addresses]
FROM Employees

-- 9. Write a SQL query to find all different employee salaries.

SELECT
DISTINCT Salary
FROM Employees

-- 10. Write a SQL query to find all information about the employees whose job title is "Sales Representative".

SELECT *
FROM Employees
WHERE JobTitle = 'Sales Representative'

-- 11. Write a SQL query to find the names of all employees whose first name starts with "SA".

SELECT FirstName, MiddleName, LastName
FROM Employees
WHERE FirstName LIKE 'SA%'

-- 12. Write a SQL query to find the names of all employees whose last name contains "ei".

SELECT FirstName, MiddleName, LastName
FROM Employees
WHERE LastName LIKE '%ei%'

-- 13. Write a SQL query to find the salary of all employees whose salary is in the range [20000…30000].

SELECT FirstName, MiddleName, LastName, Salary
FROM Employees
WHERE Salary >= 20000 AND Salary <= 30000
------second way------
SELECT FirstName, MiddleName, LastName, Salary
FROM Employees
WHERE Salary BETWEEN 20000 AND 30000

-- 14. Write a SQL query to find the names of all employees whose salary is 25000, 14000, 12500 or 23600.

SELECT FirstName, MiddleName, LastName, Salary
FROM Employees
WHERE Salary IN(25000, 14000, 12500, 23600)
------second way------
SELECT FirstName, MiddleName, LastName, Salary
FROM Employees
WHERE Salary = 25000 OR Salary = 14000 OR Salary = 12500 OR Salary = 23600

-- 15. Write a SQL query to find all employees that do not have manager.

SELECT FirstName, MiddleName, LastName,ManagerID
FROM Employees
WHERE ManagerID IS NULL

-- 16. Write a SQL query to find all employees that have salary more than 50000. Order them in decreasing order by salary.

SELECT FirstName, MiddleName, LastName, Salary
FROM Employees
WHERE Salary > 50000
ORDER BY Salary DESC

-- 17. Write a SQL query to find the top 5 best paid employees.s BETTER WAY maybe

SELECT TOP(5) FirstName, MiddleName, LastName, Salary
FROM Employees
ORDER BY Salary DESC

-- 18. Write a SQL query to find all employees along with their address. Use inner join with ON clause.

SELECT e.FirstName, e.MiddleName, e.LastName, a.AddressText AS [Address]
FROM Employees e
INNER JOIN Addresses a
ON e.AddressID = a.AddressID

-- 19. Write a SQL query to find all employees and their address. Use equijoins (conditions in the WHERE clause).

SELECT e.FirstName, e.MiddleName, e.LastName, a.AddressText AS [Address]
FROM Employees e , Addresses a
WHERE e.AddressID = a.AddressID

-- 20. Write a SQL query to find all employees along with their manager.

SELECT e.FirstName, e.MiddleName, e.LastName, m.EmployeeID AS [Manager Id], m.LastName[Manager Last Name]
FROM Employees e
INNER JOIN Employees m
ON e.ManagerID = m.EmployeeID

-- 21. Write a SQL query to find all employees, along with their manager and their address. Join the 3 tables: Employees e, Employees m and Addresses a.

SELECT e.FirstName, e.MiddleName, e.LastName, m.EmployeeID AS [Manager Id], m.LastName[Manager Last Name], a.AddressText[Address]
FROM Employees e
	JOIN Employees m
ON e.ManagerID = m.EmployeeID
	JOIN Addresses a
ON e.AddressID = a.AddressID

-- 22. Write a SQL query to find all departments and all town names as a single list. Use UNION.

SELECT d.Name
FROM Departments d
UNION
SELECT t.Name
FROM Towns t

-- 23. Write a SQL query to find all the employees and the manager for each of them along with the employees that do not have manager. Use right outer join. Rewrite the query to use left outer join.

------left outer join------

SELECT e.FirstName, e.MiddleName, e.LastName, m.EmployeeID AS [Manager Id], m.LastName[Manager Last Name]
FROM Employees e
RIGHT OUTER JOIN Employees m
ON e.ManagerID = m.EmployeeID

------right outer join------

SELECT e.FirstName, e.MiddleName, e.LastName, m.EmployeeID AS [Manager Id], m.LastName[Manager Last Name]
FROM Employees e
LEFT OUTER JOIN Employees m
ON e.ManagerID = m.EmployeeID

-- 24. Write a SQL query to find the names of all employees from the departments "Sales" and "Finance" whose hire year is between 1995 and 2005.

SELECT e.FirstName, e.MiddleName, e.LastName, e.HireDate, d.Name[Department]
FROM Employees e
JOIN Departments d
ON e.DepartmentID=d.DepartmentID
WHERE d.Name = 'Sales' OR d.Name = 'Finance'
AND YEAR(e.HireDate) BETWEEN 1995 AND 2005


text:
from django.contrib import admin
from .models import *

class SessionLogStepInline(admin.TabularInline):
    model = SessionLogStep
    fk_name = 'session'
    extra = 0
    list_display = ('id', 'control_line', 'body', 'screenshot', 'created')
    readonly_fields = ('id',)
    ordering = ('-created',)

class PlatformInline(admin.TabularInline):
    model = Platform
    fk_name = 'provider'
    extra = 0
    list_display = ('id', 'name',)
    readonly_fields = ('id', 'name',)
    ordering = ('name',)

@admin.register(Provider)
class ProviderAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'url', 'active')
    list_display_links = ('name',)
    inlines = [
        PlatformInline,
    ]

@admin.register(Platform)
class PlatformAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'provider_name')
    list_display_links = ('name',)
    readonly_fields = ('id', 'name', 'provider')
    ordering = ('-name',)

@admin.register(Endpoint)
class EndpointAdmin(admin.ModelAdmin):
    list_display = (
        'id', 'name', 'ip', 'uuid', 'ports', 'ready', 'in_use', 'deleted',
        'created_time', 'used_time', 'deleted_time'
    )
    list_display_links = ('name',)
    readonly_fields = ('id', 'name', 'ip', 'ready', 'in_use', 'deleted',)
    list_filter = ['ready', 'in_use', 'deleted']
    search_fields = ['id', 'name', 'ip', 'uuid']
    ordering = ('-created_time',)

@admin.register(Session)
class SessionAdmin(admin.ModelAdmin):
    list_display = (
        'id', 'name',
        'created', 'modified', 'deleted',
        'duration', 'status', 'error',
        'timeouted', 'closed',
        'keep_forever'
    )
    list_display_links = ('name',)
    readonly_fields = ('id', 'name', 'user', 'status', 'error', )
    list_filter = ['user', 'status', 'timeouted', 'closed', 'keep_forever']
    search_fields = ['id', 'name', 'error', ]
    ordering = ('-created',)

    inlines = [
        SessionLogStepInline,
    ]


text:
var HoneyBadger = (function($this) {

  var ts,tp,socket,host = "ws://"+location.host+"/admin/";

  var self = this;
  var __cbqueue = {},
    __logverbose = false,
    __devmode = ( window.location.host.indexOf("localhost") > -1 || window.location.host.indexOf('192.168') > -1 ) ? true : false;

  var public = {}, protected = {};
  var Emit = new Emitter(protected);
  var Modules = new Modular(this, function() { return Extend(public, protected); });

  console.log('HoneyBadger starting up');
  var _init = function() {
    console.log('HoneyBadger initializing');

    connect();

    console.log('HoneyBadger initializing submodules');
    Modules.init();

    console.log('HoneyBadger initializing complete!');
  };

  var connect = function() {
    if (ts) clearInterval(ts);
    if (tp) clearInterval(tp);

    socket = new WebSocket(host);
    socket.onopen = function() {
      if (ts) clearInterval(ts);
      tp = setInterval(function() {
        socket.send('ping');
      }, 15000);
      Emit('readyStateChange', 1);
    };

    socket.onclose = function() {
      if (tp) clearInterval(tp);
      ts = setInterval(connect, 1000);
    };

    socket.onmessage = receive;
    return socket;
  };

  var send = function(method, args, callback){
    var args = args || [];
    var msig = (callback) ? (new Date().getTime() * Math.random(1000)).toString(36) : null;
    if (msig) { __cbqueue[msig] = callback }
    if( __devmode && __logverbose ){ console.trace(); console.dir({method:method,msig:msig,args:args}); }
    socket.send(JSON.stringify({method:method,msig:msig,args:args}));
  };

  var receive = function(e) {

    if (e.data === 'pong') return;
    if (__devmode && __logverbose) { console.dir(e); }

    var d = JSON.parse(e.data);
    var msig = d.msig || null;
    if (msig && __cbqueue[msig]) {
      __cbqueue[msig](d);
      delete __cbqueue[msig];
      return;
    }

    if (d.event == 'log-stream') {
      Emit('log-stream', d);
    }
  };

  public.init = _init,
  public.module = { register: Modules.register };

  protected.__devmode = __devmode;
  protected.__logverbose = __logverbose;
  protected.exec = function(method, args, callback) {
    send(method, args, callback);
  };

  return public;

}(HoneyBadger || {}));


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include
        layout="@layout/layout_search_title_bar"/>
    <LinearLayout
        android:id="@+id/ac_ll_group_list_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            style="@style/ac_search_list_view_item"
            android:text="@string/ac_search_group"/>
        <View
            style="@style/ac_search_list_view_divider"/>
    </LinearLayout>
    <ListView
        android:id="@+id/ac_lv_group_list_detail_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/ac_tv_search_no_results"
        style="@style/ac_search_no_results"/>
</LinearLayout>


text:
using Enterprise.Invoicing.Entities.Models;
using Enterprise.Invoicing.ViewModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Enterprise.Invoicing.Repositories
{
    public class AccountRepository : BasicRepository<Employee>, IAccountRepository
    {
        public AccountRepository()            : base(new InvoicingContext())        { }

        public AccountRepository(InvoicingContext context) : base(context) { }

        public LoginUser GetLoginModel(string userid)
        {
            //context
            //using (var c = new InvoicingContext())
           // {
                var model = (from e in context.Employees
                             join r in context.Roles on e.roleSn equals r.roleSn
                             join d in context.Departments on e.depId equals d.depId
                             where e.userId==userid && e.isUser==true
                             select new LoginUser
                             {
                                 dep_name = d.depName,
                                 mobile = e.mobile,
                                 email = e.email,
                                 name = e.staffName, rigthType=e.rigthType,  showPrice=r.showPrice,
                                 role_name = r.roleName,
                                 role_sn = r.roleSn,
                                 staffid = e.staffId,
                                 userid = e.userId,
                                 userpwd = e.userPwd,depId=d.depId
                             }
                                ).FirstOrDefault();
                return model;
           // }
        }

        public List<Enterprise.Invoicing.Entities.Models.Menu> GetMenuByRole(int rolesn)
        {
            using (var c = new InvoicingContext())
            {
                var list = from m in c.Menus
                           join r in c.MenuRights on m.menuNo equals r.menuNo
                           where r.roleSn == rolesn
                           orderby m.menuNo ascending
                           select m;
                return list.ToList();
            }
        }
        public List<Function> GetFunctionByRole(int rolesn)
        {
            using (var c=new InvoicingContext())
            {
                var list = from f in c.Functions
                           join r in c.FunctionRights on f.functionNo equals r.functionNo
                           where r.roleSn == rolesn
                           orderby r.rightSn ascending
                           select f;
                return list.ToList();
            }
        }
        /// <summary>
        /// 判断菜单和ajax权限
        /// </summary>
        /// <param name="role"></param>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool CheckAjaxRight(int role, string controller, string actions)
        {
            if (actions.Contains(","))
            {
                string[] actionlist = actions.Split(',');
                foreach (var item in actionlist)
                {
                    if (item != "")
                    {
                        var h = HasAjaxRight(role, controller, item);
                        if (h)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
            else
            {
                return HasAjaxRight(role, controller, actions);
            }
        }

        public ReturnValue UpdatePwd(int staff, string oldpwd, string newpwd)
        {
            using (var c = new InvoicingContext())
            {
                var model = c.Employees.FirstOrDefault(p => p.staffId == staff);
                if (model == null) return new ReturnValue { status = false, message = "用户不存在" };
                if (model.isUser == false) return new ReturnValue { status = false, message = "该员工为非系统用户" };
                if (!model.status) return new ReturnValue { status = false, message = "该用户已被锁定" };
                if (model.userPwd.ToLower() != oldpwd.ToLower()) return new ReturnValue { status = false, message = "旧密码输入错误" };
                model.userPwd = newpwd;
                c.Entry(model).State = EntityState.Modified;
                c.SaveChanges();
                return new ReturnValue { status = true, message = "" };
            }
        }

        #region 私有方法
        private bool HasAjaxRight(int sn, string c, string a)
        {
            var h = (from m in context.Menus
                     join r in context.MenuRights on m.menuNo equals r.menuNo
                     where m.menuUrl.ToLower().Contains(c.ToLower())
                     && m.menuUrl.ToLower().Contains(a.ToLower()) && r.roleSn == sn
                     select m.menuNo).FirstOrDefault();
            if (h != null && h != "")
            {
                return true;
            }
            else return false;
        }

        #endregion
    }
}


text:
package com.piggsoft.auto.operator.service.impl;

import com.piggsoft.auto.operator.entity.Package;
import com.piggsoft.auto.operator.mapper.PackageMapper;
import com.piggsoft.auto.operator.service.IPackageService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author piggsoft
 * @since 2017-08-19
 */
@Service
public class PackageServiceImpl extends ServiceImpl<PackageMapper, Package> implements IPackageService {

}


text:
package io.advantageous.qbit.meta.builder;

import io.advantageous.boon.core.Conversions;
import io.advantageous.boon.core.reflection.Annotated;
import io.advantageous.boon.core.reflection.AnnotationData;
import io.advantageous.boon.core.reflection.MethodAccess;
import io.advantageous.qbit.annotation.RequestMethod;
import io.advantageous.qbit.http.HttpHeaders;
import io.advantageous.qbit.meta.CallType;
import io.advantageous.qbit.meta.ServiceMeta;
import io.advantageous.qbit.meta.ServiceMethodMeta;
import io.advantageous.qbit.util.MultiMap;
import io.advantageous.qbit.util.MultiMapImpl;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import static io.advantageous.qbit.meta.builder.ContextMetaBuilder.*;

/**
 * Allows you to build service method data.
 */
@SuppressWarnings("UnusedReturnValue")
public class ServiceMetaBuilder {

    private String name;
    private List<String> requestPaths = new ArrayList<>();
    private List<ServiceMethodMeta> methods = new ArrayList<>();

    private String description;
    private MultiMap<String, String> responseHeaders;

    public static ServiceMetaBuilder serviceMetaBuilder() {
        return new ServiceMetaBuilder();
    }

    public String getDescription() {
        return description;
    }

    public ServiceMetaBuilder setDescription(String description) {
        this.description = description;
        return this;
    }

    public String getName() {
        return name;
    }

    public ServiceMetaBuilder setName(String name) {
        this.name = name;
        return this;
    }

    public List<String> getRequestPaths() {
        return requestPaths;
    }

    public ServiceMetaBuilder setRequestPaths(List<String> requestPaths) {
        this.requestPaths = requestPaths;
        return this;
    }

    public ServiceMetaBuilder addRequestPath(String requestPath) {
        this.requestPaths.add(requestPath);
        return this;
    }

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

    public ServiceMetaBuilder setMethods(List<ServiceMethodMeta> methods) {
        this.methods = methods;
        return this;
    }

    public ServiceMetaBuilder addMethod(ServiceMethodMeta method) {
        this.methods.add(method);
        return this;
    }

    public ServiceMetaBuilder addMethods(ServiceMethodMeta... methodArray) {
        Collections.addAll(methods, methodArray);
        return this;
    }

    public ServiceMeta build() {

        return new ServiceMeta(getName(), getRequestPaths(), getMethods(), getDescription());
    }

    public void addMethods(final String path, final Collection<MethodAccess> methods) {

        /* Only add methods that could be REST endpoints. */
        methods.stream().filter(methodAccess ->
                !methodAccess.isPrivate() && //No private methods
                        !methodAccess.isStatic() && //No static methods
                        !methodAccess.method().isSynthetic() && //No synthetic methods
                        !methodAccess.method().getDeclaringClass().getName().contains("$$EnhancerByGuice$$") &&
                        !methodAccess.name().contains("$")) //No methods with $ as this could be Scala generated
                // method or byte code lib generated
                .forEach(methodAccess -> addMethod(path, methodAccess));
    }

    public ServiceMetaBuilder addMethod(final String rootPath, final MethodAccess methodAccess) {

        for (String servicePath : this.getRequestPaths()) {

            final AnnotationData requestMapping = getAnnotationData(methodAccess);

            final List<String> requestPaths
                    = getRequestPathsByAnnotated(methodAccess, methodAccess.name().toLowerCase());

            if (requestMapping != null && requestMapping.getName().equals("bridge")) {
                requestPaths.add("/" + methodAccess.name().toLowerCase());
            }

            final String description = getDescriptionFromRequestMapping(methodAccess);

            final String returnDescription = getReturnDescriptionFromRequestMapping(methodAccess);

            final String summary = getSummaryFromRequestMapping(methodAccess);

            final int code = getCodeFromRequestMapping(methodAccess);

            final String contentType = getContentTypeFromRequestMapping(methodAccess);

            final MultiMap<String, String> responseHeaders = getResponseHeaders(methodAccess);

            final List<RequestMethod> requestMethods = getRequestMethodsByAnnotated(methodAccess);

            final ServiceMethodMetaBuilder serviceMethodMetaBuilder = ServiceMethodMetaBuilder.serviceMethodMetaBuilder();
            serviceMethodMetaBuilder.setMethodAccess(methodAccess);
            serviceMethodMetaBuilder.setDescription(description);
            serviceMethodMetaBuilder.setSummary(summary);
            serviceMethodMetaBuilder.setReturnDescription(returnDescription);
            serviceMethodMetaBuilder.setResponseCode(code);
            serviceMethodMetaBuilder.setContentType(contentType);

            for (String path : requestPaths) {
                CallType callType = path.contains("{") ? CallType.ADDRESS_WITH_PATH_PARAMS : CallType.ADDRESS;

                final RequestMetaBuilder requestMetaBuilder = new RequestMetaBuilder();

                requestMetaBuilder.setResponseHeaders(responseHeaders);

                requestMetaBuilder.addParameters(rootPath, servicePath, path, methodAccess);
                requestMetaBuilder.setCallType(callType).setRequestURI(path).setRequestMethods(requestMethods);
                serviceMethodMetaBuilder.addRequestEndpoint(requestMetaBuilder.build());
            }
            addMethod(serviceMethodMetaBuilder.build());
        }
        return this;

    }

    private MultiMap<String, String> getResponseHeaders(final Annotated annotated) {

        MultiMap<String, String> responseHeadersMap = MultiMap.empty();

        if (responseHeaders != null && responseHeaders.size() > 0) {
            responseHeadersMap = new MultiMapImpl<>();
            responseHeadersMap.putAll(responseHeaders);
        }

        final AnnotationData responseHeaderAnnotation = annotated.annotation("ResponseHeader");

        if (responseHeaderAnnotation != null) {
            final String name = responseHeaderAnnotation.getValues().get("name").toString();
            final String value = responseHeaderAnnotation.getValues().get("value").toString();

            if (responseHeadersMap.size() == 0) {
                responseHeadersMap = new MultiMapImpl<>();
            }
            responseHeadersMap.add(name, value);
        }

        final AnnotationData responseHeadersAnnotation = annotated.annotation("ResponseHeaders");

        if (responseHeadersAnnotation != null) {
            if (responseHeadersMap.size() == 0) {
                responseHeadersMap = new MultiMapImpl<>();
            }
            final Object[] values = (Object[]) responseHeadersAnnotation.getValues().get("value");

            for (Object object : values) {

                if (object instanceof Annotation) {
                    AnnotationData annotationData = new AnnotationData((Annotation) object);

                    final String name = annotationData.getValues().get("name").toString();
                    final String value = annotationData.getValues().get("value").toString();
                    responseHeadersMap.add(name, value);
                }
            }

        }

        final AnnotationData noCache = annotated.annotation("NoCacheHeaders");
        if (noCache != null) {
            if (responseHeadersMap.size() == 0) {
                responseHeadersMap = new MultiMapImpl<>();
            }
            responseHeadersMap.add(HttpHeaders.CACHE_CONTROL, "max-age=0");
            responseHeadersMap.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
        }

        final AnnotationData getAnnotation = annotated.annotation("GET");

        if (getAnnotation != null) {
            final Object noCache1 = getAnnotation.getValues().get("noCache");
            if (Conversions.toBoolean(noCache1)) {
                if (responseHeadersMap.size() == 0) {
                    responseHeadersMap = new MultiMapImpl<>();
                }
                responseHeadersMap.add(HttpHeaders.CACHE_CONTROL, "max-age=0");
                responseHeadersMap.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
            }
        }
        return responseHeadersMap;
    }

    public ServiceMetaBuilder setResponseHeaders(MultiMap<String, String> responseHeaders) {
        this.responseHeaders = responseHeaders;
        return this;
    }
}


text:
import procedure_request from 'ember-fhir-adapter/serializers/procedure-request';
export default procedure_request;


text:
require 'pathname'

require 'puppet/forge'
require 'puppet/module_tool'
require 'puppet/module_tool/shared_behaviors'
require 'puppet/module_tool/install_directory'
require 'puppet/module_tool/installed_modules'

module Puppet::ModuleTool
  module Applications
    class Upgrader < Application

      include Puppet::ModuleTool::Errors

      def initialize(name, options)
        super(options)

        @action              = :upgrade
        @environment         = options[:environment_instance]
        @name                = name
        @ignore_dependencies = forced? || options[:ignore_dependencies]

        Semantic::Dependency.add_source(installed_modules_source)
        Semantic::Dependency.add_source(module_repository)
      end

      def run
        name = @name.tr('/', '-')
        version = options[:version] || '>= 0.0.0'

        results = {
          :action => :upgrade,
          :requested_version => options[:version] || :latest,
        }

        begin
          all_modules = @environment.modules_by_path.values.flatten
          matching_modules = all_modules.select do |x|
            x.forge_name && x.forge_name.tr('/', '-') == name
          end

          if matching_modules.empty?
            raise NotInstalledError, results.merge(:module_name => name)
          elsif matching_modules.length > 1
            raise MultipleInstalledError, results.merge(:module_name => name, :installed_modules => matching_modules)
          end

          mod = installed_modules[name]

          # `priority` is an attribute of a `Semantic::Dependency::Source`,
          # which is delegated through `ModuleRelease` instances for the sake of
          # comparison (sorting). By default, the `InstalledModules` source has
          # a priority of 10 (making it the most preferable source, so that
          # already installed versions of modules are selected in preference to
          # modules from e.g. the Forge). Since we are specifically looking to
          # upgrade this module, we don't want the installed version of this
          # module to be chosen in preference to those with higher versions.
          #
          # This implementation is suboptimal, and since we can expect this sort
          # of behavior to be reasonably common in Semantic, we should probably
          # see about implementing a `ModuleRelease#override_priority` method
          # (or something similar).
          def mod.priority
            0
          end

          mod = mod.mod
          results[:installed_version] = Semantic::Version.parse(mod.version)
          dir = Pathname.new(mod.modulepath)

          vstring = mod.version ? "v#{mod.version}" : '???'
          Puppet.notice "Found '#{name}' (#{colorize(:cyan, vstring)}) in #{dir} ..."
          unless forced?
            changes = Checksummer.run(mod.path) rescue []
            if mod.has_metadata? && !changes.empty?
              raise LocalChangesError,
                :action            => :upgrade,
                :module_name       => name,
                :requested_version => results[:requested_version],
                :installed_version => mod.version
            end
          end

          Puppet::Forge::Cache.clean

          Puppet.notice "Downloading from #{module_repository.host} ..."
          if @ignore_dependencies
            graph = build_single_module_graph(name, version)
          else
            graph = build_dependency_graph(name, version)
          end

          unless forced?
            add_module_name_constraints_to_graph(graph)
          end

          installed_modules.each do |mod, release|
            mod = mod.tr('/', '-')
            next if mod == name

            version = release.version

            unless forced?
              # Since upgrading already installed modules can be troublesome,
              # we'll place constraints on the graph for each installed
              # module, locking it to upgrades within the same major version.
              ">=#{version} #{version.major}.x".tap do |range|
                graph.add_constraint('installed', mod, range) do |node|
                  Semantic::VersionRange.parse(range).include? node.version
                end
              end

              release.mod.dependencies.each do |dep|
                dep_name = dep['name'].tr('/', '-')

                dep['version_requirement'].tap do |range|
                  graph.add_constraint("#{mod} constraint", dep_name, range) do |node|
                    Semantic::VersionRange.parse(range).include? node.version
                  end
                end
              end
            end
          end

          # Ensure that there is at least one candidate release available
          # for the target package.
          if graph.dependencies[name].empty? || graph.dependencies[name] == SortedSet.new([ installed_modules[name] ])
            if results[:requested_version] == :latest || !Semantic::VersionRange.parse(results[:requested_version]).include?(results[:installed_version])
              raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
            end
          end

          begin
            Puppet.info "Resolving dependencies ..."
            releases = Semantic::Dependency.resolve(graph)
          rescue Semantic::Dependency::UnsatisfiableGraph
            raise NoVersionsSatisfyError, results.merge(:requested_name => name)
          end

          releases.each do |rel|
            if mod = installed_modules_source.by_name[rel.name.split('-').last]
              next if mod.has_metadata? && mod.forge_name.tr('/', '-') == rel.name

              if rel.name != name
                dependency = {
                  :name => rel.name,
                  :version => rel.version
                }
              end

              raise InstallConflictError,
                :requested_module  => name,
                :requested_version => options[:version] || 'latest',
                :dependency        => dependency,
                :directory         => mod.path,
                :metadata          => mod.metadata
            end
          end

          child = releases.find { |x| x.name == name }

          unless forced?
            if child.version <= results[:installed_version]
              versions = graph.dependencies[name].map { |r| r.version }
              newer_versions = versions.select { |v| v > results[:installed_version] }

              raise VersionAlreadyInstalledError,
                :module_name       => name,
                :requested_version => results[:requested_version],
                :installed_version => results[:installed_version],
                :newer_versions    => newer_versions,
                :possible_culprits => installed_modules_source.fetched.reject { |x| x == name }
            end
          end

          Puppet.info "Preparing to upgrade ..."
          releases.each { |release| release.prepare }

          Puppet.notice 'Upgrading -- do not interrupt ...'
          releases.each do |release|
            if installed = installed_modules[release.name]
              release.install(Pathname.new(installed.mod.modulepath))
            else
              release.install(dir)
            end
          end

          results[:result] = :success
          results[:base_dir] = releases.first.install_dir
          results[:affected_modules] = releases
          results[:graph] = [ build_install_graph(releases.first, releases) ]

        rescue VersionAlreadyInstalledError => e
          results[:result] = (e.newer_versions.empty? ? :noop : :failure)
          results[:error] = { :oneline => e.message, :multiline => e.multiline }
        rescue => e
          results[:error] = {
            :oneline   => e.message,
            :multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
          }
        ensure
          results[:result] ||= :failure
        end

        results
      end

      private
      def module_repository
        @repo ||= Puppet::Forge.new
      end

      def installed_modules_source
        @installed ||= Puppet::ModuleTool::InstalledModules.new(@environment)
      end

      def installed_modules
        installed_modules_source.modules
      end

      def build_single_module_graph(name, version)
        range = Semantic::VersionRange.parse(version)
        graph = Semantic::Dependency::Graph.new(name => range)
        releases = Semantic::Dependency.fetch_releases(name)
        releases.each { |release| release.dependencies.clear }
        graph << releases
      end

      def build_dependency_graph(name, version)
        Semantic::Dependency.query(name => version)
      end

      def build_install_graph(release, installed, graphed = [])
        previous = installed_modules[release.name]
        previous = previous.version if previous

        action = :upgrade
        unless previous && previous != release.version
          action = :install
        end

        graphed << release

        dependencies = release.dependencies.values.map do |deps|
          dep = (deps & installed).first
          if dep == installed_modules[dep.name]
            next
          end

          if dep && !graphed.include?(dep)
            build_install_graph(dep, installed, graphed)
          end
        end.compact

        return {
          :release          => release,
          :name             => release.name,
          :path             => release.install_dir,
          :dependencies     => dependencies.compact,
          :version          => release.version,
          :previous_version => previous,
          :action           => action,
        }
      end

      include Puppet::ModuleTool::Shared
    end
  end
end


text:
"""
implementations of validation commands for YubiHSM
"""
# Copyright (c) 2011, Yubico AB
# All rights reserved.

import struct

__all__ = [
    # constants
    # functions
    # classes
    'YHSM_Cmd_AEAD_Validate_OTP',
    'YHSM_ValidationResult',
]

import pyhsm.defines
import pyhsm.exception
from pyhsm.aead_cmd import YHSM_AEAD_Cmd

class YHSM_Cmd_AEAD_Validate_OTP(YHSM_AEAD_Cmd):
    """
    Request the YubiHSM to validate an OTP using an externally stored AEAD.
    """

    response = None
    status = None

    def __init__(self, stick, public_id, otp, key_handle, aead):
        self.public_id = pyhsm.util.input_validate_nonce(public_id, pad = True)
        self.otp = pyhsm.util.input_validate_str(otp, 'otp', exact_len = pyhsm.defines.YSM_OTP_SIZE)
        self.key_handle = pyhsm.util.input_validate_key_handle(key_handle)
        aead = pyhsm.util.input_validate_aead(aead, expected_len = pyhsm.defines.YSM_YUBIKEY_AEAD_SIZE)
        # typedef struct {
        #   uint8_t publicId[YSM_PUBLIC_ID_SIZE];   // Public id (nonce)
        #   uint32_t keyHandle;                     // Key handle
        #   uint8_t otp[YSM_OTP_SIZE];              // OTP
        #   uint8_t aead[YSM_YUBIKEY_AEAD_SIZE];    // AEAD block
        # } YSM_AEAD_YUBIKEY_OTP_DECODE_REQ;
        fmt = "< %is I %is %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE, \
                                       pyhsm.defines.YSM_OTP_SIZE, \
                                       pyhsm.defines.YSM_YUBIKEY_AEAD_SIZE)
        packed = struct.pack(fmt, self.public_id, \
                                 self.key_handle, \
                                 self.otp, \
                                 aead)
        YHSM_AEAD_Cmd.__init__(self, stick, pyhsm.defines.YSM_AEAD_YUBIKEY_OTP_DECODE, packed)

    def parse_result(self, data):
        # typedef struct {
        #   uint8_t public_id[YSM_PUBLIC_ID_SIZE];   // Public id
        #   uint32_t keyHandle;                  // Key handle
        #   uint16_t use_ctr;                    // Use counter
        #   uint8_t session_ctr;                 // Session counter
        #   uint8_t tstph;                       // Timestamp (high part)
        #   uint16_t tstpl;                      // Timestamp (low part)
        #   YHSM_STATUS status;                  // Validation status
        # } YHSM_AEAD_OTP_DECODED_RESP;
        fmt = "< %is I H B B H B" % (pyhsm.defines.YSM_PUBLIC_ID_SIZE)
        public_id, \
            key_handle, \
            use_ctr, \
            session_ctr, \
            ts_high, \
            ts_low, \
            self.status = struct.unpack(fmt, data)

        pyhsm.util.validate_cmd_response_str('public_id', public_id, self.public_id)
        pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle)

        if self.status == pyhsm.defines.YSM_STATUS_OK:
            self.response = YHSM_ValidationResult(self.public_id, use_ctr, session_ctr, ts_high, ts_low)
            return self.response
        else:
            raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)

class YHSM_ValidationResult():
    """
    The result of a Validate operation.

    Contains the counters and timestamps decrypted from the OTP.
    """
    def __init__(self, public_id, use_ctr, session_ctr, ts_high, ts_low):
        self.public_id = public_id
        self.use_ctr = use_ctr
        self.session_ctr = session_ctr
        self.ts_high = ts_high
        self.ts_low = ts_low

    def __repr__(self):
        return '<%s instance at %s: public_id=%s, use_ctr=%i, session_ctr=%i, ts=%i/%i>' % (
            self.__class__.__name__,
            hex(id(self)),
            self.public_id.encode('hex'),
            self.use_ctr,
            self.session_ctr,
            self.ts_high,
            self.ts_low
            )


text:
var express = require('express');
var router = express.Router();

var fs = require('fs');
var carpool = require('../modules/carpool');

router.get('/', function(req, res, next) {

/*
	Getting the data object from readBookings function and
  passing the object to the JADE template.
*/

	carpool.readBookings(pushContent);

    console.log('Booking list as: ' + req.cookies.username);

    function pushContent(obj){

      // console.log('object from readBookings:\n\n' + JSON.stringify(obj));

      /* Filter based on logged in user.
         Show only the users bookings if normal user.
         Admin can see all. */

      if("admin" !== req.cookies.username){

        obj.bookings = obj.bookings.filter(function (el) {
          return el.userId == req.cookies.employeeNumber;
        });

        // console.log('New object from readBookings:\n\n' + JSON.stringify(obj));

      }

      /* Reverse order */

      obj.bookings.reverse();

    	res.render('bookings', {
          username: req.cookies.username,
        	title: 'BOKNINGAR',
        	bookings: obj
    	});

  	}
});

module.exports = router;


text:
Template.companyList.onCreated(function () {
    Session.set("company-word", "");
});

Template.companyList.helpers({
    filter: function () {
        const dict = {};
        if (Session.get("company-word")) {
            const regExpr = {$regex: Session.get("company-word"), $options: '-i'};
            dict["$or"] = [
                {name: regExpr},
                {short: regExpr}
            ]
        }
        return dict;
    }
});

Template.companyList.events({
    "input #iCompanyWord": _.debounce(function (e) {
        const value = e.target.value;
        if (!Session.equals("company-word", value)) {
            Session.set("company-word", value);
        }
    }, 300)

});


text:
package com.stackexchange.stacman;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

public final class Revision implements Serializable {
    private String body;
    public String getBody() {return body;}

    private String comment;
    public String getComment(){return comment;}

    private long creation_date;
    public Date getCreationDate(){return new Date(creation_date* 1000);}

    private boolean is_rollback;
    public boolean getIsRollback() {return is_rollback; }

    private String last_body;
    public String getLastBody(){return last_body;}

    private String[] last_tags;
    public String[] getLastTags(){return last_tags;}

    private String last_title;
    public String getLastTitle(){return last_title; }

    private int post_id;
    public int getPostId(){return post_id;}

    private String post_type;
    public PostType getPostType(){return StacManClient.parseEnum(PostType.class, post_type); }

    private String revision_guid;
    public UUID getRevisionGuid(){return UUID.fromString(revision_guid);}

    private int revision_number;
    public int getRevisionNumber() {return revision_number; }

    private String revision_type;
    public RevisionType getRevisionType(){return StacManClient.parseEnum(RevisionType.class, revision_type); }

    private boolean set_community_wiki;
    public boolean getSetCommunityWiki(){return set_community_wiki;}

    private String[] tags;
    public String[] getTags(){return tags;}

    private String title;
    public String getTitle(){return title;}

    private ShallowUser user;
    public ShallowUser getUser(){return user;}
}


text:
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.github.jwoehr</groupId>
    <artifactId>ublu</artifactId>
    <version>2.0.2-dev</version>
    <name>Ublu</name>
    <description>Ublu Midrange and Mainframe Life Cycle Extension Language</description>
    <url>https://github.com/jwoehr/ublu</url>
    <packaging>jar</packaging>
    <scm>
        <connection>scm:git:https://github.com/jwoehr/ublu</connection>
        <developerConnection>scm:git:https://github.com/jwoehr/ublu</developerConnection>
        <tag>HEAD</tag>
        <url>https://github.com/jwoehr/ublu</url>
    </scm>
    <developers>
        <developer>
            <id>jwoehr</id>
            <name>Jack Woehr</name>
            <email>jack@softwoehr.com</email>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
    </properties>
    <build>
        <defaultGoal>install</defaultGoal>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <version>3.3.1</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                    </configuration>
                    <executions>
                        <execution>
                            <id>attach-javadocs</id>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>3.2.0</version>
                    <executions>
                        <execution>
                            <id>attach-sources</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>jar-no-fork</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.9.0</version>
                    <configuration>
                        <source>8</source>
                        <target>8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.2.0</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>com.google.code.maven-replacer-plugin</groupId>
                    <artifactId>maven-replacer-plugin</artifactId>
                    <version>1.4.0</version>
                    <executions>
                        <execution>
                            <phase>process-sources</phase>
                            <goals>
                                <goal>replace</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <file>Version.java.tpl</file>
                        <outputFile>src/main/java/ublu/Version.java</outputFile>
                        <replacements>
                            <replacement>
                                <token>@ubluversion@</token>
                                <value>${project.version}</value>
                            </replacement>

                            <replacement>
                                <token>@timestamp@</token>
                                <value>${maven.build.timestamp}</value>
                            </replacement>
                        </replacements>
                    </configuration>
                </plugin>
                <!-- Allows the program to be built into a single executable jar -->
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <groupId>org.apache.maven.plugins</groupId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <mainClass>ublu.Ublu</mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-gpg-plugin</artifactId>
                    <version>3.0.1</version>
                    <executions>
                        <execution>
                            <id>sign-artifacts</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>sign</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <gpgArguments>
                            <arg>--pinentry-mode</arg>
                            <arg>loopback</arg>
                        </gpgArguments>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.sonatype.plugins</groupId>
                    <artifactId>nexus-staging-maven-plugin</artifactId>
                    <version>1.6.7</version>
                    <extensions>true</extensions>
                    <configuration>
                        <serverId>ossrh</serverId>
                        <nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
                        <autoReleaseAfterClose>true</autoReleaseAfterClose>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>com.google.code.maven-replacer-plugin</groupId>
                                        <artifactId>maven-replacer-plugin</artifactId>
                                        <versionRange>[0.0,)</versionRange>
                                        <goals>
                                            <goal>replace</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute>
                                            <runOnIncremental>true</runOnIncremental>
                                        </execute>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>

            <plugin>
                <groupId>com.google.code.maven-replacer-plugin</groupId>
                <artifactId>maven-replacer-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <groupId>org.apache.maven.plugins</groupId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
            </plugin>
        </plugins>
    </build>
    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
    </distributionManagement>
    <repositories>
        <repository>
            <id>my-local-repo</id>
            <url>file://${project.basedir}/lib</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>ublu.staticlib</groupId>
            <artifactId>pigiron</artifactId>
            <version>only</version>
        </dependency>
        <dependency>
            <groupId>ublu.staticlib</groupId>
            <artifactId>tn5250j</artifactId>
            <version>only</version>
        </dependency>
        <dependency>
            <groupId>ublu.staticlib</groupId>
            <artifactId>sblim-cim-client2-HEAD</artifactId>
            <version>only</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.jt400/jt400 -->
        <dependency>
            <groupId>net.sf.jt400</groupId>
            <artifactId>jt400</artifactId>
            <version>11.0</version>
        </dependency>
        <!--        <dependency>
            <groupId>ublu.staticlib</groupId>
            <artifactId>jt400</artifactId>
            <version>9.6-patched</version>
        </dependency>-->
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>11.2.1.jre8</version>
        </dependency>
    </dependencies>

</project>


text:
package com.google.cloud.spanner.jdbc;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.connection.AbstractSqlScriptVerifier;
import com.google.cloud.spanner.connection.AbstractStatementParser;
import com.google.cloud.spanner.connection.StatementResult.ResultType;
import com.google.rpc.Code;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/** SQL Script verifier for JDBC connections */
public class JdbcSqlScriptVerifier extends AbstractSqlScriptVerifier {

  static class JdbcGenericStatementResult extends GenericStatementResult {
    private final boolean result;
    private final long updateCount;
    private final ResultSet resultSet;

    private JdbcGenericStatementResult(Statement statement, boolean result) throws SQLException {
      this.result = result;
      if (result) {
        this.resultSet = statement.getResultSet();
        this.updateCount = -1L;
      } else {
        this.resultSet = null;
        this.updateCount = statement.getUpdateCount();
      }
    }

    @Override
    protected ResultType getResultType() {
      if (result) {
        return ResultType.RESULT_SET;
      }
      if (updateCount == -2L) {
        return ResultType.NO_RESULT;
      }
      return ResultType.UPDATE_COUNT;
    }

    @Override
    protected GenericResultSet getResultSet() {
      return new JdbcGenericResultSet(resultSet);
    }

    @Override
    protected long getUpdateCount() {
      return updateCount;
    }
  }

  static class JdbcGenericResultSet extends GenericResultSet {
    private final ResultSet resultSet;

    private JdbcGenericResultSet(ResultSet resultSet) {
      this.resultSet = resultSet;
    }

    @Override
    protected boolean next() throws SQLException {
      return resultSet.next();
    }

    @Override
    protected Object getValue(String col) throws SQLException {
      Object value = resultSet.getObject(col);
      if (value instanceof Timestamp) {
        return com.google.cloud.Timestamp.of((Timestamp) value);
      } else if (value instanceof Array) {
        Array array = (Array) value;
        if (array.getBaseType() == Types.BIGINT) {
          Long[] longs = (Long[]) array.getArray();
          List<Long> res = new ArrayList<>();
          Collections.addAll(res, longs);
          return res;
        }
        throw new IllegalArgumentException("Unsupported array base type: " + array.getBaseType());
      }
      return value;
    }

    @Override
    protected int getColumnCount() throws Exception {
      return resultSet.getMetaData().getColumnCount();
    }

    @Override
    protected Object getFirstValue() throws Exception {
      String col = resultSet.getMetaData().getColumnName(1);
      return getValue(col);
    }
  }

  public static class JdbcGenericConnection extends GenericConnection {
    private final CloudSpannerJdbcConnection connection;
    /**
     * Use this to strip comments from a statement before the statement is executed. This should
     * only be used when the connection is used in a unit test with a mocked underlying connection.
     */
    private boolean stripCommentsBeforeExecute;

    public static JdbcGenericConnection of(CloudSpannerJdbcConnection connection) {
      return new JdbcGenericConnection(connection);
    }

    private JdbcGenericConnection(CloudSpannerJdbcConnection connection) {
      this.connection = connection;
    }

    @Override
    protected GenericStatementResult execute(String sql) throws SQLException {
      Statement statement = connection.createStatement();
      if (isStripCommentsBeforeExecute()) {
        sql = AbstractStatementParser.getInstance(getDialect()).removeCommentsAndTrim(sql);
      }
      boolean result = statement.execute(sql);
      return new JdbcGenericStatementResult(statement, result);
    }

    @Override
    public void close() throws Exception {
      if (this.connection != null) {
        this.connection.close();
      }
    }

    boolean isStripCommentsBeforeExecute() {
      return stripCommentsBeforeExecute;
    }

    void setStripCommentsBeforeExecute(boolean stripCommentsBeforeExecute) {
      this.stripCommentsBeforeExecute = stripCommentsBeforeExecute;
    }

    @Override
    public Dialect getDialect() {
      return connection.getDialect();
    }
  }

  public JdbcSqlScriptVerifier() {}

  public JdbcSqlScriptVerifier(GenericConnectionProvider connectionProvider) {
    super(connectionProvider);
  }

  @Override
  protected void verifyExpectedException(
      String statement, Exception e, String code, String messagePrefix) {
    assertThat(e).isInstanceOf(JdbcSqlException.class);
    JdbcSqlException jdbcException = (JdbcSqlException) e;
    assertWithMessage(statement).that(jdbcException.getCode()).isEqualTo(Code.valueOf(code));
    if (messagePrefix != null) {
      assertWithMessage(statement)
          .that(e.getMessage())
          .startsWith(messagePrefix.substring(1, messagePrefix.length() - 1));
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.icaynia.pracler.activities.SongDetailsActivity"
    android:background="@color/colorFragmentBackground">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email"
        android:visibility="gone"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:background="@color/colorFragmentBackground"
        android:orientation="vertical">

        <include layout="@layout/view_profile_header"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>


text:
// 11 june 2016
#import "uipriv_darwin.h"

// TODO the assorted test doesn't work right at all

@interface gridChild : NSView
@property uiControl *c;
@property int left;
@property int top;
@property int xspan;
@property int yspan;
@property int hexpand;
@property uiAlign halign;
@property int vexpand;
@property uiAlign valign;

@property (strong) NSLayoutConstraint *leadingc;
@property (strong) NSLayoutConstraint *topc;
@property (strong) NSLayoutConstraint *trailingc;
@property (strong) NSLayoutConstraint *bottomc;
@property (strong) NSLayoutConstraint *xcenterc;
@property (strong) NSLayoutConstraint *ycenterc;

@property NSLayoutPriority oldHorzHuggingPri;
@property NSLayoutPriority oldVertHuggingPri;
- (void)setC:(uiControl *)c grid:(uiGrid *)g;
- (void)onDestroy;
- (NSView *)view;
@end

@interface gridView : NSView {
	uiGrid *g;
	NSMutableArray *children;
	int padded;

	NSMutableArray *edges;
	NSMutableArray *inBetweens;

	NSMutableArray *emptyCellViews;
}
- (id)initWithG:(uiGrid *)gg;
- (void)onDestroy;
- (void)removeOurConstraints;
- (void)syncEnableStates:(int)enabled;
- (CGFloat)paddingAmount;
- (void)establishOurConstraints;
- (void)append:(gridChild *)gc;
- (void)insert:(gridChild *)gc after:(uiControl *)c at:(uiAt)at;
- (int)isPadded;
- (void)setPadded:(int)p;
- (BOOL)hugsTrailing;
- (BOOL)hugsBottom;
- (int)nhexpand;
- (int)nvexpand;
@end

struct uiGrid {
	uiDarwinControl c;
	gridView *view;
};

@implementation gridChild

- (void)setC:(uiControl *)c grid:(uiGrid *)g
{
	self.c = c;
	self.oldHorzHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(self.c), NSLayoutConstraintOrientationHorizontal);
	self.oldVertHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(self.c), NSLayoutConstraintOrientationVertical);

	uiControlSetParent(self.c, uiControl(g));
	uiDarwinControlSetSuperview(uiDarwinControl(self.c), self);
	uiDarwinControlSyncEnableState(uiDarwinControl(self.c), uiControlEnabledToUser(uiControl(g)));

	if (self.halign == uiAlignStart || self.halign == uiAlignFill) {
		self.leadingc = mkConstraint(self, NSLayoutAttributeLeading,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeLeading,
			1, 0,
			@"uiGrid child horizontal alignment start constraint");
		[self addConstraint:self.leadingc];
	}
	if (self.halign == uiAlignCenter) {
		self.xcenterc = mkConstraint(self, NSLayoutAttributeCenterX,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeCenterX,
			1, 0,
			@"uiGrid child horizontal alignment center constraint");
		[self addConstraint:self.xcenterc];
	}
	if (self.halign == uiAlignEnd || self.halign == uiAlignFill) {
		self.trailingc = mkConstraint(self, NSLayoutAttributeTrailing,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeTrailing,
			1, 0,
			@"uiGrid child horizontal alignment end constraint");
		[self addConstraint:self.trailingc];
	}

	if (self.valign == uiAlignStart || self.valign == uiAlignFill) {
		self.topc = mkConstraint(self, NSLayoutAttributeTop,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeTop,
			1, 0,
			@"uiGrid child vertical alignment start constraint");
		[self addConstraint:self.topc];
	}
	if (self.valign == uiAlignCenter) {
		self.ycenterc = mkConstraint(self, NSLayoutAttributeCenterY,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeCenterY,
			1, 0,
			@"uiGrid child vertical alignment center constraint");
		[self addConstraint:self.ycenterc];
	}
	if (self.valign == uiAlignEnd || self.valign == uiAlignFill) {
		self.bottomc = mkConstraint(self, NSLayoutAttributeBottom,
			NSLayoutRelationEqual,
			[self view], NSLayoutAttributeBottom,
			1, 0,
			@"uiGrid child vertical alignment end constraint");
		[self addConstraint:self.bottomc];
	}
}

- (void)onDestroy
{
	if (self.leadingc != nil) {
		[self removeConstraint:self.leadingc];
		self.leadingc = nil;
	}
	if (self.topc != nil) {
		[self removeConstraint:self.topc];
		self.topc = nil;
	}
	if (self.trailingc != nil) {
		[self removeConstraint:self.trailingc];
		self.trailingc = nil;
	}
	if (self.bottomc != nil) {
		[self removeConstraint:self.bottomc];
		self.bottomc = nil;
	}
	if (self.xcenterc != nil) {
		[self removeConstraint:self.xcenterc];
		self.xcenterc = nil;
	}
	if (self.ycenterc != nil) {
		[self removeConstraint:self.ycenterc];
		self.ycenterc = nil;
	}

	uiControlSetParent(self.c, NULL);
	uiDarwinControlSetSuperview(uiDarwinControl(self.c), nil);
	uiDarwinControlSetHuggingPriority(uiDarwinControl(self.c), self.oldHorzHuggingPri, NSLayoutConstraintOrientationHorizontal);
	uiDarwinControlSetHuggingPriority(uiDarwinControl(self.c), self.oldVertHuggingPri, NSLayoutConstraintOrientationVertical);
}

- (NSView *)view
{
	return (NSView *) uiControlHandle(self.c);
}

@end

@implementation gridView

- (id)initWithG:(uiGrid *)gg
{
	self = [super initWithFrame:NSZeroRect];
	if (self != nil) {
		self->g = gg;
		self->padded = 0;
		self->children = [NSMutableArray new];

		self->edges = [NSMutableArray new];
		self->inBetweens = [NSMutableArray new];

		self->emptyCellViews = [NSMutableArray new];
	}
	return self;
}

- (void)onDestroy
{
	gridChild *gc;

	[self removeOurConstraints];
	[self->edges release];
	[self->inBetweens release];

	[self->emptyCellViews release];

	for (gc in self->children) {
		[gc onDestroy];
		uiControlDestroy(gc.c);
		[gc removeFromSuperview];
	}
	[self->children release];
}

- (void)removeOurConstraints
{
	NSView *v;

	if ([self->edges count] != 0) {
		[self removeConstraints:self->edges];
		[self->edges removeAllObjects];
	}
	if ([self->inBetweens count] != 0) {
		[self removeConstraints:self->inBetweens];
		[self->inBetweens removeAllObjects];
	}

	for (v in self->emptyCellViews)
		[v removeFromSuperview];
	[self->emptyCellViews removeAllObjects];
}

- (void)syncEnableStates:(int)enabled
{
	gridChild *gc;

	for (gc in self->children)
		uiDarwinControlSyncEnableState(uiDarwinControl(gc.c), enabled);
}

- (CGFloat)paddingAmount
{
	if (!self->padded)
		return 0.0;
	return uiDarwinPaddingAmount(NULL);
}

// LONGTERM stop early if all controls are hidden
- (void)establishOurConstraints
{
	gridChild *gc;
	CGFloat padding;
	int xmin, ymin;
	int xmax, ymax;
	int xcount, ycount;
	BOOL first;
	int **gg;
	NSView ***gv;
	BOOL **gspan;
	int x, y;
	int i;
	NSLayoutConstraint *c;
	int firstx, firsty;
	BOOL *hexpand, *vexpand;
	BOOL doit;
	BOOL onlyEmptyAndSpanning;

	[self removeOurConstraints];
	if ([self->children count] == 0)
		return;
	padding = [self paddingAmount];

	// first, figure out the minimum and maximum row and column numbers
	// ignore hidden controls
	first = YES;
	for (gc in self->children) {
		// this bit is important: it ensures row ymin and column xmin have at least one cell to draw, so the onlyEmptyAndSpanning logic below will never run on those rows
		if (!uiControlVisible(gc.c))
			continue;
		if (first) {
			xmin = gc.left;
			ymin = gc.top;
			xmax = gc.left + gc.xspan;
			ymax = gc.top + gc.yspan;
			first = NO;
			continue;
		}
		if (xmin > gc.left)
			xmin = gc.left;
		if (ymin > gc.top)
			ymin = gc.top;
		if (xmax < (gc.left + gc.xspan))
			xmax = gc.left + gc.xspan;
		if (ymax < (gc.top + gc.yspan))
			ymax = gc.top + gc.yspan;
	}
	if (first != NO)		// the entire grid is hidden; do nothing
		return;
	xcount = xmax - xmin;
	ycount = ymax - ymin;

	// now build a topological map of the grid gg[y][x]
	// also figure out which cells contain spanned views so they can be ignored later
	// treat hidden controls by keeping the indices -1
	gg = (int **) uiAlloc(ycount * sizeof (int *), "int[][]");
	gspan = (BOOL **) uiAlloc(ycount * sizeof (BOOL *), "BOOL[][]");
	for (y = 0; y < ycount; y++) {
		gg[y] = (int *) uiAlloc(xcount * sizeof (int), "int[]");
		gspan[y] = (BOOL *) uiAlloc(xcount * sizeof (BOOL), "BOOL[]");
		for (x = 0; x < xcount; x++)
			gg[y][x] = -1;		// empty
	}
	for (i = 0; i < [self->children count]; i++) {
		gc = (gridChild *) [self->children objectAtIndex:i];
		if (!uiControlVisible(gc.c))
			continue;
		for (y = gc.top; y < gc.top + gc.yspan; y++)
			for (x = gc.left; x < gc.left + gc.xspan; x++) {
				gg[y - ymin][x - xmin] = i;
				if (x != gc.left || y != gc.top)
					gspan[y - ymin][x - xmin] = YES;
			}
	}

	// if a row or column only contains emptys and spanning cells of a opposite-direction spannings, remove it by duplicating the previous row or column
	for (y = 0; y < ycount; y++) {
		onlyEmptyAndSpanning = YES;
		for (x = 0; x < xcount; x++)
			if (gg[y][x] != -1) {
				gc = (gridChild *) [self->children objectAtIndex:gg[y][x]];
				if (gc.yspan == 1 || gc.top - ymin == y) {
					onlyEmptyAndSpanning = NO;
					break;
				}
			}
		if (onlyEmptyAndSpanning)
			for (x = 0; x < xcount; x++) {
				gg[y][x] = gg[y - 1][x];
				gspan[y][x] = YES;
			}
	}
	for (x = 0; x < xcount; x++) {
		onlyEmptyAndSpanning = YES;
		for (y = 0; y < ycount; y++)
			if (gg[y][x] != -1) {
				gc = (gridChild *) [self->children objectAtIndex:gg[y][x]];
				if (gc.xspan == 1 || gc.left - xmin == x) {
					onlyEmptyAndSpanning = NO;
					break;
				}
			}
		if (onlyEmptyAndSpanning)
			for (y = 0; y < ycount; y++) {
				gg[y][x] = gg[y][x - 1];
				gspan[y][x] = YES;
			}
	}

	// now build a topological map of the grid's views gv[y][x]
	// for any empty cell, create a dummy view
	gv = (NSView ***) uiAlloc(ycount * sizeof (NSView **), "NSView *[][]");
	for (y = 0; y < ycount; y++) {
		gv[y] = (NSView **) uiAlloc(xcount * sizeof (NSView *), "NSView *[]");
		for (x = 0; x < xcount; x++)
			if (gg[y][x] == -1) {
				gv[y][x] = [[NSView alloc] initWithFrame:NSZeroRect];
				[gv[y][x] setTranslatesAutoresizingMaskIntoConstraints:NO];
				[self addSubview:gv[y][x]];
				[self->emptyCellViews addObject:gv[y][x]];
			} else {
				gc = (gridChild *) [self->children objectAtIndex:gg[y][x]];
				gv[y][x] = gc;
			}
	}

	// now figure out which rows and columns really expand
	hexpand = (BOOL *) uiAlloc(xcount * sizeof (BOOL), "BOOL[]");
	vexpand = (BOOL *) uiAlloc(ycount * sizeof (BOOL), "BOOL[]");
	// first, which don't span
	for (gc in self->children) {
		if (!uiControlVisible(gc.c))
			continue;
		if (gc.hexpand && gc.xspan == 1)
			hexpand[gc.left - xmin] = YES;
		if (gc.vexpand && gc.yspan == 1)
			vexpand[gc.top - ymin] = YES;
	}
	// second, which do span
	// the way we handle this is simple: if none of the spanned rows/columns expand, make all rows/columns expand
	for (gc in self->children) {
		if (!uiControlVisible(gc.c))
			continue;
		if (gc.hexpand && gc.xspan != 1) {
			doit = YES;
			for (x = gc.left; x < gc.left + gc.xspan; x++)
				if (hexpand[x - xmin]) {
					doit = NO;
					break;
				}
			if (doit)
				for (x = gc.left; x < gc.left + gc.xspan; x++)
					hexpand[x - xmin] = YES;
		}
		if (gc.vexpand && gc.yspan != 1) {
			doit = YES;
			for (y = gc.top; y < gc.top + gc.yspan; y++)
				if (vexpand[y - ymin]) {
					doit = NO;
					break;
				}
			if (doit)
				for (y = gc.top; y < gc.top + gc.yspan; y++)
					vexpand[y - ymin] = YES;
		}
	}

	// now establish all the edge constraints
	// leading and trailing edges
	for (y = 0; y < ycount; y++) {
		c = mkConstraint(self, NSLayoutAttributeLeading,
			NSLayoutRelationEqual,
			gv[y][0], NSLayoutAttributeLeading,
			1, 0,
			@"uiGrid leading edge constraint");
		[self addConstraint:c];
		[self->edges addObject:c];
		c = mkConstraint(self, NSLayoutAttributeTrailing,
			NSLayoutRelationEqual,
			gv[y][xcount - 1], NSLayoutAttributeTrailing,
			1, 0,
			@"uiGrid trailing edge constraint");
		[self addConstraint:c];
		[self->edges addObject:c];
	}
	// top and bottom edges
	for (x = 0; x < xcount; x++) {
		c = mkConstraint(self, NSLayoutAttributeTop,
			NSLayoutRelationEqual,
			gv[0][x], NSLayoutAttributeTop,
			1, 0,
			@"uiGrid top edge constraint");
		[self addConstraint:c];
		[self->edges addObject:c];
		c = mkConstraint(self, NSLayoutAttributeBottom,
			NSLayoutRelationEqual,
			gv[ycount - 1][x], NSLayoutAttributeBottom,
			1, 0,
			@"uiGrid bottom edge constraint");
		[self addConstraint:c];
		[self->edges addObject:c];
	}

	// now align leading and top edges
	// do NOT align spanning cells!
	for (x = 0; x < xcount; x++) {
		for (y = 0; y < ycount; y++)
			if (!gspan[y][x])
				break;
		firsty = y;
		for (y++; y < ycount; y++) {
			if (gspan[y][x])
				continue;
			c = mkConstraint(gv[firsty][x], NSLayoutAttributeLeading,
				NSLayoutRelationEqual,
				gv[y][x], NSLayoutAttributeLeading,
				1, 0,
				@"uiGrid column leading constraint");
			[self addConstraint:c];
			[self->edges addObject:c];
		}
	}
	for (y = 0; y < ycount; y++) {
		for (x = 0; x < xcount; x++)
			if (!gspan[y][x])
				break;
		firstx = x;
		for (x++; x < xcount; x++) {
			if (gspan[y][x])
				continue;
			c = mkConstraint(gv[y][firstx], NSLayoutAttributeTop,
				NSLayoutRelationEqual,
				gv[y][x], NSLayoutAttributeTop,
				1, 0,
				@"uiGrid row top constraint");
			[self addConstraint:c];
			[self->edges addObject:c];
		}
	}

	// now string adjacent views together
	for (y = 0; y < ycount; y++)
		for (x = 1; x < xcount; x++)
			if (gv[y][x - 1] != gv[y][x]) {
				c = mkConstraint(gv[y][x - 1], NSLayoutAttributeTrailing,
					NSLayoutRelationEqual,
					gv[y][x], NSLayoutAttributeLeading,
					1, -padding,
					@"uiGrid internal horizontal constraint");
				[self addConstraint:c];
				[self->inBetweens addObject:c];
			}
	for (x = 0; x < xcount; x++)
		for (y = 1; y < ycount; y++)
			if (gv[y - 1][x] != gv[y][x]) {
				c = mkConstraint(gv[y - 1][x], NSLayoutAttributeBottom,
					NSLayoutRelationEqual,
					gv[y][x], NSLayoutAttributeTop,
					1, -padding,
					@"uiGrid internal vertical constraint");
				[self addConstraint:c];
				[self->inBetweens addObject:c];
			}

	// now set priorities for all widgets that expand or not
	// if a cell is in an expanding row, OR If it spans, then it must be willing to stretch
	// otherwise, it tries not to
	// note we don't use NSLayoutPriorityRequired as that will cause things to squish when they shouldn't
	for (gc in self->children) {
		NSLayoutPriority priority;

		if (!uiControlVisible(gc.c))
			continue;
		if (hexpand[gc.left - xmin] || gc.xspan != 1)
			priority = NSLayoutPriorityDefaultLow;
		else
			priority = NSLayoutPriorityDefaultHigh;
		uiDarwinControlSetHuggingPriority(uiDarwinControl(gc.c), priority, NSLayoutConstraintOrientationHorizontal);
		// same for vertical direction
		if (vexpand[gc.top - ymin] || gc.yspan != 1)
			priority = NSLayoutPriorityDefaultLow;
		else
			priority = NSLayoutPriorityDefaultHigh;
		uiDarwinControlSetHuggingPriority(uiDarwinControl(gc.c), priority, NSLayoutConstraintOrientationVertical);
	}

	// TODO make all expanding rows/columns the same height/width

	// and finally clean up
	uiFree(hexpand);
	uiFree(vexpand);
	for (y = 0; y < ycount; y++) {
		uiFree(gg[y]);
		uiFree(gv[y]);
		uiFree(gspan[y]);
	}
	uiFree(gg);
	uiFree(gv);
	uiFree(gspan);
}

- (void)append:(gridChild *)gc
{
	BOOL update;
	int oldnh, oldnv;

	[gc setTranslatesAutoresizingMaskIntoConstraints:NO];
	[self addSubview:gc];

	// no need to set priority here; that's done in establishOurConstraints

	oldnh = [self nhexpand];
	oldnv = [self nvexpand];
	[self->children addObject:gc];

	[self establishOurConstraints];
	update = NO;
	if (gc.hexpand)
		if (oldnh == 0)
			update = YES;
	if (gc.vexpand)
		if (oldnv == 0)
			update = YES;
	if (update)
		uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->g));

	[gc release];		// we don't need the initial reference now
}

- (void)insert:(gridChild *)gc after:(uiControl *)c at:(uiAt)at
{
	gridChild *other;
	BOOL found;

	found = NO;
	for (other in self->children)
		if (other.c == c) {
			found = YES;
			break;
		}
	if (!found)
		userbug("Existing control %p is not in grid %p; you cannot add other controls next to it", c, self->g);

	switch (at) {
	case uiAtLeading:
		gc.left = other.left - gc.xspan;
		gc.top = other.top;
		break;
	case uiAtTop:
		gc.left = other.left;
		gc.top = other.top - gc.yspan;
		break;
	case uiAtTrailing:
		gc.left = other.left + other.xspan;
		gc.top = other.top;
		break;
	case uiAtBottom:
		gc.left = other.left;
		gc.top = other.top + other.yspan;
		break;
	// TODO add error checks to ALL enums
	}

	[self append:gc];
}

- (int)isPadded
{
	return self->padded;
}

- (void)setPadded:(int)p
{
	CGFloat padding;
	NSLayoutConstraint *c;

#if 0 /* TODO */
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC),
dispatch_get_main_queue(),
^{ [[self window] visualizeConstraints:[self constraints]]; }
);
#endif
	self->padded = p;
	padding = [self paddingAmount];
	for (c in self->inBetweens)
		switch ([c firstAttribute]) {
		case NSLayoutAttributeLeading:
		case NSLayoutAttributeTop:
			[c setConstant:padding];
			break;
		case NSLayoutAttributeTrailing:
		case NSLayoutAttributeBottom:
			[c setConstant:-padding];
			break;
		}
}

- (BOOL)hugsTrailing
{
	// only hug if we have horizontally expanding
	return [self nhexpand] != 0;
}

- (BOOL)hugsBottom
{
	// only hug if we have vertically expanding
	return [self nvexpand] != 0;
}

- (int)nhexpand
{
	gridChild *gc;
	int n;

	n = 0;
	for (gc in self->children) {
		if (!uiControlVisible(gc.c))
			continue;
		if (gc.hexpand)
			n++;
	}
	return n;
}

- (int)nvexpand
{
	gridChild *gc;
	int n;

	n = 0;
	for (gc in self->children) {
		if (!uiControlVisible(gc.c))
			continue;
		if (gc.vexpand)
			n++;
	}
	return n;
}

@end

static void uiGridDestroy(uiControl *c)
{
	uiGrid *g = uiGrid(c);

	[g->view onDestroy];
	[g->view release];
	uiFreeControl(uiControl(g));
}

uiDarwinControlDefaultHandle(uiGrid, view)
uiDarwinControlDefaultParent(uiGrid, view)
uiDarwinControlDefaultSetParent(uiGrid, view)
uiDarwinControlDefaultToplevel(uiGrid, view)
uiDarwinControlDefaultVisible(uiGrid, view)
uiDarwinControlDefaultShow(uiGrid, view)
uiDarwinControlDefaultHide(uiGrid, view)
uiDarwinControlDefaultEnabled(uiGrid, view)
uiDarwinControlDefaultEnable(uiGrid, view)
uiDarwinControlDefaultDisable(uiGrid, view)

static void uiGridSyncEnableState(uiDarwinControl *c, int enabled)
{
	uiGrid *g = uiGrid(c);

	if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(g), enabled))
		return;
	[g->view syncEnableStates:enabled];
}

uiDarwinControlDefaultSetSuperview(uiGrid, view)

static BOOL uiGridHugsTrailingEdge(uiDarwinControl *c)
{
	uiGrid *g = uiGrid(c);

	return [g->view hugsTrailing];
}

static BOOL uiGridHugsBottom(uiDarwinControl *c)
{
	uiGrid *g = uiGrid(c);

	return [g->view hugsBottom];
}

static void uiGridChildEdgeHuggingChanged(uiDarwinControl *c)
{
	uiGrid *g = uiGrid(c);

	[g->view establishOurConstraints];
}

uiDarwinControlDefaultHuggingPriority(uiGrid, view)
uiDarwinControlDefaultSetHuggingPriority(uiGrid, view)

static void uiGridChildVisibilityChanged(uiDarwinControl *c)
{
	uiGrid *g = uiGrid(c);

	[g->view establishOurConstraints];
}

static gridChild *toChild(uiControl *c, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign, uiGrid *g)
{
	gridChild *gc;

	if (xspan < 0)
		userbug("You cannot have a negative xspan in a uiGrid cell.");
	if (yspan < 0)
		userbug("You cannot have a negative yspan in a uiGrid cell.");
	gc = [gridChild new];
	gc.xspan = xspan;
	gc.yspan = yspan;
	gc.hexpand = hexpand;
	gc.halign = halign;
	gc.vexpand = vexpand;
	gc.valign = valign;
	[gc setC:c grid:g];
	return gc;
}

void uiGridAppend(uiGrid *g, uiControl *c, int left, int top, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign)
{
	gridChild *gc;

	// LONGTERM on other platforms
	// or at leat allow this and implicitly turn it into a spacer
	if (c == NULL)
		userbug("You cannot add NULL to a uiGrid.");
	gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign, g);
	gc.left = left;
	gc.top = top;
	[g->view append:gc];
}

void uiGridInsertAt(uiGrid *g, uiControl *c, uiControl *existing, uiAt at, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign)
{
	gridChild *gc;

	gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign, g);
	[g->view insert:gc after:existing at:at];
}

int uiGridPadded(uiGrid *g)
{
	return [g->view isPadded];
}

void uiGridSetPadded(uiGrid *g, int padded)
{
	[g->view setPadded:padded];
}

uiGrid *uiNewGrid(void)
{
	uiGrid *g;

	uiDarwinNewControl(uiGrid, g);

	g->view = [[gridView alloc] initWithG:g];

	return g;
}


text:
class ExtensionToolbarModel;
class Profile;

class ExtensionToolbarModelFactory : public BrowserContextKeyedServiceFactory {
 public:
  static ExtensionToolbarModel* GetForProfile(Profile* profile);

  static ExtensionToolbarModelFactory* GetInstance();

 private:
  friend struct DefaultSingletonTraits<ExtensionToolbarModelFactory>;

  ExtensionToolbarModelFactory();
  virtual ~ExtensionToolbarModelFactory();

  virtual KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* profile) const OVERRIDE;
  virtual content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const OVERRIDE;
  virtual bool ServiceIsCreatedWithBrowserContext() const OVERRIDE;
  virtual bool ServiceIsNULLWhileTesting() const OVERRIDE;
};

#endif  // CHROME_BROWSER_EXTENSIONS_EXTENSION_TOOLBAR_MODEL_FACTORY_H_


text:
layout: page
title: Flex Mesa International Award Ceremony
date: 2016-05-24
author: James Shaffer
tags: weekly links, java
status: published
summary: Aliquam quis rutrum lorem. Duis feugiat ultricies.
banner: images/banner/office-01.jpg
booking:
  startDate: 08/30/2019
  endDate: 09/02/2019
  ctyhocn: FLLANHX
  groupCode: FMIAC
published: true
---
Nam rhoncus erat ante, sit amet sodales purus viverra id. Duis sed commodo enim. Quisque augue ex, hendrerit quis laoreet non, imperdiet in ex. Donec metus arcu, laoreet sit amet imperdiet sed, dapibus nec metus. Nam eget luctus odio, sed interdum diam. Aenean sodales urna justo, at sodales odio tempor ac. Praesent vitae tincidunt enim. Vestibulum at libero vel ligula ornare sagittis finibus nec tellus. Morbi condimentum viverra sem, vitae malesuada tortor mollis id.
Cras aliquam turpis justo, non ornare sem mattis vel. Aliquam non semper lorem, quis congue ante. Pellentesque nec consequat ipsum. In hac habitasse platea dictumst. Curabitur imperdiet quam ex, ac condimentum tellus laoreet sed. Donec facilisis congue aliquet. Morbi nibh metus, euismod a sem ornare, consectetur posuere odio. Aenean luctus nunc nec massa venenatis iaculis. Vivamus congue felis vitae ligula rhoncus vehicula. Nunc a aliquam elit, a dictum libero. Pellentesque non mauris quis magna maximus tempor. Nam et rutrum elit, et vestibulum metus. Proin tincidunt porta ipsum eu ultrices.

* Cras porta dolor sed augue ultricies venenatis
* Curabitur faucibus metus quis dui mattis, sit amet faucibus mauris pulvinar
* Praesent dapibus odio eu elit pellentesque ornare
* Morbi hendrerit felis ac tellus varius lacinia
* Nam rutrum eros ut imperdiet elementum.

Vestibulum sodales viverra odio et ullamcorper. Morbi efficitur cursus enim eu iaculis. Suspendisse sodales, mauris vitae maximus pulvinar, ex diam laoreet mauris, at sollicitudin magna libero et massa. Nam eget sem id turpis bibendum varius. Proin in efficitur erat, vel imperdiet turpis. Ut volutpat nulla ac tortor sodales, vel placerat nisi pellentesque. Sed consequat justo euismod, consequat est quis, euismod metus.