text:
package v2

import (
	"net/http"
	"net/url"
	"strings"

	"github.com/docker/distribution/digest"
	"github.com/gorilla/mux"
)

// URLBuilder creates registry API urls from a single base endpoint. It can be
// used to create urls for use in a registry client or server.
//
// All urls will be created from the given base, including the api version.
// For example, if a root of "/foo/" is provided, urls generated will be fall
// under "/foo/v2/...". Most application will only provide a schema, host and
// port, such as "https://localhost:5000/".
type URLBuilder struct {
	root   *url.URL // url root (ie http://localhost/)
	router *mux.Router
}

// NewURLBuilder creates a URLBuilder with provided root url object.
func NewURLBuilder(root *url.URL) *URLBuilder {
	return &URLBuilder{
		root:   root,
		router: Router(),
	}
}

// NewURLBuilderFromString workes identically to NewURLBuilder except it takes
// a string argument for the root, returning an error if it is not a valid
// url.
func NewURLBuilderFromString(root string) (*URLBuilder, error) {
	u, err := url.Parse(root)
	if err != nil {
		return nil, err
	}

	return NewURLBuilder(u), nil
}

// NewURLBuilderFromRequest uses information from an *http.Request to
// construct the root url.
func NewURLBuilderFromRequest(r *http.Request) *URLBuilder {
	var scheme string

	forwardedProto := r.Header.Get("X-Forwarded-Proto")

	switch {
	case len(forwardedProto) > 0:
		scheme = forwardedProto
	case r.TLS != nil:
		scheme = "https"
	case len(r.URL.Scheme) > 0:
		scheme = r.URL.Scheme
	default:
		scheme = "http"
	}

	host := r.Host
	forwardedHost := r.Header.Get("X-Forwarded-Host")
	if len(forwardedHost) > 0 {
		// According to the Apache mod_proxy docs, X-Forwarded-Host can be a
		// comma-separated list of hosts, to which each proxy appends the
		// requested host. We want to grab the first from this comma-separated
		// list.
		hosts := strings.SplitN(forwardedHost, ",", 2)
		host = strings.TrimSpace(hosts[0])
	}

	basePath := routeDescriptorsMap[RouteNameBase].Path

	requestPath := r.URL.Path
	index := strings.Index(requestPath, basePath)

	u := &url.URL{
		Scheme: scheme,
		Host:   host,
	}

	if index > 0 {
		// N.B. index+1 is important because we want to include the trailing /
		u.Path = requestPath[0 : index+1]
	}

	return NewURLBuilder(u)
}

// BuildBaseURL constructs a base url for the API, typically just "/v2/".
func (ub *URLBuilder) BuildBaseURL() (string, error) {
	route := ub.cloneRoute(RouteNameBase)

	baseURL, err := route.URL()
	if err != nil {
		return "", err
	}

	return baseURL.String(), nil
}

// BuildCatalogURL constructs a url get a catalog of repositories
func (ub *URLBuilder) BuildCatalogURL(values ...url.Values) (string, error) {
	route := ub.cloneRoute(RouteNameCatalog)

	catalogURL, err := route.URL()
	if err != nil {
		return "", err
	}

	return appendValuesURL(catalogURL, values...).String(), nil
}

// BuildTagsURL constructs a url to list the tags in the named repository.
func (ub *URLBuilder) BuildTagsURL(name string) (string, error) {
	route := ub.cloneRoute(RouteNameTags)

	tagsURL, err := route.URL("name", name)
	if err != nil {
		return "", err
	}

	return tagsURL.String(), nil
}

// BuildManifestURL constructs a url for the manifest identified by name and
// reference. The argument reference may be either a tag or digest.
func (ub *URLBuilder) BuildManifestURL(name, reference string) (string, error) {
	route := ub.cloneRoute(RouteNameManifest)

	manifestURL, err := route.URL("name", name, "reference", reference)
	if err != nil {
		return "", err
	}

	return manifestURL.String(), nil
}

// BuildBlobURL constructs the url for the blob identified by name and dgst.
func (ub *URLBuilder) BuildBlobURL(name string, dgst digest.Digest) (string, error) {
	route := ub.cloneRoute(RouteNameBlob)

	layerURL, err := route.URL("name", name, "digest", dgst.String())
	if err != nil {
		return "", err
	}

	return layerURL.String(), nil
}

// BuildBlobUploadURL constructs a url to begin a blob upload in the
// repository identified by name.
func (ub *URLBuilder) BuildBlobUploadURL(name string, values ...url.Values) (string, error) {
	route := ub.cloneRoute(RouteNameBlobUpload)

	uploadURL, err := route.URL("name", name)
	if err != nil {
		return "", err
	}

	return appendValuesURL(uploadURL, values...).String(), nil
}

// BuildBlobUploadChunkURL constructs a url for the upload identified by uuid,
// including any url values. This should generally not be used by clients, as
// this url is provided by server implementations during the blob upload
// process.
func (ub *URLBuilder) BuildBlobUploadChunkURL(name, uuid string, values ...url.Values) (string, error) {
	route := ub.cloneRoute(RouteNameBlobUploadChunk)

	uploadURL, err := route.URL("name", name, "uuid", uuid)
	if err != nil {
		return "", err
	}

	return appendValuesURL(uploadURL, values...).String(), nil
}

// clondedRoute returns a clone of the named route from the router. Routes
// must be cloned to avoid modifying them during url generation.
func (ub *URLBuilder) cloneRoute(name string) clonedRoute {
	route := new(mux.Route)
	root := new(url.URL)

	*route = *ub.router.GetRoute(name) // clone the route
	*root = *ub.root

	return clonedRoute{Route: route, root: root}
}

type clonedRoute struct {
	*mux.Route
	root *url.URL
}

func (cr clonedRoute) URL(pairs ...string) (*url.URL, error) {
	routeURL, err := cr.Route.URL(pairs...)
	if err != nil {
		return nil, err
	}

	if routeURL.Scheme == "" && routeURL.User == nil && routeURL.Host == "" {
		routeURL.Path = routeURL.Path[1:]
	}

	return cr.root.ResolveReference(routeURL), nil
}

// appendValuesURL appends the parameters to the url.
func appendValuesURL(u *url.URL, values ...url.Values) *url.URL {
	merged := u.Query()

	for _, v := range values {
		for k, vv := range v {
			merged[k] = append(merged[k], vv...)
		}
	}

	u.RawQuery = merged.Encode()
	return u
}

// appendValues appends the parameters to the url. Panics if the string is not
// a url.
func appendValues(u string, values ...url.Values) string {
	up, err := url.Parse(u)

	if err != nil {
		panic(err) // should never happen
	}

	return appendValuesURL(up, values...).String()
}


text:
<?php

// src/Sdz/BlogBundle/Controller/BlogController.php

namespace Sdz\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;

class BlogController extends Controller {

    public function indexAction() {
        return $this->redirect($this->generateUrl("oc_platform_home"));
    }

}

redpajama_set_name: RedPajamaGithub


text:
title: 'Tickets: I bought tickets from a "friend" / scalper / third party / some dude
  off Craigslist. How can I verify this pass will work or that it's legit?'
date: 2017-03-03 19:52:00 Z
position: 11
topic: tickets-wristband
question_text: I bought tickets from a "friend" / scalper / third party / some dude
  off Craigslist. How can I verify this pass will work or that it's legit?
answer_text: 'We can only guarantee ticket validity for purchases made through our
  official vendor, Front Gate Tickets. Any other ticket source could get a little
  sketchy.

'
---


text:
package VMOMI::VmFaultToleranceVmTerminatedEvent;
use parent 'VMOMI::VmEvent';

use strict;
use warnings;

our @class_ancestors = (
    'VmEvent',
    'Event',
    'DynamicData',
);

our @class_members = (
    ['reason', undef, 0, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
require 'minitest/unit'
require 'minitest/autorun'

$LOAD_PATH.unshift(File.expand_path('../lib/', __dir__))
require 'custom_rails_logger/formatter'

class DummyRequest
  attr_accessor :ip,
    :cookies,
    :env,
    :filtered_path,
    :host,
    :request_method,
    :port,
    :scheme,
    :user_agent
end

module CustomRailsLogger
  class TestFormatter < MiniTest::Unit::TestCase
    def setup
      @request = DummyRequest.new.tap do |req|
        req.ip = '192.168.0.1'
        req.cookies = { 'foo' => 'foo' }
        req.env = { 'bar' => 'bar'}
        req.filtered_path = '/path/to'
        req.host = 'localhost'
        req.request_method = 'GET'
        req.port = '80'
        req.scheme = 'http'
        req.user_agent = 'Browser'
      end
    end

    def test_call_parcent_pattern
      result = CustomRailsLogger::Formatter.call('Started % %% %%%', @request)
      assert_equal 'Started % % %%', result
    end

    def test_call_ip_pattern
      result = CustomRailsLogger::Formatter.call('Started %a %%a %%%a', @request)
      assert_equal 'Started 192.168.0.1 %a %192.168.0.1', result
    end

    def test_call_cookies_pattern
      result = CustomRailsLogger::Formatter.call('Started %{foo}C %{hoge}C', @request)
      assert_equal 'Started foo ', result
    end

    def test_call_env_pattern
      result = CustomRailsLogger::Formatter.call('Started %{bar}e %{hoge}e', @request)
      assert_equal 'Started bar ', result
    end

    def test_call_path_pattern
      result = CustomRailsLogger::Formatter.call('Started "%f"', @request)
      assert_equal 'Started "/path/to"', result
    end

    def test_call_host_pattern
      result = CustomRailsLogger::Formatter.call('Started %h', @request)
      assert_equal 'Started localhost', result
    end

    def test_call_method_pattern
      result = CustomRailsLogger::Formatter.call('Started %m', @request)
      assert_equal 'Started GET', result
    end

    def test_call_port_pattern
      result = CustomRailsLogger::Formatter.call('Started %p', @request)
      assert_equal 'Started 80', result
    end

    def test_call_scheme_pattern
      result = CustomRailsLogger::Formatter.call('Started %s', @request)
      assert_equal 'Started http', result
    end

    def test_call_agent_pattern
      result = CustomRailsLogger::Formatter.call('Started %u', @request)
      assert_equal 'Started Browser', result
    end
  end
end


text:
[kakao](../../index.md) / [com.agoda.kakao](../index.md) / [ViewBuilder](index.md) / [getViewInteraction](./get-view-interaction.md)

# getViewInteraction

`fun getViewInteraction(): ViewInteraction`

Returns view interaction based on all given matchers

**Return**
ViewInteraction


text:
package engineer.echo.floatwindow.cmpts.floatpannel;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * SecondActivity
 * Created by Plucky<plucky@echo.engineer> on 2018/1/9 - 10:22
 * more about me: http://www.1991th.com
 */

public class FloatPannel {

    private Context mContext;
    private FloatWindowService mService;

    private FloatPannel() {

    }

    private static FloatPannel mPannel;

    private static FloatPannel getPannel() {
        if (mPannel == null) {
            mPannel = new FloatPannel();
        }
        return mPannel;
    }

    private void bindService() {
        if (mContext != null) {
            Intent intent = new Intent(mContext, FloatWindowService.class);
            mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private void unBindService() {
        if (mContext != null) {
            mContext.unbindService(mServiceConnection);
        }
    }

    private void print(String msg) {
        if (mService != null) {
            mService.print(msg);
        }
    }

    public static void Log(String msg) {
        getPannel().print(msg);
    }

    private void install(Context context) {
        mContext = context.getApplicationContext();
        bindService();
    }

    private void unInstall() {
        unBindService();
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((FloatWindowService.FloatWindowServiceBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    public static void register(Context context) {
        getPannel().install(context);
    }

    public static void unRegister() {
        getPannel().unInstall();
    }

}


text:
package bio.terra.workspace.common.logging;

import static bio.terra.workspace.common.utils.FlightUtils.getRequired;
import static bio.terra.workspace.db.model.DbWorkspaceActivityLog.getDbWorkspaceActivityLog;
import static bio.terra.workspace.service.workspace.flight.WorkspaceFlightMapKeys.ControlledResourceKeys.CONTROLLED_RESOURCES_TO_DELETE;
import static bio.terra.workspace.service.workspace.flight.WorkspaceFlightMapKeys.FOLDER_ID;
import static bio.terra.workspace.service.workspace.flight.WorkspaceFlightMapKeys.UPDATED_WORKSPACES;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import bio.terra.stairway.FlightContext;
import bio.terra.stairway.FlightStatus;
import bio.terra.stairway.HookAction;
import bio.terra.stairway.StairwayHook;
import bio.terra.workspace.common.exception.UnhandledDeletionFlightException;
import bio.terra.workspace.common.logging.model.ActivityFlight;
import bio.terra.workspace.db.FolderDao;
import bio.terra.workspace.db.ResourceDao;
import bio.terra.workspace.db.WorkspaceActivityLogDao;
import bio.terra.workspace.db.WorkspaceDao;
import bio.terra.workspace.db.exception.WorkspaceNotFoundException;
import bio.terra.workspace.service.admin.flights.cloudcontexts.gcp.SyncGcpIamRolesFlight;
import bio.terra.workspace.service.iam.AuthenticatedUserRequest;
import bio.terra.workspace.service.iam.SamService;
import bio.terra.workspace.service.job.JobMapKeys;
import bio.terra.workspace.service.resource.controlled.model.ControlledResource;
import bio.terra.workspace.service.resource.exception.ResourceNotFoundException;
import bio.terra.workspace.service.workspace.flight.WorkspaceFlightMapKeys;
import bio.terra.workspace.service.workspace.model.CloudPlatform;
import bio.terra.workspace.service.workspace.model.OperationType;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WorkspaceActivityLogHook implements StairwayHook {
  private static final Logger logger = LoggerFactory.getLogger(StairwayHook.class);

  private final FolderDao folderDao;
  private final WorkspaceActivityLogDao activityLogDao;
  private final WorkspaceDao workspaceDao;
  private final ResourceDao resourceDao;
  private final SamService samService;

  @Autowired
  public WorkspaceActivityLogHook(
      WorkspaceActivityLogDao activityLogDao,
      FolderDao folderDao,
      WorkspaceDao workspaceDao,
      ResourceDao resourceDao,
      SamService samService) {
    this.activityLogDao = activityLogDao;
    this.folderDao = folderDao;
    this.workspaceDao = workspaceDao;
    this.resourceDao = resourceDao;
    this.samService = samService;
  }

  @Override
  public HookAction endFlight(FlightContext context) throws InterruptedException {
    logger.info(
        String.format("endFlight %s: %s", context.getFlightClassName(), context.getFlightStatus()));
    var workspaceId =
        context.getInputParameters().get(WorkspaceFlightMapKeys.WORKSPACE_ID, String.class);
    var operationType =
        context
            .getInputParameters()
            .get(WorkspaceFlightMapKeys.OPERATION_TYPE, OperationType.class);

    if (operationType == null) {
      // The operation type will only be null if the flight is launched directly through stairway
      // and skipped JobService. This should only happen to sub-flight and in test. We skip the
      // activity logging in these cases.
      logger.warn("Operation type is null, this is only OK if it's from a sub-flight");
      return HookAction.CONTINUE;
    }

    var userRequest =
        checkNotNull(
            context
                .getInputParameters()
                .get(JobMapKeys.AUTH_USER_INFO.getKeyName(), AuthenticatedUserRequest.class));
    var userStatusInfo = samService.getUserStatusInfo(userRequest);
    // Use email from userStatusInfo instead of AuthenticatedUserRequest, because
    // AuthenticatedUserRequest might have pet SA email
    var userEmail = userStatusInfo.getUserEmail();
    var subjectId = userStatusInfo.getUserSubjectId();

    ActivityFlight af = ActivityFlight.fromFlightClassName(context.getFlightClassName());
    if (workspaceId == null) {
      if (!SyncGcpIamRolesFlight.class.getName().equals(context.getFlightClassName())) {
        logger.warn(
            "workspace id is missing from the flight, this should not happen for {}",
            context.getFlightClassName());
        return HookAction.CONTINUE;
      }
      maybeLogForSyncGcpIamRolesFlight(context, operationType, userEmail, subjectId);
      return HookAction.CONTINUE;
    }
    UUID workspaceUuid = UUID.fromString(workspaceId);
    if (context.getFlightStatus() == FlightStatus.SUCCESS) {
      activityLogDao.writeActivity(
          workspaceUuid, getDbWorkspaceActivityLog(operationType, userEmail, subjectId));
      return HookAction.CONTINUE;
    }
    if (operationType != OperationType.DELETE) {
      return HookAction.CONTINUE;
    }
    // If DELETE flight failed, cloud resource may or may not have been deleted. Check if cloud
    // resource was deleted. If so, write to activity log.
    switch (af.getActivityLogChangedTarget()) {
      case WORKSPACE -> maybeLogWorkspaceDeletionFlight(workspaceUuid, userEmail, subjectId);
      case AZURE_CLOUD_CONTEXT -> maybeLogCloudContextDeletionFlight(
          CloudPlatform.AZURE, workspaceUuid, userEmail, subjectId);
      case GCP_CLOUD_CONTEXT -> maybeLogCloudContextDeletionFlight(
          CloudPlatform.GCP, workspaceUuid, userEmail, subjectId);
      case RESOURCE -> maybeLogControlledResourceDeletion(
          context, workspaceUuid, userEmail, subjectId);
      case FOLDER -> maybeLogFolderDeletion(context, workspaceUuid, userEmail, subjectId);
      default -> throw new UnhandledDeletionFlightException(
          String.format(
              "Activity log should be updated for deletion flight %s failures",
              context.getFlightClassName()));
    }
    return HookAction.CONTINUE;
  }

  private void maybeLogWorkspaceDeletionFlight(
      UUID workspaceUuid, String userEmail, String subjectId) {
    try {
      workspaceDao.getWorkspace(workspaceUuid);
      logger.warn(
          String.format(
              "Workspace %s is failed to be deleted; "
                  + "not writing deletion to workspace activity log",
              workspaceUuid));
    } catch (WorkspaceNotFoundException e) {
      activityLogDao.writeActivity(
          workspaceUuid, getDbWorkspaceActivityLog(OperationType.DELETE, userEmail, subjectId));
    }
  }

  private void maybeLogCloudContextDeletionFlight(
      CloudPlatform cloudPlatform, UUID workspaceUuid, String userEmail, String subjectId) {
    Optional<String> cloudContext = workspaceDao.getCloudContext(workspaceUuid, cloudPlatform);
    if (cloudContext.isEmpty()) {
      activityLogDao.writeActivity(
          workspaceUuid, getDbWorkspaceActivityLog(OperationType.DELETE, userEmail, subjectId));
    } else {
      logger.warn(
          String.format(
              "CloudContext in workspace %s deletion fails; not writing deletion "
                  + "to workspace activity log",
              workspaceUuid));
    }
  }

  private void maybeLogFolderDeletion(
      FlightContext context, UUID workspaceUuid, String userEmail, String subjectId) {
    var folderId = getRequired(context.getInputParameters(), FOLDER_ID, UUID.class);
    if (folderDao.getFolderIfExists(workspaceUuid, folderId).isEmpty()) {
      activityLogDao.writeActivity(
          workspaceUuid, getDbWorkspaceActivityLog(OperationType.DELETE, userEmail, subjectId));
    }
  }

  private void maybeLogControlledResourceDeletion(
      FlightContext context, UUID workspaceUuid, String userEmail, String subjectId) {
    List<ControlledResource> controlledResource =
        checkNotNull(
            context
                .getInputParameters()
                .get(CONTROLLED_RESOURCES_TO_DELETE, new TypeReference<>() {}));
    checkState(controlledResource.size() == 1);
    UUID resourceId = controlledResource.get(0).getResourceId();
    try {
      resourceDao.getResource(workspaceUuid, resourceId);
      logger.warn(
          String.format(
              "Controlled resource %s in workspace %s is failed to be deleted; "
                  + "not writing deletion to workspace activity log",
              resourceId, workspaceUuid));
    } catch (ResourceNotFoundException e) {
      activityLogDao.writeActivity(
          workspaceUuid, getDbWorkspaceActivityLog(OperationType.DELETE, userEmail, subjectId));
    }
  }

  private void maybeLogForSyncGcpIamRolesFlight(
      FlightContext context, OperationType operationType, String userEmail, String subjectId) {
    HashSet<String> updatedWorkspaces =
        Objects.requireNonNull(
            context.getWorkingMap().get(UPDATED_WORKSPACES, new TypeReference<>() {}));
    for (var id : updatedWorkspaces) {
      activityLogDao.writeActivity(
          UUID.fromString(id), getDbWorkspaceActivityLog(operationType, userEmail, subjectId));
    }
  }
}


text:
package com.esoorf.view.impl.element.impl;

import java.io.File;

import com.esoorf.constant.Actions;
import com.esoorf.io.DirectoryUtils;
import com.esoorf.view.impl.panel.impl.LockedPanel;
import com.esoorf.view.palette.Palette;
import com.esoorf.view.palette.impl.UnlockedPalette;

public class UnlockedFileElement extends FileElement{

	public UnlockedFileElement(File f){
		super();
		this.setActions(Actions.LOCK);
		this.file= f;

		DirectoryUtils dir= DirectoryUtils.getInstance();

		if(f.equals(dir.getWorkingDirectory()))
		{
			prefix= "   *";
		}
		else if(f.isDirectory())
		{
			prefix= "   "+f.getAbsolutePath().substring(
					dir.getWorkingDirectory()
					.getAbsolutePath().length()
					);
		}
		else
		{
			prefix= "   "+this.file.getParent()
					.substring(dir.getWorkingDirectory().getPath().length());
			sufix= "      "+f.getName();
		}

		this.prefixLabel.setText(prefix);
		if(sufix.isEmpty())
			this.panel.setDividerLocation(40);
		else
			this.sufixLabel.setText(sufix);

		this.setPalette(new UnlockedPalette());
	}

	public Palette getPalette() {
		return new UnlockedPalette();
	}

	public void setPalette(Palette p) {
		this.palette= p;
	}

	@Override
	public void setIsSelected(boolean b) {
		this.isSelected= b;

		if(this.isSelected)
		{
			this.panel.setBackground(palette.getActiveBackground());
			if(this.isDirectory())
				this.panel.setBorder(palette.getActiveBorder(0, 0, 1, 0));
			this.prefixLabel.setForeground(palette.getActiveForeground());
			this.prefixLabel.setBorder(palette.getActiveBorder(10, 0, 0, 0));
			this.sufixLabel.setForeground(palette.getActiveForeground());
			this.sufixLabel.setBorder(palette.getActiveBorder(0, 0, 10, 0));
		}
		else
		{
			this.panel.setBackground(palette.getBackground());
			this.panel.setBorder(palette.getBorder(0, 0, 1, 0));
			this.prefixLabel.setForeground(palette.getForeground());
			this.prefixLabel.setBorder(palette.getBorder(10, 0, 0, 0));
			this.sufixLabel.setForeground(palette.getForeground());
			this.sufixLabel.setBorder(palette.getBorder(0, 0, 10, 0));
		}

		if(this.isDirectory())
		{
			FileElement pointer= this.getNext();

			while(pointer!=null)
			{
				if(pointer.getParent().getFile().equals(this.getFile()))
					pointer.setIsSelected(b);
				pointer= pointer.getNext();
			}
		}
	}

	@Override
	public void deselectedOthers() {
		for(FileElement fe: LockedPanel.getInstance().getFileElements())
			if(!fe.isFile())
				fe.setIsSelected(false);
	}

}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <title>  Archives | Spencer A. Hill
</title>
  <link rel="canonical" href="./archives.html">

  <link rel="stylesheet" href="./theme/css/bootstrap.min.css">
  <link rel="stylesheet" href="./theme/css/font-awesome.min.css">
  <link rel="stylesheet" href="./theme/css/pygments/default.min.css">
  <link rel="stylesheet" href="./theme/css/theme.css">

Spencer A. Hill

Postdoc | Lamont-Doherty Earth Observatory | Columbia University

blog

publications

c.v.

aospy

DIYnamics

resources

programming

about me

|

  Archives

Wed 15 July 2020

Introducing this blog

Authors

Archives

Categories

Tags

    Generated by Pelican
    / ✨


text:
package cn.serge.domain;

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

import org.springframework.format.annotation.DateTimeFormat;

public class Employee implements Serializable {
	private Integer id;
	private Dept dept;
	private Job job;
	private String name;
	private String cardId; //Éí·ÝÖ¤ºÅ
	private String address;
	private String postCode; //ÓÊÕþ±àÂë
	private String tel;//µç»°
	private String phone;//ÊÖ»ú
	private String qqNum;
	private String email;
	private Integer sex;//ÐÔ±ð
	private String party; //ÕþÖÎÃæò

	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date birthday;
	private String race;//Ãñ×å
	private String education;//ѧÀú
	private String speciality;//רҵ
	private String  hobby;//°®ºÃ
	private String remark;//±¸×¢
	private Date createDate; //½¨µµÈÕÆÚ

	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public Job getJob() {
		return job;
	}

	public void setJob(Job job) {
		this.job = job;
	}

	public String getName() {
		return name;
	}

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

	public String getCardId() {
		return cardId;
	}

	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPostCode() {
		return postCode;
	}

	public void setPostCode(String postCode) {
		this.postCode = postCode;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getQqNum() {
		return qqNum;
	}

	public void setQqNum(String qqNum) {
		this.qqNum = qqNum;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public String getParty() {
		return party;
	}

	public void setParty(String party) {
		this.party = party;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getRace() {
		return race;
	}

	public void setRace(String race) {
		this.race = race;
	}

	public String getEducation() {
		return education;
	}

	public void setEducation(String education) {
		this.education = education;
	}

	public String getSpeciality() {
		return speciality;
	}

	public void setSpeciality(String speciality) {
		this.speciality = speciality;
	}

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", dept=" + dept + ", job=" + job + ", name=" + name + ", cardId=" + cardId
				+ ", address=" + address + ", postCode=" + postCode + ", tel=" + tel + ", phone=" + phone + ", qqNum="
				+ qqNum + ", email=" + email + ", sex=" + sex + ", party=" + party + ", birthday=" + birthday
				+ ", race=" + race + ", education=" + education + ", speciality=" + speciality + ", hobby=" + hobby
				+ ", remark=" + remark + ", createDate=" + createDate + "]";
	}

}


text:
https://daveceddia.com/create-react-app-express-backend/
https://daveceddia.com/create-react-app-express-production/

Proxy only handles requests that aren't for text/html.


text:
import { Action } from '@ngrx/store';

export const LOGIN = 'login';
export const LOGOUT = 'logout';

export function authorizationReducer(store: any, action: Action) {
	switch (action.type) {
		case LOGIN:
			return {
				user: action.payload
			};
		case LOGOUT:
			return {
				user: action.payload
			};
		default:
			return store;
	}
}


text:
#pragma once

// stl include
#include <iostream>
#include <string>

// GLEW include
#include <GL/glew.h>

// GLM include files
#define GLM_FORCE_INLINE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

// glfw includes
#include <GLFW/glfw3.h>

// Locals
#include "controls.h"

using namespace std;

/*!
 This function initializes the GLFW window
 */
// The handle to the window object
GLFWwindow* initWindow(void);

/*!
 This function initializes glew
 */
bool initGlew(void);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_event_page"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical"
    tools:context="cs48.ucsb.edu.clubhop.EventPageActivity">

    <ImageView
        android:id="@+id/banner_img_view"
        android:scaleType="center"
        android:layout_width="match_parent"
        android:layout_height="128dp"
        android:layout_weight="1"
        app:srcCompat="@color/cast_intro_overlay_button_background_color" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:paddingRight="20dp"
        android:paddingLeft="20dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="512dp"
            android:orientation="vertical"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:paddingTop="16dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/imageView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    app:srcCompat="@drawable/common_google_signin_btn_icon_dark_normal" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:paddingLeft="16dp">

                    <TextView
                        android:id="@+id/title_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:autoLink="web"
                        android:text="Bad bundle read"
                        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
                        android:textIsSelectable="true" />

                    <TextView
                        android:id="@+id/status_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:autoLink="web"
                        android:text="Bad bundle read"
                        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                        android:textIsSelectable="true"
                        tools:text="Private" />
                </LinearLayout>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingTop="4dp"
                android:paddingBottom="4dp">

                <ImageView
                    android:id="@+id/clock_img_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:srcCompat="@drawable/ic_clock" />

                <TextView
                    android:id="@+id/time_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="7dp"
                    android:layout_weight="1"
                    android:autoLink="web"
                    android:text="Bad bundle read"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                    android:textIsSelectable="true" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingTop="4dp"
                android:paddingBottom="4dp">

                <ImageView
                    android:id="@+id/marker_img_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    app:srcCompat="@drawable/ic_pin" />

                <TextView
                    android:id="@+id/location_view"
                    android:textIsSelectable="true"
                    android:autoLink="web"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="7dp"
                    android:layout_weight="1"
                    android:text="Bad bundle read"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
            </LinearLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingTop="4dp"
                android:paddingBottom="4dp">

                <TextView
                    android:id="@+id/desc_view"
                    android:textIsSelectable="true"
                    android:autoLink="web"
                    android:scrollbars="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Bad bundle read"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>
</LinearLayout>


text:
package org.bouncycastle.oer.its.etsi102941;

import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.oer.its.etsi103097.EtsiTs103097DataSignedAndEncryptedUnicast;
import org.bouncycastle.oer.its.ieee1609dot2.Ieee1609Dot2Content;

public class AuthorizationValidationResponseMessage
    extends EtsiTs103097DataSignedAndEncryptedUnicast
{

    public AuthorizationValidationResponseMessage(Ieee1609Dot2Content content)
    {
        super(content);
    }

    protected AuthorizationValidationResponseMessage(ASN1Sequence src)
    {
        super(src);
    }

    public static AuthorizationValidationResponseMessage getInstance(Object o)
    {
        if (o instanceof AuthorizationValidationResponseMessage)
        {
            return (AuthorizationValidationResponseMessage)o;
        }
        if (o != null)
        {
            return new AuthorizationValidationResponseMessage(ASN1Sequence.getInstance(o));
        }
        return null;
    }

}


text:
<?php

/**
 * Database exception.
 *
 * @author Curtis Oakley
 */
class DatabaseException extends RuntimeException
{
    /**
     * @var string
     */
    protected $error_msg;

    /**
     * @var string
     */
    protected $query;

    /**
     * Construct a database exception.
     *
     * Handles an error that occured with the database.
     *
     * @param string $message The Exception message to throw.
     * @param int $errorno The SQL exception number.
     * @param string $error_msg The SQL error message.
     * @param string $query The SQL query that caused the exception.
     * @param Exception $previous The previous exception used for the exception chaining.
     */
    public function __construct(
            $message = "",
            $errorno = 0,
            $error_msg = "",
            $query = "",
            Exception $previous = null
    ) {
        parent::__construct($message, $errorno, $previous);
        $this->error_msg = $error_msg;
        $this->query = $query;
    }

    /**
     * Returns the SQL query that caused the exception, or
     * an empty string if there was no query.
     *
     * @return string The SQL query that caused the exception.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Returns the SQL error message.
     *
     * @return string The SQL error message.
     */
    public function getErrorMessage()
    {
        return $this->error_msg;
    }

}


text: java -cp target/lib/*:target/classes -Dhazelcast.logging.type=jdk  Member


text:
package com.spryrocks.android.modules.ui.lifecycle;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

public interface IFragmentLifecycleListener extends ILifecycleListener {
    void onActivityCreated(@Nullable Bundle savedInstanceState);

    void onAttach(Context context);
    void onDetach();

    void onViewCreated(View view, @Nullable Bundle savedInstanceState);
    void onDestroyView();
}


text:
package com.harmazing.framework.extension.interfaces;

import com.harmazing.framework.extension.ParserContext;
import com.harmazing.framework.extension.config.Configuration;
import com.harmazing.framework.extension.config.Node;

public abstract interface INamespaceHandler {
	public abstract void init();

	public abstract Configuration parse(Node node, ParserContext context);

	public abstract void afterLoad();

	public abstract void beforeLoad();
}


text:
package ch.ethz.inf.vs.semantics.parser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class ExecutionPlan {
	public final ReferenceManager refManager;
	Map<String, Request> requests;
	private final ExecutionPlan.IRequestFactory factory;

	public ExecutionPlan(String plan, ExecutionPlan.IRequestFactory factory) {
		refManager = new ReferenceManager();
		this.factory = factory;
		JSONObject obj = new JSONObject(plan);
		try {
			refManager.setRelated(obj.getString("related"));
		} catch (JSONException ex) {

		}
		this.parse(obj);
	}

	private void parse(JSONObject obj) {
		JSONArray objRequests = obj.getJSONArray("requests");
		this.requests = new HashMap<String, Request>();
		for (int i = 0; i < objRequests.length(); i++) {
			Request req = this.parseRequest(objRequests.getJSONObject(i));
			this.requests.put(req.getID(), req);
		}
		for (int i = 0; i < objRequests.length(); i++) {
			JSONObject item = objRequests.getJSONObject(i);
			if (item.has("dependencies")) {
				JSONArray dependencies = item.getJSONArray("dependencies");
				String id = item.getString("id");
				Request r = this.requests.get(id);
				for (int j = 0; j < dependencies.length(); j++) {
					r.addDependency(this.requests.get(dependencies.getString(j)));
				}
			}
		}
	}

	public Map<String, Request> getRequests() {
		return requests;
	}

	private Request parseRequest(JSONObject jsonObject) {
		ExecutionPlan.RequestValue method = this.unserialize(jsonObject.get("method"));
		ExecutionPlan.RequestValue uri = this.unserialize(jsonObject.get("uri"));
		ExecutionPlan.RequestValue reqBody = null;
		if (jsonObject.has("reqBody"))
			reqBody = this.unserialize(jsonObject.get("reqBody"));
		ExecutionPlan.RequestValue resp = null;
		if (jsonObject.has("resp"))
			resp = this.unserialize(jsonObject.get("resp"));

		return this.factory.getRequest(jsonObject.getString("id"), method, uri, reqBody, resp);

	}

	private ExecutionPlan.RequestValue unserialize(Object val) {
		if (val instanceof JSONObject) {
			String ref = ((JSONObject) val).getString("ref");
			if (ref != null) {
				return new ExecutionPlan.ReferenceValue(ref);
			}
		} else if (val instanceof JSONArray) {
			ExecutionPlan.ListValue values = new ExecutionPlan.ListValue();

			for (int i = 0; i < ((JSONArray) val).length(); i++) {
				values.add(this.unserialize(((JSONArray) val).get(i)));
			}
			return values;

		} else if (val instanceof String) {
			return new StringValue((String) val);
		}
		throw new RuntimeException("Unknown format");
	}

	public void addTransformer(Transformer t) {
		this.refManager.addTransformer(t);
	}

	public <T> void execute(RequestCallback callback) {
		this.execute(callback, null);
	}

	public <T> void execute(final RequestCallback callback, T result) {
		for (final Request r : this.requests.values()) {
			if (!r.isDone() && !r.isRunning() && r.isExecutable()) {
				r.execute(new ExecutionPlan.RequestCallback() {
					@Override
					public void onComplete(Object result) {
						if (r.resp instanceof ExecutionPlan.ReferenceValue) {
							ExecutionPlan.this.refManager.set(((ExecutionPlan.ReferenceValue) r.resp).ref, result);
						}
						ExecutionPlan.this.execute(callback, result);
					}
				});
			} else if (r.isDone()) {
				if (callback != null) {
					callback.onComplete(result);
				}
			}
		}
	}

	public interface RequestValue {

	}

	public interface IRequestFactory {
		Request getRequest(String id, ExecutionPlan.RequestValue method, ExecutionPlan.RequestValue uri, ExecutionPlan.RequestValue reqBody, ExecutionPlan.RequestValue resp);
	}

	public interface RequestCallback {
		void onComplete(Object result);
	}

	public abstract static class Request {

		public String id;
		public ExecutionPlan.RequestValue method;
		public ExecutionPlan.RequestValue uri;
		public ExecutionPlan.RequestValue reqBody;
		public ExecutionPlan.RequestValue resp;
		public boolean running;
		public boolean done;

		public Request(String id, ExecutionPlan.RequestValue method, ExecutionPlan.RequestValue uri, ExecutionPlan.RequestValue reqBody, ExecutionPlan.RequestValue resp) {
			this.id = id;
			this.method = method;
			this.uri = uri;
			this.reqBody = reqBody;
			this.resp = resp;
		}

		private final ArrayList<Request> dependencies = new ArrayList<Request>();

		public abstract void execute(ExecutionPlan.RequestCallback callback);

		public String getID() {
			return this.id;
		}

		public void addDependency(Request request) {

			this.dependencies.add(request);
		}

		public boolean isRunning() {
			return this.running;
		}

		public boolean isDone() {
			return this.done;
		}

		public boolean isExecutable() {
			for (Request d : this.dependencies) {
				if (!d.isDone()) {
					return false;
				}
			}
			return true;
		}
	}

	public class ReferenceValue implements ExecutionPlan.RequestValue {
		public final String ref;

		public ReferenceValue(String ref) {
			this.ref = ref;
		}

		@Override
		public String toString() {
			return ExecutionPlan.this.refManager.get(this.ref);
		}
	}

	public class StringValue implements ExecutionPlan.RequestValue {
		private final String value;

		public StringValue(String value) {
			this.value = value;
		}

		@Override
		public String toString() {
			return this.value;
		}

	}

	public class ListValue extends ArrayList<ExecutionPlan.RequestValue> implements ExecutionPlan.RequestValue {

		private static final long serialVersionUID = -1256112403589855134L;

		@Override
		public String toString() {
			StringBuilder sb = new StringBuilder();
			for (ExecutionPlan.RequestValue v : this) {
				sb.append(v);
			}
			return sb.toString();
		}

	}

}


text:
/**
 * RectSlots generally hold strings and are edited through a prompt dialog
 * @param {Block} parent
 * @param {string} key
 * @param {number} snapType
 * @param {number} outputType
 * @param {Data} data
 * @constructor
 */
function RectSlot(parent, key, snapType, outputType, data){
	EditableSlot.call(this, parent, key, EditableSlot.inputTypes.string, snapType, outputType, data);
	this.slotShape = new RectSlotShape(this, this.dataToString(data));
	this.slotShape.show();
}
RectSlot.prototype = Object.create(EditableSlot.prototype);
RectSlot.prototype.constructor = RectSlot;

/**
 * @inheritDoc
 */
RectSlot.prototype.highlight = function(){ //TODO: Fix BlockGraphics
	let isSlot = !this.hasChild;
	Highlighter.highlight(this.getAbsX(),this.getAbsY(),this.width,this.height,3,isSlot);
};

/**
 * @inheritDoc
 * @param {string} textSummary
 * @return {string}
 */
RectSlot.prototype.formatTextSummary = function(textSummary) {
	return "[" + textSummary + "]";
};

/**
 * @inheritDoc
 * @return {InputDialog}
 */
RectSlot.prototype.createInputSystem = function(){
	return new InputDialog(this.parent.textSummary(this), true);
};


text:
Date: 2012/02/01
Authors: [Duodezimalsystem](http://duodezimal.me)

---
---

<iframe src="http://player.vimeo.com/video/36075981?title=0&byline=0&portrait=0&badge=0&color=c9ff23" width="640" height="360" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

Rain is not only water anymore. Heavy molecules bind to what once was just an oxygen hydrogen mix. The atmosphere is getting heavy. Humanity ought to be careful so that this compound does not fall on our heads.


text:
namespace oxygine
{
    class HttpRequestCocoaTask: public HttpRequestTask
    {
    public:
        HttpRequestCocoaTask();
        ~HttpRequestCocoaTask();

        void complete_(NSData*);
        void progress_(int loaded, int total);

    protected:
        void _run();

    private:
    };
}


text:
Import the SOFTPWM module as follows

  ```python
  import CHIP_IO.SOFTPWM as SPWM
  ```

### toggle_debug()
Enable/Disable the Debug

* Parameters

  None

* Examples

  ```python
  SPWM.toggle_debug()
  ```

### is_chip_pro()
Function to report to the calling script if the SBC is a CHIP or a CHIP Pro

* Parameters

  None

* Returns

  int - 1 for CHIP Pro, 0 for CHIP

* Examples

  ```python
  is_chip_pro = SPWM.is_chip_pro()
  ```

### start(channel, duty_cycle=0.0, frequency=2000.0, polarity=0)
Start the Software PWM

* Parameters

  channel - pin for software PWM is configured
  duty_cycle - initial duty cycle of the PWM (optional)
  frequency - frequency of the PWM (optional)
  polarity - signal polarity of the PWM (optional)

* Returns

  None

* Examples

  ```python
  SPWM.start("CSID0")
  SPWM.start("CSID0", 37.0)
  SPWM.start("CSID0", 10.0, 500.0)
  SPWM.start("CSID0", 50.0, 1000.0, 1)
  ```

### stop(channel)
Stop the Software PWM

* Parameters

  channel - pin software PWM is configured

* Returns

  None

* Examples

  ```python
  SPWM.stop("CSID0")
  ```

### set_duty_cycle(channel, duty_cycle)
Set the duty cycle of the Software PWM

* Parameters

  channel - pin software PWM is configured
  duty_cycle - duty cycle of the PWM (0.0 to 100.0)

* Returns

  None

* Examples

  ```python
  SPWM.set_duty_cycle("CSID0", 25.0)
  ```

### set_frequency(channel, frequency)
Set the frequency of the Software PWM in Hertz

* Parameters

  channel - pin PWM is configured
  frequency - frequency of the PWM

* Returns

  None

* Examples

  ```python
  SPWM.set_frequency("CSID0", 450.0)
  ```

### cleanup(channel)
Cleanup Software PWM.  If not channel input, all Software PWM will be cleaned up

* Parameters

  channel - pin Software PWM is configured (optional)

* Returns

  None

* Examples

  ```python
  SPWM.cleanup()
  SPWM.cleanup("CSID0")
  ```

[home](./index.md)


text:
package org.cobbzilla.wizard.model.entityconfig;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import lombok.experimental.Accessors;
import org.cobbzilla.util.collection.ArrayUtil;
import org.cobbzilla.util.io.FileUtil;
import org.cobbzilla.wizard.model.Identifiable;
import org.cobbzilla.wizard.model.IdentifiableBase;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.cobbzilla.util.daemon.ZillaRuntime.die;
import static org.cobbzilla.util.daemon.ZillaRuntime.empty;
import static org.cobbzilla.util.io.FileUtil.abs;
import static org.cobbzilla.util.io.FileUtil.listDirs;
import static org.cobbzilla.util.json.JsonUtil.FULL_MAPPER_ALLOW_COMMENTS;
import static org.cobbzilla.util.json.JsonUtil.json;
import static org.cobbzilla.util.reflect.ReflectionUtil.copy;
import static org.cobbzilla.util.security.ShaUtil.sha256_hex;

@MappedSuperclass @NoArgsConstructor @AllArgsConstructor @Accessors(chain=true)
@ToString(of={"version", "hash", "description"})
public class ModelVersion extends IdentifiableBase {

    public static final String ERR_MODEL_VERSION_ALREADY_SUCCESSFULLY_APPLIED = "err.modelVersion.alreadySuccessfullyApplied";
    public static final String ERR_MODEL_VERSION_INVALID = "err.modelVersion.invalid";

    public static final String CURRENT = "current";

    public static final String[] UPDATE_FIELDS = { "description", "hash", "installedBy", "installedOn", "executionTime", "success" };
    public static final String[] CREATE_FIELDS = ArrayUtil.append(UPDATE_FIELDS, "version");

    public ModelVersion (ModelVersion other) { copy(this, other, CREATE_FIELDS); }
    @Override public Identifiable update(Identifiable other) { copy(this, other, UPDATE_FIELDS); return this; }

    public static final String VERSION_DIR_REGEX = "^V(\\d+)__(.+)$";
    public static final Pattern VERSION_DIR_PATTERN = Pattern.compile(VERSION_DIR_REGEX);

    public static final String MODEL_FILE_REGEX = "^([A-Za-z]+)(_.+)?$";
    public static final Pattern MODEL_FILE_PATTERN = Pattern.compile(MODEL_FILE_REGEX);

    public static boolean isMigrationDir (File dir) {
        return VERSION_DIR_PATTERN.matcher(dir.getName()).find();
    }
    public static int parseVersion (File f) { return Integer.parseInt(VERSION_DIR_PATTERN.matcher(f.getName()).group(1)); }

    public static Collection<ModelVersion> fromBaseDir(File baseDir) {
        // find migration dirs
        final File[] dirs = listDirs(baseDir, VERSION_DIR_REGEX);

        // build/sort ModelVersion objects
        final Set<ModelVersion> sorted = new TreeSet<>(new Comparator<ModelVersion>() {
            @Override public int compare(ModelVersion mv1, ModelVersion mv2) {
                return Integer.compare(mv1.getVersion(), mv2.getVersion());
            }
        });
        for (File dir : dirs) sorted.add(new ModelVersion(dir));

        return sorted;
    }

    public static String getEntityType (String path) {
        final Matcher m = MODEL_FILE_PATTERN.matcher(path);
        return m.find() ? m.group(1) : null;
    }

    public ModelVersion (File dir) {
        final String errPrefix = "ModelVersion("+abs(dir)+"): ";
        final Matcher m = VERSION_DIR_PATTERN.matcher(dir.getName());
        if (!m.find()) die(errPrefix+"invalid name (does not match regex "+VERSION_DIR_REGEX+"): "+dir.getName());
        setVersion(Integer.parseInt(m.group(1)));
        setDescription(m.group(2).replace("_", " "));

        final File manifestFile = new File(dir, "manifest.json");
        if (!manifestFile.exists() || !manifestFile.canRead()) die(errPrefix+" manifest file does not exist or is unreadable: "+abs(manifestFile));
        final String[] migrationFiles = json(FileUtil.toStringOrDie(manifestFile), String[].class, FULL_MAPPER_ALLOW_COMMENTS);
        if (empty(migrationFiles)) die(errPrefix+"manifest had no model files");

        final StringBuilder b = new StringBuilder();
        final LinkedHashMap<String, String> migrations = new LinkedHashMap<>();
        for (String file : migrationFiles) {

            final String entityType = getEntityType(file);
            if (entityType == null) die(errPrefix+"invalid model file (no entity type could be determined): "+file);

            final File f = new File(dir, file + ".json");
            if (!f.exists()) die(errPrefix+"model file does not exist: "+abs(f));

            final String singleFileJson = FileUtil.toStringOrDie(f);
            migrations.put(file, singleFileJson);
            b.append(singleFileJson);
        }
        setHash(sha256_hex(b.toString()));
        setModels(migrations);
    }

    @Column(nullable=false, updatable=false, unique=true)
    @Getter @Setter private int version;

    @Column(nullable=false, length=1024)
    @Getter @Setter private String description;

    public String shortString() { return getVersion()+"/"+getDescription(); }

    @Transient @JsonIgnore @Getter @Setter private LinkedHashMap<String, String> models;

    @Column(nullable=false, length=200)
    @Getter @Setter private String hash;

    @Column(nullable=false, length=200)
    @Getter @Setter private String installedBy;

    @Column(nullable=false)
    @Getter @Setter private long installedOn;

    @Column(nullable=false)
    @Getter @Setter private long executionTime;

    @Column(nullable=false)
    @Getter @Setter private boolean success;

}


text:
#include <portability.h>
#include <stat_portable.h>

/* Note: The Portable Header will define stat to stat_portable */
int WRAP(stat)(const char *path, struct stat_portable *s)
{
    struct stat x86_stat;
    int ret = REAL(stat)(path, &x86_stat);
    stat_ntop(&x86_stat, s);
    return ret;
}

int WRAP(fstat)(int fd, struct stat_portable *s)
{
    struct stat x86_stat;
    int ret = REAL(fstat)(fd, &x86_stat);
    stat_ntop(&x86_stat, s);
    return ret;
}

int WRAP(lstat)(const char *path, struct stat_portable *s)
{
    struct stat x86_stat;
    int ret = REAL(lstat)(path, &x86_stat);
    stat_ntop(&x86_stat, s);
    return ret;
}

int WRAP(fstatat)(int dirfd, const char *path, struct stat_portable *s, int flags)
{
    struct stat x86_stat;
    int ret = REAL(fstatat)(dirfd, path, &x86_stat, flags);
    stat_ntop(&x86_stat, s);
    return ret;
}


text:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include "hexchat-plugin.h"

static hexchat_plugin *ph;   /* plugin handle */
static char name[] = "Spotify Now Playing";
static char desc[] = "Sends currently playing song in Spotify to the current channel.";
static char version[] = "1.0";
static const char helpmsg[] = "Sends currently playing song in Spotify to the current channel. USAGE: /spotify";

static int spotify_cb(char *word[], char *word_eol[], void *userdata)
{
	HWND hWnd = FindWindowW (L"SpotifyMainWindow", NULL);
	wchar_t window_text[1024];

	if (hWnd == NULL)
	{
		hexchat_print (ph, "Unable to find Spotify window.");
		return HEXCHAT_EAT_ALL;
	}

	if (GetWindowTextW (hWnd, window_text, 1024))
	{
		char utf8_title[2048], *title = utf8_title;

		if (wcscmp (window_text, L"Spotify") == 0)
		{
			hexchat_print (ph, "Spotify is not playing anything right now.");
			return HEXCHAT_EAT_ALL;
		}

		/* UTF-16 to UTF-8 */
		if (!WideCharToMultiByte (CP_UTF8, 0, window_text, -1, &utf8_title, sizeof(utf8_title), NULL, NULL))
		{
			hexchat_print (ph, "Failed to convert song title to utf8");
			return HEXCHAT_EAT_ALL;
		}

		/* Older versions have a prefix */
		if (strncmp (title, "Spotify - ", 10) == 0)
			title += 10;

		hexchat_commandf (ph, "me is now listening to: %s", title);
	}
	return HEXCHAT_EAT_ALL;
}

int hexchat_plugin_init(hexchat_plugin *plugin_handle,
                      char **plugin_name,
                      char **plugin_desc,
                      char **plugin_version,
                      char *arg)
{
	/* we need to save this for use with any hexchat_* functions */
	ph = plugin_handle;

	/* tell HexChat our info */
	*plugin_name = name;
	*plugin_desc = desc;
	*plugin_version = version;

	hexchat_hook_command (ph, "SPOTIFY", HEXCHAT_PRI_NORM, spotify_cb, helpmsg, 0);

	hexchat_printf (ph, "%s plugin loaded\n", name);

	return 1;	/* return 1 for success */
}

int hexchat_plugin_deinit(hexchat_plugin *plugin_handle)
{
	hexchat_printf (plugin_handle, "%s plugin unloaded\n", name);
	return 1;
}


text:
require 'minitest_helper'

FDB.directory.remove_if_exists(FDB.open, 'hasone_docs')
Hypostasis::Connection.create_namespace 'hasone_docs', data_model: :document

class HasOneOwnerDocument
  include Hypostasis::Document

  use_namespace 'hasone_docs'

  field :name
  field :age

  has_one :has_one_child_document
end

class HasOneChildDocument
  include Hypostasis::Document

  use_namespace 'hasone_docs'

  field :name
  field :age

  belongs_to :has_one_owner_document
end

describe 'Document has_one Relationship' do
  before do
    FDB.directory.remove_if_exists(database, 'hasone_docs')
    Hypostasis::Connection.create_namespace 'hasone_docs', data_model: :document
    @owner = HasOneOwnerDocument.create(name: 'John', age: '25')
    @child = HasOneChildDocument.create(name: 'James', age: '6', has_one_owner_document_id: @owner.id)
  end

  after do
    Hypostasis::Connection.destroy_namespace 'hasone_docs'
  end

  it { @owner.must_respond_to :has_one_child_document }
  it { @child.must_respond_to :has_one_owner_document }

  it { @owner.has_one_child_document.is_a?(HasOneChildDocument).must_equal true }
  it { @owner.has_one_child_document.id.must_equal @child.id }

  it { @child.has_one_owner_document.is_a?(HasOneOwnerDocument).must_equal true }
  it { @child.has_one_owner_document.id.must_equal @owner.id }
end