text:
using KindergartentManagerment.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KindergartentManagerment.Areas.Admin.Controllers
{
    [Authorize]
    public class RoleController : Controller
    {
        ApplicationDbContext context = new ApplicationDbContext();
        public ApplicationUserManager userManager;

        [Authorize(Roles = "Admin")]
        public ActionResult RoleCreate()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleCreate(string roleName)
        {
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roleManager.Create(new IdentityRole(roleName));
                context.SaveChanges();
            }

            ViewBag.ResultMessage = "Role created successfully !";
            return RedirectToAction("RoleIndex", "Role");
        }

        [Authorize(Roles = "Admin")]
        public ActionResult RoleIndex()
        {
            List<string> roles;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roles = (from r in roleManager.Roles select r.Name).ToList();
            }

            return View(roles.ToList());
        }

        [Authorize(Roles = "Admin")]
        public ActionResult RoleDelete(string roleName)
        {
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var role = roleManager.FindByName(roleName);

                roleManager.Delete(role);
                context.SaveChanges();
            }

            ViewBag.ResultMessage = "Role deleted succesfully !";
            return RedirectToAction("RoleIndex", "Role");
        }

        [Authorize(Roles ="Admin")]
        public ActionResult RoleAddToUser(string id)
        {
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                users = (from u in userManager.Users select u.UserName).ToList();
                roles = (from r in roleManager.Roles select r.Name).ToList();
            }

            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View();
        }
        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string roleName, string userName)
        {
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                users = (from u in userManager.Users select u.UserName).ToList();

                var user = userManager.FindByName(userName);
                if (user == null)
                    throw new Exception("User not found!");

                var role = roleManager.FindByName(roleName);
                if (role == null)
                    throw new Exception("Role not found!");

                if (userManager.IsInRole(user.Id, role.Name))
                {
                    ViewBag.ResultMessage = "This user already has the role specified !";
                }
                else
                {
                    userManager.AddToRole(user.Id, role.Name);
                    context.SaveChanges();

                    ViewBag.ResultMessage = "Username added to the role succesfully !";
                }

                roles = (from r in roleManager.Roles select r.Name).ToList();
            }

            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetRoles(string userName)
        {
            if (!string.IsNullOrWhiteSpace(userName))
            {
                List<string> userRoles;
                List<string> roles;
                List<string> users;
                using (var context = new ApplicationDbContext())
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    var roleManager = new RoleManager<IdentityRole>(roleStore);

                    roles = (from r in roleManager.Roles select r.Name).ToList();

                    var userStore = new UserStore<ApplicationUser>(context);
                    var userManager = new UserManager<ApplicationUser>(userStore);

                    users = (from u in userManager.Users select u.UserName).ToList();

                    var user = userManager.FindByName(userName);
                    if (user == null)
                        throw new Exception("User not found!");

                    var userRoleIds = (from r in user.Roles select r.RoleId);
                    userRoles = (from id in userRoleIds
                                 let r = roleManager.FindById(id)
                                 select r.Name).ToList();
                }

                ViewBag.Roles = new SelectList(roles);
                ViewBag.Users = new SelectList(users);
                ViewBag.RolesForThisUser = userRoles;
            }

            return View("RoleAddToUser");
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteRoleForUser(string userName, string roleName)
        {
            List<string> userRoles;
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roles = (from r in roleManager.Roles select r.Name).ToList();

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);

                users = (from u in userManager.Users select u.UserName).ToList();

                var user = userManager.FindByName(userName);
                if (user == null)
                    throw new Exception("User not found!");

                if (userManager.IsInRole(user.Id, roleName))
                {
                    userManager.RemoveFromRole(user.Id, roleName);
                    context.SaveChanges();

                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                var userRoleIds = (from r in user.Roles select r.RoleId);
                userRoles = (from id in userRoleIds
                             let r = roleManager.FindById(id)
                             select r.Name).ToList();
            }

            ViewBag.RolesForThisUser = userRoles;
            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View("RoleAddToUser");
        }

    }
}


text:
    <title>{% block title %}{% endblock %}</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
          YOURDOMAIN.com

Blog

AnotherMenuLink

AndOneMoreMenuLink

        {% block content %}{% endblock %}

    {% load staticfiles %}

redpajama_set_name: RedPajamaGithub


text:
migration 2, :create_admin_user  do
  up do
    a = User.new(:login => 'admin', :email => 'asset@example.com', :name => "Admin User")
    a.password = a.password_confirmation = "admin"
    a.admin = true
    a.save()
    Merb.logger << "An admin user has been set up with user/pw = admin/admin"
    Merb.logger << "You should probably change that password."
  end
  down do
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#ff00ff00"
              android:orientation="horizontal">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="3dp"
            android:src="@mipmap/ic_launcher"/>

    <TextView
            android:id="@+id/notification_remoteviews_custom_txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="20dp"
            android:text="我是一个自定义通知哦~~"
            android:textColor="#ff000000"/>

</LinearLayout>


text:
package com.gzmelife.app.adapter;

import java.util.ArrayList;

import com.gzmelife.app.R;
import com.gzmelife.app.bean.LocalFoodMaterialLevelThree;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class FoodAdapter extends BaseAdapter {
	ViewHolder viewHolder;
	Context context;
	ArrayList<LocalFoodMaterialLevelThree> foodBeans;
	String TAG = "FoodAdapter";

	public FoodAdapter(Context context,
			ArrayList<LocalFoodMaterialLevelThree> foodBeans) {
		super();
		this.context = context;
		this.foodBeans = foodBeans;
	}

	@Override
	public int getCount() {

		return foodBeans.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.layout_lv_food, null);
			viewHolder.tv_name = (TextView) convertView
					.findViewById(R.id.tv_name);
			viewHolder.et_name = (EditText) convertView
					.findViewById(R.id.et_name);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.tv_name.setText(foodBeans.get(position).getName());
		if (!"".equals(foodBeans.get(position).getWeight())) {
			viewHolder.et_name
					.setText(foodBeans.get(position).getWeight() + "");
		}
		// viewHolder.et_name.setOnClickListener(l);
		// viewHolder.tv_name
		// .setOnFocusChangeListener(new OnFocusChangeListener() {
		//
		// @Override
		// public void onFocusChange(View v, boolean hasFocus) {
		// EditText et = (EditText) v;
		// if(!hasFocus){
		//
		// System.out.println(">>>>============");
		// }
		// }
		//
		// });
		// viewHolder.et_name.setText(foodBeans.get(position).getWeight() + "");
		viewHolder.et_name.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				// if (foodBeans.get(position).getWeight() == 0) {
				// // viewHolder.et_name.setText("0");
				// // } else {
				// viewHolder.et_name.setText("");
				// }
				if (viewHolder.et_name.getText().toString().equals("0")) {
					viewHolder.et_name.setText("");
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

				if (s.equals("0")) {
					viewHolder.et_name.setText("");
				}else{
					 String string = viewHolder.et_name.getText().toString();
				}

			}
		});
		Log.i(TAG, String.valueOf(foodBeans.get(position).getId()));
		return convertView;
	}

	class ViewHolder {
		TextView tv_name;
		EditText et_name;
	}

}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Infrastructure.TestHelpers;

namespace Squidex.Infrastructure;

public class DomainObjectExceptionTests
{
    [Fact]
    public void Should_serialize_and_deserialize_DomainException()
    {
        var source = new DomainException("Message", "ErrorCode");
        var actual = source.SerializeAndDeserializeBinary();

        Assert.Equal(actual.ErrorCode, source.ErrorCode);
        Assert.Equal(actual.Message, source.Message);
    }

    [Fact]
    public void Should_serialize_and_deserialize_DomainObjectDeletedException()
    {
        var source = new DomainObjectDeletedException("123");
        var actual = source.SerializeAndDeserializeBinary();

        Assert.Equal(actual.Id, source.Id);
        Assert.Equal(actual.Message, source.Message);
    }

    [Fact]
    public void Should_serialize_and_deserialize_DomainObjectNotFoundException()
    {
        var source = new DomainObjectNotFoundException("123");
        var actual = source.SerializeAndDeserializeBinary();

        Assert.Equal(actual.Id, source.Id);
        Assert.Equal(actual.Message, source.Message);
    }

    [Fact]
    public void Should_serialize_and_deserialize_DomainObjectVersionExceptionn()
    {
        var source = new DomainObjectVersionException("123", 100, 200);
        var actual = source.SerializeAndDeserializeBinary();

        Assert.Equal(actual.Id, source.Id);
        Assert.Equal(actual.ExpectedVersion, source.ExpectedVersion);
        Assert.Equal(actual.CurrentVersion, source.CurrentVersion);
        Assert.Equal(actual.Message, source.Message);
    }
}


text:
require "anvil/helpers"
require "anvil/manifest"
require "distributor/client"
require "listen"
require "pathname"

# run your local code on heroku
#
class Heroku::Command::Start < Heroku::Command::Base

  include Anvil::Helpers

  PROTOCOL_COMMAND_HEADER = "\000\042\000"
  PROTOCOL_COMMAND_EXIT   = 1

  # start [DIR]
  #
  # start a development dyno on development app APP
  #
  # -b, --buildpack    # use a custom buildpack
  # -e, --runtime-env  # use the runtime env
  #
  def index
    dir = Pathname.new(File.expand_path(shift_argument || ".")).realpath.to_s
    app = options[:app] || error("Must specify a development app with -a")
    validate_arguments!

    user = api.post_login("", Heroku::Auth.password).body["email"]

    Anvil.append_agent "interface=start user=#{user} app=#{app}"

    slug_url = Anvil::Engine.build(dir, :buildpack => options[:buildpack])

    action("Preparing development dyno on #{app}") do
      heroku.release(app, "Initial development dyno sync", :slug_url => development_dyno_slug_url){
        print "."
        $stdout.flush
      }
    end

    build_env = {
      "ANVIL_HOST"    => ENV["ANVIL_HOST"] || "https://api.anvilworks.org",
      "BUILDPACK_URL" => prepare_buildpack(options[:buildpack]),
      "SLUG_URL"      => slug_url
    }

    develop_options = build_env.inject({}) do |ax, (key, val)|
      ax.update("ps_env[#{key}]" => val)
    end

    process = action("Starting development dyno") do
      status "http://localhost:9000"
      run_attached app, "bin/development-dyno", develop_options
    end

    client_to_dyno = pipe
    dyno_to_client = pipe

    client = Distributor::Client.new(dyno_to_client.first, client_to_dyno.last)

    client.on_hello do
      client.run("/app/vendor/bundle/ruby/1.9.1/bin/foreman start -c -p 5000") do |ch|
        client.hookup ch, $stdin.dup, $stdout.dup
        client.on_close(ch) { shutdown(app, process["process"]) }
      end

      start_file_watcher   client, dir
      start_console_server client, dir
      start_http_tunnel    client, 5000, 9000
    end

    client.on_command do |command, data|
      case command
      when /file.*/
        # sync complete messages
      when "error"
        error data["message"]
      end
    end

    Thread.abort_on_exception = true

    rendezvous = Heroku::Client::Rendezvous.new(
      :rendezvous_url => process["rendezvous_url"],
      :connect_timeout => 120,
      :activity_timeout => nil,
      :input => client_to_dyno.first,
      :output => dyno_to_client.last
    )

    rendezvous.on_connect do
      Thread.new { client.start }
    end

    Signal.trap("INT") do
      shutdown(app, process["process"])
    end

    begin
      $stdin.sync = $stdout.sync = true
      set_buffer false
      rendezvous.start
    rescue Timeout::Error
      error "\nTimeout awaiting process"
    rescue Errno::ECONNREFUSED, Errno::ECONNRESET, OpenSSL::SSL::SSLError
      error "\nError connecting to process"
    rescue Interrupt
    ensure
      set_buffer true
    end
  end

  # start:console
  #
  # get a console into your development dyno
  #
  def console
    connector = Distributor::Connector.new
    console   = TCPSocket.new("localhost", read_anvil_metadata(".", "console.port").to_i)

    set_buffer false

    connector.handle(console) do |io|
      $stdout.write io.readpartial(4096)
      $stdout.flush
    end

    connector.handle($stdin.dup) do |io|
      console.write io.readpartial(4096)
      console.flush
    end

    connector.on_close(console) do
      exit 0
    end

    connector.on_close($stdin.dup) do |io|
      exit 0
    end

    loop { connector.listen }
  rescue Errno::ECONNREFUSED
    error "Unable to connect to development dyno"
  ensure
    set_buffer true
  end

private

  def development_dyno_slug_url
    ENV["DEVELOPMENT_DYNO_SLUG_URL"] || "https://api.anvilworks.org/slugs/889a67b1-fc71-11e1-97c4-e57ab9695538.tgz"
  end

  def run_attached(app, command, options={})
    process_data = api.post_ps(app, command, { :attach => true }.merge(options)).body
    process_data
  end

  def upload_manifest(name, dir)
    manifest = Heroku::Manifest.new(dir)

    action("Synchronizing local files") do
      count = manifest.upload
    end

    manifest
  end

  def prepare_buildpack(buildpack_url)
    return "https://buildkit.herokuapp.com/buildkit/default.tgz" unless buildpack_url
    return buildpack_url unless File.exists?(buildpack_url) && File.directory?(buildpack_url)
    manifest = upload_manifest("buildpack", buildpack_url)
    manifest.save
  end

  def process_commands(chunk)
    if location = chunk.index(PROTOCOL_COMMAND_HEADER)
      buffer = StringIO.new(chunk[location..-1])
      header = buffer.read(3)
      case command = buffer.read(1).ord
      when PROTOCOL_COMMAND_EXIT then
        code = buffer.read(1).ord
        unless code.zero?
          puts "ERROR: Build exited with code: #{code}"
          exit code
        end
      else
        puts "unknown[#{command}]"
      end
      chunk = chunk[0..location-1]
    end
    chunk
  end

  def pipe
    IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY")
  end

  def shutdown(app, process)
    # api.post_ps_stop app, :ps => process
    exit 0
  end

  def upload_file(dir, file, client)
    return if ignore_file?(File.join(dir, file))
    manifest = Anvil::Manifest.new
    full_filename = File.join(dir, file)
    manifest.add full_filename
    manifest.upload manifest.missing
    hash = manifest.manifest[full_filename]["hash"]
    client.command "file.download", "name" => file, "hash" => hash
  end

  def remove_file(dir, file, client)
    return if ignore_file?(File.join(dir, file))
    client.command "file.delete", "name" => file
  end

  def ignore_file?(file)
    return true unless File.exists?(file)
    return true if File.stat(file).pipe?
    return true if file =~ /\.swp/
    return true if file =~ /\.anvil/
    false
  end

  def start_file_watcher(client, dir)
    Thread.new do
      listener = Listen.to(dir)
      listener.change do |modified, added, removed|
        modified.concat(added).each do |file|
          relative = file[dir.length+1..-1]
          upload_file dir, relative, client
        end
        removed.each do |file|
          relative = file[dir.length+1..-1]
          remove_file dir, relative, client
        end
      end
      listener.latency(1.5)
      listener.polling_fallback_message("")
      listener.force_polling(true)
      listener.start
    end
  end

  def start_console_server(client, dir)
    Thread.new do
      console_server = TCPServer.new(0)
      write_anvil_metadata dir, "console.port", console_server.addr[1]
      loop do
        Thread.start(console_server.accept) do |console_client|
          client.run("env TERM=xterm bash") do |ch|
            client.hookup ch, console_client
            client.on_close(ch) { console_client.close }
          end
        end
      end
    end
  end

  def start_http_tunnel(client, remote_port=5000, local_port=9000)
    Thread.new do
      http_tunnel = TCPServer.new(local_port)
      loop do
        Thread.start(http_tunnel.accept) do |tunnel_client|
          client.tunnel(remote_port) do |ch|
            client.hookup ch, tunnel_client
          end
        end
      end
    end
  end

end

class Heroku::Client::Rendezvous
  def fixup(data)
    data
  end
end


text:
package com.zutubi.services.mail.rest.client.apis;

import javax.ws.rs.client.Client;

/**
 *
 */
public class AbstractRestAPI {

    private Client client;
    private String baseUri;

    public AbstractRestAPI(Client client, String baseUri) {
        this.client = client;
        this.baseUri = baseUri;
    }

    protected final Client getClient() {
        return client;
    }

    protected final String getBaseUri() {
        return baseUri;
    }
}


text:
namespace Futura::Core
{

class CEngineModule;

class CEngine : public IEngine
{
public:
	CEngine();
    ~CEngine();

	CEngine(const CEngine&) = delete;
	CEngine& operator=(const CEngine&) = delete;

	void Init(SEngineDesc& engineDesc);
	void Destroy();

    void Start();
    void Shutdown();

    void Update();

    bool IsRunning() {return true;}

	void Wait();

    template <class T>
    void RegisterModuleType(const char*name)
    {
        static_assert(std::is_base_of<CEngineModule, T>::value,
			"CEngine::RegisterModule doesn't accept this type "
			"because it doesn't derive from CEngineModule");

		ActorSystem.RegisterActorType<T>(name);
    }

private:
	ActorSystem::CActorSystem ActorSystem;
	CRendererSystem RendererSystem;
}; // class CEngine

} // namespace Futura::Core


text:
// $Id: heap_array.h,v 1.1.1.1 2007/11/05 19:10:18 jpolastre Exp $

/* Authors:             Philip Levis
 *
 */

/*
 *   FILE: heap.h
 * AUTHOR: pal
 *   DESC: Simple array-based priority heap for discrete event simulation.
 */

/**
 * @author pal
 * @author Philip Levis
 */

#ifndef HEAP_H_INCLUDED
#define HEAP_H_INCLUDED

typedef struct {
  int size;
  void* data;
  int private_size;
} heap_t;

void init_heap(heap_t* heap);
int heap_size(heap_t* heap);
int heap_is_empty(heap_t* heap);

long long heap_get_min_key(heap_t* heap);
void* heap_peek_min_data(heap_t* heap);
void* heap_pop_min_data(heap_t* heap, long long* key);
void heap_insert(heap_t * heap, void* data, long long key);

#endif // HEAP_H_INCLUDED


text:
package com.computing.cloud.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.computing.cloud.dao.InstanceRepository;
import com.computing.cloud.domain.Instance;
import com.computing.cloud.service.InstanceService;

@Service
@Transactional
public class InstanceServiceImpl implements InstanceService {

	@Autowired
	private InstanceRepository instanceRepository;

	@Override
	public Instance findById(Long id) {
		return instanceRepository.findOne(id);
	}

	@Override
	public List<Instance> findAll() {
		return (List<Instance>) instanceRepository.findAll();
	}

}


text:
//
//  Copyright 2010-2017 Deveel
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

using System;

using Deveel.Data.Sql.Expressions;

namespace Deveel.Data.Sql.Parsing {
	class SqlParseFunctionArgument {
		public string Id { get; set; }

		public SqlExpression Expression { get; set; }

		public static SqlParseFunctionArgument Form(IContext context, PlSqlParser.ArgumentContext argument) {
			if (argument == null)
				return null;

			var id = SqlParseName.Simple(argument.id());
			var exp = Parsing.SqlParseExpression.Build(context, argument.expressionWrapper());

			return new SqlParseFunctionArgument {
				Id = id,
				Expression = exp
			};
		}
	}
}


text:
package gval

import (
	"context"
	"fmt"
	"text/scanner"
	"unicode"

	"github.com/shopspring/decimal"
)

// Language is an expression language
type Language struct {
	prefixes        map[interface{}]extension
	operators       map[string]operator
	operatorSymbols map[rune]struct{}
	init            extension
	def             extension
	selector        func(Evaluables) Evaluable
}

// NewLanguage returns the union of given Languages as new Language.
func NewLanguage(bases ...Language) Language {
	l := newLanguage()
	for _, base := range bases {
		for i, e := range base.prefixes {
			l.prefixes[i] = e
		}
		for i, e := range base.operators {
			l.operators[i] = e.merge(l.operators[i])
			l.operators[i].initiate(i)
		}
		for i := range base.operatorSymbols {
			l.operatorSymbols[i] = struct{}{}
		}
		if base.init != nil {
			l.init = base.init
		}
		if base.def != nil {
			l.def = base.def
		}
		if base.selector != nil {
			l.selector = base.selector
		}
	}
	return l
}

func newLanguage() Language {
	return Language{
		prefixes:        map[interface{}]extension{},
		operators:       map[string]operator{},
		operatorSymbols: map[rune]struct{}{},
	}
}

// NewEvaluable returns an Evaluable for given expression in the specified language
func (l Language) NewEvaluable(expression string) (Evaluable, error) {
	return l.NewEvaluableWithContext(context.Background(), expression)
}

// NewEvaluableWithContext returns an Evaluable for given expression in the specified language using context
func (l Language) NewEvaluableWithContext(c context.Context, expression string) (Evaluable, error) {
	p := newParser(expression, l)

	eval, err := p.parse(c)
	if err == nil && p.isCamouflaged() && p.lastScan != scanner.EOF {
		err = p.camouflage
	}
	if err != nil {
		pos := p.scanner.Pos()
		return nil, fmt.Errorf("parsing error: %s - %d:%d %s", p.scanner.Position, pos.Line, pos.Column, err)
	}

	return eval, nil
}

// Evaluate given parameter with given expression
func (l Language) Evaluate(expression string, parameter interface{}) (interface{}, error) {
	return l.EvaluateWithContext(context.Background(), expression, parameter)
}

// Evaluate given parameter with given expression using context
func (l Language) EvaluateWithContext(c context.Context, expression string, parameter interface{}) (interface{}, error) {
	eval, err := l.NewEvaluableWithContext(c, expression)
	if err != nil {
		return nil, err
	}
	v, err := eval(c, parameter)
	if err != nil {
		return nil, fmt.Errorf("can not evaluate %s: %v", expression, err)
	}
	return v, nil
}

// Function returns a Language with given function.
// Function has no conversion for input types.
//
// If the function returns an error it must be the last return parameter.
//
// If the function has (without the error) more then one return parameter,
// it returns them as []interface{}.
func Function(name string, function interface{}) Language {
	l := newLanguage()
	l.prefixes[name] = func(c context.Context, p *Parser) (eval Evaluable, err error) {
		args := []Evaluable{}
		scan := p.Scan()
		switch scan {
		case '(':
			args, err = p.parseArguments(c)
			if err != nil {
				return nil, err
			}
		default:
			p.Camouflage("function call", '(')
		}
		return p.callFunc(toFunc(function), args...), nil
	}
	return l
}

// Constant returns a Language with given constant
func Constant(name string, value interface{}) Language {
	l := newLanguage()
	l.prefixes[l.makePrefixKey(name)] = func(c context.Context, p *Parser) (eval Evaluable, err error) {
		return p.Const(value), nil
	}
	return l
}

// PrefixExtension extends a Language
func PrefixExtension(r rune, ext func(context.Context, *Parser) (Evaluable, error)) Language {
	l := newLanguage()
	l.prefixes[r] = ext
	return l
}

// Init is a language that does no parsing, but invokes the given function when
// parsing starts. It is incumbent upon the function to call ParseExpression to
// continue parsing.
//
// This function can be used to customize the parser settings, such as
// whitespace or ident behavior.
func Init(ext func(context.Context, *Parser) (Evaluable, error)) Language {
	l := newLanguage()
	l.init = ext
	return l
}

// DefaultExtension is a language that runs the given function if no other
// prefix matches.
func DefaultExtension(ext func(context.Context, *Parser) (Evaluable, error)) Language {
	l := newLanguage()
	l.def = ext
	return l
}

// PrefixMetaPrefix chooses a Prefix to be executed
func PrefixMetaPrefix(r rune, ext func(context.Context, *Parser) (call string, alternative func() (Evaluable, error), err error)) Language {
	l := newLanguage()
	l.prefixes[r] = func(c context.Context, p *Parser) (Evaluable, error) {
		call, alternative, err := ext(c, p)
		if err != nil {
			return nil, err
		}
		if prefix, ok := p.prefixes[l.makePrefixKey(call)]; ok {
			return prefix(c, p)
		}
		return alternative()
	}
	return l
}

//PrefixOperator returns a Language with given prefix
func PrefixOperator(name string, e Evaluable) Language {
	l := newLanguage()
	l.prefixes[l.makePrefixKey(name)] = func(c context.Context, p *Parser) (Evaluable, error) {
		eval, err := p.ParseNextExpression(c)
		if err != nil {
			return nil, err
		}
		prefix := func(c context.Context, v interface{}) (interface{}, error) {
			a, err := eval(c, v)
			if err != nil {
				return nil, err
			}
			return e(c, a)
		}
		if eval.IsConst() {
			v, err := prefix(c, nil)
			if err != nil {
				return nil, err
			}
			prefix = p.Const(v)
		}
		return prefix, nil
	}
	return l
}

// PostfixOperator extends a Language.
func PostfixOperator(name string, ext func(context.Context, *Parser, Evaluable) (Evaluable, error)) Language {
	l := newLanguage()
	l.operators[l.makeInfixKey(name)] = postfix{
		f: func(c context.Context, p *Parser, eval Evaluable, pre operatorPrecedence) (Evaluable, error) {
			return ext(c, p, eval)
		},
	}
	return l
}

// InfixOperator for two arbitrary values.
func InfixOperator(name string, f func(a, b interface{}) (interface{}, error)) Language {
	return newLanguageOperator(name, &infix{arbitrary: f})
}

// InfixShortCircuit operator is called after the left operand is evaluated.
func InfixShortCircuit(name string, f func(a interface{}) (interface{}, bool)) Language {
	return newLanguageOperator(name, &infix{shortCircuit: f})
}

// InfixTextOperator for two text values.
func InfixTextOperator(name string, f func(a, b string) (interface{}, error)) Language {
	return newLanguageOperator(name, &infix{text: f})
}

// InfixNumberOperator for two number values.
func InfixNumberOperator(name string, f func(a, b float64) (interface{}, error)) Language {
	return newLanguageOperator(name, &infix{number: f})
}

// InfixDecimalOperator for two decimal values.
func InfixDecimalOperator(name string, f func(a, b decimal.Decimal) (interface{}, error)) Language {
	return newLanguageOperator(name, &infix{decimal: f})
}

// InfixBoolOperator for two bool values.
func InfixBoolOperator(name string, f func(a, b bool) (interface{}, error)) Language {
	return newLanguageOperator(name, &infix{boolean: f})
}

// Precedence of operator. The Operator with higher operatorPrecedence is evaluated first.
func Precedence(name string, operatorPrecendence uint8) Language {
	return newLanguageOperator(name, operatorPrecedence(operatorPrecendence))
}

// InfixEvalOperator operates on the raw operands.
// Therefore it cannot be combined with operators for other operand types.
func InfixEvalOperator(name string, f func(a, b Evaluable) (Evaluable, error)) Language {
	return newLanguageOperator(name, directInfix{infixBuilder: f})
}

func newLanguageOperator(name string, op operator) Language {
	op.initiate(name)
	l := newLanguage()
	l.operators[l.makeInfixKey(name)] = op
	return l
}

func (l *Language) makePrefixKey(key string) interface{} {
	runes := []rune(key)
	if len(runes) == 1 && !unicode.IsLetter(runes[0]) {
		return runes[0]
	}
	return key
}

func (l *Language) makeInfixKey(key string) string {
	for _, r := range key {
		l.operatorSymbols[r] = struct{}{}
	}
	return key
}

// VariableSelector returns a Language which uses given variable selector.
// It must be combined with a Language that uses the vatiable selector. E.g. gval.Base().
func VariableSelector(selector func(path Evaluables) Evaluable) Language {
	l := newLanguage()
	l.selector = selector
	return l
}


text:
package nam.model.configuration;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import nam.ui.design.AbstractDomainTreeManager;
import nam.ui.tree.ModelTreeNode;

import org.aries.Assert;
import org.richfaces.model.TreeNode;

@SessionScoped
@Named("configurationTreeManager")
@SuppressWarnings("serial")
public class ConfigurationTreeManager extends AbstractDomainTreeManager implements Serializable {

	private ModelTreeNode configurationTreeRootNode;

	private ModelTreeNode configurationTreeSelectedNode;

	protected ConfigurationTreeBuilder configurationTreeBuilder;

	private String rerenderList;

	public ConfigurationTreeManager() {
		configurationTreeBuilder = new ConfigurationTreeBuilder();
	}

	@Override
	public String getTreeId() {
		return "configurationTree";
	}

	@Override
	public ModelTreeNode getRootNode() {
		return configurationTreeRootNode;
	}

	@Override
	public TreeNode getNodeById(String nodeId) {
		return configurationTreeBuilder.getNodeById(nodeId);
	}

	public String getRerenderList() {
		return rerenderList;
	}

	public void setRerenderList(String rerenderList) {
		this.rerenderList = rerenderList;
	}

	@Override
	public void refreshModel() {
		//TODO ModelTreeNode rootNode = configurationTreeBuilder.createTree(projects);
		//TODO configurationTreeRootNode = rootNode;
	}

	public String saveSelection() {
		if (configurationTreeSelectedNode != null) {
			Assert.notNull(configurationTreeSelectedNode, "An configuration must be selected");
			//ModelTreeObject<?> data = configurationTreeSelectedNode.getData();
			//TODO Configuration configuration = (Configuration) data.getObject();
			//TODO selectionListener.handle(configuration);
		}
		return null;
	}

}


text:
ActiveRecord::Schema.define(:version => 20110605071315) do

  create_table "activities", :force => true do |t|
    t.integer  "user_id"
    t.string   "event_name"
    t.integer  "target_id"
    t.text     "data"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "project_id"
  end

  create_table "comments", :force => true do |t|
    t.integer  "issue_id"
    t.integer  "user_id"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "documents", :force => true do |t|
    t.integer  "project_id"
    t.integer  "user_id"
    t.string   "title"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "images", :force => true do |t|
    t.string   "file"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "issue_assignments", :force => true do |t|
    t.integer  "issue_id"
    t.integer  "user_id"
    t.integer  "position"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "issues", :force => true do |t|
    t.integer  "project_id"
    t.string   "title"
    t.text     "content"
    t.string   "workflow_state"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.string   "label"
    t.integer  "milestone_id"
    t.date     "planned_date"
  end

  create_table "milestones", :force => true do |t|
    t.integer  "project_id"
    t.string   "name"
    t.date     "due_date"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "projects", :force => true do |t|
    t.integer  "user_id"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "todo_items", :force => true do |t|
    t.integer  "issue_id"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "workflow_state"
    t.integer  "position"
  end

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.string   "encrypted_password"
    t.string   "salt"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "persistence_token"
    t.string   "locale"
    t.string   "role"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true

end


text:
using UnityEngine;
using System.Collections;

namespace Strategies {
	public class IdleAction : AIAction {
		public static readonly IdleAction Default = new IdleAction();
	}

	public class Idle : AIStrategy<IdleAction> {
		void Update () {
			// do nothing...
		}
	}
}


text:
function Models () {
	var mongoose = require('mongoose');
	var bcrypt = require('bcrypt-nodejs');
	mongoose.connect('mongodb://localhost/GetMeToClassDb');

	var db = mongoose.connect;
	//declare basic user schema below
	var userSchema = mongoose.Schema({
		name: String,
		password: String
	});

	userSchema.methods.generateHash = function (password){
		return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
	};
	userSchema.methods.validPassword = function (password){
		return bcrypt.compareSync(password, this.local.password);
	};
	var User = mogosose.model('User', userSchema);
}
module.exports = Models;


text:
template < typename T >
class BaseDlg : public CDialogImpl<T>
{
public:
    BaseDlg()
    {
        m_strAppName = CStringBundle::GetInst().Get(_T("TITLE"));
    }
    ~BaseDlg()
    {
        ;
    }

    int MsgBox(LPCTSTR szText, DWORD dwFlags)
    {
        return ::MessageBox(m_hWnd, szText, m_strAppName, dwFlags);
    }

private:
    CString m_strAppName;
};


text:
if __name__ == '__main__':
    import instance_occlsegm_lib
    dataset = instance_occlsegm_lib.datasets.apc.arc2017.JskARC2017DatasetV3(
        'train', aug='none')
    instance_occlsegm_lib.datasets.view_class_seg_dataset(dataset)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.taverna.scufl2.xml.t2flow.jaxb.StandardWSDLSecurityProfile (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)</title>
<meta name="date" content="2016-03-14">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.taverna.scufl2.xml.t2flow.jaxb.StandardWSDLSecurityProfile

Packages that use StandardWSDLSecurityProfile

Package
Description

org.apache.taverna.scufl2.xml.t2flow.jaxb

Uses of StandardWSDLSecurityProfile in org.apache.taverna.scufl2.xml.t2flow.jaxb

Methods in org.apache.taverna.scufl2.xml.t2flow.jaxb that return StandardWSDLSecurityProfile

Modifier and Type
Method and Description

static StandardWSDLSecurityProfile
StandardWSDLSecurityProfile.fromValue(String v)

static StandardWSDLSecurityProfile
StandardWSDLSecurityProfile.valueOf(String name)

Returns the enum constant of this type with the specified name.

static StandardWSDLSecurityProfile[]
StandardWSDLSecurityProfile.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015–2016 The Apache Software Foundation. All rights reserved.


text:
import { NotificationData, DataChangeNotification, EventNotificationList } from "node-opcua-types";
import { Variant, DataType } from "node-opcua-variant";
import { IBasicSession } from "node-opcua-pseudo-session";
import { promoteOpaqueStructure } from "./promote_opaque_structure";

export async function promoteOpaqueStructureInNotificationData(
    session: IBasicSession,
    notificationData: NotificationData[]
): Promise<void> {
    const dataValuesToPromote: { value: Variant }[] = [];
    for (const notification of notificationData) {
        if (!notification) {
            continue;
        }
        if (notification instanceof DataChangeNotification) {
            if (notification.monitoredItems) {
                for (const monitoredItem of notification.monitoredItems) {
                    if (monitoredItem.value.value && monitoredItem.value.value.dataType === DataType.ExtensionObject) {
                        dataValuesToPromote.push(monitoredItem.value);
                    }
                }
            }
        } else if (notification instanceof EventNotificationList) {
            if (notification.events) {
                for (const events of notification.events) {
                    if (events.eventFields) {
                        // eslint-disable-next-line max-depth
                        for (const eventField of events.eventFields) {
                            // eslint-disable-next-line max-depth
                            if (eventField.dataType === DataType.ExtensionObject) {
                                dataValuesToPromote.push({ value: eventField });
                            }
                        }
                    }
                }
            }
        }
    }
    await promoteOpaqueStructure(session, dataValuesToPromote);
}


text:
package net.sf.jasperreports.export;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: SimpleOdtExporterConfiguration.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class SimpleOdtExporterConfiguration extends SimpleExporterConfiguration implements OdtExporterConfiguration
{
}


text:
CXX = g++
LIB = ar cr

CXXFLAGS = -O3 -DGONA_FOR_MAC -I../../../src/foundation \
		-I../../../src/foundation/graphics \
		-I../../../src/foundation/graphics/gl \
		-I../../../src/foundation/third_party/agg/include \
		-I../../../src/foundation/third_party/agg/font_freetype \
		-I../../../src/foundation/third_party/freetype/include \
		-I../../../src/foundation/third_party/png \
		-L../

SRC_DIR=../../../src/foundation

SRC_CXX=\
$(SRC_DIR)/graphics/GnCanvas.cpp \
$(SRC_DIR)/graphics/GnImageLoader_png.cpp \
$(SRC_DIR)/graphics/GnImage.cpp \
$(SRC_DIR)/graphics/agg/GnAggRenderer.cpp \
$(SRC_DIR)/graphics/agg/GnBitmap.cpp \
$(SRC_DIR)/graphics/gl/GnGLRenderer.cpp \
$(SRC_DIR)/graphics/gl/GnGLFontManager.cpp \
$(SRC_DIR)/graphics/native/GnRendererFactory_mac.cpp \
$(SRC_DIR)/third_party/agg/font_freetype/agg_font_freetype.cpp

OBJ=$(SRC_CXX:.cpp=.o)

%.o: %.cpp
	$(CXX) -c $(CXXFLAGS) $*.cpp -o $@

all:	$(OBJ)
	$(LIB) libgona_foundation.a $(OBJ)

clean:
	rm -f *.a
	rm -f $(SRC_DIR)/*.o
	rm -f $(SRC_DIR)/graphics/*.o
	rm -f $(SRC_DIR)/graphics/agg/*.o
	rm -f $(SRC_DIR)/graphics/gl/*.o
	rm -f $(SRC_DIR)/graphics/native/*.o


text:
namespace ui {

WaylandZcrColorManagementOutput::WaylandZcrColorManagementOutput(
    WaylandOutput* wayland_output,
    zcr_color_management_output_v1* color_management_output)
    : wayland_output_(wayland_output),
      zcr_color_management_output_(color_management_output) {
  DCHECK(color_management_output);
  static const zcr_color_management_output_v1_listener listener = {
      &WaylandZcrColorManagementOutput::OnColorSpaceChanged,
      &WaylandZcrColorManagementOutput::OnExtendedDynamicRange,
  };

  zcr_color_management_output_v1_add_listener(
      zcr_color_management_output_.get(), &listener, this);
}

WaylandZcrColorManagementOutput::~WaylandZcrColorManagementOutput() = default;

void WaylandZcrColorManagementOutput::OnColorSpaceDone(
    const gfx::ColorSpace& color_space) {
  gfx_color_space_ = std::make_unique<gfx::ColorSpace>(color_space);
  // Notify WaylandScreen that the output has been updated, so it will check for
  // the new ColorSpace.
  wayland_output_->TriggerDelegateNotifications();
}

// static
void WaylandZcrColorManagementOutput::OnColorSpaceChanged(
    void* data,
    struct zcr_color_management_output_v1* cmo) {
  WaylandZcrColorManagementOutput* zcr_color_management_output =
      static_cast<WaylandZcrColorManagementOutput*>(data);
  DCHECK(zcr_color_management_output);

  // request new color space
  zcr_color_management_output->color_space_ =
      base::MakeRefCounted<WaylandZcrColorSpace>(
          zcr_color_management_output_v1_get_color_space(
              zcr_color_management_output->zcr_color_management_output_.get()));

  zcr_color_management_output->color_space_->SetColorSpaceDoneCallback(
      base::BindOnce(&WaylandZcrColorManagementOutput::OnColorSpaceDone,
                     zcr_color_management_output->weak_factory_.GetWeakPtr()));
}
// static
void WaylandZcrColorManagementOutput::OnExtendedDynamicRange(
    void* data,
    struct zcr_color_management_output_v1* cmo,
    uint32_t value) {
  NOTIMPLEMENTED_LOG_ONCE();
}

}  // namespace ui


text:
#pragma once

#include "WdtBase.h"
#include "FileCreator.h"
#include "ErrorCodes.h"
#include "WdtOptions.h"
#include "Reporting.h"
#include "ServerSocket.h"
#include "Protocol.h"
#include "Writer.h"
#include "Throttler.h"
#include "TransferLogManager.h"
#include <memory>
#include <string>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <chrono>

namespace facebook {
namespace wdt {
/**
 * Receiver is the receiving side of the transfer. Receiver listens on ports
 * accepts connections, receives the files and writes to the destination
 * directory. Receiver has two modes of operation : You can spawn a receiver
 * for one transfer or alternatively it can also be used in a long running
 * mode where it accepts subsequent transfers and runs in an infinite loop.
 */
class Receiver : public WdtBase {
 public:
  /// Constructor using wdt transfer request (@see in WdtBase.h)
  explicit Receiver(const WdtTransferRequest &transferRequest);

  /**
   * Constructor with start port, number of ports and directory to write to.
   * If the start port is specified as zero, it auto configures the ports
   */
  Receiver(int port, int numSockets, const std::string &destDir);

  /// Setup before starting (@see WdtBase.h)
  WdtTransferRequest init() override;

  /**
   * Joins on the threads spawned by start. This method
   * is called by default when the wdt receiver is expected
   * to run as forever running process. However this has to
   * be explicitly called when the caller expects to conclude
   * a transfer.
   */
  std::unique_ptr<TransferReport> finish() override;

  /**
   * Call this method instead of transferAsync() when you don't
   * want the wdt receiver to stop after one transfer.
   */
  ErrorCode runForever();

  /**
   * Starts the threads, and returns. Caller should call finish() after
   * calling this method to get the statistics of the transfer.
   */
  ErrorCode transferAsync() override;

  /// Setter for the directory where the files received are written to
  void setDir(const std::string &destDir);

  /// Get the dir where receiver is transferring
  const std::string &getDir();

  /// @param recoveryId   unique-id used to verify transfer log
  void setRecoveryId(const std::string &recoveryId);

  /**
   * Destructor for the receiver. The destructor automatically cancels
   * any incomplete transfers that are going on. 'Incomplete transfer' is a
   * transfer where there is no receiver thread that has received
   * confirmation from wdt sender that the transfer is 'DONE'. Destructor also
   * internally calls finish() for every transfer if finish() wasn't called
   */
  virtual ~Receiver();

  /**
   * Take a lock on the instance mutex and return the value of
   * whether the existing transfer has been finished
   */
  bool hasPendingTransfer();

  /**
   * Use the method to get the list of ports receiver is listening on
   */
  std::vector<int32_t> getPorts() const;

 protected:
  /**
   * @param isFinished         Mark transfer active/inactive
   */
  void markTransferFinished(bool isFinished);

  /**
   * Wdt receiver has logic to maintain the consistency of the
   * transfers through connection errors. All threads are run by the logic
   * defined as a state machine. These are the all the states in that
   * state machine
   */
  enum ReceiverState {
    LISTEN,
    ACCEPT_FIRST_CONNECTION,
    ACCEPT_WITH_TIMEOUT,
    SEND_LOCAL_CHECKPOINT,
    READ_NEXT_CMD,
    PROCESS_FILE_CMD,
    PROCESS_EXIT_CMD,
    PROCESS_SETTINGS_CMD,
    PROCESS_DONE_CMD,
    PROCESS_SIZE_CMD,
    SEND_FILE_CHUNKS,
    SEND_GLOBAL_CHECKPOINTS,
    SEND_DONE_CMD,
    SEND_ABORT_CMD,
    WAIT_FOR_FINISH_OR_NEW_CHECKPOINT,
    WAIT_FOR_FINISH_WITH_THREAD_ERROR,
    FAILED,
    END
  };

  /**
   * Structure to pass data to the state machine and also to share data between
   * different state
   */
  struct ThreadData {
    /// Index of the thread that this data belongs to
    const int threadIndex_;

    /**
     * Server socket object that provides functionality such as listen()
     * accept, read, write on the socket
     */
    ServerSocket &socket_;

    /// Statistics of the transfer for this thread
    TransferStats &threadStats_;

    /// protocol version for this thread. This per thread protocol version is
    /// kept separately from the global one to avoid locking
    int threadProtocolVersion_;

    /// Buffer that receivers reads data into from the network
    std::unique_ptr<char[]> buf_;
    /// Maximum size of the buffer
    const int64_t bufferSize_;

    /// Marks the number of bytes already read in the buffer
    int64_t numRead_{0};

    /// Following two are markers to mark how much data has been read/parsed
    int64_t off_{0};
    int64_t oldOffset_{0};

    /// Number of bytes written for the current block
    int64_t curBlockWrittenBytes_{0};

    /// number of checkpoints already transferred
    int checkpointIndex_{0};

    /**
     * Pending value of checkpoint count. Since write call success does not
     * guarantee actual transfer, we do not apply checkpoint count update after
     * the write. Only after receiving next cmd from sender, we apply the
     * update
     */
    int pendingCheckpointIndex_{0};

    /// a counter incremented each time a new session starts for this thread
    int64_t transferStartedCount_{0};

    /// a counter incremented each time a new session ends for this thread
    int64_t transferFinishedCount_{0};

    /// read timeout for sender
    int64_t senderReadTimeout_{-1};

    /// write timeout for sender
    int64_t senderWriteTimeout_{-1};

    /// whether checksum verification is enabled or not
    bool enableChecksum_{false};

    /**
     * Whether SEND_DONE_CMD state has already failed for this session or not.
     * This has to be separately handled, because session barrier is
     * implemented before sending done cmd
     */
    bool doneSendFailure_{false};

    /// Checkpoints that have not been sent back to the sender
    std::vector<Checkpoint> newCheckpoints_;

    /// Constructor for thread data
    ThreadData(int threadIndex, ServerSocket &socket,
               TransferStats &threadStats, int protocolVersion,
               int64_t bufferSize)
        : threadIndex_(threadIndex),
          socket_(socket),
          threadStats_(threadStats),
          threadProtocolVersion_(protocolVersion),
          bufferSize_(bufferSize) {
      buf_.reset(new char[bufferSize_]);
    }

    /**
     * In long running mode, we need to reset thread variables after each
     * session. Before starting each session, reset() has to called to do that.
     */
    void reset() {
      numRead_ = off_ = 0;
      checkpointIndex_ = pendingCheckpointIndex_ = 0;
      doneSendFailure_ = false;
      senderReadTimeout_ = senderWriteTimeout_ = -1;
      threadStats_.reset();
    }

    /// Get the raw pointer to the buffer
    char *getBuf() {
      return buf_.get();
    }
  };

  /// Overloaded operator for printing thread info
  friend std::ostream &operator<<(std::ostream &os, const ThreadData &data);

  typedef ReceiverState (Receiver::*StateFunction)(ThreadData &data);

  /**
   * Tries to listen/bind to port. If this fails, thread is considered failed.
   * Previous states : n/a (start state)
   * Next states : ACCEPT_FIRST_CONNECTION(success),
   *               FAILED(failure)
   */
  ReceiverState listen(ThreadData &data);
  /**
   * Tries to accept first connection of a new session. Periodically checks
   * whether a new session has started or not. If a new session has started then
   * goes to ACCEPT_WITH_TIMEOUT state. Also does session initialization. In
   * joinable mode, tries to accept for a limited number of user specified
   * retries.
   * Previous states : LISTEN,
   *                   END(if in long running mode)
   * Next states : ACCEPT_WITH_TIMEOUT(if a new transfer has started and this
   *               thread has not received a connection),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(if did not receive a
   *               connection in specified number of retries),
   *               READ_NEXT_CMD(if a connection was received)
   */
  ReceiverState acceptFirstConnection(ThreadData &data);
  /**
   * Tries to accept a connection with timeout. There are 2 kinds of timeout. At
   * the beginning of the session, it uses accept window as the timeout. Later
   * when sender settings are known it uses max(readTimeOut, writeTimeout)) +
   * buffer(500) as the timeout.
   * Previous states : Almost all states(for any network errors during transfer,
   *                   we transition to this state),
   * Next states : READ_NEXT_CMD(if there are no previous errors and accept
   *               was successful),
   *               SEND_LOCAL_CHECKPOINT(if there were previous errors and
   *               accept was successful),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(if accept failed and
   *               transfer previously failed during SEND_DONE_CMD state. Thus
   *               case needs special handling to ensure that we do not mess up
   *               session variables),
   *               END(if accept fails otherwise)
   */
  ReceiverState acceptWithTimeout(ThreadData &data);
  /**
   * Sends local checkpoint to the sender. In case of previous error during
   * SEND_LOCAL_CHECKPOINT state, we send -1 as the checkpoint.
   * Previous states : ACCEPT_WITH_TIMEOUT
   * Next states : ACCEPT_WITH_TIMEOUT(if sending fails),
   *               SEND_DONE_CMD(if send is successful and we have previous
   *               SEND_DONE_CMD error),
   *               READ_NEXT_CMD(if send is successful otherwise)
   */
  ReceiverState sendLocalCheckpoint(ThreadData &data);
  /**
   * Reads next cmd and transitions to the state accordingly.
   * Previous states : SEND_LOCAL_CHECKPOINT,
   *                   ACCEPT_FIRST_CONNECTION,
   *                   ACCEPT_WITH_TIMEOUT,
   *                   PROCESS_SETTINGS_CMD,
   *                   PROCESS_FILE_CMD,
   *                   SEND_GLOBAL_CHECKPOINTS,
   * Next states : PROCESS_FILE_CMD,
   *               PROCESS_EXIT_CMD,
   *               PROCESS_DONE_CMD,
   *               PROCESS_SETTINGS_CMD,
   *               PROCESS_SIZE_CMD,
   *               ACCEPT_WITH_TIMEOUT(in case of read failure),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(in case of protocol errors)
   */
  ReceiverState readNextCmd(ThreadData &data);
  /**
   * Processes exit cmd. Wdt standalone or any application will exit after
   * reaching this state
   * Previous states : READ_NEXT_CMD
   * Next states :
   */
  ReceiverState processExitCmd(ThreadData &data);
  /**
   * Processes file cmd. Logic of how we write the file to the destination
   * directory is defined here.
   * Previous states : READ_NEXT_CMD
   * Next states : READ_NEXT_CMD(success),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(protocol error),
   *               ACCEPT_WITH_TIMEOUT(socket read failure)
   */
  ReceiverState processFileCmd(ThreadData &data);
  /**
   * Processes settings cmd. Settings has a connection settings,
   * protocol version, transfer id, etc. For more info check Protocol.h
   * Previous states : READ_NEXT_CMD,
   * Next states : READ_NEXT_CMD(success),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(protocol error),
   *               ACCEPT_WITH_TIMEOUT(socket read failure),
   *               SEND_FILE_CHUNKS(If the sender wants to resume transfer)
   */
  ReceiverState processSettingsCmd(ThreadData &data);
  /**
   * Processes done cmd. Also checks to see if there are any new global
   * checkpoints or not
   * Previous states : READ_NEXT_CMD,
   * Next states : WAIT_FOR_FINISH_OR_ERROR(protocol error),
   *               WAIT_FOR_FINISH_OR_NEW_CHECKPOINT(success),
   *               SEND_GLOBAL_CHECKPOINTS(if there are global errors)
   */
  ReceiverState processDoneCmd(ThreadData &data);
  /**
   * Processes size cmd. Sets the value of totalSenderBytes_
   * Previous states : READ_NEXT_CMD,
   * Next states : READ_NEXT_CMD(success),
   *               WAIT_FOR_FINISH_WITH_THREAD_ERROR(protocol error)
   */
  ReceiverState processSizeCmd(ThreadData &data);
  /**
   * Sends file chunks that were received successfully in any previous transfer,
   * this is the first step in download resumption.
   * Checks to see if they have already been transferred or not.
   * If yes, send ACK. If some other thread is sending it, sends wait cmd
   * and checks again later. Otherwise, breaks the entire data into bufferSIze_
   * chunks and sends it.
   * Previous states: PROCESS_SETTINGS_CMD,
   * Next states : ACCEPT_WITH_TIMEOUT(network error),
   *               READ_NEXT_CMD(success)
   */
  ReceiverState sendFileChunks(ThreadData &data);
  /**
   * Sends global checkpoints to sender
   * Previous states : PROCESS_DONE_CMD,
   *                   WAIT_FOR_FINISH_OR_ERROR
   * Next states : READ_NEXT_CMD(success),
   *               ACCEPT_WITH_TIMEOUT(socket write failure)
   */
  ReceiverState sendGlobalCheckpoint(ThreadData &data);
  /**
   * Sends DONE to sender, also tries to read back ack. If anything fails during
   * this state, doneSendFailure_ thread variable is set. This flag makes the
   * state machine behave differently, effectively bypassing all session related
   * things.
   * Previous states : SEND_LOCAL_CHECKPOINT,
   *                   WAIT_FOR_FINISH_OR_ERROR
   * Next states : END(success),
   *               ACCEPT_WITH_TIMEOUT(failure)
   */
  ReceiverState sendDoneCmd(ThreadData &data);

  /**
   * Sends ABORT cmd back to the sender
   * Previous states : PROCESS_FILE_CMD
   * Next states : WAIT_FOR_FINISH_WITH_THREAD_ERROR
   */
  ReceiverState sendAbortCmd(ThreadData &data);

  /**
   * Waits for transfer to finish or new checkpoints. This state first
   * increments waitingThreadCount_. Then, it
   * waits till all the threads have finished. It sends periodic WAIT signal to
   * prevent sender from timing out. If a new checkpoint is found, we move to
   * SEND_GLOBAL_CHECKPOINTS state.
   * Previous states : PROCESS_DONE_CMD
   * Next states : SEND_DONE_CMD(all threads finished),
   *               SEND_GLOBAL_CHECKPOINTS(if new checkpoints are found),
   *               ACCEPT_WITH_TIMEOUT(if socket write fails)
   */
  ReceiverState waitForFinishOrNewCheckpoint(ThreadData &data);

  /**
   * Waits for transfer to finish. Only called when there is an error for the
   * thread. It adds a checkpoint to the global list of checkpoints if a
   * connection was received. It increments waitingWithErrorThreadCount_ and
   * waits till the session ends.
   * Previous states : Almost all states
   * Next states : END
   */
  ReceiverState waitForFinishWithThreadError(ThreadData &data);

  /// Mapping from receiver states to state functions
  static const StateFunction stateMap_[];

  /// Responsible for basic setup and starting threads
  void start();

  /// This method is the entry point for each thread.
  void receiveOne(int threadIndex, ServerSocket &s, int64_t bufferSize,
                  TransferStats &threadStats);

  /**
   * Periodically calculates current transfer report and send it to progress
   * reporter. This only works in the single transfer mode.
   */
  void progressTracker();

  /**
   * Adds a checkpoint to the global checkpoint list
   * @param checkpoint    checkpoint to be added
   */
  void addCheckpoint(Checkpoint checkpoint);

  /**
   * @param startIndex    number of checkpoints already transferred by the
   *                      calling thread
   * @return              list of new checkpoints
   */
  std::vector<Checkpoint> getNewCheckpoints(int startIndex);

  /// Returns true if all threads finished for this session
  bool areAllThreadsFinished(bool checkpointAdded);

  /// Ends current global session
  void endCurGlobalSession();

  /**
   * Returns if a new session has started and the thread is not aware of it
   * A thread must hold lock on mutex_ before calling this
   */
  bool hasNewSessionStarted(ThreadData &data);

  /**
   * Start new transfer by incrementing transferStartedCount_
   * A thread must hold lock on mutex_ before calling this
   */
  void startNewGlobalSession(ThreadData &data);

  /**
   * Returns whether the current session has finished or not.
   * A thread must hold lock on mutex_ before calling this
   */
  bool hasCurSessionFinished(ThreadData &data);

  /// Starts a new session for the thread
  void startNewThreadSession(ThreadData &data);

  /// Ends current thread session
  void endCurThreadSession(ThreadData &data);

  /// Increments failed thread count, does not wait for transfer to finish
  void incrFailedThreadCountAndCheckForSessionEnd(ThreadData &data);

  /**
   * Get transfer report, meant to be called after threads have been finished
   * This method is not thread safe
   */
  std::unique_ptr<TransferReport> getTransferReport();

  /// The thread that is responsible for calling running the progress tracker
  std::thread progressTrackerThread_;
  /**
   * Flags that represents if a transfer has finished. Threads on completion
   * set this flag. This is always accurate even if you don't call finish()
   * No transfer can be started as long as this flag is false.
   */
  bool transferFinished_{true};

  /// Flag based on which threads finish processing on receiving a done
  bool isJoinable_{false};

  /// Destination directory where the received files will be written
  std::string destDir_;

  /// Responsible for writing files on the disk
  std::unique_ptr<FileCreator> fileCreator_;

  /**
   * Unique-id used to verify transfer log. This value must be same for
   * transfers across resumption
   */
  std::string recoveryId_;

  /**
   * Progress tracker thread is a thread which has to be joined when the
   * transfer is finished. The root thread in finish() and the progress
   * tracker coordinate with each other through the boolean and this
   * condition variable.
   */
  std::condition_variable conditionRecvFinished_;

  /**
   * The instance of the receiver threads are stored in this vector.
   * This will not be destroyed until this object is destroyed, hence
   * it has to be made sure that these threads are joined at least before
   * the destruction of this object.
   */
  std::vector<std::thread> receiverThreads_;

  /**
   * start() gives each thread the instance of the serversocket, these
   * sockets can be closed and changed completely by the progress tracker
   * thread thus ending any hope of receiver threads doing any further
   * successful transfer
   */
  std::vector<ServerSocket> threadServerSockets_;

  /**
   * Bunch of stats objects given to each thread by the root thread
   * so that finish() can summarize the result at the end of joining.
   */
  std::vector<TransferStats> threadStats_;

  /// Per thread perf report
  std::vector<PerfStatReport> perfReports_;

  /// Transfer log manager
  TransferLogManager transferLogManager_;

  /// Enum representing status of file chunks transfer
  enum SendChunkStatus { NOT_STARTED, IN_PROGRESS, SENT };

  /// State of the receiver when sending file chunks in sendFileChunksCmd
  SendChunkStatus sendChunksStatus_{NOT_STARTED};

  /**
   * All threads coordinate with each other to send previously received file
   * chunks using this condition variable.
   */
  mutable std::condition_variable conditionFileChunksSent_;

  /// Number of blocks sent by the sender
  int64_t numBlocksSend_{-1};

  /// Global list of checkpoints
  std::vector<Checkpoint> checkpoints_;

  /// Number of threads which failed in the transfer
  int failedThreadCount_{0};

  /// Number of threads which are waiting for finish or new checkpoint
  int waitingThreadCount_{0};

  /// Number of threads which are waiting with an error
  int waitingWithErrorThreadCount_{0};

  /// Counter that is incremented each time a new session starts
  int64_t transferStartedCount_{0};

  /// Counter that is incremented each time a new session ends
  int64_t transferFinishedCount_{0};

  /// Total number of data bytes sender wants to transfer
  int64_t totalSenderBytes_{-1};

  /// Start time of the session
  std::chrono::time_point<Clock> startTime_;

  /// Mutex to guard all the shared variables
  mutable std::mutex mutex_;

  /// Condition variable to coordinate transfer finish
  mutable std::condition_variable conditionAllFinished_;

  /**
   * Returns true if threads have been joined (done in finish())
   * This is how destructor determines whether it should join threads
   */
  bool areThreadsJoined_{false};

  /// Number of active threads, decremented every time a thread is finished
  int32_t numActiveThreads_{0};

  /**
   * Mutex for the management of this instance, specifically to keep the
   * instance sane for multi threaded public API calls
   */
  std::mutex instanceManagementMutex_;
};
}
}  // namespace facebook::wdt


text:
package jobs;

import models.Usuario;
import play.jobs.*;
import play.mvc.Before;
import play.test.Fixtures;

@OnApplicationStart
public class Bootstrap extends Job {

	public void doJob() {
        if(Usuario.count() == 0){
            Fixtures.loadModels("initial-data.yml");
        }
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.appcomplianceautomation.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Indicates the control family type. */
public final class ControlFamilyType extends ExpandableStringEnum<ControlFamilyType> {
    /** Static value FullyAutomated for ControlFamilyType. */
    public static final ControlFamilyType FULLY_AUTOMATED = fromString("FullyAutomated");

    /** Static value PartiallyAutomated for ControlFamilyType. */
    public static final ControlFamilyType PARTIALLY_AUTOMATED = fromString("PartiallyAutomated");

    /** Static value Manual for ControlFamilyType. */
    public static final ControlFamilyType MANUAL = fromString("Manual");

    /**
     * Creates or finds a ControlFamilyType from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ControlFamilyType.
     */
    @JsonCreator
    public static ControlFamilyType fromString(String name) {
        return fromString(name, ControlFamilyType.class);
    }

    /**
     * Gets known ControlFamilyType values.
     *
     * @return known ControlFamilyType values.
     */
    public static Collection<ControlFamilyType> values() {
        return values(ControlFamilyType.class);
    }
}


text:
<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Enum\GranteeType;
use Zimbra\Mail\Struct\ActionGrantSelector;

/**
 * Testcase class for ActionGrantSelector.
 */
class ActionGrantSelectorTest extends ZimbraMailTestCase
{
    public function testActionGrantSelector()
    {
        $rights = $this->faker->word;
        $zimbraId = $this->faker->uuid;
        $displayName = $this->faker->word;
        $args = $this->faker->word;
        $password = $this->faker->word;
        $accessKey = $this->faker->word;

        $grant = new ActionGrantSelector(
            $rights, GranteeType::USR(), $zimbraId, $displayName, $args, $password, $accessKey
        );

        $this->assertSame($rights, $grant->getRights());
        $this->assertTrue($grant->getGranteeType()->is('usr'));
        $this->assertSame($zimbraId, $grant->getZimbraId());
        $this->assertSame($displayName, $grant->getDisplayName());
        $this->assertSame($args, $grant->getArgs());
        $this->assertSame($password, $grant->getPassword());
        $this->assertSame($accessKey, $grant->getAccessKey());

        $grant->setRights($rights)
              ->setGranteeType(GranteeType::USR())
              ->setZimbraId($zimbraId)
              ->setDisplayName($displayName)
              ->setArgs($args)
              ->setPassword($password)
              ->setAccessKey($accessKey);
        $this->assertSame($rights, $grant->getRights());
        $this->assertTrue($grant->getGranteeType()->is('usr'));
        $this->assertSame($zimbraId, $grant->getZimbraId());
        $this->assertSame($displayName, $grant->getDisplayName());
        $this->assertSame($args, $grant->getArgs());
        $this->assertSame($password, $grant->getPassword());
        $this->assertSame($accessKey, $grant->getAccessKey());

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<grant perm="' . $rights . '" gt="' . GranteeType::USR() . '" zid="' . $zimbraId . '" d="' . $displayName . '" args="' . $args . '" pw="' . $password . '" key="' . $accessKey . '" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $grant);

        $array = array(
            'grant' => array(
                'perm' => $rights,
                'gt' => GranteeType::USR()->value(),
                'zid' => $zimbraId,
                'd' => $displayName,
                'args' => $args,
                'pw' => $password,
                'key' => $accessKey,
            ),
        );
        $this->assertEquals($array, $grant->toArray());
    }
}


text:
import os
import click
import logging
import pandas as pd
import glob
from dotenv import find_dotenv, load_dotenv

@click.command()
@click.argument('input_filepath', type=click.Path(exists=True))
@click.argument('fine_csv_filepath', type=click.Path(exists=True))
@click.argument('output_filepath', type=click.Path())
def main(input_filepath, fine_csv_filepath, output_filepath):
    """ Runs data processing scripts to turn raw data from (../raw) into
        cleaned data ready to be analyzed (saved in ../processed).
    """
    logger = logging.getLogger(__name__)
    logger.info('Enriching Dataset')

    fines_df = pd.read_csv(fine_csv_filepath, encoding="utf-8-sig")
    fines_df.columns = [col.lower() for col in fines_df.columns]
    fines_df.drop('shortdesc', axis=1, inplace=True)
    fines_df.rename(columns={'code': 'violation_code'}, inplace=True)

    df = pd.read_csv(input_filepath, sep='\t')
    df = df.merge(fines_df) # on='violation_code')

    columns_to_drop = ['desc']
    df.drop(columns_to_drop, inplace=True, axis=1, errors='ignore')

    logger.info('Saving Enriched Dataset')
    df.to_csv(output_filepath, sep='\t', index=False)

if __name__ == '__main__':
    log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(level=logging.INFO, format=log_fmt)

    # not used in this stub but often useful for finding various files
    project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)

    # find .env automagically by walking up directories until it's found, then
    # load up the .env entries as environment variables
    load_dotenv(find_dotenv())

    main()


text:
<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "job".
 *
 * @property integer $job_id
 * @property integer $employer_id
 * @property string $time_created
 * @property string $time_updated
 * @property string $job_description
 * @property string $expiration_date
 */
class Job extends \yii\db\ActiveRecord
{
    public static $expirationTimes = [
        '1w'=>'1 Week',
        '2w'=>'2 Weeks',
        '3w'=>'2 Weeks',
        '1m'=>'1 Month',
        '2m'=>'2 Months',
    ];

    public static $job_type = [
        'fullTime'=>'Full Time',
        'partTime'=>'Part Time',
        'intern'=>'Intern',
        'hourly'=>'Hourly',
    ];
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'job';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['employer_id'], 'required'],
            [['employer_id'], 'integer'],
            [['time_created', 'time_updated','expiration_date'], 'safe'],
            [['job_description'], 'string', 'max' => 2000],
            [['job_type'], 'string', 'max' => 40],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'job_id' => 'Job ID',
            'employer_id' => 'Employer ID',
            'time_created' => 'Time Created',
            'time_updated' => 'Time Updated',
            'job_description' => 'Job Description',
            'job_type'=>'Job Type'
        ];
    }
}


text:
package eu.fraho.spring.securityJwt.base.dto;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Value;

@JsonDeserialize(builder = RefreshToken.RefreshTokenBuilder.class)
@Value
@EqualsAndHashCode(callSuper = true)
public class RefreshToken extends AbstractToken {
    @Builder
    public RefreshToken(String token, long expiresIn) {
        super(token, expiresIn);
    }

    @JsonPOJOBuilder(withPrefix = "")
    public static final class RefreshTokenBuilder {
    }
}


text:
//
//  ViewController.m
//  VideoCube
//
//  Created by John Brewer on 2/22/12.
//  Copyright (c) 2012 Jera Design LLC. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Uniform index.
enum
{
    UNIFORM_MODELVIEWPROJECTION_MATRIX,
    UNIFORM_NORMAL_MATRIX,
    UNIFORM_TEXTURE,
    NUM_UNIFORMS
};
GLint uniforms[NUM_UNIFORMS];

// Attribute index.
enum
{
    ATTRIB_VERTEX,
    ATTRIB_NORMAL,
    NUM_ATTRIBUTES
};

// three xyz coordinates, three normal coordinates, two texture coordinates *
// four bytes per coordinate *
// six vertices per face *
// six faces per cube
GLfloat gCubeVertexData[(3 + 3 + 2) * 4 * 6 * 6] =
{
// Data layout for each line below is:
//         position                    normal            texCoord0
//      X,     Y,     Z,           X,     Y,     Z,       S.     T,
     0.5f, -0.5f, -0.5f,        1.0f,  0.0f,  0.0f,     0.875, 1.0,
     0.5f,  0.5f, -0.5f,        1.0f,  0.0f,  0.0f,     0.125, 1.0,
     0.5f, -0.5f,  0.5f,        1.0f,  0.0f,  0.0f,     0.875, 0.0,
     0.5f, -0.5f,  0.5f,        1.0f,  0.0f,  0.0f,     0.875, 0.0,
     0.5f,  0.5f,  0.5f,        1.0f,  0.0f,  0.0f,     0.125, 0.0,
     0.5f,  0.5f, -0.5f,        1.0f,  0.0f,  0.0f,     0.125, 1.0,

     0.5f,  0.5f, -0.5f,        0.0f,  1.0f,  0.0f,     0.125, 1.0,
    -0.5f,  0.5f, -0.5f,        0.0f,  1.0f,  0.0f,     0.125, 0.0,
     0.5f,  0.5f,  0.5f,        0.0f,  1.0f,  0.0f,     0.875, 1.0,
     0.5f,  0.5f,  0.5f,        0.0f,  1.0f,  0.0f,     0.875, 1.0,
    -0.5f,  0.5f, -0.5f,        0.0f,  1.0f,  0.0f,     0.125, 0.0,
    -0.5f,  0.5f,  0.5f,        0.0f,  1.0f,  0.0f,     0.875, 0.0,

    -0.5f,  0.5f, -0.5f,       -1.0f,  0.0f,  0.0f,     0.125, 0.0,
    -0.5f, -0.5f, -0.5f,       -1.0f,  0.0f,  0.0f,     0.875, 0.0,
    -0.5f,  0.5f,  0.5f,       -1.0f,  0.0f,  0.0f,     0.125, 1.0,
    -0.5f,  0.5f,  0.5f,       -1.0f,  0.0f,  0.0f,     0.125, 1.0,
    -0.5f, -0.5f, -0.5f,       -1.0f,  0.0f,  0.0f,     0.875, 0.0,
    -0.5f, -0.5f,  0.5f,       -1.0f,  0.0f,  0.0f,     0.875, 1.0,

    -0.5f, -0.5f, -0.5f,        0.0f, -1.0f,  0.0f,     0.875, 0.0,
     0.5f, -0.5f, -0.5f,        0.0f, -1.0f,  0.0f,     0.875, 1.0,
    -0.5f, -0.5f,  0.5f,        0.0f, -1.0f,  0.0f,     0.125, 0.0,
    -0.5f, -0.5f,  0.5f,        0.0f, -1.0f,  0.0f,     0.125, 0.0,
     0.5f, -0.5f, -0.5f,        0.0f, -1.0f,  0.0f,     0.875, 1.0,
     0.5f, -0.5f,  0.5f,        0.0f, -1.0f,  0.0f,     0.125, 1.0,

     0.5f,  0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.125, 1.0,
    -0.5f,  0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.125, 0.0,
     0.5f, -0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.875, 1.0,
     0.5f, -0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.875, 1.0,
    -0.5f,  0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.125, 0.0,
    -0.5f, -0.5f,  0.5f,        0.0f,  0.0f,  1.0f,     0.875, 0.0,

     0.5f, -0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.875, 0.0,
    -0.5f, -0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.875, 1.0,
     0.5f,  0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.125, 0.0,
     0.5f,  0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.125, 0.0,
    -0.5f, -0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.875, 1.0,
    -0.5f,  0.5f, -0.5f,        0.0f,  0.0f, -1.0f,     0.125, 1.0,
};

@interface ViewController () {
    GLuint _program;

    GLKMatrix4 _modelViewProjectionMatrix;
    GLKMatrix3 _normalMatrix;
    float _rotation;

    GLuint _vertexArray;
    GLuint _vertexBuffer;

    AVCaptureDevice *_cameraDevice;
    AVCaptureSession *_session;

    CVOpenGLESTextureCacheRef _textureCache;
    CVOpenGLESTextureRef    _cvTexture;

    GLuint _textureId;
}
@property (strong, nonatomic) EAGLContext *context;

- (void)setupGL;
- (void)tearDownGL;

- (BOOL)loadShaders;
- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file;
- (BOOL)linkProgram:(GLuint)prog;
- (BOOL)validateProgram:(GLuint)prog;

- (void)setupSimpleTexture;
@end

@implementation ViewController

@synthesize context = _context;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    if (!self.context) {
        NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [self setupCamera];
    [self turnCameraOn];
    [self setupGL];
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    [self tearDownGL];
    [self turnCameraOff];

    if ([EAGLContext currentContext] == self.context) {
        [EAGLContext setCurrentContext:nil];
    }
    self.context = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc. that aren't in use.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)setupGL
{
    [EAGLContext setCurrentContext:self.context];

    [self loadShaders];

    glEnable(GL_DEPTH_TEST);

    glGenVertexArraysOES(1, &_vertexArray);
    glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(gCubeVertexData), gCubeVertexData, GL_STATIC_DRAW);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 32, BUFFER_OFFSET(0));
    glEnableVertexAttribArray(GLKVertexAttribNormal);
    glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 32, BUFFER_OFFSET(12));
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 32, BUFFER_OFFSET(24));

    glBindVertexArrayOES(0);

//    glActiveTexture(GL_TEXTURE0);

//    [self setupSimpleTexture];

    CVReturn error = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault,
                                                  NULL,
                                                  self.context,
                                                  NULL,
                                                  &_textureCache);
    if (error != kCVReturnSuccess) {
        NSLog(@"CVOpenGLESTextureCacheCreate returned %d", error);
    }
}

- (void)setupSimpleTexture
{
    // 2 x 2 Image, 3 bytes per pixel(R, G, B)
    static GLubyte pixels[4 * 3] =
    {
        255, 0, 0, // red
        0, 255, 0, // green
        0, 0, 255, // blue
        255, 255, 0, // yellow
    };

    // Use tightly packed data
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    // Generate a texture object
    glGenTextures(1, &_textureId);

    //Bind the texture object
    glBindTexture(GL_TEXTURE_2D, _textureId);

    // Load the texture
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);

    // Set the filtering mode
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}

- (void)tearDownGL
{
    [EAGLContext setCurrentContext:self.context];

    glDeleteBuffers(1, &_vertexBuffer);
    glDeleteVertexArraysOES(1, &_vertexArray);

    if (_program) {
        glDeleteProgram(_program);
        _program = 0;
    }
}

#pragma mark - GLKView and GLKViewController delegate methods

- (void)update
{
    float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
    GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);

    GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -2.0f);
    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f);

//    // Compute the model view matrix for the object rendered with ES2
//    GLKMatrix4 modelViewMatrix;
//    modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 0.0f);
//    modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f);
//    modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix);

    _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL);

    _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);

    _rotation += self.timeSinceLastUpdate * 2.0f;
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    if (_cvTexture == nil) {
        return;
    }
    glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindVertexArrayOES(_vertexArray);

    // Render the object again with ES2
    glUseProgram(_program);

    glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
    glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0, _normalMatrix.m);

    glEnable(GL_TEXTURE_2D);
    glEnable(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE0);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glBindTexture(CVOpenGLESTextureGetTarget(_cvTexture), CVOpenGLESTextureGetName(_cvTexture));
    // Set the filtering mode
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(uniforms[UNIFORM_TEXTURE], 0);

    glDrawArrays(GL_TRIANGLES, 0, 36);
    glFlush();
}

#pragma mark -  OpenGL ES 2 shader compilation

- (BOOL)loadShaders
{
    GLuint vertShader, fragShader;
    NSString *vertShaderPathname, *fragShaderPathname;

    // Create shader program.
    _program = glCreateProgram();

    // Create and compile vertex shader.
    vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"];
    if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname]) {
        NSLog(@"Failed to compile vertex shader");
        return NO;
    }

    // Create and compile fragment shader.
    fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"];
    if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) {
        NSLog(@"Failed to compile fragment shader");
        return NO;
    }

    // Attach vertex shader to program.
    glAttachShader(_program, vertShader);

    // Attach fragment shader to program.
    glAttachShader(_program, fragShader);

    // Bind attribute locations.
    // This needs to be done prior to linking.
    glBindAttribLocation(_program, ATTRIB_VERTEX, "position");
    glBindAttribLocation(_program, ATTRIB_NORMAL, "normal");
    glBindAttribLocation(_program, GLKVertexAttribTexCoord0, "texCoord0");

    // Link program.
    if (![self linkProgram:_program]) {
        NSLog(@"Failed to link program: %d", _program);

        if (vertShader) {
            glDeleteShader(vertShader);
            vertShader = 0;
        }
        if (fragShader) {
            glDeleteShader(fragShader);
            fragShader = 0;
        }
        if (_program) {
            glDeleteProgram(_program);
            _program = 0;
        }

        return NO;
    }

    // Get uniform locations.
    uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX] = glGetUniformLocation(_program, "modelViewProjectionMatrix");
    uniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, "normalMatrix");
    uniforms[UNIFORM_TEXTURE] = glGetUniformLocation(_program, "texture");

    // Release vertex and fragment shaders.
    if (vertShader) {
        glDetachShader(_program, vertShader);
        glDeleteShader(vertShader);
    }
    if (fragShader) {
        glDetachShader(_program, fragShader);
        glDeleteShader(fragShader);
    }

    return YES;
}

- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file
{
    GLint status;
    const GLchar *source;

    source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String];
    if (!source) {
        NSLog(@"Failed to load vertex shader");
        return NO;
    }

    *shader = glCreateShader(type);
    glShaderSource(*shader, 1, &source, NULL);
    glCompileShader(*shader);

#if defined(DEBUG)
    GLint logLength;
    glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength);
    if (logLength > 0) {
        GLchar *log = (GLchar *)malloc(logLength);
        glGetShaderInfoLog(*shader, logLength, &logLength, log);
        NSLog(@"Shader compile log:\n%s", log);
        free(log);
    }
#endif

    glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);
    if (status == 0) {
        glDeleteShader(*shader);
        return NO;
    }

    return YES;
}

- (BOOL)linkProgram:(GLuint)prog
{
    GLint status;
    glLinkProgram(prog);

#if defined(DEBUG)
    GLint logLength;
    glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
    if (logLength > 0) {
        GLchar *log = (GLchar *)malloc(logLength);
        glGetProgramInfoLog(prog, logLength, &logLength, log);
        NSLog(@"Program link log:\n%s", log);
        free(log);
    }
#endif

    glGetProgramiv(prog, GL_LINK_STATUS, &status);
    if (status == 0) {
        return NO;
    }

    return YES;
}

- (BOOL)validateProgram:(GLuint)prog
{
    GLint logLength, status;

    glValidateProgram(prog);
    glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
    if (logLength > 0) {
        GLchar *log = (GLchar *)malloc(logLength);
        glGetProgramInfoLog(prog, logLength, &logLength, log);
        NSLog(@"Program validate log:\n%s", log);
        free(log);
    }

    glGetProgramiv(prog, GL_VALIDATE_STATUS, &status);
    if (status == 0) {
        return NO;
    }

    return YES;
}

#pragma mark - Camera support

- (void)setupCamera {
    _cameraDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSArray *devices = [AVCaptureDevice devices];
    for (AVCaptureDevice *device in devices) {
        if (device.position == AVCaptureDevicePositionFront) {
            _cameraDevice = device;
            break;
        }
    }

}

- (void)turnCameraOn {
    NSError *error;
    _session = [[AVCaptureSession alloc] init];
    [_session beginConfiguration];
    [_session setSessionPreset:AVCaptureSessionPresetMedium];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:_cameraDevice
                                                                        error:&error];
    if (input == nil) {
        NSLog(@"%@", error);
    }

    [_session addInput:input];

    // Create a VideoDataOutput and add it to the session
    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

    // Configure your output.
    //  dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
    [output setSampleBufferDelegate:self queue:dispatch_get_main_queue() /* queue */];
    //  dispatch_release(queue);

    [output setAlwaysDiscardsLateVideoFrames:YES];

    // Specify the pixel format
    output.videoSettings =
    [NSDictionary dictionaryWithObject:
     [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];

    [_session addOutput:output];

    // Start the session running to start the flow of data
    [_session commitConfiguration];
    [_session startRunning];
}

- (void)turnCameraOff {
    [_session stopRunning];
    _session = nil;
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection {
    CVReturn error;
    // Get a CMSampleBuffer's Core Video image buffer for the media data
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);

    if (_cvTexture) {
        CFRelease(_cvTexture);
        _cvTexture = nil;
        CVOpenGLESTextureCacheFlush(_textureCache, 0);
    }
    glActiveTexture(GL_TEXTURE0);
    error = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
                                                         _textureCache,
                                                         imageBuffer,
                                                         NULL,
                                                         GL_TEXTURE_2D,
                                                         GL_RGBA,
                                                         (GLint) width,
                                                         (GLint) height,
                                                         GL_BGRA,
                                                         GL_UNSIGNED_BYTE,
                                                         0,
                                                         &_cvTexture);
    if (error != kCVReturnSuccess) {
        NSLog(@"CVOpenGLESTextureCacheCreateTextureFromImage returned %d", error);
    }

    // Bind texture immediately, or you'll get occasional flicker.
    glBindTexture(CVOpenGLESTextureGetTarget(_cvTexture), CVOpenGLESTextureGetName(_cvTexture));
}

@end


text:
{% extends 'infrastructure/base.html' %}
{% load i18n %}
{% block title %}{% trans "Resource Class Action Confirmation" %}{% endblock %}
{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Resource Class Action") %}
{% endblock page_header %}
{% block infrastructure_main %}
    {% include "infrastructure/resource_management/resource_classes/_edit_status.html" %}
{% endblock %}


text:
namespace Levolution.TypeSchema.ConceptualType
{
    /// <summary>
    ///
    /// </summary>
    public interface IIntegerType : INumericType
    {
        /// <summary>
        ///
        /// </summary>
        IntegerSign Sign { get; }
    }
}


text:
id: 1028
title: Back in the SL
date: 2014-01-12T13:26:57+00:00
author_name: Adrianna Tan
layout: post
guid: http://popagandhi.com/?p=1028
permalink: /2014/01/back-in-the-sl/
dsq_thread_id:
  - 2111106600
categories:
  - 'Life & Love'
  - Travel
---
I have become one of those people.

For the fourth time this year, I am sitting at the Coffee Bean and Tea Leaf at Colombo airport drinking the world's worst coffee and the worst food.

I am also strutting around in heels. Here. Also in Indonesia. In the Philippines. Everywhere. I walked into a TASMAC in dodgy neighbourhood in Madras in my Asian office lady dress and in my heels. Everybody stared. The truth is I have misplaced my flip flops and the hippie that was wearing them along with it.

The heels make my friends laugh. A, who hasn't lived in Singapore for the last five years, literally dropped her cocktail all over our bags as she stood there marvelling at how I was wearing proper shoes.

Here I am now in a designer top, hippie pants, heels and uncombed hair. I have lost my hairbrush, too.

My life these days is at once more stable and at once more colourful. The opportunities get larger and more varied. The opportunity costs increase. There is clarity. I say "epic" and "amazeballs" a lot. I also say "let's jam" when talking about meetings because I work with so many Americans and call so many of them my friends.

I've had the chance to pursue some incredible opportunities at work (in tech), for play (in writing), for causes I care about; I am pleased.

My dog goes to doggie kindergarten and camping trips, and I go to meetings. Sometimes I remember to comb my hair. I pay rent in one of the world's most expensive cities and I travel once a week, sometimes more. I get to see my lovely family all the time now, which is a vast improvement from 2008-2013.

We ringed in the new year in an apartment overlooking the Singapore River. The fireworks were beautiful but the best part was the good friends I love. Years ago in the back room of a tiny political party's office — an episode we will probably laugh about for the rest of our lives — I met N and S, and they have been exactly what one Facebook caption said, "together through good and bad, politics, broken hearts and unwritten novels." The all-nighters will come to something. The elections were our becoming. The friends to whose sides you flee to for refuge and for pineapple tarts and gin when you've had your heart broken are the ones to keep.

Last night I attended a beautiful wedding in Sri Lanka. Normally weddings make me want to cry with how trite and awful they are, yet despite the rituals and the chaos, this one was full of love and light. It was clear every single soul that made it out there came because we truly loved these guys. From Johannesburg to New York to Singapore, guests were family to the couple, jointly and separately, at various points of lives led in Sri Lanka, Singapore, New York City and elsewhere. Here were two souls who had withstood trials of such intensity and magnitude, who had moved mountains to be with each other. Though the guests fumbled, we eventually managed to let loose a flurry of wishing lights into the sky over Pannupitiya.

That's what all this is about, the bride not so tearfully (compared to her best friend) told us. Family, friends that are family, and love.

In the balmy Sri Lankan heat I felt at home in the tropics, my heart full of love and happiness for the first time in a long while.

Never again will I settle for second best, nor for anything short of extraordinary, unconditional love.