text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>PostDoctoral Research Fellowship</AwardTitle>
    <AwardEffectiveDate>06/01/2009</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2013</AwardExpirationDate>
    <AwardAmount>135000</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      03040000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Mathematical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Bruce P. Palka</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award is funded under the American Recovery and Reinvestment Act of 2009 (Public Law 111-5). Postdoctoral Research Fellowship.</AbstractNarration>
    <MinAmdLetterDate>07/04/2009</MinAmdLetterDate>
    <MaxAmdLetterDate>02/22/2012</MaxAmdLetterDate>
    <ARRAAmount>135000</ARRAAmount>
    <AwardID>0903120</AwardID>
    <Investigator>
      <FirstName>Vincent</FirstName>
      <LastName>Vu</LastName>
      <EmailAddress/>
      <StartDate>07/04/2009</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Vu Vincent Q</Name>
      <CityName>Berkeley</CityName>
      <ZipCode>947203860</ZipCode>
      <PhoneNumber/>
      <StreetAddress/>
      <CountryName>United States</CountryName>
      <StateName>California</StateName>
      <StateCode>CA</StateCode>
    </Institution>
    <FoaInformation>
      0000099
      <Name>Other Applications NEC</Name>
    </FoaInformation>
  </Award>
</rootTag>


text:
package dk.troelssiggaard.iacontacts.sensors;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import dk.troelssiggaard.iacontacts.IAService;
import dk.troelssiggaard.iacontacts.database.CurrentPrediction;
import dk.troelssiggaard.iacontacts.estimation.InterruptibilityLogic;

/**
 * Created by ts.
 */
public class ProximitySensor implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor proximitySensor;
    private CurrentPrediction currentPrediction;
    private Context context;

    public ProximitySensor(SensorManager manager, int delay, Context context) {
        this.context = context;
        this.sensorManager = manager;
        proximitySensor = manager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sensorManager.registerListener(this, proximitySensor, delay);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        currentPrediction = new CurrentPrediction(context);

        Log.i("ProximitySensor", "Proxmity changed");

        // Sensor changed
        float distance = event.values[0];
        if (distance > 1.0) {
            currentPrediction.setPhoneInPocket(false);
        } else {
            currentPrediction.setPhoneInPocket(true);
        }

        // Update interruptibility and send new information as local broadcast
        new InterruptibilityLogic(context).update();

        currentPrediction.close();

        //stopSensor();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void stopSensor() {
        sensorManager.unregisterListener(this);
        sensorManager.flush(this);
        proximitySensor = null;
        currentPrediction.close();
    }
}

redpajama_set_name: RedPajamaGithub


text:
'''
Created on Nov 22, 2014

@author: gearsad
'''
from user_update_t import user_update_t
from kinect_update_t import kinect_update_t, kinect_joint_t
from oculus_update_t import oculus_update_t
from wearable_update_t import wearable_update_t
from scene import User

class UserManager(object):
    '''
    A manager for all the users in the scene (populated by LCM, consumed everywhere :))
    '''

    def __init__(self, thisUserName):
        '''
        Constructor
        '''
        self.__thisUserName = thisUserName

        self.currentUser = user_update_t()
        # Initialize him/her until LCM updates it.
        self.currentUser.kinect = kinect_update_t()
        self.currentUser.kinect.headposition = kinect_joint_t.kinect_joint_t()
        self.currentUser.kinect.torsoposition = kinect_joint_t.kinect_joint_t()
        self.currentUser.oculus = oculus_update_t()
        print "HACK - populate a full user UserManager __init__ if you are planning on using it in the future."

        # Save the state of the last user position
        self.__lastCurrentUser = self.currentUser

    def Attach(self, botManager, roleManager, renderManager):
        '''
        Attach the managers to the UserManager
        '''
        self.__renderManager = renderManager
        self.__botManager = botManager
        self.__roleManager = roleManager

        # Create the other users.
        self.users = []

        self.currentUserModel = User.User(self.__botManager, self.__roleManager, self.__renderManager, self.__thisUserName)
        self.otherUserModels = []

    def Update(self):
        '''
        Update the current user
        '''
        isHandSelecting = (self.__lastCurrentUser.kinect.is_lhandclosed == 1 and self.currentUser.kinect.is_lhandclosed == 0)
        self.__lastCurrentUser = self.currentUser

        self.currentUserModel.Update(isHandSelecting)

    def UpdateUserFromLCM(self, user):
        '''
        Method to update the users list with a new or current user.
        '''
        if(user.name == self.__thisUserName):
            self.currentUser = user
            self.currentUserModel.UpdateUserFromLCM(self.currentUser)
#             print "Oculus Orientation for {0} = {1}, {2}, {3}".format(user.name, user.oculus.headorientation[0],user.oculus.headorientation[1], user.oculus.headorientation[2])
        else:
            #Update the other users
            found = False
            index = 0
            for myUser in self.users:
                if(myUser.name == user.name): #Update this user
                    self.users[index] = user #Replace the user, we found it
                    self.otherUserModels[index].UpdateUserFromLCM(user)
                    found = True
                else:
                    index = index + 1
            if(found is not True):
                newUser = User.User(self.__renderManager.renderers, user.name)
                print "Adding another user - moving him away from the axis! Remove in future."
                newUser.vtkActor.SetPosition([0, 0, 10])
                self.users.append(user)
                self.otherUserModels.append(newUser)

    def GetCurrentUser(self):
        return self.__thisUserName


text:
package org.guess.sys.controller;

import java.util.List;

import org.guess.core.web.BaseController;
import org.guess.sys.model.Role;
import org.guess.sys.model.User;
import org.guess.sys.service.RoleService;
import org.guess.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController<User, UserService> {

	{
		editView = "/sys/user/edit";
		listView = "/sys/user/list";
		showView = "/sys/user/show";
	}

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@RequestMapping("isAvailable")
	public @ResponseBody
	boolean isLoginIdAvailable(@RequestParam("loginId") String id, @RequestParam("oldValue") String old) {
		if (id.equals(old))
			return true;
		User u = userService.findUniqueBy("loginId", id);
		return u == null;
	}

	@Override
	public ModelAndView create() throws Exception {
		ModelAndView mav = new ModelAndView(editView);
		List<Role> roles = roleService.getAll();
		mav.addObject("roles", roles);
		return mav;
	}

	@Override
	public String create(User user) throws Exception {
		String oldpwd = request.getParameter("oldpwd");
		String[] roleIds = request.getParameterValues("roleIds");
		userService.save(user,roleIds,oldpwd);
		return REDIRECT + listView;
	}

	@Override
	public ModelAndView update(@PathVariable("id") Long id) throws Exception {
		ModelAndView mav = new ModelAndView(editView);
		List<Role> roles = roleService.getAll();
		mav.addObject("roles", roles);
		User obj = userService.get(id);
		mav.addObject("obj", obj);
		return mav;
	}

	/**
	 * 更改用户状态
	 */
	@RequestMapping(value="changeUserStatus",method=RequestMethod.POST)
	@ResponseBody
	public int changeUserStatus(@RequestParam("id") Long id){
		return userService.changeUserStatus(id);
	}

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Statement</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Phoenix 3.0">
<link rel="up" href="../modules.html" title="Modules">
<link rel="prev" href="operator.html" title="Operator">
<link rel="next" href="statement/block_statement.html" title="Block Statement">

Home
Libraries
People
FAQ
More

Statement

Block Statement

if_ Statement

if_else_ Statement

switch_
        Statement

while_
        Statement

do_while_ Statement

for_ Statement

try_
        catch_ Statement

throw_

        Lazy statements...

        The expressions presented so far are sufficiently powerful to construct quite
        elaborate structures. We have presented lazy-functions and lazy-operators.
        How about lazy-statements? First, an appetizer:

        Print all odd-numbered contents of an STL container using std::for_each
        (all_odds.cpp):

std::for_each(c.begin(), c.end(),
    if_(arg1 % 2 == 1)
    [
        cout << arg1 << ' '
    ]
);

        Huh? Is that valid C++? Read on...

        Yes, it is valid C++. The sample code above is as close as you can get to
        the syntax of C++. This stylized C++ syntax differs from actual C++ code.
        First, the if has a trailing
        underscore. Second, the block uses square brackets instead of the familiar
        curly braces {}.

Note

          C++ in C++?

          In as much as Spirit
          attempts to mimic EBNF in C++, Phoenix attempts to mimic C++ in C++!!!

Note

          Unlike lazy functions and lazy operators, lazy statements always return
          void.

        Here are more examples with annotations. The code almost speaks for itself.

Copyright © 2002-2005, 2010 Joel de Guzman, Dan Marsden, Thomas Heller

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
@interface CardCell : UITableViewCell

@property (nonatomic, strong) UIImageView *cardImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *sizeLabel;
@property (nonatomic, strong) UILabel *priceLabel;

@end


text:
package listener

import (
	"encoder-backend/pkg/watcher/events"
	"path/filepath"
	"strings"
	"time"
)

type Option func(*options)

type options struct {
	ScanInterval       time.Duration
	ExtensionWhitelist []string
	Publisher          chan<- events.Event
}

// IsAllowedExtension
// whether or not a filename contains a whitelisted extension or not
func (o options) IsAllowedExtension(name string) bool {
	if len(o.ExtensionWhitelist) == 0 {
		return true
	}

	match := strings.ToLower(strings.Replace(filepath.Ext(name), ".", "", 1))
	for _, ext := range o.ExtensionWhitelist {
		if match == ext {
			return true
		}
	}

	return false
}

// WithScanInterval
// Interval in milliseconds
// how often to poll the file system smaller equals faster
func WithScanInterval(interval int64) Option {
	return func(o *options) {
		o.ScanInterval = time.Duration(interval) * time.Millisecond
	}
}

// WithExtensionWhitelist
// Restricts the extension types we wish to watch to the ones provided
func WithExtensionWhitelist(extensions ...string) Option {
	return func(o *options) {
		o.ExtensionWhitelist = append(o.ExtensionWhitelist, extensions...)
	}
}


text:
package validator

import (
	"github.com/open-policy-agent/opa/internal/gqlparser/ast"

	//nolint:revive // Validator rules each use dot imports for convenience.
	. "github.com/open-policy-agent/opa/internal/gqlparser/validator"
)

func init() {
	AddRule("VariablesInAllowedPosition", func(observers *Events, addError AddErrFunc) {
		observers.OnValue(func(walker *Walker, value *ast.Value) {
			if value.Kind != ast.Variable || value.ExpectedType == nil || value.VariableDefinition == nil || walker.CurrentOperation == nil {
				return
			}

			tmp := *value.ExpectedType

			// todo: move me into walk
			// If there is a default non nullable types can be null
			if value.VariableDefinition.DefaultValue != nil && value.VariableDefinition.DefaultValue.Kind != ast.NullValue {
				if value.ExpectedType.NonNull {
					tmp.NonNull = false
				}
			}

			if !value.VariableDefinition.Type.IsCompatible(&tmp) {
				addError(
					Message(
						`Variable "%s" of type "%s" used in position expecting type "%s".`,
						value,
						value.VariableDefinition.Type.String(),
						value.ExpectedType.String(),
					),
					At(value.Position),
				)
			}
		})
	})
}


text:
/*
 * Copyright 2014 Cloudius Systems
 */

#include "core/reactor.hh"
#include <iostream>

struct test {
    test(pollable_fd l) : listener(std::move(l)) {}
    pollable_fd listener;
    struct connection {
        connection(pollable_fd fd) : fd(std::move(fd)) {}
        pollable_fd fd;
        char buffer[8192];
        void copy_data() {
            fd.read_some(buffer, sizeof(buffer)).then([this] (size_t n) {
                if (n) {
                    fd.write_all(buffer, n).then([this] {
                        copy_data();
                    });
                } else {
                    delete this;
                }
            });
        }
    };
    void new_connection(pollable_fd fd, socket_address sa) {
        auto c = new connection(std::move(fd));
        c->copy_data();
    }
    void start_accept() {
        listener.accept().then([this] (pollable_fd fd, socket_address sa) {
            new_connection(std::move(fd), std::move(sa));
            start_accept();
        });
    }
};

int main(int ac, char** av)
{
    ipv4_addr addr{10000};
    listen_options lo;
    lo.reuse_address = true;
    test t(engine().posix_listen(make_ipv4_address(addr), lo));
    t.start_accept();
    engine().run();
    return 0;
}


text:
package Ferret::Lexer;

use warnings;
use strict;
use 5.010;

# Lexer.pm loads both the constructor and the tokenizer,
# but they can be loaded individually if desired.
use F;
use Ferret::Lexer::Tokenizer;
use Ferret::Lexer::Constructor;

1


text:
The sample source codes on this page shows how to draw text, images and lines in pdf with pdf generator sdk for javascript in JavaScript. ByteScout Premium Suite is the set that includes 12 SDK products from ByteScout including tools and components for PDF, barcodes, spreadsheets, screen video recording and you can use it to draw text, images and lines in pdf with pdf generator sdk for javascript with JavaScript.

The following code snippet for ByteScout Premium Suite works best when you need to quickly draw text, images and lines in pdf with pdf generator sdk for javascript in your JavaScript application. IF you want to implement the functionality, just copy and paste this code for JavaScript below into your code editor with your app, compile and run your application. If you want to use these JavaScript sample examples in one or many applications then they can be used easily.

You can download free trial version of ByteScout Premium Suite from our website to see and try many others source code samples for JavaScript.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Premium%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Premium%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****checkdatauri.js:**

```
	// checks if we have datauri support in current browser
        // if we have support for datauri support then we can stream generated PDF right into the browser
        // otherwise we should use Downloadify script to allow user to save PDF file
	function CheckDataURISupport(){

	var result = true;
	var checkDataURISupportImage = new Image();

	checkDataURISupportImage.onload = checkDataURISupportImage.onerror = function(){
		if(this.width != 1 || this.height != 1){
			result = false;
		}
	}
	checkDataURISupportImage.src = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
	// check if we have datauri support in current browser - end

		return result;
	}

```

<!-- code block end -->

<!-- code block begin -->

##### ****createpdf.js:**

```
// function that creates BytescoutPDF instance (defined in BytescoutPDF.js script which have to be included into the same page)
// then calls API methods and properties to create PDF document
// and returns created BytescoutPDF object instance
// this CreatePDF() function is called from Sample.html
// IsInternetExplorer8OrLower parameter indicates if we use IE8 or lower so we CAN'T use images (as it requires HTML5 Canvas available in IE9 or higher). Other browsers should be working fine

// IMPORTANT ABOUT IMAGES:
// When using Firefox or IE, pdf generation may fail because images are not accessible when pdf generation works
// the solution for this issue is to preload images in main HTML document before running PDF generation
// to preload images, put them into hidden div block "pdfreportimages" - you can see it in the sample.html right after <body> opening tag

function CreatePDF(IsInternetExplorer8OrLower) {

	// create BytescoutPDF object instance
    var pdf = new BytescoutPDF();

    // set document properties: Title, subject, keywords, author name and creator name
    pdf.propertiesSet("Sample document title", "Sample subject", "keyword1, keyword 2, keyword3", "Document Author Name", "Document Creator Name");

	// set page size
    pdf.pageSetSize(BytescoutPDF.Letter);
    // set page orientation
    pdf.pageSetOrientation(true);

	// add new page
    pdf.pageAdd();

    pdf.fontSetName('Helvetica');
    pdf.fontSetStyle(false, false, false);

    for (var i = 0; i < 5; i++) {
        pdf.fontSetSize(10 + i * 4);
        pdf.textAdd(20 + 70 * i, 20, 'hola');
    }

    pdf.fontSetStyle(false, true, true);
    pdf.textAdd(50, 50, 'hello');
    pdf.fontSetStyle(true, true, true);
    pdf.textAdd(250, 50, 'hello');

    pdf.pageSetOrientation(false);
    pdf.pageAdd();

    pdf.fontSetName('Times-Roman');
    pdf.textAdd(20, 70, 'hello');
    pdf.fontSetStyle(true, false, true);
    pdf.textAdd(100, 70, 'hello');
    pdf.fontSetStyle(false, true, true);
    pdf.textAdd(190, 70, 'hello');
    pdf.fontSetStyle(true, true, true);
    pdf.textAdd(280, 70, 'hello');

    pdf.fontSetName('Courier');
    pdf.textAdd(20, 90, 'hello');
    pdf.fontSetStyle(true, false, false);
    pdf.textAdd(100, 90, 'hello');
    pdf.fontSetStyle(false, true, false);
    pdf.textAdd(190, 90, 'hello');
    pdf.fontSetStyle(true, true, true);
    pdf.textAdd(280, 90, 'hello');

    for (var j = 0; j < 50; j++) {
        pdf.graphicsSetColor(j * 5, 0, 250 - j * 5);
        pdf.graphicsSetLineWidth(1 + j / 25);
        pdf.graphicsDrawLine(20, 120 + j * 4, 120, 120 + j * 4);
    }

    pdf.textAdd(200, 150, 'hello');

    pdf.pageSetOrientation(true);
    pdf.pageAdd();

// we can use images only if we are on IE9 or higher (or non-IE browser)
 if (!IsInternetExplorer8OrLower)
 {

    pdf.imageLoadFromUrl('image1.jpg');
    pdf.imagePlace(20, 40);

    pdf.imageLoadFromUrl('image2.jpg');
    pdf.imagePlace(120, 220);
}
    // return BytescoutPDF object instance
    return pdf;
}

```

<!-- code block end -->


text:
<?php

/**
 * @file
 * Contains \Drupal\entity_reference\Plugin\Field\FieldWidget\AutocompleteTagsWidget.
 */

namespace Drupal\entity_reference\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\Tags;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'entity_reference autocomplete-tags' widget.
 *
 * @FieldWidget(
 *   id = "entity_reference_autocomplete_tags",
 *   label = @Translation("Autocomplete (Tags style)"),
 *   description = @Translation("An autocomplete text field."),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = TRUE
 * )
 */
class AutocompleteTagsWidget extends AutocompleteWidgetBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function elementValidate($element, FormStateInterface $form_state, $form) {
    $value = array();
    // If a value was entered into the autocomplete.
    $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition);
    $bundles = entity_get_bundles($this->getFieldSetting('target_type'));
    $auto_create = $this->getSelectionHandlerSetting('auto_create');

    if (!empty($element['#value'])) {
      $value = array();
      foreach (Tags::explode($element['#value']) as $input) {
        $match = FALSE;

        // Take "label (entity id)', match the ID from parenthesis when it's a
        // number.
        if (preg_match("/.+\((\d+)\)/", $input, $matches)) {
          $match = $matches[1];
        }
        // Match the ID when it's a string (e.g. for config entity types).
        elseif (preg_match("/.+\(([\w.]+)\)/", $input, $matches)) {
          $match = $matches[1];
        }
        else {
          // Try to get a match from the input string when the user didn't use
          // the autocomplete but filled in a value manually.
          $match = $handler->validateAutocompleteInput($input, $element, $form_state, $form, !$auto_create);
        }

        if ($match) {
          $value[] = array('target_id' => $match);
        }
        elseif ($auto_create && (count($this->getSelectionHandlerSetting('target_bundles')) == 1 || count($bundles) == 1)) {
          // Auto-create item. See
          // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
          $value[] = array(
            'target_id' => NULL,
            'entity' => $this->createNewEntity($input, $element['#autocreate_uid']),
          );
        }
      }
    };
    // Change the element['#parents'], so in setValueForElement() we populate
    // the correct key.
    array_pop($element['#parents']);
    $form_state->setValueForElement($element, $value);
  }
}


text:
package net.bytebuddy.implementation.bind.annotation;

import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.method.ParameterList;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.bind.ArgumentTypeResolver;
import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import net.bytebuddy.implementation.bytecode.StackSize;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

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

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;

public class ArgumentBinderTest extends AbstractAnnotationBinderTest<Argument> {

    @Mock
    private TypeDescription sourceType, targetType;

    @Mock
    private TypeDescription.Generic genericSourceType, genericTargetType;

    public ArgumentBinderTest() {
        super(Argument.class);
    }

    @Override
    @Before
    @SuppressWarnings("unchecked")
    public void setUp() throws Exception {
        super.setUp();
        when(genericSourceType.asErasure()).thenReturn(sourceType);
        when(sourceType.asGenericType()).thenReturn(genericSourceType);
        when(genericSourceType.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(genericSourceType);
        when(genericTargetType.asErasure()).thenReturn(targetType);
        when(targetType.asGenericType()).thenReturn(genericTargetType);
        when(genericTargetType.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(targetType);
    }

    @Override
    protected TargetMethodAnnotationDrivenBinder.ParameterBinder<Argument> getSimpleBinder() {
        return Argument.Binder.INSTANCE;
    }

    @Test
    public void testLegalBindingNoRuntimeTypeUnique() throws Exception {
        assertBinding(Assigner.Typing.STATIC, Argument.BindingMechanic.UNIQUE);
    }

    @Test
    public void testLegalBindingRuntimeTypeUnique() throws Exception {
        assertBinding(Assigner.Typing.DYNAMIC, Argument.BindingMechanic.UNIQUE);
    }

    @Test
    public void testLegalBindingNoRuntimeTypeAnonymous() throws Exception {
        assertBinding(Assigner.Typing.STATIC, Argument.BindingMechanic.ANONYMOUS);
    }

    @Test
    public void testLegalBindingRuntimeTypeAnonymous() throws Exception {
        assertBinding(Assigner.Typing.DYNAMIC, Argument.BindingMechanic.ANONYMOUS);
    }

    private void assertBinding(Assigner.Typing typing, Argument.BindingMechanic bindingMechanic) throws Exception {
        final int sourceIndex = 2;
        when(stackManipulation.isValid()).thenReturn(true);
        when(annotation.value()).thenReturn(sourceIndex);
        when(annotation.bindingMechanic()).thenReturn(bindingMechanic);
        List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(sourceIndex + 1);
        for (int i = 0; i < sourceIndex; i++) {
            TypeDescription typeDescription = mock(TypeDescription.class);
            when(typeDescription.getStackSize()).thenReturn(StackSize.ZERO);
            typeDescriptions.add(i, typeDescription);
        }
        when(sourceType.getStackSize()).thenReturn(StackSize.ZERO);
        typeDescriptions.add(sourceIndex, sourceType);
        when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, typeDescriptions));
        when(source.isStatic()).thenReturn(false);
        when(target.getType()).thenReturn(genericTargetType);
        MethodDelegationBinder.ParameterBinding<?> parameterBinding = Argument.Binder.INSTANCE
                .bind(annotationDescription, source, target, implementationTarget, assigner, typing);
        assertThat(parameterBinding.isValid(), is(true));
        Object expectedToken = new ArgumentTypeResolver.ParameterIndexToken(sourceIndex);
        if (bindingMechanic == Argument.BindingMechanic.UNIQUE) {
            assertThat(parameterBinding.getIdentificationToken(), is(expectedToken));
            assertThat(parameterBinding.getIdentificationToken().hashCode(), is(expectedToken.hashCode()));
        } else {
            assertThat(parameterBinding.getIdentificationToken(), not(expectedToken));
            assertThat(parameterBinding.getIdentificationToken().hashCode(), not(expectedToken.hashCode()));
        }
        verify(annotation, atLeast(1)).value();
        verify(source, atLeast(1)).getParameters();
        verify(target, atLeast(1)).getType();
        verify(target, never()).getDeclaredAnnotations();
        verify(assigner).assign(genericSourceType, genericTargetType, typing);
        verifyNoMoreInteractions(assigner);
    }

    @Test
    public void testIllegalBinding() throws Exception {
        final int sourceIndex = 0, targetIndex = 0;
        when(annotation.value()).thenReturn(sourceIndex);
        when(target.getIndex()).thenReturn(targetIndex);
        when(source.getParameters()).thenReturn(new ParameterList.Empty<ParameterDescription.InDefinedShape>());
        MethodDelegationBinder.ParameterBinding<?> parameterBinding = Argument.Binder.INSTANCE
                .bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
        assertThat(parameterBinding.isValid(), is(false));
        verify(annotation, atLeast(1)).value();
        verify(source, atLeast(1)).getParameters();
        verifyZeroInteractions(assigner);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNegativeAnnotationValue() throws Exception {
        when(annotation.value()).thenReturn(-1);
        Argument.Binder.INSTANCE.bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
    }

    @SuppressWarnings("unused")
    private static class Carrier {

        private void method(@Argument(0) Void parameter) {
            /* do nothing */
        }
    }
}


text:
@interface LittleEndianByteBuffer : NSObject
- (id)initWithData:(NSData *)data;
- (id)initWithData:(NSData *)data littleEndian: (BOOL) lth;
@property(nonatomic) long long int position;
@property(nonatomic, retain) NSData *data;
- (short)nextShort;
- (int)nextInt;
- (long long int)nextLong;
- (NSString *)nextString;
- (NSString *)nextBytesAsString:(int)len;
- (NSString *)nextLine;
- (float)nextFloat;
- (double)nextDouble;
- (BOOL)isEOF;
- (int)available;
- (u_char)nextByte;
+ (id)littleEndianByteBufferWithData:(NSData *)data;
+ (id)littleEndianByteBufferWithData:(NSData *)data littleEndian:(BOOL)lth;
@end


text:
.aboutTextInputs {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-right: 1em;
  margin-right: auto;
}

.coverInputContainer {
  position: relative;
  height: 12.5em;
  width: 12.5em;
}

.coverLabel {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  border: 1px solid #d3d3d3;
  padding: 0.25em;
  flex-shrink: 0;
  cursor: pointer;
}

.coverInput {
  opacity: 0;
}
.coverInput:invalid ~ .coverLabel {
  border-color: red;
}
.coverInput:focus ~ .coverLabel {
  border-color: orange;
}

.shareFormAboutFieldset {
  width: 40em;
  margin: 0 auto;
  border: none;
  display: flex;
}

.shareFormAboutFieldsetInline {
  display: flex;
  align-items: center;
}


text:
package com.quartzodev.api.entities.google;

import com.google.gson.annotations.SerializedName;

/**
 * Created by victoraldir on 12/04/2017.
 */

public class ImageLink {

    @SerializedName("smallThumbnail")
    public String smallThumbnail;

    @SerializedName("thumbnail")
    public String thumbnail;

    public ImageLink() {
    }

    public String getSmallThumbnail() {
        return smallThumbnail;
    }

    public void setSmallThumbnail(String smallThumbnail) {
        this.smallThumbnail = smallThumbnail;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
}


text:
package org.apache.poi.poifs.storage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import junit.framework.TestCase;

import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.util.DummyPOILogger;
import org.apache.poi.util.POILogger;

/**
 * Class to test RawDataBlockList functionality
 *
 * @author Marc Johnson
 */
public final class TestRawDataBlockList extends TestCase {
    /**
     * Test creating a normal RawDataBlockList
     */
    public void testNormalConstructor() throws IOException {
        byte[] data = new byte[ 2560 ];

        for (int j = 0; j < 2560; j++)
        {
            data[ j ] = ( byte ) j;
        }
        new RawDataBlockList(new ByteArrayInputStream(data), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
    }

    /**
     * Test creating an empty RawDataBlockList
     */
    public void testEmptyConstructor() throws IOException {
        new RawDataBlockList(new ByteArrayInputStream(new byte[ 0 ]), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
    }

    /**
     * Test creating a short RawDataBlockList
     */
    public void testShortConstructor() throws Exception {
        // Get the logger to be used
        POILogger oldLogger = RawDataBlock.log;
        DummyPOILogger logger = new DummyPOILogger();
        try {
            RawDataBlock.log = logger;
            assertEquals(0, logger.logged.size());

            // Test for various short sizes
            for (int k = 2049; k < 2560; k++)
            {
                byte[] data = new byte[ k ];

                for (int j = 0; j < k; j++)
                {
                    data[ j ] = ( byte ) j;
                }

                // Check we logged the error
                logger.reset();
                new RawDataBlockList(new ByteArrayInputStream(data), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
                assertEquals(1, logger.logged.size());
            }
        } finally {
            RawDataBlock.log = oldLogger;
        }
    }
}


text:
set -euo pipefail

if [ -x .gopath/bin/repeatr ]; then PATH=$PWD/.gopath/bin/:$PATH; fi
if [ ! -d .git ]; then echo "this script assumes it is run from a local git repo containing repeatr." 1>&2 ; exit 1 ; fi

### Set values for metadata our build injects for debugging purposes.
#  These are used by go-generate (see `cli/go.version.tmpl`);
#  In order to produce consistent outputs, we have to affix them.

# Pick out the current head hash.
# Of course you could use any commit hash you want.
GITCOMMIT=${GITCOMMIT:-$(git rev-parse HEAD)}

# Nil builddate by default.  But if you want to set one, go ahead.
BUILDDATE=${BUILDDATE:-"xxx"}

### Assemble the full formula
# This is mostly just taking our metadata variables above, and injecting them.
Formula="$(cat <<EOF
inputs:
	"/":
		type: "tar"
		hash: "uJRF46th6rYHt0zt_n3fcDuBfGFVPS6lzRZla5hv6iDoh5DVVzxUTMMzENfPoboL"
		silo: "http+ca://repeatr.s3.amazonaws.com/assets/"
	"/app/go/":
		type: "tar"
		hash: "vbl0TwPjBrjoph65IaWxOy-Yl0MZXtXEDKcxodzY0_-inUDq7rPVTEDvqugYpJAH"
		silo: "https://storage.googleapis.com/golang/go1.5.linux-amd64.tar.gz"
	"/task/repeatr/":
		type: "git"
		hash: "${GITCOMMIT}"
		silo:
			- "."
			- "https://github.com/polydawn/repeatr.git"
action:
	command:
		- "/bin/bash"
		- "-c"
		- |
			#!/bin/bash
			export GOROOT=/app/go/go
			export PATH=\$PATH:/app/go/go/bin
			./goad install
	cwd: "/task/repeatr/"
	env:
		"GITCOMMIT": "${GITCOMMIT}"
		"BUILDDATE": "${BUILDDATE}"
outputs:
	"executable":
		type: "tar"
		mount: "/task/repeatr/.gopath/bin/"
		filters:
			- uid 10100
			- gid 10100
			- mtime @0
		silo: "file://repeatr.tar"
EOF
)"

### run it!
time repeatr run -i <(echo "${Formula}")


text:
package consulo.lombok.processors.util;

import javax.annotation.Nonnull;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiAnnotationMemberValue;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.light.LightMethodBuilder;
import consulo.module.extension.ModuleExtension;

/**
 * @author VISTALL
 * @since 19:45/29.03.13
 */
public class LombokUtil
{
	public static boolean isExtensionEnabled(@Nonnull PsiElement element, @Nonnull Class<? extends ModuleExtension> extensionClass)
	{
		Module moduleForPsiElement = ModuleUtilCore.findModuleForPsiElement(element);
		if(moduleForPsiElement == null)
		{
			return false;
		}
		return ModuleUtil.getExtension(moduleForPsiElement, extensionClass) != null;
	}

	public static void copyAccessModifierFromOriginal(PsiModifierListOwner from, LightMethodBuilder to)
	{
		if(from.hasModifierProperty(PsiModifier.PRIVATE))
		{
			to.addModifier(PsiModifier.PRIVATE);
		}
		else if(from.hasModifierProperty(PsiModifier.PUBLIC))
		{
			to.addModifier(PsiModifier.PUBLIC);
		}
		else if(from.hasModifierProperty(PsiModifier.PROTECTED))
		{
			to.addModifier(PsiModifier.PROTECTED);
		}
	}

	public static void setAccessModifierFromAnnotation(@Nonnull PsiAnnotation annotation, LightMethodBuilder to, String methodName)
	{
		String modifier = getModifierFromAnnotation(annotation, methodName);
		to.addModifier(modifier);
	}

	@Nonnull
	public static String getModifierFromAnnotation(@Nonnull PsiAnnotation annotation, String methodName)
	{
		final PsiAnnotationMemberValue attributeValue = annotation.findAttributeValue(methodName);
		if(attributeValue instanceof PsiReference)
		{
			final PsiElement resolve = ((PsiReference) attributeValue).resolve();
			if(resolve instanceof PsiEnumConstant)
			{
				final String name = ((PsiEnumConstant) resolve).getName();

				if(name.equals("PUBLIC"))
				{
					return PsiModifier.PUBLIC;
				}
				else if(name.equals("PRIVATE"))
				{
					return PsiModifier.PRIVATE;
				}
				else if(name.equals("PROTECTED"))
				{
					return PsiModifier.PROTECTED;
				}
				else if(name.equals("PACKAGE"))
				{
					return PsiModifier.PACKAGE_LOCAL;
				}

				// FIXME [VISTALL] MODULE & NONE modifier
			}
		}
		return PsiModifier.PUBLIC;
	}
}


text:
use crate::future::Future;
use crate::runtime::task::core::{Core, Trailer};
use crate::runtime::task::{Cell, Harness, Header, Id, Schedule, State};

use std::ptr::NonNull;
use std::task::{Poll, Waker};

/// Raw task handle
pub(super) struct RawTask {
    ptr: NonNull<Header>,
}

pub(super) struct Vtable {
    /// Polls the future.
    pub(super) poll: unsafe fn(NonNull<Header>),

    /// Schedules the task for execution on the runtime.
    pub(super) schedule: unsafe fn(NonNull<Header>),

    /// Deallocates the memory.
    pub(super) dealloc: unsafe fn(NonNull<Header>),

    /// Reads the task output, if complete.
    pub(super) try_read_output: unsafe fn(NonNull<Header>, *mut (), &Waker),

    /// The join handle has been dropped.
    pub(super) drop_join_handle_slow: unsafe fn(NonNull<Header>),

    /// An abort handle has been dropped.
    pub(super) drop_abort_handle: unsafe fn(NonNull<Header>),

    /// Scheduler is being shutdown.
    pub(super) shutdown: unsafe fn(NonNull<Header>),

    /// The number of bytes that the `trailer` field is offset from the header.
    pub(super) trailer_offset: usize,

    /// The number of bytes that the `scheduler` field is offset from the header.
    pub(super) scheduler_offset: usize,

    /// The number of bytes that the `id` field is offset from the header.
    pub(super) id_offset: usize,
}

/// Get the vtable for the requested `T` and `S` generics.
pub(super) fn vtable<T: Future, S: Schedule>() -> &'static Vtable {
    &Vtable {
        poll: poll::<T, S>,
        schedule: schedule::<S>,
        dealloc: dealloc::<T, S>,
        try_read_output: try_read_output::<T, S>,
        drop_join_handle_slow: drop_join_handle_slow::<T, S>,
        drop_abort_handle: drop_abort_handle::<T, S>,
        shutdown: shutdown::<T, S>,
        trailer_offset: OffsetHelper::<T, S>::TRAILER_OFFSET,
        scheduler_offset: OffsetHelper::<T, S>::SCHEDULER_OFFSET,
        id_offset: OffsetHelper::<T, S>::ID_OFFSET,
    }
}

/// Calling `get_trailer_offset` directly in vtable doesn't work because it
/// prevents the vtable from being promoted to a static reference.
///
/// See this thread for more info:
/// <https://users.rust-lang.org/t/custom-vtables-with-integers/78508>
struct OffsetHelper<T, S>(T, S);
impl<T: Future, S: Schedule> OffsetHelper<T, S> {
    // Pass `size_of`/`align_of` as arguments rather than calling them directly
    // inside `get_trailer_offset` because trait bounds on generic parameters
    // of const fn are unstable on our MSRV.
    const TRAILER_OFFSET: usize = get_trailer_offset(
        std::mem::size_of::<Header>(),
        std::mem::size_of::<Core<T, S>>(),
        std::mem::align_of::<Core<T, S>>(),
        std::mem::align_of::<Trailer>(),
    );

    // The `scheduler` is the first field of `Core`, so it has the same
    // offset as `Core`.
    const SCHEDULER_OFFSET: usize = get_core_offset(
        std::mem::size_of::<Header>(),
        std::mem::align_of::<Core<T, S>>(),
    );

    const ID_OFFSET: usize = get_id_offset(
        std::mem::size_of::<Header>(),
        std::mem::align_of::<Core<T, S>>(),
        std::mem::size_of::<S>(),
        std::mem::align_of::<Id>(),
    );
}

/// Compute the offset of the `Trailer` field in `Cell<T, S>` using the
/// `#[repr(C)]` algorithm.
///
/// Pseudo-code for the `#[repr(C)]` algorithm can be found here:
/// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>
const fn get_trailer_offset(
    header_size: usize,
    core_size: usize,
    core_align: usize,
    trailer_align: usize,
) -> usize {
    let mut offset = header_size;

    let core_misalign = offset % core_align;
    if core_misalign > 0 {
        offset += core_align - core_misalign;
    }
    offset += core_size;

    let trailer_misalign = offset % trailer_align;
    if trailer_misalign > 0 {
        offset += trailer_align - trailer_misalign;
    }

    offset
}

/// Compute the offset of the `Core<T, S>` field in `Cell<T, S>` using the
/// `#[repr(C)]` algorithm.
///
/// Pseudo-code for the `#[repr(C)]` algorithm can be found here:
/// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>
const fn get_core_offset(header_size: usize, core_align: usize) -> usize {
    let mut offset = header_size;

    let core_misalign = offset % core_align;
    if core_misalign > 0 {
        offset += core_align - core_misalign;
    }

    offset
}

/// Compute the offset of the `Id` field in `Cell<T, S>` using the
/// `#[repr(C)]` algorithm.
///
/// Pseudo-code for the `#[repr(C)]` algorithm can be found here:
/// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>
const fn get_id_offset(
    header_size: usize,
    core_align: usize,
    scheduler_size: usize,
    id_align: usize,
) -> usize {
    let mut offset = get_core_offset(header_size, core_align);
    offset += scheduler_size;

    let id_misalign = offset % id_align;
    if id_misalign > 0 {
        offset += id_align - id_misalign;
    }

    offset
}

impl RawTask {
    pub(super) fn new<T, S>(task: T, scheduler: S, id: Id) -> RawTask
    where
        T: Future,
        S: Schedule,
    {
        let ptr = Box::into_raw(Cell::<_, S>::new(task, scheduler, State::new(), id));
        let ptr = unsafe { NonNull::new_unchecked(ptr as *mut Header) };

        RawTask { ptr }
    }

    pub(super) unsafe fn from_raw(ptr: NonNull<Header>) -> RawTask {
        RawTask { ptr }
    }

    pub(super) fn header_ptr(&self) -> NonNull<Header> {
        self.ptr
    }

    pub(super) fn trailer_ptr(&self) -> NonNull<Trailer> {
        unsafe { Header::get_trailer(self.ptr) }
    }

    /// Returns a reference to the task's header.
    pub(super) fn header(&self) -> &Header {
        unsafe { self.ptr.as_ref() }
    }

    /// Returns a reference to the task's trailer.
    pub(super) fn trailer(&self) -> &Trailer {
        unsafe { &*self.trailer_ptr().as_ptr() }
    }

    /// Returns a reference to the task's state.
    pub(super) fn state(&self) -> &State {
        &self.header().state
    }

    /// Safety: mutual exclusion is required to call this function.
    pub(super) fn poll(self) {
        let vtable = self.header().vtable;
        unsafe { (vtable.poll)(self.ptr) }
    }

    pub(super) fn schedule(self) {
        let vtable = self.header().vtable;
        unsafe { (vtable.schedule)(self.ptr) }
    }

    pub(super) fn dealloc(self) {
        let vtable = self.header().vtable;
        unsafe {
            (vtable.dealloc)(self.ptr);
        }
    }

    /// Safety: `dst` must be a `*mut Poll<super::Result<T::Output>>` where `T`
    /// is the future stored by the task.
    pub(super) unsafe fn try_read_output(self, dst: *mut (), waker: &Waker) {
        let vtable = self.header().vtable;
        (vtable.try_read_output)(self.ptr, dst, waker);
    }

    pub(super) fn drop_join_handle_slow(self) {
        let vtable = self.header().vtable;
        unsafe { (vtable.drop_join_handle_slow)(self.ptr) }
    }

    pub(super) fn drop_abort_handle(self) {
        let vtable = self.header().vtable;
        unsafe { (vtable.drop_abort_handle)(self.ptr) }
    }

    pub(super) fn shutdown(self) {
        let vtable = self.header().vtable;
        unsafe { (vtable.shutdown)(self.ptr) }
    }

    /// Increment the task's reference count.
    ///
    /// Currently, this is used only when creating an `AbortHandle`.
    pub(super) fn ref_inc(self) {
        self.header().state.ref_inc();
    }
}

impl Clone for RawTask {
    fn clone(&self) -> Self {
        RawTask { ptr: self.ptr }
    }
}

impl Copy for RawTask {}

unsafe fn poll<T: Future, S: Schedule>(ptr: NonNull<Header>) {
    let harness = Harness::<T, S>::from_raw(ptr);
    harness.poll();
}

unsafe fn schedule<S: Schedule>(ptr: NonNull<Header>) {
    use crate::runtime::task::{Notified, Task};

    let scheduler = Header::get_scheduler::<S>(ptr);
    scheduler
        .as_ref()
        .schedule(Notified(Task::from_raw(ptr.cast())));
}

unsafe fn dealloc<T: Future, S: Schedule>(ptr: NonNull<Header>) {
    let harness = Harness::<T, S>::from_raw(ptr);
    harness.dealloc();
}

unsafe fn try_read_output<T: Future, S: Schedule>(
    ptr: NonNull<Header>,
    dst: *mut (),
    waker: &Waker,
) {
    let out = &mut *(dst as *mut Poll<super::Result<T::Output>>);

    let harness = Harness::<T, S>::from_raw(ptr);
    harness.try_read_output(out, waker);
}

unsafe fn drop_join_handle_slow<T: Future, S: Schedule>(ptr: NonNull<Header>) {
    let harness = Harness::<T, S>::from_raw(ptr);
    harness.drop_join_handle_slow()
}

unsafe fn drop_abort_handle<T: Future, S: Schedule>(ptr: NonNull<Header>) {
    let harness = Harness::<T, S>::from_raw(ptr);
    harness.drop_reference();
}

unsafe fn shutdown<T: Future, S: Schedule>(ptr: NonNull<Header>) {
    let harness = Harness::<T, S>::from_raw(ptr);
    harness.shutdown()
}


text:
/* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */
/* cairo - a vector graphics library with display and print output
 *
 * Copyright © 2002 University of Southern California
 *
 * This library is free software; you can redistribute it and/or
 * modify it either under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * (the "LGPL") or, at your option, under the terms of the Mozilla
 * Public License Version 1.1 (the "MPL"). If you do not alter this
 * notice, a recipient may use your version of this file under either
 * the MPL or the LGPL.
 *
 * You should have received a copy of the LGPL along with this library
 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
 * You should have received a copy of the MPL along with this library
 * in the file COPYING-MPL-1.1
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (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.mozilla.org/MPL/
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
 * the specific language governing rights and limitations.
 *
 * The Original Code is the cairo graphics library.
 *
 * The Initial Developer of the Original Code is University of Southern
 * California.
 *
 * Contributor(s):
 *	Carl D. Worth <cworth@cworth.org>
 *	Chris Wilson <chris@chris-wilson.co.uk>
 */

#define _BSD_SOURCE /* for hypot() */
#include "cairoint.h"

#include "cairo-box-inline.h"
#include "cairo-boxes-private.h"
#include "cairo-error-private.h"
#include "cairo-path-fixed-private.h"
#include "cairo-slope-private.h"
#include "cairo-stroke-dash-private.h"

typedef struct _segment_t {
    cairo_point_t p1, p2;
    unsigned flags;
#define HORIZONTAL 0x1
#define FORWARDS 0x2
#define JOIN 0x4
} segment_t;

typedef struct _cairo_rectilinear_stroker {
    const cairo_stroke_style_t *stroke_style;
    const cairo_matrix_t *ctm;
    cairo_antialias_t antialias;

    cairo_fixed_t half_line_x, half_line_y;
    cairo_boxes_t *boxes;
    cairo_point_t current_point;
    cairo_point_t first_point;
    cairo_bool_t open_sub_path;

    cairo_stroker_dash_t dash;

    cairo_bool_t has_bounds;
    cairo_box_t bounds;

    int num_segments;
    int segments_size;
    segment_t *segments;
    segment_t segments_embedded[8]; /* common case is a single rectangle */
} cairo_rectilinear_stroker_t;

static void
_cairo_rectilinear_stroker_limit (cairo_rectilinear_stroker_t *stroker,
				  const cairo_box_t *boxes,
				  int num_boxes)
{
    stroker->has_bounds = TRUE;
    _cairo_boxes_get_extents (boxes, num_boxes, &stroker->bounds);

    stroker->bounds.p1.x -= stroker->half_line_x;
    stroker->bounds.p2.x += stroker->half_line_x;

    stroker->bounds.p1.y -= stroker->half_line_y;
    stroker->bounds.p2.y += stroker->half_line_y;
}

static cairo_bool_t
_cairo_rectilinear_stroker_init (cairo_rectilinear_stroker_t	*stroker,
				 const cairo_stroke_style_t	*stroke_style,
				 const cairo_matrix_t		*ctm,
				 cairo_antialias_t		 antialias,
				 cairo_boxes_t			*boxes)
{
    /* This special-case rectilinear stroker only supports
     * miter-joined lines (not curves) and a translation-only matrix
     * (though it could probably be extended to support a matrix with
     * uniform, integer scaling).
     *
     * It also only supports horizontal and vertical line_to
     * elements. But we don't catch that here, but instead return
     * UNSUPPORTED from _cairo_rectilinear_stroker_line_to if any
     * non-rectilinear line_to is encountered.
     */
    if (stroke_style->line_join	!= CAIRO_LINE_JOIN_MITER)
	return FALSE;

    /* If the miter limit turns right angles into bevels, then we
     * can't use this optimization. Remember, the ratio is
     * 1/sin(ɸ/2). So the cutoff is 1/sin(π/4.0) or ⎷2,
     * which we round for safety. */
    if (stroke_style->miter_limit < M_SQRT2)
	return FALSE;

    if (! (stroke_style->line_cap == CAIRO_LINE_CAP_BUTT ||
	   stroke_style->line_cap == CAIRO_LINE_CAP_SQUARE))
    {
	return FALSE;
    }

    if (! _cairo_matrix_is_scale (ctm))
	return FALSE;

    stroker->stroke_style = stroke_style;
    stroker->ctm = ctm;
    stroker->antialias = antialias;

    stroker->half_line_x =
	_cairo_fixed_from_double (fabs(ctm->xx) * stroke_style->line_width / 2.0);
    stroker->half_line_y =
	_cairo_fixed_from_double (fabs(ctm->yy) * stroke_style->line_width / 2.0);

    stroker->open_sub_path = FALSE;
    stroker->segments = stroker->segments_embedded;
    stroker->segments_size = ARRAY_LENGTH (stroker->segments_embedded);
    stroker->num_segments = 0;

    _cairo_stroker_dash_init (&stroker->dash, stroke_style);

    stroker->has_bounds = FALSE;

    stroker->boxes = boxes;

    return TRUE;
}

static void
_cairo_rectilinear_stroker_fini (cairo_rectilinear_stroker_t	*stroker)
{
    if (stroker->segments != stroker->segments_embedded)
	free (stroker->segments);
}

static cairo_status_t
_cairo_rectilinear_stroker_add_segment (cairo_rectilinear_stroker_t *stroker,
					const cairo_point_t	*p1,
					const cairo_point_t	*p2,
					unsigned		 flags)
{
    if (CAIRO_INJECT_FAULT ())
	return _cairo_error (CAIRO_STATUS_NO_MEMORY);

    if (stroker->num_segments == stroker->segments_size) {
	int new_size = stroker->segments_size * 2;
	segment_t *new_segments;

	if (stroker->segments == stroker->segments_embedded) {
	    new_segments = _cairo_malloc_ab (new_size, sizeof (segment_t));
	    if (unlikely (new_segments == NULL))
		return _cairo_error (CAIRO_STATUS_NO_MEMORY);

	    memcpy (new_segments, stroker->segments,
		    stroker->num_segments * sizeof (segment_t));
	} else {
	    new_segments = _cairo_realloc_ab (stroker->segments,
					      new_size, sizeof (segment_t));
	    if (unlikely (new_segments == NULL))
		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
	}

	stroker->segments_size = new_size;
	stroker->segments = new_segments;
    }

    stroker->segments[stroker->num_segments].p1 = *p1;
    stroker->segments[stroker->num_segments].p2 = *p2;
    stroker->segments[stroker->num_segments].flags = flags;
    stroker->num_segments++;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_rectilinear_stroker_emit_segments (cairo_rectilinear_stroker_t *stroker)
{
    cairo_line_cap_t line_cap = stroker->stroke_style->line_cap;
    cairo_fixed_t half_line_x = stroker->half_line_x;
    cairo_fixed_t half_line_y = stroker->half_line_y;
    cairo_status_t status;
    int i, j;

    /* For each segment we generate a single rectangle.
     * This rectangle is based on a perpendicular extension (by half the
     * line width) of the segment endpoints * after some adjustments of the
     * endpoints to account for caps and joins.
     */
    for (i = 0; i < stroker->num_segments; i++) {
	cairo_bool_t lengthen_initial, lengthen_final;
	cairo_point_t *a, *b;
	cairo_box_t box;

	a = &stroker->segments[i].p1;
	b = &stroker->segments[i].p2;

	/* We adjust the initial point of the segment to extend the
	 * rectangle to include the previous cap or join, (this
	 * adjustment applies to all segments except for the first
	 * segment of open, butt-capped paths). However, we must be
	 * careful not to emit a miter join across a degenerate segment
	 * which has been elided.
	 *
	 * Overlapping segments will be eliminated by the tessellation.
	 * Ideally, we would not emit these self-intersections at all,
	 * but that is tricky with segments shorter than half_line_width.
	 */
	j = i == 0 ? stroker->num_segments - 1 : i-1;
	lengthen_initial = (stroker->segments[i].flags ^ stroker->segments[j].flags) & HORIZONTAL;
	j = i == stroker->num_segments - 1 ? 0 : i+1;
	lengthen_final = (stroker->segments[i].flags ^ stroker->segments[j].flags) & HORIZONTAL;
	if (stroker->open_sub_path) {
	    if (i == 0)
		lengthen_initial = line_cap != CAIRO_LINE_CAP_BUTT;

	    if (i == stroker->num_segments - 1)
		lengthen_final = line_cap != CAIRO_LINE_CAP_BUTT;
	}

	/* Perform the adjustments of the endpoints. */
	if (lengthen_initial | lengthen_final) {
	    if (a->y == b->y) {
		if (a->x < b->x) {
		    if (lengthen_initial)
			a->x -= half_line_x;
		    if (lengthen_final)
			b->x += half_line_x;
		} else {
		    if (lengthen_initial)
			a->x += half_line_x;
		    if (lengthen_final)
			b->x -= half_line_x;
		}
	    } else {
		if (a->y < b->y) {
		    if (lengthen_initial)
			a->y -= half_line_y;
		    if (lengthen_final)
			b->y += half_line_y;
		} else {
		    if (lengthen_initial)
			a->y += half_line_y;
		    if (lengthen_final)
			b->y -= half_line_y;
		}
	    }
	}

	/* Form the rectangle by expanding by half the line width in
	 * either perpendicular direction. */
	if (a->y == b->y) {
	    a->y -= half_line_y;
	    b->y += half_line_y;
	} else {
	    a->x -= half_line_x;
	    b->x += half_line_x;
	}

	if (a->x < b->x) {
	    box.p1.x = a->x;
	    box.p2.x = b->x;
	} else {
	    box.p1.x = b->x;
	    box.p2.x = a->x;
	}
	if (a->y < b->y) {
	    box.p1.y = a->y;
	    box.p2.y = b->y;
	} else {
	    box.p1.y = b->y;
	    box.p2.y = a->y;
	}

	status = _cairo_boxes_add (stroker->boxes, stroker->antialias, &box);
	if (unlikely (status))
	    return status;
    }

    stroker->num_segments = 0;
    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_rectilinear_stroker_emit_segments_dashed (cairo_rectilinear_stroker_t *stroker)
{
    cairo_status_t status;
    cairo_line_cap_t line_cap = stroker->stroke_style->line_cap;
    cairo_fixed_t half_line_x = stroker->half_line_x;
    cairo_fixed_t half_line_y = stroker->half_line_y;
    int i;

    for (i = 0; i < stroker->num_segments; i++) {
	cairo_point_t *a, *b;
	cairo_bool_t is_horizontal;
	cairo_box_t box;

	a = &stroker->segments[i].p1;
	b = &stroker->segments[i].p2;

	is_horizontal = stroker->segments[i].flags & HORIZONTAL;

	/* Handle the joins for a potentially degenerate segment. */
	if (line_cap == CAIRO_LINE_CAP_BUTT &&
	    stroker->segments[i].flags & JOIN &&
	    (i != stroker->num_segments - 1 ||
	     (! stroker->open_sub_path && stroker->dash.dash_starts_on)))
	{
	    cairo_slope_t out_slope;
	    int j = (i + 1) % stroker->num_segments;
	    cairo_bool_t forwards = !!(stroker->segments[i].flags & FORWARDS);

	    _cairo_slope_init (&out_slope,
			       &stroker->segments[j].p1,
			       &stroker->segments[j].p2);
	    box.p2 = box.p1 = stroker->segments[i].p2;

	    if (is_horizontal) {
		if (forwards)
		    box.p2.x += half_line_x;
		else
		    box.p1.x -= half_line_x;

		if (out_slope.dy > 0)
		    box.p1.y -= half_line_y;
		else
		    box.p2.y += half_line_y;
	    } else {
		if (forwards)
		    box.p2.y += half_line_y;
		else
		    box.p1.y -= half_line_y;

		if (out_slope.dx > 0)
		    box.p1.x -= half_line_x;
		else
		    box.p2.x += half_line_x;
	    }

	    status = _cairo_boxes_add (stroker->boxes, stroker->antialias, &box);
	    if (unlikely (status))
		return status;
	}

	/* Perform the adjustments of the endpoints. */
	if (is_horizontal) {
	    if (line_cap == CAIRO_LINE_CAP_SQUARE) {
		if (a->x <= b->x) {
		    a->x -= half_line_x;
		    b->x += half_line_x;
		} else {
		    a->x += half_line_x;
		    b->x -= half_line_x;
		}
	    }

	    a->y += half_line_y;
	    b->y -= half_line_y;
	} else {
	    if (line_cap == CAIRO_LINE_CAP_SQUARE) {
		if (a->y <= b->y) {
		    a->y -= half_line_y;
		    b->y += half_line_y;
		} else {
		    a->y += half_line_y;
		    b->y -= half_line_y;
		}
	    }

	    a->x += half_line_x;
	    b->x -= half_line_x;
	}

	if (a->x == b->x && a->y == b->y)
	    continue;

	if (a->x < b->x) {
	    box.p1.x = a->x;
	    box.p2.x = b->x;
	} else {
	    box.p1.x = b->x;
	    box.p2.x = a->x;
	}
	if (a->y < b->y) {
	    box.p1.y = a->y;
	    box.p2.y = b->y;
	} else {
	    box.p1.y = b->y;
	    box.p2.y = a->y;
	}

	status = _cairo_boxes_add (stroker->boxes, stroker->antialias, &box);
	if (unlikely (status))
	    return status;
    }

    stroker->num_segments = 0;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_rectilinear_stroker_move_to (void		*closure,
				    const cairo_point_t	*point)
{
    cairo_rectilinear_stroker_t *stroker = closure;
    cairo_status_t status;

    if (stroker->dash.dashed)
	status = _cairo_rectilinear_stroker_emit_segments_dashed (stroker);
    else
	status = _cairo_rectilinear_stroker_emit_segments (stroker);
    if (unlikely (status))
	return status;

    /* reset the dash pattern for new sub paths */
    _cairo_stroker_dash_start (&stroker->dash);

    stroker->current_point = *point;
    stroker->first_point = *point;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_rectilinear_stroker_line_to (void		*closure,
				    const cairo_point_t	*b)
{
    cairo_rectilinear_stroker_t *stroker = closure;
    cairo_point_t *a = &stroker->current_point;
    cairo_status_t status;

    /* We only support horizontal or vertical elements. */
    assert (a->x == b->x || a->y == b->y);

    /* We don't draw anything for degenerate paths. */
    if (a->x == b->x && a->y == b->y)
	return CAIRO_STATUS_SUCCESS;

    status = _cairo_rectilinear_stroker_add_segment (stroker, a, b,
						     (a->y == b->y) | JOIN);

    stroker->current_point = *b;
    stroker->open_sub_path = TRUE;

    return status;
}

static cairo_status_t
_cairo_rectilinear_stroker_line_to_dashed (void		*closure,
					   const cairo_point_t	*point)
{
    cairo_rectilinear_stroker_t *stroker = closure;
    const cairo_point_t *a = &stroker->current_point;
    const cairo_point_t *b = point;
    cairo_bool_t fully_in_bounds;
    double sf, sign, remain;
    cairo_fixed_t mag;
    cairo_status_t status;
    cairo_line_t segment;
    cairo_bool_t dash_on = FALSE;
    unsigned is_horizontal;

    /* We don't draw anything for degenerate paths. */
    if (a->x == b->x && a->y == b->y)
	return CAIRO_STATUS_SUCCESS;

    /* We only support horizontal or vertical elements. */
    assert (a->x == b->x || a->y == b->y);

    fully_in_bounds = TRUE;
    if (stroker->has_bounds &&
	(! _cairo_box_contains_point (&stroker->bounds, a) ||
	 ! _cairo_box_contains_point (&stroker->bounds, b)))
    {
	fully_in_bounds = FALSE;
    }

    is_horizontal = a->y == b->y;
    if (is_horizontal) {
	mag = b->x - a->x;
	sf = fabs (stroker->ctm->xx);
    } else {
	mag = b->y - a->y;
	sf = fabs (stroker->ctm->yy);
    }
    if (mag < 0) {
	remain = _cairo_fixed_to_double (-mag);
	sign = 1.;
    } else {
	remain = _cairo_fixed_to_double (mag);
	is_horizontal |= FORWARDS;
	sign = -1.;
    }

    segment.p2 = segment.p1 = *a;
    while (remain > 0.) {
	double step_length;

	step_length = MIN (sf * stroker->dash.dash_remain, remain);
	remain -= step_length;

	mag = _cairo_fixed_from_double (sign*remain);
	if (is_horizontal & 0x1)
	    segment.p2.x = b->x + mag;
	else
	    segment.p2.y = b->y + mag;

	if (stroker->dash.dash_on &&
	    (fully_in_bounds ||
	     _cairo_box_intersects_line_segment (&stroker->bounds, &segment)))
	{
	    status = _cairo_rectilinear_stroker_add_segment (stroker,
							     &segment.p1,
							     &segment.p2,
							     is_horizontal | (remain <= 0.) << 2);
	    if (unlikely (status))
		return status;

	    dash_on = TRUE;
	}
	else
	{
	    dash_on = FALSE;
	}

	_cairo_stroker_dash_step (&stroker->dash, step_length / sf);
	segment.p1 = segment.p2;
    }

    if (stroker->dash.dash_on && ! dash_on &&
	(fully_in_bounds ||
	 _cairo_box_intersects_line_segment (&stroker->bounds, &segment)))
    {

	/* This segment ends on a transition to dash_on, compute a new face
	 * and add cap for the beginning of the next dash_on step.
	 */

	status = _cairo_rectilinear_stroker_add_segment (stroker,
							 &segment.p1,
							 &segment.p1,
							 is_horizontal | JOIN);
	if (unlikely (status))
	    return status;
    }

    stroker->current_point = *point;
    stroker->open_sub_path = TRUE;

    return CAIRO_STATUS_SUCCESS;
}

static cairo_status_t
_cairo_rectilinear_stroker_close_path (void *closure)
{
    cairo_rectilinear_stroker_t *stroker = closure;
    cairo_status_t status;

    /* We don't draw anything for degenerate paths. */
    if (! stroker->open_sub_path)
	return CAIRO_STATUS_SUCCESS;

    if (stroker->dash.dashed) {
	status = _cairo_rectilinear_stroker_line_to_dashed (stroker,
							    &stroker->first_point);
    } else {
	status = _cairo_rectilinear_stroker_line_to (stroker,
						     &stroker->first_point);
    }
    if (unlikely (status))
	return status;

    stroker->open_sub_path = FALSE;

    if (stroker->dash.dashed)
	status = _cairo_rectilinear_stroker_emit_segments_dashed (stroker);
    else
	status = _cairo_rectilinear_stroker_emit_segments (stroker);
    if (unlikely (status))
	return status;

    return CAIRO_STATUS_SUCCESS;
}

cairo_int_status_t
_cairo_path_fixed_stroke_rectilinear_to_boxes (const cairo_path_fixed_t	*path,
					       const cairo_stroke_style_t	*stroke_style,
					       const cairo_matrix_t	*ctm,
					       cairo_antialias_t	 antialias,
					       cairo_boxes_t		*boxes)
{
    cairo_rectilinear_stroker_t rectilinear_stroker;
    cairo_int_status_t status;
    cairo_box_t box;

    assert (_cairo_path_fixed_stroke_is_rectilinear (path));

    if (! _cairo_rectilinear_stroker_init (&rectilinear_stroker,
					   stroke_style, ctm, antialias,
					   boxes))
    {
	return CAIRO_INT_STATUS_UNSUPPORTED;
    }

    if (! rectilinear_stroker.dash.dashed &&
	_cairo_path_fixed_is_stroke_box (path, &box) &&
	/* if the segments overlap we need to feed them into the tessellator */
	box.p2.x - box.p1.x > 2* rectilinear_stroker.half_line_x &&
	box.p2.y - box.p1.y > 2* rectilinear_stroker.half_line_y)
    {
	cairo_box_t b;

	/* top */
	b.p1.x = box.p1.x - rectilinear_stroker.half_line_x;
	b.p2.x = box.p2.x + rectilinear_stroker.half_line_x;
	b.p1.y = box.p1.y - rectilinear_stroker.half_line_y;
	b.p2.y = box.p1.y + rectilinear_stroker.half_line_y;
	status = _cairo_boxes_add (boxes, antialias, &b);
	assert (status == CAIRO_INT_STATUS_SUCCESS);

	/* left  (excluding top/bottom) */
	b.p1.x = box.p1.x - rectilinear_stroker.half_line_x;
	b.p2.x = box.p1.x + rectilinear_stroker.half_line_x;
	b.p1.y = box.p1.y + rectilinear_stroker.half_line_y;
	b.p2.y = box.p2.y - rectilinear_stroker.half_line_y;
	status = _cairo_boxes_add (boxes, antialias, &b);
	assert (status == CAIRO_INT_STATUS_SUCCESS);

	/* right  (excluding top/bottom) */
	b.p1.x = box.p2.x - rectilinear_stroker.half_line_x;
	b.p2.x = box.p2.x + rectilinear_stroker.half_line_x;
	b.p1.y = box.p1.y + rectilinear_stroker.half_line_y;
	b.p2.y = box.p2.y - rectilinear_stroker.half_line_y;
	status = _cairo_boxes_add (boxes, antialias, &b);
	assert (status == CAIRO_INT_STATUS_SUCCESS);

	/* bottom */
	b.p1.x = box.p1.x - rectilinear_stroker.half_line_x;
	b.p2.x = box.p2.x + rectilinear_stroker.half_line_x;
	b.p1.y = box.p2.y - rectilinear_stroker.half_line_y;
	b.p2.y = box.p2.y + rectilinear_stroker.half_line_y;
	status = _cairo_boxes_add (boxes, antialias, &b);
	assert (status == CAIRO_INT_STATUS_SUCCESS);

	goto done;
    }

    if (boxes->num_limits) {
	_cairo_rectilinear_stroker_limit (&rectilinear_stroker,
					  boxes->limits,
					  boxes->num_limits);
    }

    status = _cairo_path_fixed_interpret (path,
					  _cairo_rectilinear_stroker_move_to,
					  rectilinear_stroker.dash.dashed ?
					  _cairo_rectilinear_stroker_line_to_dashed :
					  _cairo_rectilinear_stroker_line_to,
					  NULL,
					  _cairo_rectilinear_stroker_close_path,
					  &rectilinear_stroker);
    if (unlikely (status))
	goto BAIL;

    if (rectilinear_stroker.dash.dashed)
	status = _cairo_rectilinear_stroker_emit_segments_dashed (&rectilinear_stroker);
    else
	status = _cairo_rectilinear_stroker_emit_segments (&rectilinear_stroker);
    if (unlikely (status))
	goto BAIL;

    /* As we incrementally tessellate, we do not eliminate self-intersections */
    status = _cairo_bentley_ottmann_tessellate_boxes (boxes,
						      CAIRO_FILL_RULE_WINDING,
						      boxes);
    if (unlikely (status))
	goto BAIL;

done:
    _cairo_rectilinear_stroker_fini (&rectilinear_stroker);
    return CAIRO_STATUS_SUCCESS;

BAIL:
    _cairo_rectilinear_stroker_fini (&rectilinear_stroker);
    _cairo_boxes_clear (boxes);
    return status;
}


text:
package com.dasa.communication.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import com.dasa.communication.dao.BusinessOrderDAO;
import com.dasa.communication.vo.BusinessOrderVo;
import com.dasa.communication.vo.Notification;
import com.dasa.communication.vo.SendNotification;
import com.vertexid.vo.KeyValueVo;
import com.vertexid.vo.NaviVo;
import com.vertexid.vo.OrganizationVo;

public class BusinessOrderService extends SqlSessionDaoSupport  implements BusinessOrderDAO {

	@Autowired
	private HttpSession session;

	@Autowired
	private SendNotification sendNotification;

	@Override
	public List<OrganizationVo> selectListByCp(String cm_code)throws SQLException {
		return getSqlSession().selectList("organization.selectOrganizationListByCp", cm_code);
	}

	@Override
	public NaviVo businessOrderListCnt(NaviVo naviVo) throws SQLException {
		naviVo.setTotRow((Integer)getSqlSession().selectOne("businessOrderListCnt" ,naviVo));
		return naviVo;
	}

	@Override
	public NaviVo businessPopupListCnt(NaviVo naviVo) throws SQLException {
		naviVo.setTotRow((Integer)getSqlSession().selectOne("businessPopupListCnt" ,naviVo));
		return naviVo;
	}

	@Override
	public List<BusinessOrderVo> businessOrderList(NaviVo naviVo)throws SQLException {
		return getSqlSession().selectList("businessOrderList", naviVo);
	}

	@Override
	public List<BusinessOrderVo> businessPopupList(NaviVo naviVo) throws SQLException {
		return getSqlSession().selectList("businessPopupList",naviVo);
	}
	/*@Override
	public List<BusinessOrderVo> businessPopupList(NaviVo naviVo)throws SQLException {
		return getSqlSession().selectList("businessPopupList", naviVo);
	}*/

	@Override
	public List<KeyValueVo> martAutoComplate(Map<String,Object> map) throws SQLException {
		return getSqlSession().selectList("Business.martAutoComplate", map);
	}

	@Override
	public List<KeyValueVo> martAutoComplate_cp(Map<String,Object> map) throws SQLException {
		return getSqlSession().selectList("Business.martAutoComplate_cp", map);
	}

	@Override
	public List<KeyValueVo> emplAutoComplate(Map<String,Object> map) throws SQLException {
		return getSqlSession().selectList("Business.emplAutoComplate", map);
	}

	/*@Override
	public List<BusinessOrderVo> noticeList(NaviVo naviVo) throws SQLException {
		return  getSqlSession().selectList("Business.noticeList", naviVo);
	}*/

	/*public NaviVo noticeListCnt(NaviVo naviVo) throws SQLException {
	@Override
		naviVo.setTotRow((Integer)getSqlSession().selectOne("Business.noticeListCnt" ,naviVo));
		return naviVo;
	}*/

	@Override
	public String businessSave(BusinessOrderVo businessOrderVo) throws SQLException {
		int cnt = 0;
		if(businessOrderVo.getSaveType().equals("I")){
			businessOrderVo.setBm_code("2");  //게시판 종류(공지사항(1), 업무지시(2))
			cnt = getSqlSession().insert("businessInsert",businessOrderVo); //게시판 insert
			if(cnt > 0 ){
				List<Map<String, String>> omArr = businessOrderVo.getOmArr();
				if (omArr == null) {
					System.out.println("전달받은 수신지점목록이 없습니다.");
				}else {
					try{
						for(Map<String,String> map : businessOrderVo.getOmArr() ) {
							map.put("bm_innb", businessOrderVo.getBm_innb());
							map.put("bt_flag", "1");
							map.put("regist_man", businessOrderVo.getRegist_man());
							cnt = getSqlSession().insert("businessOmInsert",map);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}

				List<Map<String, String>> smArr = businessOrderVo.getSmArr();
				if (smArr == null) {
					System.out.println("전달받은 수신매장목록이 없습니다.");
				}else {
					try{
						for(Map<String,String> map : businessOrderVo.getSmArr() ) {
							map.put("bm_innb", businessOrderVo.getBm_innb());
							map.put("bt_flag", "2");
							map.put("regist_man", businessOrderVo.getRegist_man());
							cnt = getSqlSession().insert("businessSmInsert",map);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}

				List<Map<String, String>> emArr = businessOrderVo.getEmArr();
				if (emArr == null) {
					System.out.println("전달받은 사원목록이 없습니다.");
				}else {
					try{
						for(Map<String,String> map : businessOrderVo.getEmArr() ) {
							map.put("bm_innb", businessOrderVo.getBm_innb());
							map.put("bt_flag", "3");
							map.put("em_code", map.get("em_no"));
							map.put("regist_man", businessOrderVo.getRegist_man());
							cnt = getSqlSession().insert("businessEmInsert",map);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
//				System.out.println("businessOrderVo : " + businessOrderVo);
				cnt = getSqlSession().insert("businessInsertFinish",businessOrderVo); //업무지시 insert
			}
		}else{
			cnt = getSqlSession().update("businessUpdate",businessOrderVo);
//			String bm_innb = businessOrderVo.getBm_innb();
//			Map<String,String> delmap = new HashMap<String, String>();
//			delmap.put("cm_innb", bm_innb);
//			delmap.put("cmmnc_se", "2");
//			getSqlSession().delete("businessOmDelete",delmap);
//			getSqlSession().delete("businessSmDelete",delmap);
//			delmap.put("cm_innb", bm_innb);
//			getSqlSession().delete("businessOmDelete",delmap);

//			if(cnt > 0 ){
//				try{
//					for(Map<String,String> map : businessOrderVo.getOmArr() ) {
//						map.put("bm_innb", bm_innb);
//						map.put("bt_flag", "1");
//						map.put("regist_man", businessOrderVo.getRegist_man());
//						cnt = getSqlSession().insert("businessOmInsert",map);
//					}
//				}catch(Exception e){
//					e.printStackTrace();
//				}
//
//				try{
//					for(Map<String,String> map : businessOrderVo.getSmArr() ) {
//						map.put("bm_innb", bm_innb);
//						map.put("bt_flag", "2");
//						map.put("regist_man", businessOrderVo.getRegist_man());
//						cnt = getSqlSession().insert("businessSmInsert",map);
//					}
//				}catch(Exception e){
//					e.printStackTrace();
//				}
//
//				try{
//					for(Map<String,String> map : businessOrderVo.getEmArr() ) {
//						map.put("bm_innb", bm_innb);
//						map.put("bt_flag", "3");
//						map.put("em_code", map.get("em_no"));
//						map.put("regist_man", businessOrderVo.getRegist_man());
//						cnt = getSqlSession().insert("businessEmInsert",map);
//					}
//				}catch(Exception e){
//					e.printStackTrace();
//				}
//			}
//			cnt = getSqlSession().insert("businessInsertFinish",businessOrderVo); //업무지시 insert
		}
		return cnt > 0 ? businessOrderVo.getBm_innb():"";
	}

	@Override
	public int noticeFileSave(String bmInnb, int amNo) throws SQLException {
		Map<String,String> map = new HashMap<String,String>();
		map.put("bm_innb", bmInnb);
		map.put("am_no", amNo+"");
		return getSqlSession().update("businessFileSave", map);
	}

	@Override
	public BusinessOrderVo businessView(String bmInnb) throws SQLException {
		return (BusinessOrderVo)getSqlSession().selectOne("businessView",bmInnb);
	}

	/*@Override
	public BusinessOrderVo businessInserType(String bmInnb) throws SQLException{
		return (BusinessOrderVo)getSqlSession().selectOne("businessInsertType",bmInnb);
	}*/

	@Override
	public BusinessOrderVo businessReceiverView(BusinessOrderVo businessOrderVo) throws SQLException {
		return (BusinessOrderVo) getSqlSession().selectOne("businessReceiverView", businessOrderVo);
	}

	@Override
	public int businessReceiverReply(BusinessOrderVo businessOrderVo) throws SQLException {
		return getSqlSession().update("businessReceiverReply", businessOrderVo);
	}

	@Override
	public List<KeyValueVo> businessOmList(String bmInnb) throws SQLException {
		return getSqlSession().selectList("businessOmList", bmInnb);
	}

	@Override
	public List<KeyValueVo> businessSmList(String bmInnb) throws SQLException {
		return getSqlSession().selectList("businessSmList", bmInnb);
	}

	@Override
	public int businessPopupDelete(HashMap map) throws SQLException {
		return getSqlSession().update("businessPopupDelete",map);
	}

	@Override
	public List<KeyValueVo> businessEmList(String bmInnb) throws SQLException {
		return getSqlSession().selectList("businessEmList", bmInnb);
	}

	@Override
	public List<KeyValueVo> businessTmList(String bmInnb) throws SQLException {
		return getSqlSession().selectList("businessTmList", bmInnb);
	}

	@Override
	public List<KeyValueVo> bizFixRoundList(String bmInnb) throws SQLException {
		return getSqlSession().selectList("bizFixRoundList", bmInnb);
	}

	@Override
	public int businessPush(String bm_innb) throws SQLException {
		//SendNotification sendNotification = new SendNotification();
		List<BusinessOrderVo> list = new ArrayList<BusinessOrderVo>();
		List<Notification> bizNoti1 = new ArrayList<Notification>();
		List<Notification> bizNoti2 = new ArrayList<Notification>();
		HashMap<String, String> map = new HashMap<String, String>();

		String auth_flag =  (String)session.getAttribute("auth_flag"); //권한코드
		String auth_Code = "";
		String result = "";
		if(auth_flag.equals("1")) {
			auth_Code = "0000000009";
		}else if(auth_flag.equals("2")) {
			auth_Code = "0000000008";
		}else if(auth_flag.equals("4")) {
			auth_Code = "0000000007";
		}else if(auth_flag.equals("3")) {
			auth_Code = "0000000006";
		}
		map.put("auth_flag", auth_Code);
		map.put("bm_innb", bm_innb);

		list =getSqlSession().selectList("businessPushList", map);

		for(BusinessOrderVo vo : list) {
			Notification noti1 = new Notification();
			Notification noti2 = new Notification();

			String em_push_id = vo.getEm_push_id();
			String em_device_type = vo.getEm_device_type();
			result = "[업무지시] " + vo.getBm_sj();

//			System.out.println("em_device_type:" +em_device_type );

			if(em_device_type.equals("A")){
				noti1.setStringPropRegId(em_push_id);
				noti1.setDeviceType(em_device_type);
				bizNoti1.add(noti1);
			}else if(em_device_type.equals("I")){
				noti2.setStringPropRegId(em_push_id);
				noti2.setDeviceType(em_device_type);

				/*noti2.setRunMode("REAL");
				noti2.setCertificatePath("C:\\DASA\\iphone_rel.p12");
				noti2.setCertificatePassword("vertexid");*/

				bizNoti2.add(noti2);
			}
		}
		try {
			sendNotification.sendPushMessage(bizNoti1, bizNoti2, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list.size();
	}

	@Override
	public int businessPush2(String bm_innb, String em_no) throws SQLException {
		//SendNotification sendNotification = new SendNotification();
		List<BusinessOrderVo> list = new ArrayList<BusinessOrderVo>();
		List<Notification> bizNoti1 = new ArrayList<Notification>();
		List<Notification> bizNoti2 = new ArrayList<Notification>();
		HashMap<String, String> map = new HashMap<String, String>();

		String auth_flag =  (String)session.getAttribute("auth_flag"); //권한코드
		String auth_Code = "";
		String result = "";

		if(auth_flag.equals("1")) {
			auth_Code = "0000000009";
		}else if(auth_flag.equals("2")) {
			auth_Code = "0000000008";
		}else if(auth_flag.equals("4")) {
			auth_Code = "0000000007";
		}else if(auth_flag.equals("3")) {
			auth_Code = "0000000006";
		}

		map.put("auth_flag", auth_Code);
		map.put("bm_innb", bm_innb);
		map.put("em_no", em_no);

		list =getSqlSession().selectList("businessPushList2", map);

		for(BusinessOrderVo vo : list) {
			Notification noti1 = new Notification();
			Notification noti2 = new Notification();

			String em_push_id = vo.getEm_push_id();
			String em_device_type = vo.getEm_device_type();
			result = "[업무지시] " + vo.getBm_sj();

			if(em_device_type.equals("A")){
				noti1.setStringPropRegId(em_push_id);
				noti1.setDeviceType(em_device_type);
				bizNoti1.add(noti1);
			}else if(em_device_type.equals("I")){
				noti2.setStringPropRegId(em_push_id);
				noti2.setDeviceType(em_device_type);

				/*noti2.setRunMode("REAL");
				noti2.setCertificatePath("C:\\DASA\\iphone_rel.p12");
				noti2.setCertificatePassword("vertexid");*/

				bizNoti2.add(noti2);
			}

		}

		try {
			sendNotification.sendPushMessage(bizNoti1, bizNoti2, result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list.size();
	}
}