code stringlengths 4 1.01M | language stringclasses 2
values |
|---|---|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sandsound</title>
<link rel="stylesheet" href="/css/reset.css">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<canvas id="canvas" class="background"></canvas>
<!-- Ne s'affiche que si sur mobile :) -->
<div class="mobile">
<a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a>
<p>Pour profiter de l'expérience SandSound, rendez-vous sur une tablette ou desktop !</p>
</div>
<div class="sidebar">
<a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a>
<nav>
<ul>
<li class="active"><a href="{{ route('profile', ['name' => $user->name]) }}">Profil</a></li>
<li>{{ link_to_route('room', 'Rejoindre un salon') }}</li>
<li>{{ link_to_route('form-private', 'Nouveau salon') }}</li>
<li>{{ link_to_route('rank', 'Classement') }}</li>
</ul>
</nav>
</div>
<div class="content">
<div class="content__infos">
<ul>
<li class="content__infos--pseudo">{{ $user->name }}</li>
<li class="content__infos--pts">{{ $user->score->xp }}<span> pts </span></li>
<li class="content__infos--niv"><span>Niv :</span> {{ $user->score->lvl_total }}</li>
</ul>
</div>
<div class="content__title">
<h1>| {{ $user->name }}</h1>
<div class="content__title--intro">
<p>{{ $user->name }} est niveau <span>{{ $user->score->lvl_total }}</span>.</p>
</div>
<div class="content__title--explain">
<p>
Découvrez les dernières musiques de <span>{{ $user->name }}</span>.
</p>
</div>
<div class="content__experiencepre">
<ul>
<li class="content__experiencepre--bass">| Bass : <span>{{ $user->score->lvl_bass }}</span></li>
<li class="content__experiencepre--pads">| Ambiance : <span>{{ $user->score->lvl_ambiance }}</span></li>
<li class="content__experiencepre--drum">| Drum : <span>{{ $user->score->lvl_drum }}</span></li>
<li class="content__experiencepre--lead">| Lead : <span>{{ $user->score->lvl_lead }}</span></li>
</ul>
</div>
<div class="content__experience">
<ul>
<li class="content__experience--bass"></li>
<li class="content__experience--pads"></li>
<li class="content__experience--drum"></li>
<li class="content__experience--lead"></li>
</ul>
</div>
@if (count($songs))
<div class="content__title--score">
<table>
<thead>
<tr>
<th scope="col">Nom de la chanson :</th>
<th scope="col">Score :</th>
</tr>
<tbody>
@foreach ($songs as $song)
<tr>
<td>
{{ $song->name }}</td>
<td>{{ $song->score }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="/js/index.js"></script>
</body>
</html>
| Java |
require 'lapine/test/exchange'
module Lapine
module Test
module RSpecHelper
def self.setup(_example = nil)
RSpec::Mocks::AllowanceTarget.new(Lapine::Exchange).to(
RSpec::Mocks::Matchers::Receive.new(:new, ->(name, properties) {
Lapine::Test::Exchange.new(name, properties)
})
)
end
def self.teardown
Lapine.close_connections!
end
end
end
end
| Java |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/animation/UnitBezier.h"
#include <gtest/gtest.h>
using namespace WebCore;
namespace {
TEST(UnitBezierTest, BasicUse)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.875, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, Overshoot)
{
UnitBezier bezier(0.5, 2.0, 0.5, 2.0);
EXPECT_EQ(1.625, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, Undershoot)
{
UnitBezier bezier(0.5, -1.0, 0.5, -1.0);
EXPECT_EQ(-0.625, bezier.solve(0.5, 0.005));
}
TEST(UnitBezierTest, InputAtEdgeOfRange)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(0.0, 0.005));
EXPECT_EQ(1.0, bezier.solve(1.0, 0.005));
}
TEST(UnitBezierTest, InputOutOfRange)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(-1.0, 0.005));
EXPECT_EQ(1.0, bezier.solve(2.0, 0.005));
}
TEST(UnitBezierTest, InputOutOfRangeLargeEpsilon)
{
UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
EXPECT_EQ(0.0, bezier.solve(-1.0, 1.0));
EXPECT_EQ(1.0, bezier.solve(2.0, 1.0));
}
} // namespace
| Java |
using Brandbank.Xml.Logging;
using System;
namespace Brandbank.Api.Clients
{
public sealed class FeedbackClientLogger : IFeedbackClient
{
private readonly ILogger<IFeedbackClient> _logger;
private readonly IFeedbackClient _feedbackClient;
public FeedbackClientLogger(ILogger<IFeedbackClient> logger, IFeedbackClient feedbackClient)
{
_logger = logger;
_feedbackClient = feedbackClient;
}
public int UploadCompressedFeedback(byte[] compressedFeedback)
{
_logger.LogDebug("Uploading compressed feedback to Brandbank");
try
{
var response = _feedbackClient.UploadCompressedFeedback(compressedFeedback);
_logger.LogDebug(response == 0
? "Uploaded compressed feedback to Brandbank"
: $"Upload compressed feedback to Brandbank failed, response code {response}");
return response;
}
catch (Exception e)
{
_logger.LogError($"Upload compressed feedback to Brandbank failed: {e}");
throw;
}
}
public void Dispose()
{
_logger.LogDebug("Disposing feedback client");
try
{
_feedbackClient.Dispose();
_logger.LogDebug("Disposed feedback client");
}
catch (Exception e)
{
_logger.LogError($"Disposing feedback client failed: {e}");
throw;
}
}
}
}
| Java |
<?php
namespace Zodream\Infrastructure\Http\Input;
/**
* Created by PhpStorm.
* User: zx648
* Date: 2016/4/3
* Time: 9:23
*/
use Zodream\Infrastructure\Base\MagicObject;
abstract class BaseInput extends MagicObject {
/**
* 格式化
* @param array|string $data
* @return array|string
*/
protected function _clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[strtolower($this->_clean($key))] = $this->_clean($value);
}
} else if (defined('APP_SAFE') && APP_SAFE){
$data = htmlspecialchars($data, ENT_COMPAT);
}
return $data;
}
protected function setValues(array $data) {
$this->set($this->_clean($data));
}
public function get($name = null, $default = null) {
return parent::get(strtolower($name), $default);
}
} | Java |
---
home: true
heroImage: /sofa128.png
actionText: Get Started →
features:
- title: Schema definition
details: Strict modeling based on schema with automatic and custom type validation.
- title: Database operations
details: Insert, upsert and remove documents.
- title: Middleware
details: Support for pre and post middleware hooks.
- title: Embedded documents
details: Embedded documents with automatic or manual population.
- title: Indexing
details: Automatic indexing for performant queries using reference lookup documents.
- title: Flexible API
details: Use either callback or promise based API.
actionLink: /guide/
footer: MIT Licensed | Copyright © 2018 - present Bojan D.
---
```js
var lounge = require('lounge')
lounge.connect({
connectionString: 'couchbase://127.0.0.1',
bucket: 'lounge_test'
})
var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
kitty.save(function (err) {
if (err) // ...
console.log('meow')
})
```
| Java |
<?php
/*
* This file is part of the Grosona.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Grosona;
use Grosona\PhpProcess\Utils\Logger;
use Grosona\PhpProcess\TrobuleHandler;
/**
* Read configurations from the file.
*
* @author hchsiao
*/
class TroubleHandler implements TrobuleHandler {
protected $logger = null;
public function activate(Logger $logger) {
$this->logger = $logger;
}
public function handle(\Exception $err) {
if(
is_int(stripos($err->getMessage(), "Error validating access token: Session has expired")) ||
is_int(stripos($err->getMessage(), "Invalid appsecret_proof"))
) {
$msg = "token died\n";
echo $msg;
} else if(is_int(stripos($err->getMessage(), "Access token mismatch"))) {
$msg = "token confilict\n";
echo $msg;
} else {
$msg = (string) $err;
}
$this->logger->log("<Exception> $msg", Logger::LEVEL_ERROR);
}
public function shutdown() {
$logger = $this->logger;
if(!$logger instanceof Logger) {
die();
}
$err = error_get_last();
$errMsg = $err['message'];
if(is_int(stripos($errMsg, "FacebookSDKException' with message 'Connection timed out"))) {
$logger->log("facebook server down", Logger::LEVEL_WARN);
} else if(
is_int(stripos($errMsg, "operation failed")) ||
is_int(stripos($errMsg, "Gateway Time-out")) ||
is_int(stripos($errMsg, "HTTP request failed")) ||
is_int(stripos($errMsg, "Connection timed out")) ||
// faild to download image, will retry so it's OK
is_int(stripos($errMsg, "Undefined variable: http_response_header")) ||
is_int(stripos($errMsg, "Stream returned an empty response"))
// facebook http request failed, retry too
) {
$logger->log("HTTP request failed", Logger::LEVEL_INFO);
} else if($errMsg) {
$type = $err['type'];
$place = $err['file'] . '(' . $err['line'] . ')';
$logger->log("<Shutdown Type=$type> $errMsg at $place", Logger::LEVEL_ERROR);
}
}
}
| Java |
class DashboardController < ApplicationController
def index
end
end
# vim: fo=tcq
| Java |
-- 创建T_Good表
CREATE TABLE IF NOT EXISTS T_Good
(
goodId INTEGER PRIMARY KEY NOT NULL,
good TEXT,
"createAt" TEXT DEFAULT (datetime('now', 'localtime'))
);
| Java |
const getAllMatchers = require("./getAllMatchers");
describe("unit: getAllMatchers", () => {
let handler;
let matcherStore;
beforeEach(() => {
matcherStore = [{}, {}, {}];
handler = getAllMatchers(matcherStore);
});
test("it should return all matchers", () => {
expect(handler()).toHaveProperty("body", matcherStore);
});
test("it should return a status of 200", () => {
expect(handler()).toHaveProperty("status", 200);
});
});
| Java |
table {
font-family: Consolas, Monaco, monospace;
font-size: 1em;
line-height: 1.44em;
}
table th,
table td {
padding: 0.4em 0.8em;
}
| Java |
---
layout: post
title: "Welcome to Jekyll!"
tags: [web, jekyll]
---
Vestibulum vulputate ac sem dapibus sagittis. Phasellus vestibulum ligula quam, vitae porta risus posuere sit amet. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Aliquam lobortis nisl ut semper suscipit. Aenean eget sem nisl. Sed gravida suscipit mauris et pellentesque. Sed eget euismod sem. Vivamus volutpat sem odio, ut hendrerit arcu tempor non. Sed at sodales nisl. Mauris dui sem, bibendum vel tortor ac, vulputate sollicitudin massa. Proin mattis rhoncus tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed eget metus purus. Vestibulum sagittis non velit id tempus.

```js
const options = {
size: 45
};
```
Mauris posuere arcu eu erat ullamcorper, a auctor elit semper. In quis consectetur leo. In et dictum justo. Fusce at urna ultrices, sodales lacus eget, molestie ex. In eleifend orci et ipsum lacinia, vitae fermentum augue laoreet. Sed a ultricies lorem. Pellentesque varius nisi ac neque aliquam porta. Nunc viverra imperdiet augue, quis vulputate odio pellentesque sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam tristique ante et tristique euismod. Proin rutrum interdum nisl id elementum. Pellentesque lacinia velit orci, a tincidunt tortor porta id. Donec mauris urna, rhoncus nec mauris eget, suscipit feugiat risus. Maecenas in viverra metus. Nulla facilisi. Aliquam porta venenatis enim in congue.
Phasellus ut suscipit libero. Vestibulum urna magna, pretium eu lorem vel, dapibus sollicitudin ligula. Maecenas varius aliquam malesuada. Donec consectetur ultricies turpis ultrices gravida. Praesent efficitur nulla ac vehicula consequat. Praesent feugiat, magna dignissim varius eleifend, ligula sapien accumsan nisi, eu tincidunt magna neque a neque. Donec interdum, magna id vestibulum suscipit, neque quam dignissim nibh, ut molestie felis purus vitae sem. Phasellus imperdiet eleifend erat ac posuere. Donec id vehicula enim. Maecenas vel blandit nisl.
Sed porta convallis lacinia. Phasellus sit amet aliquet velit. Proin consectetur malesuada tortor sed consequat. Morbi arcu odio, dictum eget nibh eget, tempor gravida risus. Nulla at tortor id libero rutrum luctus et id leo. Nam dolor urna, congue eu dapibus et, ultrices eget magna. Fusce dignissim lacinia elementum. Aenean condimentum nulla iaculis velit dictum gravida. Pellentesque eleifend dignissim est, volutpat consectetur est ornare a. Vestibulum ut nulla commodo, iaculis augue sit amet, volutpat orci.
Nullam sit amet lacinia justo. Mauris eu elit quam. Aliquam erat volutpat. Ut pulvinar quis enim ut placerat. Duis dictum varius iaculis. Suspendisse potenti. Nam tellus magna, consequat a dictum a, elementum a nisl. Pellentesque posuere nulla eu gravida rhoncus. Maecenas non ipsum ut felis vulputate consequat ac quis lectus. Nulla in porttitor elit. Nam at metus consectetur, sollicitudin augue ut, vulputate mi. Donec lobortis bibendum mauris vel vehicula. Fusce scelerisque id sapien sed bibendum.
| Java |
# [parser](https://github.com/yanhaijing/template.js/blob/master/packages/parser)
[](https://github.com/yanhaijing/jslib-base)
[template.js](https://github.com/yanhaijing/template.js)的模板编译器
## 兼容性
单元测试保证支持如下环境:
| IE | CH | FF | SF | OP | IOS | Android | Node |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- |
| 6+ | 29+ | 55+ | 9+ | 50+ | 9+ | 4+ | 0.10+ |
**注意:编译代码依赖ES5环境,对于ie6-8需要引入[es5-shim](http://github.com/es-shims/es5-shim/)才可以兼容,可以查看[demo/demo-global.html](./demo/demo-global.html)中的例子**
## 使用者指南
通过npm下载安装代码
```bash
$ npm install --save @templatejs/parser
```
如果你是node环境
```js
const parser = require('@templatejs/parser');
const tpl = `
<div><%=a%></div>
`;
parser.parse(tpl); // return a render string like '<div>' + a + '</div>'
```
支持的参数
```js
// sTag 开始标签
// eTag 结束标签
// escape 是否默认转移输出变量
parser.parse(tpl, {sTag: '<#', eTag: '#>', escape: true});
```
## 文档
[API](https://github.com/yanhaijing/template.js/blob/master/./doc/api.md)
## 贡献者列表
[contributors](https://github.com/yanhaijing/template.js/graphs/contributors)
## 更新日志
[CHANGELOG.md](https://github.com/yanhaijing/template.js/blob/master/TODO.md/CHANGELOG.md)
## 计划列表
[TODO.md](https://github.com/yanhaijing/template.js/blob/master/TODO.md) | Java |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_get_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_by_query_request(
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
subscription_id: str,
*,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2020-11-01-preview"
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'),
"managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'),
"databaseName": _SERIALIZER.url("database_name", database_name, 'str'),
"queryId": _SERIALIZER.url("query_id", query_id, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if start_time is not None:
query_parameters['startTime'] = _SERIALIZER.query("start_time", start_time, 'str')
if end_time is not None:
query_parameters['endTime'] = _SERIALIZER.query("end_time", end_time, 'str')
if interval is not None:
query_parameters['interval'] = _SERIALIZER.query("interval", interval, 'str')
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class ManagedDatabaseQueriesOperations(object):
"""ManagedDatabaseQueriesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.sql.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def get(
self,
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
**kwargs: Any
) -> "_models.ManagedInstanceQuery":
"""Get query by query id.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance.
:type managed_instance_name: str
:param database_name: The name of the database.
:type database_name: str
:param query_id:
:type query_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceQuery, or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceQuery
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQuery"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('ManagedInstanceQuery', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}'} # type: ignore
@distributed_trace
def list_by_query(
self,
resource_group_name: str,
managed_instance_name: str,
database_name: str,
query_id: str,
start_time: Optional[str] = None,
end_time: Optional[str] = None,
interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None,
**kwargs: Any
) -> Iterable["_models.ManagedInstanceQueryStatistics"]:
"""Get query execution statistics by query id.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance.
:type managed_instance_name: str
:param database_name: The name of the database.
:type database_name: str
:param query_id:
:type query_id: str
:param start_time: Start time for observed period.
:type start_time: str
:param end_time: End time for observed period.
:type end_time: str
:param interval: The time step to be used to summarize the metric values.
:type interval: str or ~azure.mgmt.sql.models.QueryTimeGrainType
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedInstanceQueryStatistics or the result of
cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceQueryStatistics]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQueryStatistics"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_query_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
start_time=start_time,
end_time=end_time,
interval=interval,
template_url=self.list_by_query.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_by_query_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
database_name=database_name,
query_id=query_id,
subscription_id=self._config.subscription_id,
start_time=start_time,
end_time=end_time,
interval=interval,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedInstanceQueryStatistics", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_query.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics'} # type: ignore
| Java |
Unicode.sublime-package
=======================
Disclaimer
----------
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Installation
------------
Install package to:
* __OSX:__ `~/Library/Application Support/Sublime Text 2/Installed Packages`
* __Windows:__ `%APPDATA%\Sublime Text 2\Installed Packages`
* __Linux:__ `~/.config/sublime-text-2/Installed Packages`
Usage
-----
* __Main Menu:__ `Edit` | `Convert Unicode`
* __Context Menu:__ `Convert Unicode`
* __Command Palette:__ `Convert ...`
* __Keymap:__ (Windows, Linux)
* Unicode characters to escape sequences: <kbd>alt+shift+w</kbd>
* Unicode escape sequences to characters: <kbd>alt+shift+e</kbd>
* __Keymap:__ (OSX)
* Unicode characters to escape sequences: <kbd>⌥⇧⌘w</kbd>
* Unicode escape sequences to characters: <kbd>⌥⇧⌘e</kbd>
LICENSE
-------
See file [__LICENSE__](../master/LICENSE) for details.
| Java |
<?php
namespace Koalamon\IntegrationBundle\Integration;
class Integration
{
private $name;
private $image;
private $description;
private $url;
private $activeElements;
private $totalElements;
/**
* Integration constructor.
*
* @param $name
* @param $image
* @param $description
* @param $url
*/
public function __construct($name, $image, $description, $url = null, $activeElements = null, $totalElements = null)
{
$this->name = $name;
$this->image = $image;
$this->description = $description;
$this->url = $url;
$this->activeElements = $activeElements;
$this->totalElements = $totalElements;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @return mixed
*/
public function getUrl()
{
return $this->url;
}
/**
* @return null
*/
public function getActiveElements()
{
return $this->activeElements;
}
/**
* @return null
*/
public function getTotalElements()
{
return $this->totalElements;
}
/**
* @param null $activeElements
*/
public function setActiveElements($activeElements)
{
$this->activeElements = $activeElements;
}
public function setUrl($url)
{
$this->url = $url;
}
} | Java |
---
layout: page
title: Roger Mercado's 91st Birthday
date: 2016-05-24
author: Juan Rodgers
tags: weekly links, java
status: published
summary: In molestie nec mauris a pretium. Pellentesque massa.
banner: images/banner/meeting-01.jpg
booking:
startDate: 06/25/2016
endDate: 06/27/2016
ctyhocn: SCOINHX
groupCode: RM9B
published: true
---
Praesent rhoncus neque at tincidunt dictum. Aenean sagittis pretium pulvinar. Integer a lectus at lectus pulvinar rutrum in fermentum ante. Duis tincidunt id nunc tincidunt porttitor. Fusce ultrices, ligula sit amet malesuada hendrerit, augue ante viverra est, vel viverra quam tortor vel ligula. Nam justo enim, interdum vel vestibulum ac, lacinia nec velit. Suspendisse efficitur magna sit amet arcu pretium porta. Mauris accumsan venenatis nulla, quis vulputate libero imperdiet porta. In mi justo, malesuada quis eleifend eu, tincidunt vitae enim. Aliquam erat volutpat.
Suspendisse scelerisque urna eu accumsan suscipit. Suspendisse non enim nulla. Ut a sapien vel nisi porttitor iaculis vitae at orci. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin nec commodo erat. Pellentesque sed vehicula nisi, a maximus massa. Nam aliquam nisi metus, in tincidunt diam consequat eu. Donec sit amet diam feugiat, mollis ante sit amet, vehicula risus. Curabitur in lobortis eros.
1 Aliquam vel dui a enim rhoncus venenatis
1 Morbi varius est quis mauris efficitur, vel mattis ante molestie.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin euismod hendrerit pulvinar. Mauris ac tortor consectetur, tincidunt eros at, luctus dolor. Aliquam vel diam vitae quam aliquet aliquet. In sed ante massa. Donec orci arcu, consectetur nec placerat eget, dapibus vitae neque. Pellentesque in urna arcu. Nulla pharetra aliquam malesuada. Proin accumsan dolor ac tortor aliquet, eget tempor enim efficitur. Nulla blandit dignissim mattis. Duis at erat tellus. In hac habitasse platea dictumst. Duis elit nibh, consectetur vel mi non, interdum consectetur augue. Donec malesuada congue sagittis.
Vestibulum rhoncus leo non velit malesuada feugiat. Praesent faucibus nibh non tempor tempor. In posuere magna eu gravida pulvinar. Proin vel orci diam. Ut at accumsan augue. Proin tincidunt, lacus vitae egestas finibus, sem mi ultricies enim, nec blandit massa mauris eu diam. Aenean ac ipsum eget leo finibus consequat. Praesent id varius leo.
| Java |
import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
| Java |
/*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.4.2 *
* Date : 27 February 2017 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2017 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
/*******************************************************************************
* *
* This is a translation of the Delphi Clipper library and the naming style *
* used has retained a Delphi flavour. *
* *
*******************************************************************************/
#include "clipper.hpp"
#include <cmath>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
namespace ClipperLib {
static double const pi = 3.141592653589793238;
static double const two_pi = pi *2;
static double const def_arc_tolerance = 0.25;
enum Direction { dRightToLeft, dLeftToRight };
static int const Unassigned = -1; //edge not currently 'owning' a solution
static int const Skip = -2; //edge that would otherwise close a path
#define HORIZONTAL (-1.0E+40)
#define TOLERANCE (1.0e-20)
#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
struct TEdge {
IntPoint Bot;
IntPoint Curr; //current (updated for every new scanbeam)
IntPoint Top;
double Dx;
PolyType PolyTyp;
EdgeSide Side; //side only refers to current side of solution poly
int WindDelta; //1 or -1 depending on winding direction
int WindCnt;
int WindCnt2; //winding count of the opposite polytype
int OutIdx;
TEdge *Next;
TEdge *Prev;
TEdge *NextInLML;
TEdge *NextInAEL;
TEdge *PrevInAEL;
TEdge *NextInSEL;
TEdge *PrevInSEL;
};
struct IntersectNode {
TEdge *Edge1;
TEdge *Edge2;
IntPoint Pt;
};
struct LocalMinimum {
cInt Y;
TEdge *LeftBound;
TEdge *RightBound;
};
struct OutPt;
//OutRec: contains a path in the clipping solution. Edges in the AEL will
//carry a pointer to an OutRec when they are part of the clipping solution.
struct OutRec {
int Idx;
bool IsHole;
bool IsOpen;
OutRec *FirstLeft; //see comments in clipper.pas
PolyNode *PolyNd;
OutPt *Pts;
OutPt *BottomPt;
};
struct OutPt {
int Idx;
IntPoint Pt;
OutPt *Next;
OutPt *Prev;
};
struct Join {
OutPt *OutPt1;
OutPt *OutPt2;
IntPoint OffPt;
};
struct LocMinSorter
{
inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
{
return locMin2.Y < locMin1.Y;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
inline cInt Round(double val)
{
if ((val < 0)) return static_cast<cInt>(val - 0.5);
else return static_cast<cInt>(val + 0.5);
}
//------------------------------------------------------------------------------
inline cInt Abs(cInt val)
{
return val < 0 ? -val : val;
}
//------------------------------------------------------------------------------
// PolyTree methods ...
//------------------------------------------------------------------------------
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
//------------------------------------------------------------------------------
PolyNode* PolyTree::GetFirst() const
{
if (!Childs.empty())
return Childs[0];
else
return 0;
}
//------------------------------------------------------------------------------
int PolyTree::Total() const
{
int result = (int)AllNodes.size();
//with negative offsets, ignore the hidden outer polygon ...
if (result > 0 && Childs[0] != AllNodes[0]) result--;
return result;
}
//------------------------------------------------------------------------------
// PolyNode methods ...
//------------------------------------------------------------------------------
PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
{
}
//------------------------------------------------------------------------------
int PolyNode::ChildCount() const
{
return (int)Childs.size();
}
//------------------------------------------------------------------------------
void PolyNode::AddChild(PolyNode& child)
{
unsigned cnt = (unsigned)Childs.size();
Childs.push_back(&child);
child.Parent = this;
child.Index = cnt;
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNext() const
{
if (!Childs.empty())
return Childs[0];
else
return GetNextSiblingUp();
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNextSiblingUp() const
{
if (!Parent) //protects against PolyTree.GetNextSiblingUp()
return 0;
else if (Index == Parent->Childs.size() - 1)
return Parent->GetNextSiblingUp();
else
return Parent->Childs[Index + 1];
}
//------------------------------------------------------------------------------
bool PolyNode::IsHole() const
{
bool result = true;
PolyNode* node = Parent;
while (node)
{
result = !result;
node = node->Parent;
}
return result;
}
//------------------------------------------------------------------------------
bool PolyNode::IsOpen() const
{
return m_IsOpen;
}
//------------------------------------------------------------------------------
#ifndef use_int32
//------------------------------------------------------------------------------
// Int128 class (enables safe math on signed 64bit integers)
// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
// Int128 val2((long64)9223372036854775807);
// Int128 val3 = val1 * val2;
// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
//------------------------------------------------------------------------------
class Int128
{
public:
ulong64 lo;
long64 hi;
Int128(long64 _lo = 0)
{
lo = (ulong64)_lo;
if (_lo < 0) hi = -1; else hi = 0;
}
Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
Int128& operator = (const long64 &val)
{
lo = (ulong64)val;
if (val < 0) hi = -1; else hi = 0;
return *this;
}
bool operator == (const Int128 &val) const
{return (hi == val.hi && lo == val.lo);}
bool operator != (const Int128 &val) const
{ return !(*this == val);}
bool operator > (const Int128 &val) const
{
if (hi != val.hi)
return hi > val.hi;
else
return lo > val.lo;
}
bool operator < (const Int128 &val) const
{
if (hi != val.hi)
return hi < val.hi;
else
return lo < val.lo;
}
bool operator >= (const Int128 &val) const
{ return !(*this < val);}
bool operator <= (const Int128 &val) const
{ return !(*this > val);}
Int128& operator += (const Int128 &rhs)
{
hi += rhs.hi;
lo += rhs.lo;
if (lo < rhs.lo) hi++;
return *this;
}
Int128 operator + (const Int128 &rhs) const
{
Int128 result(*this);
result+= rhs;
return result;
}
Int128& operator -= (const Int128 &rhs)
{
*this += -rhs;
return *this;
}
Int128 operator - (const Int128 &rhs) const
{
Int128 result(*this);
result -= rhs;
return result;
}
Int128 operator-() const //unary negation
{
if (lo == 0)
return Int128(-hi, 0);
else
return Int128(~hi, ~lo + 1);
}
operator double() const
{
const double shift64 = 18446744073709551616.0; //2^64
if (hi < 0)
{
if (lo == 0) return (double)hi * shift64;
else return -(double)(~lo + ~hi * shift64);
}
else
return (double)(lo + hi * shift64);
}
};
//------------------------------------------------------------------------------
Int128 Int128Mul (long64 lhs, long64 rhs)
{
bool negate = (lhs < 0) != (rhs < 0);
if (lhs < 0) lhs = -lhs;
ulong64 int1Hi = ulong64(lhs) >> 32;
ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
if (rhs < 0) rhs = -rhs;
ulong64 int2Hi = ulong64(rhs) >> 32;
ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
//nb: see comments in clipper.pas
ulong64 a = int1Hi * int2Hi;
ulong64 b = int1Lo * int2Lo;
ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
Int128 tmp;
tmp.hi = long64(a + (c >> 32));
tmp.lo = long64(c << 32);
tmp.lo += long64(b);
if (tmp.lo < b) tmp.hi++;
if (negate) tmp = -tmp;
return tmp;
};
#endif
//------------------------------------------------------------------------------
// Miscellaneous global functions
//------------------------------------------------------------------------------
bool Orientation(const Path &poly)
{
return Area(poly) >= 0;
}
//------------------------------------------------------------------------------
double Area(const Path &poly)
{
int size = (int)poly.size();
if (size < 3) return 0;
double a = 0;
for (int i = 0, j = size -1; i < size; ++i)
{
a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
j = i;
}
return -a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutPt *op)
{
const OutPt *startOp = op;
if (!op) return 0;
double a = 0;
do {
a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
op = op->Next;
} while (op != startOp);
return a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutRec &outRec)
{
return Area(outRec.Pts);
}
//------------------------------------------------------------------------------
bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
{
OutPt *pp2 = pp;
do
{
if (pp2->Pt == Pt) return true;
pp2 = pp2->Next;
}
while (pp2 != pp);
return false;
}
//------------------------------------------------------------------------------
//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
int PointInPolygon(const IntPoint &pt, const Path &path)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
size_t cnt = path.size();
if (cnt < 3) return 0;
IntPoint ip = path[0];
for(size_t i = 1; i <= cnt; ++i)
{
IntPoint ipNext = (i == cnt ? path[0] : path[i]);
if (ipNext.Y == pt.Y)
{
if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
}
if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
{
if (ip.X >= pt.X)
{
if (ipNext.X > pt.X) result = 1 - result;
else
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
} else
{
if (ipNext.X > pt.X)
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
}
}
ip = ipNext;
}
return result;
}
//------------------------------------------------------------------------------
int PointInPolygon (const IntPoint &pt, OutPt *op)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
OutPt* startOp = op;
for(;;)
{
if (op->Next->Pt.Y == pt.Y)
{
if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
}
if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
{
if (op->Pt.X >= pt.X)
{
if (op->Next->Pt.X > pt.X) result = 1 - result;
else
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
} else
{
if (op->Next->Pt.X > pt.X)
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
}
}
op = op->Next;
if (startOp == op) break;
}
return result;
}
//------------------------------------------------------------------------------
bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
{
OutPt* op = OutPt1;
do
{
//nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
int res = PointInPolygon(op->Pt, OutPt2);
if (res >= 0) return res > 0;
op = op->Next;
}
while (op != OutPt1);
return true;
}
//----------------------------------------------------------------------
bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==
Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);
else
#endif
return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==
(e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
}
//------------------------------------------------------------------------------
inline bool IsHorizontal(TEdge &e)
{
return e.Dx == HORIZONTAL;
}
//------------------------------------------------------------------------------
inline double GetDx(const IntPoint pt1, const IntPoint pt2)
{
return (pt1.Y == pt2.Y) ?
HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
}
//---------------------------------------------------------------------------
inline void SetDx(TEdge &e)
{
cInt dy = (e.Top.Y - e.Bot.Y);
if (dy == 0) e.Dx = HORIZONTAL;
else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;
}
//---------------------------------------------------------------------------
inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
{
EdgeSide Side = Edge1.Side;
Edge1.Side = Edge2.Side;
Edge2.Side = Side;
}
//------------------------------------------------------------------------------
inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
{
int OutIdx = Edge1.OutIdx;
Edge1.OutIdx = Edge2.OutIdx;
Edge2.OutIdx = OutIdx;
}
//------------------------------------------------------------------------------
inline cInt TopX(TEdge &edge, const cInt currentY)
{
return ( currentY == edge.Top.Y ) ?
edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
}
//------------------------------------------------------------------------------
void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
{
#ifdef use_xyz
ip.Z = 0;
#endif
double b1, b2;
if (Edge1.Dx == Edge2.Dx)
{
ip.Y = Edge1.Curr.Y;
ip.X = TopX(Edge1, ip.Y);
return;
}
else if (Edge1.Dx == 0)
{
ip.X = Edge1.Bot.X;
if (IsHorizontal(Edge2))
ip.Y = Edge2.Bot.Y;
else
{
b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
ip.Y = Round(ip.X / Edge2.Dx + b2);
}
}
else if (Edge2.Dx == 0)
{
ip.X = Edge2.Bot.X;
if (IsHorizontal(Edge1))
ip.Y = Edge1.Bot.Y;
else
{
b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
ip.Y = Round(ip.X / Edge1.Dx + b1);
}
}
else
{
b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
ip.Y = Round(q);
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = Round(Edge1.Dx * q + b1);
else
ip.X = Round(Edge2.Dx * q + b2);
}
if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
{
if (Edge1.Top.Y > Edge2.Top.Y)
ip.Y = Edge1.Top.Y;
else
ip.Y = Edge2.Top.Y;
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = TopX(Edge1, ip.Y);
else
ip.X = TopX(Edge2, ip.Y);
}
//finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
if (ip.Y > Edge1.Curr.Y)
{
ip.Y = Edge1.Curr.Y;
//use the more vertical edge to derive X ...
if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
ip.X = TopX(Edge2, ip.Y); else
ip.X = TopX(Edge1, ip.Y);
}
}
//------------------------------------------------------------------------------
void ReversePolyPtLinks(OutPt *pp)
{
if (!pp) return;
OutPt *pp1, *pp2;
pp1 = pp;
do {
pp2 = pp1->Next;
pp1->Next = pp1->Prev;
pp1->Prev = pp2;
pp1 = pp2;
} while( pp1 != pp );
}
//------------------------------------------------------------------------------
void DisposeOutPts(OutPt*& pp)
{
if (pp == 0) return;
pp->Prev->Next = 0;
while( pp )
{
OutPt *tmpPp = pp;
pp = pp->Next;
delete tmpPp;
}
}
//------------------------------------------------------------------------------
inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
{
std::memset(e, 0, sizeof(TEdge));
e->Next = eNext;
e->Prev = ePrev;
e->Curr = Pt;
e->OutIdx = Unassigned;
}
//------------------------------------------------------------------------------
void InitEdge2(TEdge& e, PolyType Pt)
{
if (e.Curr.Y >= e.Next->Curr.Y)
{
e.Bot = e.Curr;
e.Top = e.Next->Curr;
} else
{
e.Top = e.Curr;
e.Bot = e.Next->Curr;
}
SetDx(e);
e.PolyTyp = Pt;
}
//------------------------------------------------------------------------------
TEdge* RemoveEdge(TEdge* e)
{
//removes e from double_linked_list (but without removing from memory)
e->Prev->Next = e->Next;
e->Next->Prev = e->Prev;
TEdge* result = e->Next;
e->Prev = 0; //flag as removed (see ClipperBase.Clear)
return result;
}
//------------------------------------------------------------------------------
inline void ReverseHorizontal(TEdge &e)
{
//swap horizontal edges' Top and Bottom x's so they follow the natural
//progression of the bounds - ie so their xbots will align with the
//adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
std::swap(e.Top.X, e.Bot.X);
#ifdef use_xyz
std::swap(e.Top.Z, e.Bot.Z);
#endif
}
//------------------------------------------------------------------------------
void SwapPoints(IntPoint &pt1, IntPoint &pt2)
{
IntPoint tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
//------------------------------------------------------------------------------
bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
{
//precondition: segments are Collinear.
if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
{
if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
return pt1.X < pt2.X;
} else
{
if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
return pt1.Y > pt2.Y;
}
}
//------------------------------------------------------------------------------
bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
{
OutPt *p = btmPt1->Prev;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt1->Next;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt2->Prev;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
p = btmPt2->Next;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&
std::min(dx1p, dx1n) == std::min(dx2p, dx2n))
return Area(btmPt1) > 0; //if otherwise identical use orientation
else
return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
}
//------------------------------------------------------------------------------
OutPt* GetBottomPt(OutPt *pp)
{
OutPt* dups = 0;
OutPt* p = pp->Next;
while (p != pp)
{
if (p->Pt.Y > pp->Pt.Y)
{
pp = p;
dups = 0;
}
else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
{
if (p->Pt.X < pp->Pt.X)
{
dups = 0;
pp = p;
} else
{
if (p->Next != pp && p->Prev != pp) dups = p;
}
}
p = p->Next;
}
if (dups)
{
//there appears to be at least 2 vertices at BottomPt so ...
while (dups != p)
{
if (!FirstIsBottomPt(p, dups)) pp = dups;
dups = dups->Next;
while (dups->Pt != pp->Pt) dups = dups->Next;
}
}
return pp;
}
//------------------------------------------------------------------------------
bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
const IntPoint pt2, const IntPoint pt3)
{
if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
return false;
else if (pt1.X != pt3.X)
return (pt2.X > pt1.X) == (pt2.X < pt3.X);
else
return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
}
//------------------------------------------------------------------------------
bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
{
if (seg1a > seg1b) std::swap(seg1a, seg1b);
if (seg2a > seg2b) std::swap(seg2a, seg2b);
return (seg1a < seg2b) && (seg2a < seg1b);
}
//------------------------------------------------------------------------------
// ClipperBase class methods ...
//------------------------------------------------------------------------------
ClipperBase::ClipperBase() //constructor
{
m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
m_UseFullRange = false;
}
//------------------------------------------------------------------------------
ClipperBase::~ClipperBase() //destructor
{
Clear();
}
//------------------------------------------------------------------------------
void RangeTest(const IntPoint& Pt, bool& useFullRange)
{
if (useFullRange)
{
if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
throw clipperException("Coordinate outside allowed range");
}
else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
{
useFullRange = true;
RangeTest(Pt, useFullRange);
}
}
//------------------------------------------------------------------------------
TEdge* FindNextLocMin(TEdge* E)
{
for (;;)
{
while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
while (IsHorizontal(*E->Prev)) E = E->Prev;
TEdge* E2 = E;
while (IsHorizontal(*E)) E = E->Next;
if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
if (E2->Prev->Bot.X < E->Bot.X) E = E2;
break;
}
return E;
}
//------------------------------------------------------------------------------
TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
{
TEdge *Result = E;
TEdge *Horz = 0;
if (E->OutIdx == Skip)
{
//if edges still remain in the current bound beyond the skip edge then
//create another LocMin and call ProcessBound once more
if (NextIsForward)
{
while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
//don't include top horizontals when parsing a bound a second time,
//they will be contained in the opposite bound ...
while (E != Result && IsHorizontal(*E)) E = E->Prev;
}
else
{
while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
while (E != Result && IsHorizontal(*E)) E = E->Next;
}
if (E == Result)
{
if (NextIsForward) Result = E->Next;
else Result = E->Prev;
}
else
{
//there are more edges in the bound beyond result starting with E
if (NextIsForward)
E = Result->Next;
else
E = Result->Prev;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
E->WindDelta = 0;
Result = ProcessBound(E, NextIsForward);
m_MinimaList.push_back(locMin);
}
return Result;
}
TEdge *EStart;
if (IsHorizontal(*E))
{
//We need to be careful with open paths because this may not be a
//true local minima (ie E may be following a skip edge).
//Also, consecutive horz. edges may start heading left before going right.
if (NextIsForward)
EStart = E->Prev;
else
EStart = E->Next;
if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
{
if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
ReverseHorizontal(*E);
}
else if (EStart->Bot.X != E->Bot.X)
ReverseHorizontal(*E);
}
EStart = E;
if (NextIsForward)
{
while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
Result = Result->Next;
if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
{
//nb: at the top of a bound, horizontals are added to the bound
//only when the preceding edge attaches to the horizontal's left vertex
//unless a Skip edge is encountered when that becomes the top divide
Horz = Result;
while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
}
while (E != Result)
{
E->NextInLML = E->Next;
if (IsHorizontal(*E) && E != EStart &&
E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
E = E->Next;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
ReverseHorizontal(*E);
Result = Result->Next; //move to the edge just beyond current bound
} else
{
while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
Result = Result->Prev;
if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
{
Horz = Result;
while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
if (Horz->Next->Top.X == Result->Prev->Top.X ||
Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
}
while (E != Result)
{
E->NextInLML = E->Prev;
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
E = E->Prev;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
Result = Result->Prev; //move to the edge just beyond current bound
}
return Result;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
{
#ifdef use_lines
if (!Closed && PolyTyp == ptClip)
throw clipperException("AddPath: Open paths must be subject.");
#else
if (!Closed)
throw clipperException("AddPath: Open paths have been disabled.");
#endif
int highI = (int)pg.size() -1;
if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
//create a new edge array ...
TEdge *edges = new TEdge [highI +1];
bool IsFlat = true;
//1. Basic (first) edge initialization ...
try
{
edges[1].Curr = pg[1];
RangeTest(pg[0], m_UseFullRange);
RangeTest(pg[highI], m_UseFullRange);
InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
for (int i = highI - 1; i >= 1; --i)
{
RangeTest(pg[i], m_UseFullRange);
InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
}
}
catch(...)
{
delete [] edges;
throw; //range test fails
}
TEdge *eStart = &edges[0];
//2. Remove duplicate vertices, and (when closed) collinear edges ...
TEdge *E = eStart, *eLoopStop = eStart;
for (;;)
{
//nb: allows matching start and end points when not Closed ...
if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
{
if (E == E->Next) break;
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
eLoopStop = E;
continue;
}
if (E->Prev == E->Next)
break; //only two vertices
else if (Closed &&
SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
(!m_PreserveCollinear ||
!Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
{
//Collinear edges are allowed for open paths but in closed paths
//the default is to merge adjacent collinear edges into a single edge.
//However, if the PreserveCollinear property is enabled, only overlapping
//collinear edges (ie spikes) will be removed from closed paths.
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
E = E->Prev;
eLoopStop = E;
continue;
}
E = E->Next;
if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
}
if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
{
delete [] edges;
return false;
}
if (!Closed)
{
m_HasOpenPaths = true;
eStart->Prev->OutIdx = Skip;
}
//3. Do second stage of edge initialization ...
E = eStart;
do
{
InitEdge2(*E, PolyTyp);
E = E->Next;
if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
}
while (E != eStart);
//4. Finally, add edge bounds to LocalMinima list ...
//Totally flat paths must be handled differently when adding them
//to LocalMinima list to avoid endless loops etc ...
if (IsFlat)
{
if (Closed)
{
delete [] edges;
return false;
}
E->Prev->OutIdx = Skip;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
locMin.RightBound->Side = esRight;
locMin.RightBound->WindDelta = 0;
for (;;)
{
if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
if (E->Next->OutIdx == Skip) break;
E->NextInLML = E->Next;
E = E->Next;
}
m_MinimaList.push_back(locMin);
m_edges.push_back(edges);
return true;
}
m_edges.push_back(edges);
bool leftBoundIsForward;
TEdge* EMin = 0;
//workaround to avoid an endless loop in the while loop below when
//open paths have matching start and end points ...
if (E->Prev->Bot == E->Prev->Top) E = E->Next;
for (;;)
{
E = FindNextLocMin(E);
if (E == EMin) break;
else if (!EMin) EMin = E;
//E and E.Prev now share a local minima (left aligned if horizontal).
//Compare their slopes to find which starts which bound ...
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
if (E->Dx < E->Prev->Dx)
{
locMin.LeftBound = E->Prev;
locMin.RightBound = E;
leftBoundIsForward = false; //Q.nextInLML = Q.prev
} else
{
locMin.LeftBound = E;
locMin.RightBound = E->Prev;
leftBoundIsForward = true; //Q.nextInLML = Q.next
}
if (!Closed) locMin.LeftBound->WindDelta = 0;
else if (locMin.LeftBound->Next == locMin.RightBound)
locMin.LeftBound->WindDelta = -1;
else locMin.LeftBound->WindDelta = 1;
locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
if (locMin.LeftBound->OutIdx == Skip)
locMin.LeftBound = 0;
else if (locMin.RightBound->OutIdx == Skip)
locMin.RightBound = 0;
m_MinimaList.push_back(locMin);
if (!leftBoundIsForward) E = E2;
}
return true;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
{
bool result = false;
for (Paths::size_type i = 0; i < ppg.size(); ++i)
if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::Clear()
{
DisposeLocalMinimaList();
for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
{
TEdge* edges = m_edges[i];
delete [] edges;
}
m_edges.clear();
m_UseFullRange = false;
m_HasOpenPaths = false;
}
//------------------------------------------------------------------------------
void ClipperBase::Reset()
{
m_CurrentLM = m_MinimaList.begin();
if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
m_Scanbeam = ScanbeamList(); //clears/resets priority_queue
//reset all edges ...
for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
{
InsertScanbeam(lm->Y);
TEdge* e = lm->LeftBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esLeft;
e->OutIdx = Unassigned;
}
e = lm->RightBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esRight;
e->OutIdx = Unassigned;
}
}
m_ActiveEdges = 0;
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeLocalMinimaList()
{
m_MinimaList.clear();
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)
{
if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;
locMin = &(*m_CurrentLM);
++m_CurrentLM;
return true;
}
//------------------------------------------------------------------------------
IntRect ClipperBase::GetBounds()
{
IntRect result;
MinimaList::iterator lm = m_MinimaList.begin();
if (lm == m_MinimaList.end())
{
result.left = result.top = result.right = result.bottom = 0;
return result;
}
result.left = lm->LeftBound->Bot.X;
result.top = lm->LeftBound->Bot.Y;
result.right = lm->LeftBound->Bot.X;
result.bottom = lm->LeftBound->Bot.Y;
while (lm != m_MinimaList.end())
{
//todo - needs fixing for open paths
result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
TEdge* e = lm->LeftBound;
for (;;) {
TEdge* bottomE = e;
while (e->NextInLML)
{
if (e->Bot.X < result.left) result.left = e->Bot.X;
if (e->Bot.X > result.right) result.right = e->Bot.X;
e = e->NextInLML;
}
result.left = std::min(result.left, e->Bot.X);
result.right = std::max(result.right, e->Bot.X);
result.left = std::min(result.left, e->Top.X);
result.right = std::max(result.right, e->Top.X);
result.top = std::min(result.top, e->Top.Y);
if (bottomE == lm->LeftBound) e = lm->RightBound;
else break;
}
++lm;
}
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::InsertScanbeam(const cInt Y)
{
m_Scanbeam.push(Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::PopScanbeam(cInt &Y)
{
if (m_Scanbeam.empty()) return false;
Y = m_Scanbeam.top();
m_Scanbeam.pop();
while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
return true;
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeAllOutRecs(){
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
DisposeOutRec(i);
m_PolyOuts.clear();
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeOutRec(PolyOutList::size_type index)
{
OutRec *outRec = m_PolyOuts[index];
if (outRec->Pts) DisposeOutPts(outRec->Pts);
delete outRec;
m_PolyOuts[index] = 0;
}
//------------------------------------------------------------------------------
void ClipperBase::DeleteFromAEL(TEdge *e)
{
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted
if (AelPrev) AelPrev->NextInAEL = AelNext;
else m_ActiveEdges = AelNext;
if (AelNext) AelNext->PrevInAEL = AelPrev;
e->NextInAEL = 0;
e->PrevInAEL = 0;
}
//------------------------------------------------------------------------------
OutRec* ClipperBase::CreateOutRec()
{
OutRec* result = new OutRec;
result->IsHole = false;
result->IsOpen = false;
result->FirstLeft = 0;
result->Pts = 0;
result->BottomPt = 0;
result->PolyNd = 0;
m_PolyOuts.push_back(result);
result->Idx = (int)m_PolyOuts.size() - 1;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
{
//check that one or other edge hasn't already been removed from AEL ...
if (Edge1->NextInAEL == Edge1->PrevInAEL ||
Edge2->NextInAEL == Edge2->PrevInAEL) return;
if (Edge1->NextInAEL == Edge2)
{
TEdge* Next = Edge2->NextInAEL;
if (Next) Next->PrevInAEL = Edge1;
TEdge* Prev = Edge1->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge2;
Edge2->PrevInAEL = Prev;
Edge2->NextInAEL = Edge1;
Edge1->PrevInAEL = Edge2;
Edge1->NextInAEL = Next;
}
else if (Edge2->NextInAEL == Edge1)
{
TEdge* Next = Edge1->NextInAEL;
if (Next) Next->PrevInAEL = Edge2;
TEdge* Prev = Edge2->PrevInAEL;
if (Prev) Prev->NextInAEL = Edge1;
Edge1->PrevInAEL = Prev;
Edge1->NextInAEL = Edge2;
Edge2->PrevInAEL = Edge1;
Edge2->NextInAEL = Next;
}
else
{
TEdge* Next = Edge1->NextInAEL;
TEdge* Prev = Edge1->PrevInAEL;
Edge1->NextInAEL = Edge2->NextInAEL;
if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;
Edge1->PrevInAEL = Edge2->PrevInAEL;
if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;
Edge2->NextInAEL = Next;
if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;
Edge2->PrevInAEL = Prev;
if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;
}
if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;
else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;
}
//------------------------------------------------------------------------------
void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)
{
if (!e->NextInLML)
throw clipperException("UpdateEdgeIntoAEL: invalid call");
e->NextInLML->OutIdx = e->OutIdx;
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
else m_ActiveEdges = e->NextInLML;
if (AelNext) AelNext->PrevInAEL = e->NextInLML;
e->NextInLML->Side = e->Side;
e->NextInLML->WindDelta = e->WindDelta;
e->NextInLML->WindCnt = e->WindCnt;
e->NextInLML->WindCnt2 = e->WindCnt2;
e = e->NextInLML;
e->Curr = e->Bot;
e->PrevInAEL = AelPrev;
e->NextInAEL = AelNext;
if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
}
//------------------------------------------------------------------------------
bool ClipperBase::LocalMinimaPending()
{
return (m_CurrentLM != m_MinimaList.end());
}
//------------------------------------------------------------------------------
// TClipper methods ...
//------------------------------------------------------------------------------
Clipper::Clipper(int initOptions) : ClipperBase() //constructor
{
m_ExecuteLocked = false;
m_UseFullRange = false;
m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
m_HasOpenPaths = false;
#ifdef use_xyz
m_ZFill = 0;
#endif
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::ZFillFunction(ZFillCallback zFillFunc)
{
m_ZFill = zFillFunc;
}
//------------------------------------------------------------------------------
#endif
bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
{
return Execute(clipType, solution, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
{
return Execute(clipType, polytree, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, Paths &solution,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
if (m_HasOpenPaths)
throw clipperException("Error: PolyTree struct is needed for open path clipping.");
m_ExecuteLocked = true;
solution.resize(0);
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = false;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult(solution);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
m_ExecuteLocked = true;
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = true;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult2(polytree);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::FixHoleLinkage(OutRec &outrec)
{
//skip OutRecs that (a) contain outermost polygons or
//(b) already have the correct owner/child linkage ...
if (!outrec.FirstLeft ||
(outrec.IsHole != outrec.FirstLeft->IsHole &&
outrec.FirstLeft->Pts)) return;
OutRec* orfl = outrec.FirstLeft;
while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
orfl = orfl->FirstLeft;
outrec.FirstLeft = orfl;
}
//------------------------------------------------------------------------------
bool Clipper::ExecuteInternal()
{
bool succeeded = true;
try {
Reset();
m_Maxima = MaximaList();
m_SortedEdges = 0;
succeeded = true;
cInt botY, topY;
if (!PopScanbeam(botY)) return false;
InsertLocalMinimaIntoAEL(botY);
while (PopScanbeam(topY) || LocalMinimaPending())
{
ProcessHorizontals();
ClearGhostJoins();
if (!ProcessIntersections(topY))
{
succeeded = false;
break;
}
ProcessEdgesAtTopOfScanbeam(topY);
botY = topY;
InsertLocalMinimaIntoAEL(botY);
}
}
catch(...)
{
succeeded = false;
}
if (succeeded)
{
//fix orientations ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec->IsOpen) continue;
if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
ReversePolyPtLinks(outRec->Pts);
}
if (!m_Joins.empty()) JoinCommonEdges();
//unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts) continue;
if (outRec->IsOpen)
FixupOutPolyline(*outRec);
else
FixupOutPolygon(*outRec);
}
if (m_StrictSimple) DoSimplePolygons();
}
ClearJoins();
ClearGhostJoins();
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::SetWindingCount(TEdge &edge)
{
TEdge *e = edge.PrevInAEL;
//find the edge of the same polytype that immediately preceeds 'edge' in AEL
while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
if (!e)
{
if (edge.WindDelta == 0)
{
PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);
edge.WindCnt = (pft == pftNegative ? -1 : 1);
}
else
edge.WindCnt = edge.WindDelta;
edge.WindCnt2 = 0;
e = m_ActiveEdges; //ie get ready to calc WindCnt2
}
else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
{
edge.WindCnt = 1;
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else if (IsEvenOddFillType(edge))
{
//EvenOdd filling ...
if (edge.WindDelta == 0)
{
//are we inside a subj polygon ...
bool Inside = true;
TEdge *e2 = e->PrevInAEL;
while (e2)
{
if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
Inside = !Inside;
e2 = e2->PrevInAEL;
}
edge.WindCnt = (Inside ? 0 : 1);
}
else
{
edge.WindCnt = edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else
{
//nonZero, Positive or Negative filling ...
if (e->WindCnt * e->WindDelta < 0)
{
//prev edge is 'decreasing' WindCount (WC) toward zero
//so we're outside the previous polygon ...
if (Abs(e->WindCnt) > 1)
{
//outside prev poly but still inside another.
//when reversing direction of prev poly use the same WC
if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise continue to 'decrease' WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
else
//now outside all polys of same polytype so set own WC ...
edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
} else
{
//prev edge is 'increasing' WindCount (WC) away from zero
//so we're inside the previous polygon ...
if (edge.WindDelta == 0)
edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
//if wind direction is reversing prev then use same WC
else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise add to WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
//update WindCnt2 ...
if (IsEvenOddAltFillType(edge))
{
//EvenOdd filling ...
while (e != &edge)
{
if (e->WindDelta != 0)
edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
e = e->NextInAEL;
}
} else
{
//nonZero, Positive or Negative filling ...
while ( e != &edge )
{
edge.WindCnt2 += e->WindDelta;
e = e->NextInAEL;
}
}
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_SubjFillType == pftEvenOdd; else
return m_ClipFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_ClipFillType == pftEvenOdd; else
return m_SubjFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsContributing(const TEdge& edge) const
{
PolyFillType pft, pft2;
if (edge.PolyTyp == ptSubject)
{
pft = m_SubjFillType;
pft2 = m_ClipFillType;
} else
{
pft = m_ClipFillType;
pft2 = m_SubjFillType;
}
switch(pft)
{
case pftEvenOdd:
//return false if a subj line has been flagged as inside a subj polygon
if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
break;
case pftNonZero:
if (Abs(edge.WindCnt) != 1) return false;
break;
case pftPositive:
if (edge.WindCnt != 1) return false;
break;
default: //pftNegative
if (edge.WindCnt != -1) return false;
}
switch(m_ClipType)
{
case ctIntersection:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctUnion:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
break;
case ctDifference:
if (edge.PolyTyp == ptSubject)
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctXor:
if (edge.WindDelta == 0) //XOr always contributing unless open
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
return true;
break;
default:
return true;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
OutPt* result;
TEdge *e, *prevE;
if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
{
result = AddOutPt(e1, Pt);
e2->OutIdx = e1->OutIdx;
e1->Side = esLeft;
e2->Side = esRight;
e = e1;
if (e->PrevInAEL == e2)
prevE = e2->PrevInAEL;
else
prevE = e->PrevInAEL;
} else
{
result = AddOutPt(e2, Pt);
e1->OutIdx = e2->OutIdx;
e1->Side = esRight;
e2->Side = esLeft;
e = e2;
if (e->PrevInAEL == e1)
prevE = e1->PrevInAEL;
else
prevE = e->PrevInAEL;
}
if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)
{
cInt xPrev = TopX(*prevE, Pt.Y);
cInt xE = TopX(*e, Pt.Y);
if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&
SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))
{
OutPt* outPt = AddOutPt(prevE, Pt);
AddJoin(result, outPt, e->Top);
}
}
return result;
}
//------------------------------------------------------------------------------
void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
AddOutPt( e1, Pt );
if (e2->WindDelta == 0) AddOutPt(e2, Pt);
if( e1->OutIdx == e2->OutIdx )
{
e1->OutIdx = Unassigned;
e2->OutIdx = Unassigned;
}
else if (e1->OutIdx < e2->OutIdx)
AppendPolygon(e1, e2);
else
AppendPolygon(e2, e1);
}
//------------------------------------------------------------------------------
void Clipper::AddEdgeToSEL(TEdge *edge)
{
//SEL pointers in PEdge are reused to build a list of horizontal edges.
//However, we don't need to worry about order with horizontal edge processing.
if( !m_SortedEdges )
{
m_SortedEdges = edge;
edge->PrevInSEL = 0;
edge->NextInSEL = 0;
}
else
{
edge->NextInSEL = m_SortedEdges;
edge->PrevInSEL = 0;
m_SortedEdges->PrevInSEL = edge;
m_SortedEdges = edge;
}
}
//------------------------------------------------------------------------------
bool Clipper::PopEdgeFromSEL(TEdge *&edge)
{
if (!m_SortedEdges) return false;
edge = m_SortedEdges;
DeleteFromSEL(m_SortedEdges);
return true;
}
//------------------------------------------------------------------------------
void Clipper::CopyAELToSEL()
{
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while ( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op1;
j->OutPt2 = op2;
j->OffPt = OffPt;
m_Joins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::ClearJoins()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
delete m_Joins[i];
m_Joins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::ClearGhostJoins()
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
delete m_GhostJoins[i];
m_GhostJoins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op;
j->OutPt2 = 0;
j->OffPt = OffPt;
m_GhostJoins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
{
const LocalMinimum *lm;
while (PopLocalMinima(botY, lm))
{
TEdge* lb = lm->LeftBound;
TEdge* rb = lm->RightBound;
OutPt *Op1 = 0;
if (!lb)
{
//nb: don't insert LB into either AEL or SEL
InsertEdgeIntoAEL(rb, 0);
SetWindingCount(*rb);
if (IsContributing(*rb))
Op1 = AddOutPt(rb, rb->Bot);
}
else if (!rb)
{
InsertEdgeIntoAEL(lb, 0);
SetWindingCount(*lb);
if (IsContributing(*lb))
Op1 = AddOutPt(lb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
else
{
InsertEdgeIntoAEL(lb, 0);
InsertEdgeIntoAEL(rb, lb);
SetWindingCount( *lb );
rb->WindCnt = lb->WindCnt;
rb->WindCnt2 = lb->WindCnt2;
if (IsContributing(*lb))
Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
if (rb)
{
if (IsHorizontal(*rb))
{
AddEdgeToSEL(rb);
if (rb->NextInLML)
InsertScanbeam(rb->NextInLML->Top.Y);
}
else InsertScanbeam( rb->Top.Y );
}
if (!lb || !rb) continue;
//if any output polygons share an edge, they'll need joining later ...
if (Op1 && IsHorizontal(*rb) &&
m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
{
Join* jr = m_GhostJoins[i];
//if the horizontal Rb and a 'ghost' horizontal overlap, then convert
//the 'ghost' join to a real join ready for later ...
if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
AddJoin(jr->OutPt1, Op1, jr->OffPt);
}
}
if (lb->OutIdx >= 0 && lb->PrevInAEL &&
lb->PrevInAEL->Curr.X == lb->Bot.X &&
lb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&
(lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
AddJoin(Op1, Op2, lb->Top);
}
if(lb->NextInAEL != rb)
{
if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&
(rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
AddJoin(Op1, Op2, rb->Top);
}
TEdge* e = lb->NextInAEL;
if (e)
{
while( e != rb )
{
//nb: For calculating winding counts etc, IntersectEdges() assumes
//that param1 will be to the Right of param2 ABOVE the intersection ...
IntersectEdges(rb , e , lb->Curr); //order important here
e = e->NextInAEL;
}
}
}
}
}
//------------------------------------------------------------------------------
void Clipper::DeleteFromSEL(TEdge *e)
{
TEdge* SelPrev = e->PrevInSEL;
TEdge* SelNext = e->NextInSEL;
if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
if( SelPrev ) SelPrev->NextInSEL = SelNext;
else m_SortedEdges = SelNext;
if( SelNext ) SelNext->PrevInSEL = SelPrev;
e->NextInSEL = 0;
e->PrevInSEL = 0;
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
{
if (pt.Z != 0 || !m_ZFill) return;
else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
else if (pt == e1.Top) pt.Z = e1.Top.Z;
else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
else if (pt == e2.Top) pt.Z = e2.Top.Z;
else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
}
//------------------------------------------------------------------------------
#endif
void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
{
bool e1Contributing = ( e1->OutIdx >= 0 );
bool e2Contributing = ( e2->OutIdx >= 0 );
#ifdef use_xyz
SetZ(Pt, *e1, *e2);
#endif
#ifdef use_lines
//if either edge is on an OPEN path ...
if (e1->WindDelta == 0 || e2->WindDelta == 0)
{
//ignore subject-subject open path intersections UNLESS they
//are both open paths, AND they are both 'contributing maximas' ...
if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
//if intersecting a subj line with a subj poly ...
else if (e1->PolyTyp == e2->PolyTyp &&
e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
{
if (e1->WindDelta == 0)
{
if (e2Contributing)
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
}
else
{
if (e1Contributing)
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
}
else if (e1->PolyTyp != e2->PolyTyp)
{
//toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
(m_ClipType != ctUnion || e2->WindCnt2 == 0))
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
(m_ClipType != ctUnion || e1->WindCnt2 == 0))
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
return;
}
#endif
//update winding counts...
//assumes that e1 will be to the Right of e2 ABOVE the intersection
if ( e1->PolyTyp == e2->PolyTyp )
{
if ( IsEvenOddFillType( *e1) )
{
int oldE1WindCnt = e1->WindCnt;
e1->WindCnt = e2->WindCnt;
e2->WindCnt = oldE1WindCnt;
} else
{
if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
else e1->WindCnt += e2->WindDelta;
if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
else e2->WindCnt -= e1->WindDelta;
}
} else
{
if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
}
PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
if (e1->PolyTyp == ptSubject)
{
e1FillType = m_SubjFillType;
e1FillType2 = m_ClipFillType;
} else
{
e1FillType = m_ClipFillType;
e1FillType2 = m_SubjFillType;
}
if (e2->PolyTyp == ptSubject)
{
e2FillType = m_SubjFillType;
e2FillType2 = m_ClipFillType;
} else
{
e2FillType = m_ClipFillType;
e2FillType2 = m_SubjFillType;
}
cInt e1Wc, e2Wc;
switch (e1FillType)
{
case pftPositive: e1Wc = e1->WindCnt; break;
case pftNegative: e1Wc = -e1->WindCnt; break;
default: e1Wc = Abs(e1->WindCnt);
}
switch(e2FillType)
{
case pftPositive: e2Wc = e2->WindCnt; break;
case pftNegative: e2Wc = -e2->WindCnt; break;
default: e2Wc = Abs(e2->WindCnt);
}
if ( e1Contributing && e2Contributing )
{
if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
(e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
{
AddLocalMaxPoly(e1, e2, Pt);
}
else
{
AddOutPt(e1, Pt);
AddOutPt(e2, Pt);
SwapSides( *e1 , *e2 );
SwapPolyIndexes( *e1 , *e2 );
}
}
else if ( e1Contributing )
{
if (e2Wc == 0 || e2Wc == 1)
{
AddOutPt(e1, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( e2Contributing )
{
if (e1Wc == 0 || e1Wc == 1)
{
AddOutPt(e2, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
{
//neither edge is currently contributing ...
cInt e1Wc2, e2Wc2;
switch (e1FillType2)
{
case pftPositive: e1Wc2 = e1->WindCnt2; break;
case pftNegative : e1Wc2 = -e1->WindCnt2; break;
default: e1Wc2 = Abs(e1->WindCnt2);
}
switch (e2FillType2)
{
case pftPositive: e2Wc2 = e2->WindCnt2; break;
case pftNegative: e2Wc2 = -e2->WindCnt2; break;
default: e2Wc2 = Abs(e2->WindCnt2);
}
if (e1->PolyTyp != e2->PolyTyp)
{
AddLocalMinPoly(e1, e2, Pt);
}
else if (e1Wc == 1 && e2Wc == 1)
switch( m_ClipType ) {
case ctIntersection:
if (e1Wc2 > 0 && e2Wc2 > 0)
AddLocalMinPoly(e1, e2, Pt);
break;
case ctUnion:
if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
AddLocalMinPoly(e1, e2, Pt);
break;
case ctDifference:
if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
AddLocalMinPoly(e1, e2, Pt);
break;
case ctXor:
AddLocalMinPoly(e1, e2, Pt);
}
else
SwapSides( *e1, *e2 );
}
}
//------------------------------------------------------------------------------
void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
{
TEdge *e2 = e->PrevInAEL;
TEdge *eTmp = 0;
while (e2)
{
if (e2->OutIdx >= 0 && e2->WindDelta != 0)
{
if (!eTmp) eTmp = e2;
else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;
}
e2 = e2->PrevInAEL;
}
if (!eTmp)
{
outrec->FirstLeft = 0;
outrec->IsHole = false;
}
else
{
outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];
outrec->IsHole = !outrec->FirstLeft->IsHole;
}
}
//------------------------------------------------------------------------------
OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
{
//work out which polygon fragment has the correct hole state ...
if (!outRec1->BottomPt)
outRec1->BottomPt = GetBottomPt(outRec1->Pts);
if (!outRec2->BottomPt)
outRec2->BottomPt = GetBottomPt(outRec2->Pts);
OutPt *OutPt1 = outRec1->BottomPt;
OutPt *OutPt2 = outRec2->BottomPt;
if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
else if (OutPt1->Next == OutPt1) return outRec2;
else if (OutPt2->Next == OutPt2) return outRec1;
else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
else return outRec2;
}
//------------------------------------------------------------------------------
bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)
{
do
{
outRec1 = outRec1->FirstLeft;
if (outRec1 == outRec2) return true;
} while (outRec1);
return false;
}
//------------------------------------------------------------------------------
OutRec* Clipper::GetOutRec(int Idx)
{
OutRec* outrec = m_PolyOuts[Idx];
while (outrec != m_PolyOuts[outrec->Idx])
outrec = m_PolyOuts[outrec->Idx];
return outrec;
}
//------------------------------------------------------------------------------
void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
{
//get the start and ends of both output polygons ...
OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
OutRec *holeStateRec;
if (OutRec1RightOfOutRec2(outRec1, outRec2))
holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1))
holeStateRec = outRec1;
else
holeStateRec = GetLowermostRec(outRec1, outRec2);
//get the start and ends of both output polygons and
//join e2 poly onto e1 poly and delete pointers to e2 ...
OutPt* p1_lft = outRec1->Pts;
OutPt* p1_rt = p1_lft->Prev;
OutPt* p2_lft = outRec2->Pts;
OutPt* p2_rt = p2_lft->Prev;
//join e2 poly onto e1 poly and delete pointers to e2 ...
if( e1->Side == esLeft )
{
if( e2->Side == esLeft )
{
//z y x a b c
ReversePolyPtLinks(p2_lft);
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
outRec1->Pts = p2_rt;
} else
{
//x y z a b c
p2_rt->Next = p1_lft;
p1_lft->Prev = p2_rt;
p2_lft->Prev = p1_rt;
p1_rt->Next = p2_lft;
outRec1->Pts = p2_lft;
}
} else
{
if( e2->Side == esRight )
{
//a b c z y x
ReversePolyPtLinks(p2_lft);
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
} else
{
//a b c x y z
p1_rt->Next = p2_lft;
p2_lft->Prev = p1_rt;
p1_lft->Prev = p2_rt;
p2_rt->Next = p1_lft;
}
}
outRec1->BottomPt = 0;
if (holeStateRec == outRec2)
{
if (outRec2->FirstLeft != outRec1)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec1->IsHole = outRec2->IsHole;
}
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->FirstLeft = outRec1;
int OKIdx = e1->OutIdx;
int ObsoleteIdx = e2->OutIdx;
e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
e2->OutIdx = Unassigned;
TEdge* e = m_ActiveEdges;
while( e )
{
if( e->OutIdx == ObsoleteIdx )
{
e->OutIdx = OKIdx;
e->Side = e1->Side;
break;
}
e = e->NextInAEL;
}
outRec2->Idx = outRec1->Idx;
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
{
if( e->OutIdx < 0 )
{
OutRec *outRec = CreateOutRec();
outRec->IsOpen = (e->WindDelta == 0);
OutPt* newOp = new OutPt;
outRec->Pts = newOp;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = newOp;
newOp->Prev = newOp;
if (!outRec->IsOpen)
SetHoleState(e, outRec);
e->OutIdx = outRec->Idx;
return newOp;
} else
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
//OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
OutPt* op = outRec->Pts;
bool ToFront = (e->Side == esLeft);
if (ToFront && (pt == op->Pt)) return op;
else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
OutPt* newOp = new OutPt;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = op;
newOp->Prev = op->Prev;
newOp->Prev->Next = newOp;
op->Prev = newOp;
if (ToFront) outRec->Pts = newOp;
return newOp;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::GetLastOutPt(TEdge *e)
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
if (e->Side == esLeft)
return outRec->Pts;
else
return outRec->Pts->Prev;
}
//------------------------------------------------------------------------------
void Clipper::ProcessHorizontals()
{
TEdge* horzEdge;
while (PopEdgeFromSEL(horzEdge))
ProcessHorizontal(horzEdge);
}
//------------------------------------------------------------------------------
inline bool IsMinima(TEdge *e)
{
return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
}
//------------------------------------------------------------------------------
inline bool IsMaxima(TEdge *e, const cInt Y)
{
return e && e->Top.Y == Y && !e->NextInLML;
}
//------------------------------------------------------------------------------
inline bool IsIntermediate(TEdge *e, const cInt Y)
{
return e->Top.Y == Y && e->NextInLML;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPair(TEdge *e)
{
if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
return e->Next;
else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
return e->Prev;
else return 0;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPairEx(TEdge *e)
{
//as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)
TEdge* result = GetMaximaPair(e);
if (result && (result->OutIdx == Skip ||
(result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;
return result;
}
//------------------------------------------------------------------------------
void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
{
if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
if( Edge1->NextInSEL == Edge2 )
{
TEdge* Next = Edge2->NextInSEL;
if( Next ) Next->PrevInSEL = Edge1;
TEdge* Prev = Edge1->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge2;
Edge2->PrevInSEL = Prev;
Edge2->NextInSEL = Edge1;
Edge1->PrevInSEL = Edge2;
Edge1->NextInSEL = Next;
}
else if( Edge2->NextInSEL == Edge1 )
{
TEdge* Next = Edge1->NextInSEL;
if( Next ) Next->PrevInSEL = Edge2;
TEdge* Prev = Edge2->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge1;
Edge1->PrevInSEL = Prev;
Edge1->NextInSEL = Edge2;
Edge2->PrevInSEL = Edge1;
Edge2->NextInSEL = Next;
}
else
{
TEdge* Next = Edge1->NextInSEL;
TEdge* Prev = Edge1->PrevInSEL;
Edge1->NextInSEL = Edge2->NextInSEL;
if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
Edge1->PrevInSEL = Edge2->PrevInSEL;
if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
Edge2->NextInSEL = Next;
if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
Edge2->PrevInSEL = Prev;
if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
}
if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
}
//------------------------------------------------------------------------------
TEdge* GetNextInAEL(TEdge *e, Direction dir)
{
return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
}
//------------------------------------------------------------------------------
void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
{
if (HorzEdge.Bot.X < HorzEdge.Top.X)
{
Left = HorzEdge.Bot.X;
Right = HorzEdge.Top.X;
Dir = dLeftToRight;
} else
{
Left = HorzEdge.Top.X;
Right = HorzEdge.Bot.X;
Dir = dRightToLeft;
}
}
//------------------------------------------------------------------------
/*******************************************************************************
* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
* Bottom of a scanbeam) are processed as if layered. The order in which HEs *
* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
* and with other non-horizontal edges [*]. Once these intersections are *
* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
*******************************************************************************/
void Clipper::ProcessHorizontal(TEdge *horzEdge)
{
Direction dir;
cInt horzLeft, horzRight;
bool IsOpen = (horzEdge->WindDelta == 0);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
eLastHorz = eLastHorz->NextInLML;
if (!eLastHorz->NextInLML)
eMaxPair = GetMaximaPair(eLastHorz);
MaximaList::const_iterator maxIt;
MaximaList::const_reverse_iterator maxRit;
if (m_Maxima.size() > 0)
{
//get the first maxima in range (X) ...
if (dir == dLeftToRight)
{
maxIt = m_Maxima.begin();
while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
maxIt = m_Maxima.end();
}
else
{
maxRit = m_Maxima.rbegin();
while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
maxRit = m_Maxima.rend();
}
}
OutPt* op1 = 0;
for (;;) //loop through consec. horizontal edges
{
bool IsLastHorz = (horzEdge == eLastHorz);
TEdge* e = GetNextInAEL(horzEdge, dir);
while(e)
{
//this code block inserts extra coords into horizontal edges (in output
//polygons) whereever maxima touch these horizontal edges. This helps
//'simplifying' polygons (ie if the Simplify property is set).
if (m_Maxima.size() > 0)
{
if (dir == dLeftToRight)
{
while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
maxIt++;
}
}
else
{
while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
maxRit++;
}
}
};
if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
(dir == dRightToLeft && e->Curr.X < horzLeft)) break;
//Also break if we've got to the end of an intermediate horizontal edge ...
//nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
e->Dx < horzEdge->NextInLML->Dx) break;
if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
{
#ifdef use_xyz
if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);
else SetZ(e->Curr, *e, *horzEdge);
#endif
op1 = AddOutPt(horzEdge, e->Curr);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Bot);
}
//OK, so far we're still in range of the horizontal Edge but make sure
//we're at the last of consec. horizontals when matching with eMaxPair
if(e == eMaxPair && IsLastHorz)
{
if (horzEdge->OutIdx >= 0)
AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
DeleteFromAEL(horzEdge);
DeleteFromAEL(eMaxPair);
return;
}
if(dir == dLeftToRight)
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges(horzEdge, e, Pt);
}
else
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges( e, horzEdge, Pt);
}
TEdge* eNext = GetNextInAEL(e, dir);
SwapPositionsInAEL( horzEdge, e );
e = eNext;
} //end while(e)
//Break out of loop if HorzEdge.NextInLML is not also horizontal ...
if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
} //end for (;;)
if (horzEdge->OutIdx >= 0 && !op1)
{
op1 = GetLastOutPt(horzEdge);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Top);
}
if (horzEdge->NextInLML)
{
if(horzEdge->OutIdx >= 0)
{
op1 = AddOutPt( horzEdge, horzEdge->Top);
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->WindDelta == 0) return;
//nb: HorzEdge is no longer horizontal here
TEdge* ePrev = horzEdge->PrevInAEL;
TEdge* eNext = horzEdge->NextInAEL;
if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
(ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
{
OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
{
OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
}
else
UpdateEdgeIntoAEL(horzEdge);
}
else
{
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
DeleteFromAEL(horzEdge);
}
}
//------------------------------------------------------------------------------
bool Clipper::ProcessIntersections(const cInt topY)
{
if( !m_ActiveEdges ) return true;
try {
BuildIntersectList(topY);
size_t IlSize = m_IntersectList.size();
if (IlSize == 0) return true;
if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
else return false;
}
catch(...)
{
m_SortedEdges = 0;
DisposeIntersectNodes();
throw clipperException("ProcessIntersections error");
}
m_SortedEdges = 0;
return true;
}
//------------------------------------------------------------------------------
void Clipper::DisposeIntersectNodes()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i )
delete m_IntersectList[i];
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
void Clipper::BuildIntersectList(const cInt topY)
{
if ( !m_ActiveEdges ) return;
//prepare for sorting ...
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e->Curr.X = TopX( *e, topY );
e = e->NextInAEL;
}
//bubblesort ...
bool isModified;
do
{
isModified = false;
e = m_SortedEdges;
while( e->NextInSEL )
{
TEdge *eNext = e->NextInSEL;
IntPoint Pt;
if(e->Curr.X > eNext->Curr.X)
{
IntersectPoint(*e, *eNext, Pt);
if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);
IntersectNode * newNode = new IntersectNode;
newNode->Edge1 = e;
newNode->Edge2 = eNext;
newNode->Pt = Pt;
m_IntersectList.push_back(newNode);
SwapPositionsInSEL(e, eNext);
isModified = true;
}
else
e = eNext;
}
if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
else break;
}
while ( isModified );
m_SortedEdges = 0; //important
}
//------------------------------------------------------------------------------
void Clipper::ProcessIntersectList()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i)
{
IntersectNode* iNode = m_IntersectList[i];
{
IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
}
delete iNode;
}
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
{
return node2->Pt.Y < node1->Pt.Y;
}
//------------------------------------------------------------------------------
inline bool EdgesAdjacent(const IntersectNode &inode)
{
return (inode.Edge1->NextInSEL == inode.Edge2) ||
(inode.Edge1->PrevInSEL == inode.Edge2);
}
//------------------------------------------------------------------------------
bool Clipper::FixupIntersectionOrder()
{
//pre-condition: intersections are sorted Bottom-most first.
//Now it's crucial that intersections are made only between adjacent edges,
//so to ensure this the order of intersections may need adjusting ...
CopyAELToSEL();
std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
size_t cnt = m_IntersectList.size();
for (size_t i = 0; i < cnt; ++i)
{
if (!EdgesAdjacent(*m_IntersectList[i]))
{
size_t j = i + 1;
while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
if (j == cnt) return false;
std::swap(m_IntersectList[i], m_IntersectList[j]);
}
SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
}
return true;
}
//------------------------------------------------------------------------------
void Clipper::DoMaxima(TEdge *e)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
if (!eMaxPair)
{
if (e->OutIdx >= 0)
AddOutPt(e, e->Top);
DeleteFromAEL(e);
return;
}
TEdge* eNext = e->NextInAEL;
while(eNext && eNext != eMaxPair)
{
IntersectEdges(e, eNext, e->Top);
SwapPositionsInAEL(e, eNext);
eNext = e->NextInAEL;
}
if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
{
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
{
if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
#ifdef use_lines
else if (e->WindDelta == 0)
{
if (e->OutIdx >= 0)
{
AddOutPt(e, e->Top);
e->OutIdx = Unassigned;
}
DeleteFromAEL(e);
if (eMaxPair->OutIdx >= 0)
{
AddOutPt(eMaxPair, e->Top);
eMaxPair->OutIdx = Unassigned;
}
DeleteFromAEL(eMaxPair);
}
#endif
else throw clipperException("DoMaxima error");
}
//------------------------------------------------------------------------------
void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
{
TEdge* e = m_ActiveEdges;
while( e )
{
//1. process maxima, treating them as if they're 'bent' horizontal edges,
// but exclude maxima with horizontal edges. nb: e can't be a horizontal.
bool IsMaximaEdge = IsMaxima(e, topY);
if(IsMaximaEdge)
{
TEdge* eMaxPair = GetMaximaPairEx(e);
IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
}
if(IsMaximaEdge)
{
if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
TEdge* ePrev = e->PrevInAEL;
DoMaxima(e);
if( !ePrev ) e = m_ActiveEdges;
else e = ePrev->NextInAEL;
}
else
{
//2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
{
UpdateEdgeIntoAEL(e);
if (e->OutIdx >= 0)
AddOutPt(e, e->Bot);
AddEdgeToSEL(e);
}
else
{
e->Curr.X = TopX( *e, topY );
e->Curr.Y = topY;
#ifdef use_xyz
e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);
#endif
}
//When StrictlySimple and 'e' is being touched by another edge, then
//make sure both edges have a vertex here ...
if (m_StrictSimple)
{
TEdge* ePrev = e->PrevInAEL;
if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
(ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
{
IntPoint pt = e->Curr;
#ifdef use_xyz
SetZ(pt, *ePrev, *e);
#endif
OutPt* op = AddOutPt(ePrev, pt);
OutPt* op2 = AddOutPt(e, pt);
AddJoin(op, op2, pt); //StrictlySimple (type-3) join
}
}
e = e->NextInAEL;
}
}
//3. Process horizontals at the Top of the scanbeam ...
m_Maxima.sort();
ProcessHorizontals();
m_Maxima.clear();
//4. Promote intermediate vertices ...
e = m_ActiveEdges;
while(e)
{
if(IsIntermediate(e, topY))
{
OutPt* op = 0;
if( e->OutIdx >= 0 )
op = AddOutPt(e, e->Top);
UpdateEdgeIntoAEL(e);
//if output polygons share an edge, they'll need joining later ...
TEdge* ePrev = e->PrevInAEL;
TEdge* eNext = e->NextInAEL;
if (ePrev && ePrev->Curr.X == e->Bot.X &&
ePrev->Curr.Y == e->Bot.Y && op &&
ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (ePrev->WindDelta != 0))
{
OutPt* op2 = AddOutPt(ePrev, e->Bot);
AddJoin(op, op2, e->Top);
}
else if (eNext && eNext->Curr.X == e->Bot.X &&
eNext->Curr.Y == e->Bot.Y && op &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&
(e->WindDelta != 0) && (eNext->WindDelta != 0))
{
OutPt* op2 = AddOutPt(eNext, e->Bot);
AddJoin(op, op2, e->Top);
}
}
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolyline(OutRec &outrec)
{
OutPt *pp = outrec.Pts;
OutPt *lastPP = pp->Prev;
while (pp != lastPP)
{
pp = pp->Next;
if (pp->Pt == pp->Prev->Pt)
{
if (pp == lastPP) lastPP = pp->Prev;
OutPt *tmpPP = pp->Prev;
tmpPP->Next = pp->Next;
pp->Next->Prev = tmpPP;
delete pp;
pp = tmpPP;
}
}
if (pp == pp->Prev)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolygon(OutRec &outrec)
{
//FixupOutPolygon() - removes duplicate points and simplifies consecutive
//parallel edges by removing the middle vertex.
OutPt *lastOK = 0;
outrec.BottomPt = 0;
OutPt *pp = outrec.Pts;
bool preserveCol = m_PreserveCollinear || m_StrictSimple;
for (;;)
{
if (pp->Prev == pp || pp->Prev == pp->Next)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
//test for duplicate points and collinear edges ...
if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
(SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
(!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
{
lastOK = 0;
OutPt *tmp = pp;
pp->Prev->Next = pp->Next;
pp->Next->Prev = pp->Prev;
pp = pp->Prev;
delete tmp;
}
else if (pp == lastOK) break;
else
{
if (!lastOK) lastOK = pp;
pp = pp->Next;
}
}
outrec.Pts = pp;
}
//------------------------------------------------------------------------------
int PointCount(OutPt *Pts)
{
if (!Pts) return 0;
int result = 0;
OutPt* p = Pts;
do
{
result++;
p = p->Next;
}
while (p != Pts);
return result;
}
//------------------------------------------------------------------------------
void Clipper::BuildResult(Paths &polys)
{
polys.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
if (!m_PolyOuts[i]->Pts) continue;
Path pg;
OutPt* p = m_PolyOuts[i]->Pts->Prev;
int cnt = PointCount(p);
if (cnt < 2) continue;
pg.reserve(cnt);
for (int i = 0; i < cnt; ++i)
{
pg.push_back(p->Pt);
p = p->Prev;
}
polys.push_back(pg);
}
}
//------------------------------------------------------------------------------
void Clipper::BuildResult2(PolyTree& polytree)
{
polytree.Clear();
polytree.AllNodes.reserve(m_PolyOuts.size());
//add each output polygon/contour to polytree ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
int cnt = PointCount(outRec->Pts);
if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
FixHoleLinkage(*outRec);
PolyNode* pn = new PolyNode();
//nb: polytree takes ownership of all the PolyNodes
polytree.AllNodes.push_back(pn);
outRec->PolyNd = pn;
pn->Parent = 0;
pn->Index = 0;
pn->Contour.reserve(cnt);
OutPt *op = outRec->Pts->Prev;
for (int j = 0; j < cnt; j++)
{
pn->Contour.push_back(op->Pt);
op = op->Prev;
}
}
//fixup PolyNode links etc ...
polytree.Childs.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->PolyNd) continue;
if (outRec->IsOpen)
{
outRec->PolyNd->m_IsOpen = true;
polytree.AddChild(*outRec->PolyNd);
}
else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
else
polytree.AddChild(*outRec->PolyNd);
}
}
//------------------------------------------------------------------------------
void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
{
//just swap the contents (because fIntersectNodes is a single-linked-list)
IntersectNode inode = int1; //gets a copy of Int1
int1.Edge1 = int2.Edge1;
int1.Edge2 = int2.Edge2;
int1.Pt = int2.Pt;
int2.Edge1 = inode.Edge1;
int2.Edge2 = inode.Edge2;
int2.Pt = inode.Pt;
}
//------------------------------------------------------------------------------
inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
{
if (e2.Curr.X == e1.Curr.X)
{
if (e2.Top.Y > e1.Top.Y)
return e2.Top.X < TopX(e1, e2.Top.Y);
else return e1.Top.X > TopX(e2, e1.Top.Y);
}
else return e2.Curr.X < e1.Curr.X;
}
//------------------------------------------------------------------------------
bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
cInt& Left, cInt& Right)
{
if (a1 < a2)
{
if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
}
else
{
if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
}
return Left < Right;
}
//------------------------------------------------------------------------------
inline void UpdateOutPtIdxs(OutRec& outrec)
{
OutPt* op = outrec.Pts;
do
{
op->Idx = outrec.Idx;
op = op->Prev;
}
while(op != outrec.Pts);
}
//------------------------------------------------------------------------------
void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
{
if(!m_ActiveEdges)
{
edge->PrevInAEL = 0;
edge->NextInAEL = 0;
m_ActiveEdges = edge;
}
else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
{
edge->PrevInAEL = 0;
edge->NextInAEL = m_ActiveEdges;
m_ActiveEdges->PrevInAEL = edge;
m_ActiveEdges = edge;
}
else
{
if(!startEdge) startEdge = m_ActiveEdges;
while(startEdge->NextInAEL &&
!E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
startEdge = startEdge->NextInAEL;
edge->NextInAEL = startEdge->NextInAEL;
if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
edge->PrevInAEL = startEdge;
startEdge->NextInAEL = edge;
}
}
//----------------------------------------------------------------------
OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
{
OutPt* result = new OutPt;
result->Pt = outPt->Pt;
result->Idx = outPt->Idx;
if (InsertAfter)
{
result->Next = outPt->Next;
result->Prev = outPt;
outPt->Next->Prev = result;
outPt->Next = result;
}
else
{
result->Prev = outPt->Prev;
result->Next = outPt;
outPt->Prev->Next = result;
outPt->Prev = result;
}
return result;
}
//------------------------------------------------------------------------------
bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
const IntPoint Pt, bool DiscardLeft)
{
Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
if (Dir1 == Dir2) return false;
//When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
//want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
//So, to facilitate this while inserting Op1b and Op2b ...
//when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
//otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
if (Dir1 == dLeftToRight)
{
while (op1->Next->Pt.X <= Pt.X &&
op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, !DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, !DiscardLeft);
}
}
else
{
while (op1->Next->Pt.X >= Pt.X &&
op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, DiscardLeft);
}
}
if (Dir2 == dLeftToRight)
{
while (op2->Next->Pt.X <= Pt.X &&
op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, !DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, !DiscardLeft);
};
} else
{
while (op2->Next->Pt.X >= Pt.X &&
op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, DiscardLeft);
};
};
if ((Dir1 == dLeftToRight) == DiscardLeft)
{
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
}
else
{
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
}
return true;
}
//------------------------------------------------------------------------------
bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
{
OutPt *op1 = j->OutPt1, *op1b;
OutPt *op2 = j->OutPt2, *op2b;
//There are 3 kinds of joins for output polygons ...
//1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
//along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
//2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
//location at the Bottom of the overlapping segment (& Join.OffPt is above).
//3. StrictSimple joins where edges touch but are not collinear and where
//Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
(j->OffPt == j->OutPt2->Pt))
{
//Strictly Simple join ...
if (outRec1 != outRec2) return false;
op1b = j->OutPt1->Next;
while (op1b != op1 && (op1b->Pt == j->OffPt))
op1b = op1b->Next;
bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
op2b = j->OutPt2->Next;
while (op2b != op2 && (op2b->Pt == j->OffPt))
op2b = op2b->Next;
bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
if (reverse1 == reverse2) return false;
if (reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
else if (isHorizontal)
{
//treat horizontal joins differently to non-horizontal joins since with
//them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
//may be anywhere along the horizontal edge.
op1b = op1;
while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
op1 = op1->Prev;
while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
op1b = op1b->Next;
if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
op2b = op2;
while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
op2 = op2->Prev;
while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
op2b = op2b->Next;
if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
cInt Left, Right;
//Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
return false;
//DiscardLeftSide: when overlapping edges are joined, a spike will created
//which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
//on the discard Side as either may still be needed for other joins ...
IntPoint Pt;
bool DiscardLeftSide;
if (op1->Pt.X >= Left && op1->Pt.X <= Right)
{
Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
}
else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
{
Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
}
else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
{
Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
}
else
{
Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
}
j->OutPt1 = op1; j->OutPt2 = op2;
return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
} else
{
//nb: For non-horizontal joins ...
// 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
// 2. Jr.OutPt1.Pt > Jr.OffPt.Y
//make sure the polygons are correctly oriented ...
op1b = op1->Next;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
if (Reverse1)
{
op1b = op1->Prev;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
if ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
};
op2b = op2->Next;
while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
if (Reverse2)
{
op2b = op2->Prev;
while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
if ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
}
if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
if (Reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
}
//----------------------------------------------------------------------
static OutRec* ParseFirstLeft(OutRec* FirstLeft)
{
while (FirstLeft && !FirstLeft->Pts)
FirstLeft = FirstLeft->FirstLeft;
return FirstLeft;
}
//------------------------------------------------------------------------------
void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
{
//tests if NewOutRec contains the polygon before reassigning FirstLeft
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
{
if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
outRec->FirstLeft = NewOutRec;
}
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)
{
//A polygon has split into two such that one is now the inner of the other.
//It's possible that these polygons now wrap around other polygons, so check
//every polygon that's also contained by OuterOutRec's FirstLeft container
//(including 0) to see if they've become inner to the new inner polygon ...
OutRec* orfl = OuterOutRec->FirstLeft;
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)
continue;
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)
continue;
if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))
outRec->FirstLeft = InnerOutRec;
else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))
outRec->FirstLeft = OuterOutRec;
else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)
outRec->FirstLeft = orfl;
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)
{
//reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (outRec->Pts && firstLeft == OldOutRec)
outRec->FirstLeft = NewOutRec;
}
}
//----------------------------------------------------------------------
void Clipper::JoinCommonEdges()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
{
Join* join = m_Joins[i];
OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
if (!outRec1->Pts || !outRec2->Pts) continue;
if (outRec1->IsOpen || outRec2->IsOpen) continue;
//get the polygon fragment with the correct hole state (FirstLeft)
//before calling JoinPoints() ...
OutRec *holeStateRec;
if (outRec1 == outRec2) holeStateRec = outRec1;
else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;
else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;
else holeStateRec = GetLowermostRec(outRec1, outRec2);
if (!JoinPoints(join, outRec1, outRec2)) continue;
if (outRec1 == outRec2)
{
//instead of joining two polygons, we've just created a new one by
//splitting one polygon into two.
outRec1->Pts = join->OutPt1;
outRec1->BottomPt = 0;
outRec2 = CreateOutRec();
outRec2->Pts = join->OutPt2;
//update all OutRec2.Pts Idx's ...
UpdateOutPtIdxs(*outRec2);
if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
{
//outRec1 contains outRec2 ...
outRec2->IsHole = !outRec1->IsHole;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
ReversePolyPtLinks(outRec2->Pts);
} else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
{
//outRec2 contains outRec1 ...
outRec2->IsHole = outRec1->IsHole;
outRec1->IsHole = !outRec2->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
outRec1->FirstLeft = outRec2;
if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
ReversePolyPtLinks(outRec1->Pts);
}
else
{
//the 2 polygons are completely separate ...
outRec2->IsHole = outRec1->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
//fixup FirstLeft pointers that may need reassigning to OutRec2
if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
}
} else
{
//joined 2 polygons together ...
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->Idx = outRec1->Idx;
outRec1->IsHole = holeStateRec->IsHole;
if (holeStateRec == outRec2)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec2->FirstLeft = outRec1;
if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);
}
}
}
//------------------------------------------------------------------------------
// ClipperOffset support functions ...
//------------------------------------------------------------------------------
DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
{
if(pt2.X == pt1.X && pt2.Y == pt1.Y)
return DoublePoint(0, 0);
double Dx = (double)(pt2.X - pt1.X);
double dy = (double)(pt2.Y - pt1.Y);
double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
Dx *= f;
dy *= f;
return DoublePoint(dy, -Dx);
}
//------------------------------------------------------------------------------
// ClipperOffset class
//------------------------------------------------------------------------------
ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
{
this->MiterLimit = miterLimit;
this->ArcTolerance = arcTolerance;
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
ClipperOffset::~ClipperOffset()
{
Clear();
}
//------------------------------------------------------------------------------
void ClipperOffset::Clear()
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
delete m_polyNodes.Childs[i];
m_polyNodes.Childs.clear();
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
{
int highI = (int)path.size() - 1;
if (highI < 0) return;
PolyNode* newNode = new PolyNode();
newNode->m_jointype = joinType;
newNode->m_endtype = endType;
//strip duplicate points from path and also get index to the lowest point ...
if (endType == etClosedLine || endType == etClosedPolygon)
while (highI > 0 && path[0] == path[highI]) highI--;
newNode->Contour.reserve(highI + 1);
newNode->Contour.push_back(path[0]);
int j = 0, k = 0;
for (int i = 1; i <= highI; i++)
if (newNode->Contour[j] != path[i])
{
j++;
newNode->Contour.push_back(path[i]);
if (path[i].Y > newNode->Contour[k].Y ||
(path[i].Y == newNode->Contour[k].Y &&
path[i].X < newNode->Contour[k].X)) k = j;
}
if (endType == etClosedPolygon && j < 2)
{
delete newNode;
return;
}
m_polyNodes.AddChild(*newNode);
//if this path's lowest pt is lower than all the others then update m_lowest
if (endType != etClosedPolygon) return;
if (m_lowest.X < 0)
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
else
{
IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
if (newNode->Contour[k].Y > ip.Y ||
(newNode->Contour[k].Y == ip.Y &&
newNode->Contour[k].X < ip.X))
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
}
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
{
for (Paths::size_type i = 0; i < paths.size(); ++i)
AddPath(paths[i], joinType, endType);
}
//------------------------------------------------------------------------------
void ClipperOffset::FixOrientations()
{
//fixup orientations of all closed paths if the orientation of the
//closed path with the lowermost vertex is wrong ...
if (m_lowest.X >= 0 &&
!Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon ||
(node.m_endtype == etClosedLine && Orientation(node.Contour)))
ReversePath(node.Contour);
}
} else
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
ReversePath(node.Contour);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(Paths& solution, double delta)
{
solution.clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
if (solution.size() > 0) solution.erase(solution.begin());
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(PolyTree& solution, double delta)
{
solution.Clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
//remove the outer PolyNode rectangle ...
if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
{
PolyNode* outerNode = solution.Childs[0];
solution.Childs.reserve(outerNode->ChildCount());
solution.Childs[0] = outerNode->Childs[0];
solution.Childs[0]->Parent = outerNode->Parent;
for (int i = 1; i < outerNode->ChildCount(); ++i)
solution.AddChild(*outerNode->Childs[i]);
}
else
solution.Clear();
}
}
//------------------------------------------------------------------------------
void ClipperOffset::DoOffset(double delta)
{
m_destPolys.clear();
m_delta = delta;
//if Zero offset, just copy any CLOSED polygons to m_p and return ...
if (NEAR_ZERO(delta))
{
m_destPolys.reserve(m_polyNodes.ChildCount());
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon)
m_destPolys.push_back(node.Contour);
}
return;
}
//see offset_triginometry3.svg in the documentation folder ...
if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
else m_miterLim = 0.5;
double y;
if (ArcTolerance <= 0.0) y = def_arc_tolerance;
else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
y = std::fabs(delta) * def_arc_tolerance;
else y = ArcTolerance;
//see offset_triginometry2.svg in the documentation folder ...
double steps = pi / std::acos(1 - y / std::fabs(delta));
if (steps > std::fabs(delta) * pi)
steps = std::fabs(delta) * pi; //ie excessive precision check
m_sin = std::sin(two_pi / steps);
m_cos = std::cos(two_pi / steps);
m_StepsPerRad = steps / two_pi;
if (delta < 0.0) m_sin = -m_sin;
m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
m_srcPoly = node.Contour;
int len = (int)m_srcPoly.size();
if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
continue;
m_destPoly.clear();
if (len == 1)
{
if (node.m_jointype == jtRound)
{
double X = 1.0, Y = 0.0;
for (cInt j = 1; j <= steps; j++)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
double X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
}
else
{
double X = -1.0, Y = -1.0;
for (int j = 0; j < 4; ++j)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
if (X < 0) X = 1;
else if (Y < 0) Y = 1;
else X = -1;
}
}
m_destPolys.push_back(m_destPoly);
continue;
}
//build m_normals ...
m_normals.clear();
m_normals.reserve(len);
for (int j = 0; j < len - 1; ++j)
m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
else
m_normals.push_back(DoublePoint(m_normals[len - 2]));
if (node.m_endtype == etClosedPolygon)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else if (node.m_endtype == etClosedLine)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
m_destPoly.clear();
//re-build m_normals ...
DoublePoint n = m_normals[len -1];
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-n.X, -n.Y);
k = 0;
for (int j = len - 1; j >= 0; j--)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else
{
int k = 0;
for (int j = 1; j < len - 1; ++j)
OffsetPoint(j, k, node.m_jointype);
IntPoint pt1;
if (node.m_endtype == etOpenButt)
{
int j = len - 1;
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
int j = len - 1;
k = len - 2;
m_sinA = 0;
m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
if (node.m_endtype == etOpenSquare)
DoSquare(j, k);
else
DoRound(j, k);
}
//re-build m_normals ...
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
k = len - 1;
for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
if (node.m_endtype == etOpenButt)
{
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
k = 1;
m_sinA = 0;
if (node.m_endtype == etOpenSquare)
DoSquare(0, 1);
else
DoRound(0, 1);
}
m_destPolys.push_back(m_destPoly);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
{
//cross product ...
m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
if (std::fabs(m_sinA * m_delta) < 1.0)
{
//dot product ...
double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
if (cosA > 0) // angle => 0 degrees
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
return;
}
//else angle => 180 degrees
}
else if (m_sinA > 1.0) m_sinA = 1.0;
else if (m_sinA < -1.0) m_sinA = -1.0;
if (m_sinA * m_delta < 0)
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
m_destPoly.push_back(m_srcPoly[j]);
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
else
switch (jointype)
{
case jtMiter:
{
double r = 1 + (m_normals[j].X * m_normals[k].X +
m_normals[j].Y * m_normals[k].Y);
if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
break;
}
case jtSquare: DoSquare(j, k); break;
case jtRound: DoRound(j, k); break;
}
k = j;
}
//------------------------------------------------------------------------------
void ClipperOffset::DoSquare(int j, int k)
{
double dx = std::tan(std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoMiter(int j, int k, double r)
{
double q = m_delta / r;
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoRound(int j, int k)
{
double a = std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
double X = m_normals[k].X, Y = m_normals[k].Y, X2;
for (int i = 0; i < steps; ++i)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + X * m_delta),
Round(m_srcPoly[j].Y + Y * m_delta)));
X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
//------------------------------------------------------------------------------
// Miscellaneous public functions
//------------------------------------------------------------------------------
void Clipper::DoSimplePolygons()
{
PolyOutList::size_type i = 0;
while (i < m_PolyOuts.size())
{
OutRec* outrec = m_PolyOuts[i++];
OutPt* op = outrec->Pts;
if (!op || outrec->IsOpen) continue;
do //for each Pt in Polygon until duplicate found do ...
{
OutPt* op2 = op->Next;
while (op2 != outrec->Pts)
{
if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
{
//split the polygon into two ...
OutPt* op3 = op->Prev;
OutPt* op4 = op2->Prev;
op->Prev = op4;
op4->Next = op;
op2->Prev = op3;
op3->Next = op2;
outrec->Pts = op;
OutRec* outrec2 = CreateOutRec();
outrec2->Pts = op2;
UpdateOutPtIdxs(*outrec2);
if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
{
//OutRec2 is contained by OutRec1 ...
outrec2->IsHole = !outrec->IsHole;
outrec2->FirstLeft = outrec;
if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
}
else
if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
{
//OutRec1 is contained by OutRec2 ...
outrec2->IsHole = outrec->IsHole;
outrec->IsHole = !outrec2->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
outrec->FirstLeft = outrec2;
if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
}
else
{
//the 2 polygons are separate ...
outrec2->IsHole = outrec->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
}
op2 = op; //ie get ready for the Next iteration
}
op2 = op2->Next;
}
op = op->Next;
}
while (op != outrec->Pts);
}
}
//------------------------------------------------------------------------------
void ReversePath(Path& p)
{
std::reverse(p.begin(), p.end());
}
//------------------------------------------------------------------------------
void ReversePaths(Paths& p)
{
for (Paths::size_type i = 0; i < p.size(); ++i)
ReversePath(p[i]);
}
//------------------------------------------------------------------------------
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPath(in_poly, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPaths(in_polys, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(Paths &polys, PolyFillType fillType)
{
SimplifyPolygons(polys, polys, fillType);
}
//------------------------------------------------------------------------------
inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
{
double Dx = ((double)pt1.X - pt2.X);
double dy = ((double)pt1.Y - pt2.Y);
return (Dx*Dx + dy*dy);
}
//------------------------------------------------------------------------------
double DistanceFromLineSqrd(
const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
{
//The equation of a line in general form (Ax + By + C = 0)
//given 2 points (x?y? & (x?y? is ...
//(y?- y?x + (x?- x?y + (y?- y?x?- (x?- x?y?= 0
//A = (y?- y?; B = (x?- x?; C = (y?- y?x?- (x?- x?y?
//perpendicular distance of point (x?y? = (Ax?+ By?+ C)/Sqrt(A?+ B?
//see http://en.wikipedia.org/wiki/Perpendicular_distance
double A = double(ln1.Y - ln2.Y);
double B = double(ln2.X - ln1.X);
double C = A * ln1.X + B * ln1.Y;
C = A * pt.X + B * pt.Y - C;
return (C * C) / (A * A + B * B);
}
//---------------------------------------------------------------------------
bool SlopesNearCollinear(const IntPoint& pt1,
const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
{
//this function is more accurate when the point that's geometrically
//between the other 2 points is the one that's tested for distance.
//ie makes it more likely to pick up 'spikes' ...
if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
{
if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
else
{
if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
}
//------------------------------------------------------------------------------
bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
{
double Dx = (double)pt1.X - pt2.X;
double dy = (double)pt1.Y - pt2.Y;
return ((Dx * Dx) + (dy * dy) <= distSqrd);
}
//------------------------------------------------------------------------------
OutPt* ExcludeOp(OutPt* op)
{
OutPt* result = op->Prev;
result->Next = op->Next;
op->Next->Prev = result;
result->Idx = 0;
return result;
}
//------------------------------------------------------------------------------
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
{
//distance = proximity in units/pixels below which vertices
//will be stripped. Default ~= sqrt(2).
size_t size = in_poly.size();
if (size == 0)
{
out_poly.clear();
return;
}
OutPt* outPts = new OutPt[size];
for (size_t i = 0; i < size; ++i)
{
outPts[i].Pt = in_poly[i];
outPts[i].Next = &outPts[(i + 1) % size];
outPts[i].Next->Prev = &outPts[i];
outPts[i].Idx = 0;
}
double distSqrd = distance * distance;
OutPt* op = &outPts[0];
while (op->Idx == 0 && op->Next != op->Prev)
{
if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
{
ExcludeOp(op->Next);
op = ExcludeOp(op);
size -= 2;
}
else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else
{
op->Idx = 1;
op = op->Next;
}
}
if (size < 3) size = 0;
out_poly.resize(size);
for (size_t i = 0; i < size; ++i)
{
out_poly[i] = op->Pt;
op = op->Next;
}
delete [] outPts;
}
//------------------------------------------------------------------------------
void CleanPolygon(Path& poly, double distance)
{
CleanPolygon(poly, poly, distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
{
out_polys.resize(in_polys.size());
for (Paths::size_type i = 0; i < in_polys.size(); ++i)
CleanPolygon(in_polys[i], out_polys[i], distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(Paths& polys, double distance)
{
CleanPolygons(polys, polys, distance);
}
//------------------------------------------------------------------------------
void Minkowski(const Path& poly, const Path& path,
Paths& solution, bool isSum, bool isClosed)
{
int delta = (isClosed ? 1 : 0);
size_t polyCnt = poly.size();
size_t pathCnt = path.size();
Paths pp;
pp.reserve(pathCnt);
if (isSum)
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
pp.push_back(p);
}
else
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
pp.push_back(p);
}
solution.clear();
solution.reserve((pathCnt + delta) * (polyCnt + 1));
for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
for (size_t j = 0; j < polyCnt; ++j)
{
Path quad;
quad.reserve(4);
quad.push_back(pp[i % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
if (!Orientation(quad)) ReversePath(quad);
solution.push_back(quad);
}
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
{
Minkowski(pattern, path, solution, true, pathIsClosed);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void TranslatePath(const Path& input, Path& output, const IntPoint delta)
{
//precondition: input != output
output.resize(input.size());
for (size_t i = 0; i < input.size(); ++i)
output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
{
Clipper c;
for (size_t i = 0; i < paths.size(); ++i)
{
Paths tmp;
Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
c.AddPaths(tmp, ptSubject, true);
if (pathIsClosed)
{
Path tmp2;
TranslatePath(paths[i], tmp2, pattern[0]);
c.AddPath(tmp2, ptClip, true);
}
}
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
{
Minkowski(poly1, poly2, solution, false, true);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
enum NodeType {ntAny, ntOpen, ntClosed};
void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
{
bool match = true;
if (nodetype == ntClosed) match = !polynode.IsOpen();
else if (nodetype == ntOpen) return;
if (!polynode.Contour.empty() && match)
paths.push_back(polynode.Contour);
for (int i = 0; i < polynode.ChildCount(); ++i)
AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
}
//------------------------------------------------------------------------------
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntAny, paths);
}
//------------------------------------------------------------------------------
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntClosed, paths);
}
//------------------------------------------------------------------------------
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
//Open paths are top level only, so ...
for (int i = 0; i < polytree.ChildCount(); ++i)
if (polytree.Childs[i]->IsOpen())
paths.push_back(polytree.Childs[i]->Contour);
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const IntPoint &p)
{
s << "(" << p.X << "," << p.Y << ")";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Path &p)
{
if (p.empty()) return s;
Path::size_type last = p.size() -1;
for (Path::size_type i = 0; i < last; i++)
s << "(" << p[i].X << "," << p[i].Y << "), ";
s << "(" << p[last].X << "," << p[last].Y << ")\n";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Paths &p)
{
for (Paths::size_type i = 0; i < p.size(); i++)
s << p[i];
s << "\n";
return s;
}
//------------------------------------------------------------------------------
} //ClipperLib namespace
| Java |
module AttrValidator
# Copied from here https://github.com/rails/rails/blob/master/activesupport/lib/active_support/concern.rb
#
# A typical module looks like this:
#
# module M
# def self.included(base)
# base.extend ClassMethods
# base.class_eval do
# scope :disabled, -> { where(disabled: true) }
# end
# end
#
# module ClassMethods
# ...
# end
# end
#
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
# written as:
#
# require 'active_support/concern'
#
# module M
# extend ActiveSupport::Concern
#
# included do
# scope :disabled, -> { where(disabled: true) }
# end
#
# module ClassMethods
# ...
# end
# end
#
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
# and a +Bar+ module which depends on the former, we would typically write the
# following:
#
# module Foo
# def self.included(base)
# base.class_eval do
# def self.method_injected_by_foo
# ...
# end
# end
# end
# end
#
# module Bar
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Foo # We need to include this dependency for Bar
# include Bar # Bar is the module that Host really needs
# end
#
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
#
# module Bar
# include Foo
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Bar
# end
#
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
# module dependencies are properly resolved:
#
# require 'active_support/concern'
#
# module Foo
# extend ActiveSupport::Concern
# included do
# def self.method_injected_by_foo
# ...
# end
# end
# end
#
# module Bar
# extend ActiveSupport::Concern
# include Foo
#
# included do
# self.method_injected_by_foo
# end
# end
#
# class Host
# include Bar # works, Bar takes care now of its dependencies
# end
module Concern
class MultipleIncludedBlocks < StandardError #:nodoc:
def initialize
super "Cannot define multiple 'included' blocks for a Concern"
end
end
def self.extended(base) #:nodoc:
base.instance_variable_set(:@_dependencies, [])
end
def append_features(base)
if base.instance_variable_defined?(:@_dependencies)
base.instance_variable_get(:@_dependencies) << self
return false
else
return false if base < self
@_dependencies.each { |dep| base.send(:include, dep) }
super
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
end
end
def included(base = nil, &block)
if base.nil?
raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)
@_included_block = block
else
super
end
end
end
end
| Java |
package ca.codybanman.AstroidEscape;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import ca.codybanman.AstroidEscape.AEGame;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new AEGame(), config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
} | Java |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TimeOut
{
public partial class partido : Form
{
Team local; // Equipo local
Team visitor; // Equipo visitante
List<Registro> minuteToMinute = new List<Registro>();
Counter count = new Counter();
// Constante que guarda la cantidad limite
// de faltas permitidas previo a la expulsión
const int maxFaltas = 6;
/*
* Hay dos largos procesos en un partido,
* suceden cuando hay Falta o cuando hay Balon Afuera.
*/
bool procesoFalta = false;
bool procesoBalonAfuera = false;
bool localTeamShoot = false;
// Cantidad de tiros libres a tirar tras la falta
int tirosLibresDisponibles = 0;
// This will be checked in the close event,
// avoiding unnintentional actions and lose of data.
bool closeWindow = false;
// Clase para guardar el registro completo del partido
Match partidoJugado;
// Archivo para guardar el registro del partido
string archivoPartidos = "";
public string ArchivoPartidos
{
get { return archivoPartidos; }
set { archivoPartidos = value; }
}
/// <summary>
/// El constructor de la clase.
/// </summary>
/// <param name="a">Equipo local</param>
/// <param name="b">Equipo visitante</param>
public partido(Team a, Team b)
{
InitializeComponent();
local = a;
visitor = b;
if (a != null && b != null) {
actualizarListbox();
this.label_tituloLocal.Text = local.Name;
this.label_tituloVisitante.Text = visitor.Name;
this.label_LTO_restante.Text = Team.TOmax.ToString();
this.label_VTO_restante.Text = Team.TOmax.ToString();
}
}
public void actualizarListbox()
{
cargarTitulares();
cargarVisitantes();
}
void cargarTitulares()
{
listBox_LocalRoster.Items.Clear();
comboBox_LocalSubs.Items.Clear();
foreach (Player p in this.local.Players) {
if (p.Starter)
listBox_LocalRoster.Items.Add(p);
else
comboBox_LocalSubs.Items.Add(p);
}
listBox_LocalRoster.DisplayMember = "CompleteName";
comboBox_LocalSubs.DisplayMember = "CompleteName";
}
void cargarVisitantes()
{
listBox_VisitorRoster.Items.Clear();
comboBox_VisitorSubs.Items.Clear();
foreach (Player p in this.visitor.Players) {
if (p.Starter)
listBox_VisitorRoster.Items.Add(p);
else
comboBox_VisitorSubs.Items.Add(p);
}
listBox_VisitorRoster.DisplayMember = "CompleteName";
comboBox_VisitorSubs.DisplayMember = "CompleteName";
}
/// <summary>
/// Agrega un partido en una lista generica.
/// </summary>
/// <param name="equipo">Partido que sera agregado a la lista.</param>
/// <param name="listaEquipos">Lista que tiene el resto de los partidos</param>
/// <returns>La misma lista con el partido agregado</returns>
List<Match> addMatchToList(Match partido, List<Match> listaPartidos)
{
if (listaPartidos == null)
listaPartidos = new List<Match>();
listaPartidos.Add(partido);
return listaPartidos;
}
/// <summary>
/// Guarda el partido y su información en el archivo
/// </summary>
void guardarPartidoEnArchivo()
{
// Load previous matchs from file
List<Match> listaDePartidos = Main.CargarPartidos();
// Add the new match to the list
listaDePartidos = addMatchToList(this.partidoJugado, listaDePartidos);
// Store the updated list to the file
StreamWriter flujo = new StreamWriter(this.archivoPartidos);
XmlSerializer serial = new XmlSerializer(typeof(List<Match>));
serial.Serialize(flujo, listaDePartidos);
flujo.Close();
}
/// <summary>
/// Guarda las estadísticas recogidas durante el partido.
/// </summary>
void guardarInformación()
{
// Crea la lista
this.partidoJugado = new Match();
// Add match's metadata
partidoJugado.Fecha = DateTime.Now;
partidoJugado.EquipoLocal = local.Name;
partidoJugado.EquipoVisitante = visitor.Name;
// Agrega los nombres de TODOS los jugadores
// y sus respectivas estadísticas
foreach(Player p in local.Players)
{
partidoJugado.JugadoresLocales.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasLocal.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasLocal.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasLocal.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasLocal.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasLocal.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasLocal.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasLocal.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasLocal.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasLocal.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasLocal.Faltas += p.FaltasCometidas;
}
foreach(Player p in visitor.Players)
{
partidoJugado.JugadoresVisitantes.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasVisitante.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasVisitante.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasVisitante.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasVisitante.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasVisitante.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasVisitante.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasVisitante.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasVisitante.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasVisitante.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasVisitante.Faltas += p.FaltasCometidas;
}
guardarPartidoEnArchivo();
}
/// <summary>
/// Activa el botón de Comienzo del partido
/// </summary>
void activarContinuacion()
{
timer1.Stop();
button1.Text = "Comenzar";
button1.Enabled = true;
this.button1.BackColor = Color.DeepSkyBlue;
}
/// <summary>
/// Congela/detiene el reloj del partido y desactiva el botón de Comienzo
/// </summary>
void congelarContinuacion()
{
timer1.Stop();
button1.Text = "Parado";
button1.Enabled = false;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Pone el reloj a correr y desactiva el botón
/// </summary>
void correrContinuacion()
{
timer1.Enabled = true;
button1.Text = "Pausar";
button1.Enabled = true;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Evento llamado cuando finaliza el encuentro.
/// </summary>
void finishMatch()
{
timer1.Stop();
button1.Text = "Finalizado";
button1.Enabled = false;
button1.BackColor = Color.Black;
// Almacena la información recolectada del encuentro
guardarInformación();
// Display a minute-to-minute chart
ShowEvents nuevo = new ShowEvents(this.minuteToMinute);
nuevo.ShowDialog();
// Desactiva la pregunta al salir
closeWindow = true;
this.Close();
}
/// <summary>
/// Cambia el contexto de la ventana deacuerdo al momento correspondiente
/// </summary>
void finalizarCuarto()
{
count.resetCounter();
activarContinuacion();
// Restablece los tiempos muertos
this.local.restartTO();
this.visitor.restartTO();
// Desactiva botones no disponibles
desactivarCambio();
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarRebotes();
if (this.lblCuarto.Text[0] == '1')
this.lblCuarto.Text = "2do Cuarto";
else if (this.lblCuarto.Text[0] == '2')
this.lblCuarto.Text = "3er Cuarto";
else if (this.lblCuarto.Text[0] == '3')
this.lblCuarto.Text = "4to Cuarto";
else
finishMatch();
}
private void timer1_Tick(object sender, EventArgs e)
{
count.decCounter();
this.label_timer.Text = count.getCounter;
if (count.getCounter == "00:00:00")
finalizarCuarto();
}
#region Activar y Desactivar botones y labels
#region Desactivar y Activar puntos
void desactivarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = false;
btn_dobleErrado_L.Enabled = false;
}
void desactivarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = false;
btn_dobleErrado_V.Enabled = false;
}
void desactivarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = false;
btn_tripleErrado_L.Enabled = false;
}
void desactivarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = false;
btn_tripleErrado_V.Enabled = false;
}
void desactivarPuntos()
{
desactivarDoblesLocal();
desactivarDoblesVisitante();
desactivarTriplesLocal();
desactivarTriplesVisitante();
}
void activarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = true;
btn_dobleErrado_L.Enabled = true;
}
void activarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = true;
btn_dobleErrado_V.Enabled = true;
}
void activarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = true;
btn_tripleErrado_L.Enabled = true;
}
void activarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = true;
btn_tripleErrado_V.Enabled = true;
}
void activarPuntos()
{
activarDoblesLocal();
activarDoblesVisitante();
activarTriplesLocal();
activarTriplesVisitante();
}
#endregion
void activarFalta()
{
button_faltaL.Enabled = true;
button_faltaV.Enabled = true;
}
void desactivarFalta()
{
button_faltaL.Enabled = false;
button_faltaV.Enabled = false;
}
void activarPerdida()
{
//button_perdidaL.Enabled = true;
//button_perdidaV.Enabled = true;
}
void desactivarPerdida()
{
//button_perdidaL.Enabled = false;
//button_perdidaV.Enabled = false;
}
void activarCambio()
{
this.button_changeL.Visible = true;
this.button_changeV.Visible = true;
}
void desactivarCambio()
{
this.button_changeL.Visible = false;
this.button_changeV.Visible = false;
}
void activarTOLocal()
{
if (local.TiemposMuertosRestantes > 0)
this.LocalTO.Enabled = true;
}
void activarTOVisitante()
{
if (visitor.TiemposMuertosRestantes > 0)
this.VisitorTO.Enabled = true;
}
void activarTO()
{
activarTOLocal();
activarTOVisitante();
}
void desactivarTOLocal()
{
this.LocalTO.Enabled = false;
}
void desactivarTOVisitante()
{
this.VisitorTO.Enabled = false;
}
void desactivarTO()
{
desactivarTOLocal();
desactivarTOVisitante();
}
void activarLibreLocal()
{
btn_libreEncestado_L.Enabled = true;
btn_libreErrado_L.Enabled = true;
}
void desactivarLibreLocal()
{
btn_libreEncestado_L.Enabled = false;
btn_libreErrado_L.Enabled = false;
}
void activarLibreVisitante()
{
btn_libreEncestado_V.Enabled = true;
btn_libreErrado_V.Enabled = true;
}
void desactivarLibreVisitante()
{
btn_libreEncestado_V.Enabled = false;
btn_libreErrado_V.Enabled = false;
}
/// <summary>
/// Activa el rebote defensivo del equipo defensor y
/// el rebote ofensivo del equipo atacante
/// </summary>
/// <param name="defensivoLocal">Si es falso, el visitante esta defendiendo el rebote</param>
void activarRebotes(bool defensivoLocal = true)
{
if (defensivoLocal)
{
this.btn_rebote_Defensivo_L.Visible = true;
this.btn_rebote_Ofensivo_V.Visible = true;
}
else
{
this.btn_rebote_Ofensivo_L.Visible = true;
this.btn_rebote_Defensivo_V.Visible = true;
}
}
/// <summary>
/// Desactiva TODOS los rebotes de TODOS los equipos
/// </summary>
void desactivarRebotes()
{
// Locales
this.btn_rebote_Defensivo_L.Visible = false;
this.btn_rebote_Ofensivo_L.Visible = false;
// y Visitantes
this.btn_rebote_Ofensivo_V.Visible = false;
this.btn_rebote_Defensivo_V.Visible = false;
}
#endregion
#region Registros
void registrarSimple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Tiro Libre Anotado" : "Tiro Libre Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarDoble(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Doble Anotado" : "Doble Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarTriple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Triple Anotado" : "Triple Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarRebote(string nombreJugador, bool ofensivo = false)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (ofensivo) ? "Rebote Ofensivo" : "Rebote Defensivo";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarFalta(string nombreJugador)
{
string cuarto = lblCuarto.Text[0].ToString();
Registro r = new Registro(cuarto, this.label_timer.Text, "Falta", nombreJugador);
minuteToMinute.Add(r);
}
/// <summary>
/// Registra una canasta simple, doble o triple Encestada. Cambia el anotador del partido
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el punto</param>
/// <param name="local">Si es falso, corresponde al equipo visitante</param>
void anotacion(int valor, Player jugador, bool local = true)
{
switch (valor)
{
case 1:
jugador.TirosLibresAnotados++;
registrarSimple(jugador.CompleteName);
break;
case 2:
jugador.PuntosDoblesAnotados++;
registrarDoble(jugador.CompleteName);
break;
case 3:
jugador.PuntosTriplesAnotados++;
registrarTriple(jugador.CompleteName);
break;
}
Label score = null;
if (local)
score = this.label_ptsLocal;
else
score = this.label_ptsVsitor;
int pts = Convert.ToInt32(score.Text) + valor;
score.Text = pts.ToString();
}
/// <summary>
/// Registra una canasta simple, doble o triple Fallida.
/// Of course it does not change the scorer
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el fallo</param>
void fallo(int valor, Player jugador)
{
switch (valor)
{
case 1:
jugador.TirosLibresFallados++;
registrarSimple(jugador.CompleteName, false);
break;
case 2:
jugador.PuntosDoblesFallados++;
registrarDoble(jugador.CompleteName, false);
break;
case 3:
jugador.PuntosTriplesFallados++;
registrarTriple(jugador.CompleteName, false);
break;
}
}
#endregion
// ******************** //
// * METODOS LLAMADOS * //
// * POR EL USUARIO * //
// ******************** //
/// <summary>
/// Sucede cuando el usuario presiona el boton de "Comienzo" del partido
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
desactivarCambio();
desactivarRebotes();
desactivarPuntos();
desactivarPerdida();
desactivarFalta();
desactivarLibreLocal();
desactivarLibreVisitante();
if (procesoFalta)
{
MessageBox.Show("Se continua con los tiros libres..");
congelarContinuacion();
activarCambio();
// Check which team received fault and enable its free shoots
if (localTeamShoot)
activarLibreLocal();
else
activarLibreVisitante();
localTeamShoot = false;
}
else
{
// Check if time is running...
if (timer1.Enabled)
{ //... User want to stop timing
desactivarPerdida();
desactivarPuntos();
desactivarFalta();
activarContinuacion();
activarCambio();
}
else
{ //... User want to continue timing
activarFalta();
activarPerdida();
activarTO();
activarPuntos();
correrContinuacion();
}
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el LOCAL
/// </summary>
private void LocalTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreLocal();
desactivarRebotes();
// Asigna los tiempos muertos
local.TiemposMuertosRestantes--;
this.label_LTO_restante.Text = local.TiemposMuertosRestantes.ToString();
if (local.TiemposMuertosRestantes == 0)
this.LocalTO.Enabled = false;
if (procesoFalta) {
localTeamShoot = true;
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el VISITANTE
/// </summary>
private void VisitorTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreVisitante();
desactivarRebotes();
// Asigna los tiempos muertos
visitor.TiemposMuertosRestantes--;
this.label_VTO_restante.Text = visitor.TiemposMuertosRestantes.ToString();
if (visitor.TiemposMuertosRestantes == 0)
this.VisitorTO.Enabled = false;
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del LOCAL
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
if (listBox_LocalRoster.SelectedItem != null && comboBox_LocalSubs.SelectedItem != null)
{
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_LocalSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarTitulares();
}
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del VISITANTE
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
if (listBox_VisitorRoster.SelectedItem != null && comboBox_VisitorSubs.SelectedItem != null)
{
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_VisitorSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarVisitantes();
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL comete una falta
/// </summary>
private void button_faltaL_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOLocal();
activarTOVisitante();
if (listBox_LocalRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_LocalRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesLocal();
desactivarTriplesLocal();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaL_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE comete una falta
/// </summary>
private void button_faltaV_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOVisitante();
activarTOLocal();
if (listBox_VisitorRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_VisitorRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesVisitante();
desactivarTriplesVisitante();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaV_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un DOBLE
/// </summary>
private void btn_DobleEns_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
tirosLibresDisponibles = 1;
//TODO
// Muestra el Estado
//toolStripStatusLabel1.Text = ""
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un DOBLE
/// </summary>
private void btn_dobleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz gráfica
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
// Tira 1 tiro libre
tirosLibresDisponibles = 1;
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_tripleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un DOBLE
/// </summary>
private void btn_DobleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un DOBLE
/// </summary>
private void btn_dobleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un TRIPLE
/// </summary>
private void btn_tripleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un TRIPLE
/// </summary>
private void btn_tripleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if(aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_Ofensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Ofensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOLocal();
// Desactiva los tiros libres
desactivarLibreLocal();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador LOCAL que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux, false);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOVisitante();
desactivarLibreVisitante();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador VISITANTE que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un tiro libre
/// </summary>
private void btn_libreErrado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreLocal();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer window = new SelectPlayer(local.Players);
window.ShowDialog();
this.listBox_LocalRoster.SelectedItem = window.JugadorSeleccionado;
btn_libreErrado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un tiro libre
/// </summary>
private void btn_libreErrado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreVisitante();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreErrado_V_Click(sender, e);
}
}
/// <summary>
/// Abre un dialogo pidiendo confirmación al usuario para salir del programa
/// </summary>
private void partido_FormClosing(object sender, FormClosingEventArgs e)
{
if (!closeWindow)
{
DialogResult userResponce = MessageBox.Show("Esta seguro que desea cerrar la ventana?\n"+
"Los datos no seran guardados.",
"Cerrar ventana",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (userResponce == System.Windows.Forms.DialogResult.No)
e.Cancel = true;
}
}
private void button_perdidaL_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
private void button_perdidaV_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
}
| Java |
#include "V3DResourceMemory.h"
#include "V3DDevice.h"
#include "V3DBuffer.h"
#include "V3DImage.h"
#include "V3DAdapter.h"
/******************************/
/* public - V3DResourceMemory */
/******************************/
V3DResourceMemory* V3DResourceMemory::Create()
{
return V3D_NEW_T(V3DResourceMemory);
}
V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint64_t size, const wchar_t* pDebugName)
{
V3D_ASSERT(pDevice != nullptr);
V3D_ASSERT(propertyFlags != 0);
V3D_ASSERT(size != 0);
m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));
V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName));
m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags);
// ----------------------------------------------------------------------------------------------------
// ðmÛ
// ----------------------------------------------------------------------------------------------------
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = nullptr;
allocInfo.allocationSize = size;
allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags);
VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.memory = m_Source.deviceMemory;
V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// LqðÝè
// ----------------------------------------------------------------------------------------------------
m_Desc.propertyFlags = propertyFlags;
m_Desc.size = size;
// ----------------------------------------------------------------------------------------------------
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint32_t resourceCount, IV3DResource** ppResources, const wchar_t* pDebugName)
{
V3D_ASSERT(pDevice != nullptr);
V3D_ASSERT(propertyFlags != 0);
V3D_ASSERT(resourceCount != 0);
V3D_ASSERT(ppResources != nullptr);
m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));
V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// \[XðACgÌå«¢É\[g
// ----------------------------------------------------------------------------------------------------
STLVector<IV3DResource*> resources;
resources.reserve(resourceCount);
for (uint32_t i = 0; i < resourceCount; i++)
{
#ifdef V3D_DEBUG
switch (ppResources[i]->GetResourceDesc().type)
{
case V3D_RESOURCE_TYPE_BUFFER:
if (static_cast<V3DBuffer*>(ppResources[i])->CheckBindMemory() == true)
{
V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<V3DBuffer*>(ppResources[i])->GetDebugName());
return V3D_ERROR_FAIL;
}
break;
case V3D_RESOURCE_TYPE_IMAGE:
if (static_cast<IV3DImageBase*>(ppResources[i])->CheckBindMemory() == true)
{
V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<IV3DImageBase*>(ppResources[i])->GetDebugName());
return V3D_ERROR_FAIL;
}
break;
}
#endif //V3D_DEBUG
resources.push_back(ppResources[i]);
}
std::sort(resources.begin(), resources.end(), [](const IV3DResource* lh, const IV3DResource* rh) { return lh->GetResourceDesc().memoryAlignment > rh->GetResourceDesc().memoryAlignment; });
// ----------------------------------------------------------------------------------------------------
// ACgðCɵÂÂAÌTCYðßé
// ----------------------------------------------------------------------------------------------------
uint64_t vkMinAlignment = m_pDevice->GetSource().deviceProps.limits.minMemoryMapAlignment;
VkDeviceSize vkAllocSize = 0;
STLVector<VkDeviceSize> vkOffsets;
vkOffsets.resize(resourceCount);
for (uint32_t i = 0; i < resourceCount; i++)
{
const V3DResourceDesc& resourceDesc = ppResources[i]->GetResourceDesc();
VkDeviceSize vkAlignment = V3D_MAX(vkMinAlignment, resourceDesc.memoryAlignment);
if (vkAllocSize % vkAlignment)
{
vkAllocSize = (vkAllocSize / vkAlignment) * vkAlignment + vkAlignment;
}
vkOffsets[i] = vkAllocSize;
vkAllocSize += resourceDesc.memorySize;
}
// ----------------------------------------------------------------------------------------------------
// ðì¬
// ----------------------------------------------------------------------------------------------------
m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = nullptr;
allocInfo.allocationSize = vkAllocSize;
allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags);
VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.memory = m_Source.deviceMemory;
V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName));
// ----------------------------------------------------------------------------------------------------
// LqðÝè
// ----------------------------------------------------------------------------------------------------
m_Desc.propertyFlags = propertyFlags;
m_Desc.size = vkAllocSize;
// ----------------------------------------------------------------------------------------------------
// \[XðoCh
// ----------------------------------------------------------------------------------------------------
V3D_RESULT result = V3D_ERROR_FAIL;
for (uint32_t i = 0; i < resourceCount; i++)
{
IV3DResource* pResource = ppResources[i];
switch (pResource->GetResourceDesc().type)
{
case V3D_RESOURCE_TYPE_BUFFER:
result = static_cast<V3DBuffer*>(pResource)->BindMemory(this, vkOffsets[i]);
if (result != V3D_OK)
{
return result;
}
break;
case V3D_RESOURCE_TYPE_IMAGE:
result = static_cast<V3DImage*>(pResource)->BindMemory(this, vkOffsets[i]);
if (result != V3D_OK)
{
return result;
}
break;
}
}
// ----------------------------------------------------------------------------------------------------
return V3D_OK;
}
const V3DResourceMemory::Source& V3DResourceMemory::GetSource() const
{
return m_Source;
}
V3D_RESULT V3DResourceMemory::Map(uint64_t offset, uint64_t size, void** ppMemory)
{
if (m_Desc.size < (offset + size))
{
return V3D_ERROR_FAIL;
}
if (m_pMemory != nullptr)
{
*ppMemory = m_pMemory + offset;
return V3D_OK;
}
if (m_Source.memoryMappedRange.size != 0)
{
return V3D_ERROR_FAIL;
}
VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, offset, size, 0, ppMemory);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.offset = offset;
m_Source.memoryMappedRange.size = size;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
}
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::Unmap()
{
if (m_pMemory != nullptr)
{
return V3D_OK;
}
if (m_Source.memoryMappedRange.size == 0)
{
return V3D_ERROR_FAIL;
}
V3D_RESULT result = V3D_OK;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
result = ToV3DResult(vkResult);
}
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = 0;
vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory);
return result;
}
#ifdef V3D_DEBUG
bool V3DResourceMemory::Debug_CheckMemory(uint64_t offset, uint64_t size)
{
return (m_Desc.size >= (offset + size));
}
#endif //V3D_DEBUG
/****************************************/
/* public override - IV3DResourceMemory */
/****************************************/
const V3DResourceMemoryDesc& V3DResourceMemory::GetDesc() const
{
return m_Desc;
}
V3D_RESULT V3DResourceMemory::BeginMap()
{
if (m_Source.memoryMappedRange.size != 0)
{
return V3D_ERROR_FAIL;
}
VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, 0, m_Desc.size, 0, reinterpret_cast<void**>(&m_pMemory));
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = m_Desc.size;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
return ToV3DResult(vkResult);
}
}
return V3D_OK;
}
V3D_RESULT V3DResourceMemory::EndMap()
{
if (m_Source.memoryMappedRange.size == 0)
{
return V3D_ERROR_FAIL;
}
V3D_RESULT result = V3D_OK;
if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0)
{
VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange);
if (vkResult != VK_SUCCESS)
{
result = ToV3DResult(vkResult);
}
}
m_Source.memoryMappedRange.offset = 0;
m_Source.memoryMappedRange.size = 0;
vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory);
m_pMemory = nullptr;
return result;
}
/*************************************/
/* public override - IV3DDeviceChild */
/*************************************/
void V3DResourceMemory::GetDevice(IV3DDevice** ppDevice)
{
(*ppDevice) = V3D_TO_ADD_REF(m_pDevice);
}
/********************************/
/* public override - IV3DObject */
/********************************/
int64_t V3DResourceMemory::GetRefCount() const
{
return m_RefCounter;
}
void V3DResourceMemory::AddRef()
{
V3D_REF_INC(m_RefCounter);
}
void V3DResourceMemory::Release()
{
if (V3D_REF_DEC(m_RefCounter))
{
V3D_REF_FENCE();
V3D_DELETE_THIS_T(this, V3DResourceMemory);
}
}
/*******************************/
/* private - V3DResourceMemory */
/*******************************/
V3DResourceMemory::V3DResourceMemory() :
m_RefCounter(1),
m_pDevice(nullptr),
m_Desc({}),
m_Source({}),
m_pMemory(nullptr)
{
m_Source.deviceMemory = VK_NULL_HANDLE;
m_Source.memoryMappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
m_Source.memoryMappedRange.pNext = nullptr;
}
V3DResourceMemory::~V3DResourceMemory()
{
if (m_pDevice != nullptr)
{
m_pDevice->NotifyReleaseResourceMemory();
}
if (m_Source.deviceMemory != VK_NULL_HANDLE)
{
vkFreeMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, nullptr);
V3D_REMOVE_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory);
}
V3D_REMOVE_DEBUG_MEMORY_OBJECT(this);
V3D_RELEASE(m_pDevice);
}
| Java |
<?php
namespace Peridot\Leo\Interfaces;
use Peridot\Leo\Assertion;
use Peridot\Leo\Interfaces\Assert\CollectionAssertTrait;
use Peridot\Leo\Interfaces\Assert\ObjectAssertTrait;
use Peridot\Leo\Interfaces\Assert\TypeAssertTrait;
use Peridot\Leo\Leo;
/**
* Assert is a non-chainable, object oriented interface
* on top of a Leo Assertion.
*
* @method instanceOf() instanceOf(object $actual, string $expected, string $message = "") Perform an instanceof assertion.
* @method include() include(array $haystack, string $expected, string $message = "") Perform an inclusion assertion.
*
* @package Peridot\Leo\Interfaces
*/
class Assert
{
use TypeAssertTrait;
use ObjectAssertTrait;
use CollectionAssertTrait;
/**
* An array of operators mapping to assertions.
*
* @var array
*/
public static $operators = [
'==' => 'loosely->equal',
'===' => 'equal',
'>' => 'above',
'>=' => 'least',
'<' => 'below',
'<=' => 'most',
'!=' => 'not->loosely->equal',
'!==' => 'not->equal',
];
/**
* @var Assertion
*/
protected $assertion;
/**
* @param Assertion $assertion
*/
public function __construct(Assertion $assertion = null)
{
if ($assertion === null) {
$assertion = Leo::assertion();
}
$this->assertion = $assertion;
}
/**
* Perform an a loose equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function equal($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->loosely->equal($expected, $message);
}
/**
* Perform a negated loose equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function notEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->not->equal($expected, $message);
}
/**
* Performs a throw assertion.
*
* @param callable $fn
* @param $exceptionType
* @param string $exceptionMessage
* @param string $message
*/
public function throws(callable $fn, $exceptionType, $exceptionMessage = '', $message = '')
{
$this->assertion->setActual($fn);
return $this->assertion->to->throw($exceptionType, $exceptionMessage, $message);
}
/**
* Performs a negated throw assertion.
*
* @param callable $fn
* @param $exceptionType
* @param string $exceptionMessage
* @param string $message
*/
public function doesNotThrow(callable $fn, $exceptionType, $exceptionMessage = '', $message = '')
{
$this->assertion->setActual($fn);
return $this->assertion->not->to->throw($exceptionType, $exceptionMessage, $message);
}
/**
* Perform an ok assertion.
*
* @param mixed $object
* @param string $message
*/
public function ok($object, $message = '')
{
$this->assertion->setActual($object);
return $this->assertion->to->be->ok($message);
}
/**
* Perform a negated assertion.
*
* @param mixed $object
* @param string $message
*/
public function notOk($object, $message = '')
{
$this->assertion->setActual($object);
return $this->assertion->to->not->be->ok($message);
}
/**
* Perform a strict equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function strictEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->equal($expected, $message);
}
/**
* Perform a negated strict equality assertion.
*
* @param mixed $actual
* @param mixed $expected
* @param string $message
*/
public function notStrictEqual($actual, $expected, $message = '')
{
$this->assertion->setActual($actual);
return $this->assertion->to->not->equal($expected, $message);
}
/**
* Perform a pattern assertion.
*
* @param string $value
* @param string $pattern
* @param string $message
*/
public function match($value, $pattern, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->match($pattern, $message);
}
/**
* Perform a negated pattern assertion.
*
* @param string $value
* @param string $pattern
* @param string $message
*/
public function notMatch($value, $pattern, $message = '')
{
$this->assertion->setActual($value);
return $this->assertion->to->not->match($pattern, $message);
}
/**
* Compare two values using the given operator.
*
* @param mixed $left
* @param string $operator
* @param mixed $right
* @param string $message
*/
public function operator($left, $operator, $right, $message = '')
{
if (!isset(static::$operators[$operator])) {
throw new \InvalidArgumentException("Invalid operator $operator");
}
$this->assertion->setActual($left);
return $this->assertion->{static::$operators[$operator]}($right, $message);
}
/**
* Defined to allow use of reserved words for methods.
*
* @param $method
* @param $args
*/
public function __call($method, $args)
{
switch ($method) {
case 'instanceOf':
return call_user_func_array([$this, 'isInstanceOf'], $args);
case 'include':
return call_user_func_array([$this, 'isIncluded'], $args);
default:
throw new \BadMethodCallException("Call to undefined method $method");
}
}
}
| Java |
<?php declare(strict_types=1);
namespace Gitilicious\GitClient\Test\Unit\Cli\Output;
use Gitilicious\GitClient\Cli\Output\Output;
class OutputTest extends \PHPUnit_Framework_TestCase
{
public function testGetNumberOfLines()
{
$output = new Output('foo' . PHP_EOL . 'bar');
$this->assertSame(2, $output->getNumberOfLines());
}
public function testGetLineWhenItExists()
{
$output = new Output('foo' . PHP_EOL . 'bar');
$this->assertSame('foo', $output->getLine(1));
$this->assertSame('bar', $output->getLine(2));
}
public function testGetLineWhenItDoesNotExist()
{
$output = new Output('foo' . PHP_EOL . 'bar');
$this->assertSame('', $output->getLine(3));
}
}
| Java |
black = '#202427';
red = '#EB6A58'; // red
green = '#49A61D'; // green
yellow = '#959721'; // yellow
blue = '#798FB7'; // blue
magenta = '#CD7B7E'; // pink
cyan = '#4FA090'; // cyan
white = '#909294'; // light gray
lightBlack = '#292B35'; // medium gray
lightRed = '#DB7824'; // red
lightGreen = '#09A854'; // green
lightYellow = '#AD8E4B'; // yellow
lightBlue = '#309DC1'; // blue
lightMagenta= '#C874C2'; // pink
lightCyan = '#1BA2A0'; // cyan
lightWhite = '#8DA3B8'; // white
t.prefs_.set('color-palette-overrides',
[ black , red , green , yellow,
blue , magenta , cyan , white,
lightBlack , lightRed , lightGreen , lightYellow,
lightBlue , lightMagenta , lightCyan , lightWhite ]);
t.prefs_.set('cursor-color', lightWhite);
t.prefs_.set('foreground-color', lightWhite);
t.prefs_.set('background-color', black);
| Java |
import cuid from "cuid";
import Result, { isError } from "../../common/Result";
import assert from "assert";
import { di, singleton, diKey } from "../../common/di";
import { ILocalFiles, ILocalFilesKey } from "../../common/LocalFiles";
import { IStoreDB, IStoreDBKey, MergeEntity } from "../../common/db/StoreDB";
import {
ApplicationDto,
applicationKey,
CanvasDto,
DiagramDto,
DiagramInfoDto,
DiagramInfoDtos,
FileDto,
} from "./StoreDtos";
import { LocalEntity } from "../../common/db/LocalDB";
import { RemoteEntity } from "../../common/db/RemoteDB";
export interface Configuration {
onRemoteChanged: (keys: string[]) => void;
onSyncChanged: (isOK: boolean, error?: Error) => void;
isSyncEnabled: boolean;
}
export const IStoreKey = diKey<IStore>();
export interface IStore {
configure(config: Partial<Configuration>): void;
triggerSync(): Promise<Result<void>>;
openNewDiagram(): DiagramDto;
tryOpenMostResentDiagram(): Promise<Result<DiagramDto>>;
tryOpenDiagram(diagramId: string): Promise<Result<DiagramDto>>;
setDiagramName(name: string): void;
exportDiagram(): DiagramDto; // Used for print or export
getRootCanvas(): CanvasDto;
getCanvas(canvasId: string): CanvasDto;
writeCanvas(canvas: CanvasDto): void;
getMostResentDiagramId(): Result<string>;
getRecentDiagrams(): DiagramInfoDto[];
deleteDiagram(diagramId: string): void;
saveDiagramToFile(): void;
loadDiagramFromFile(): Promise<Result<string>>;
saveAllDiagramsToFile(): Promise<void>;
}
const rootCanvasId = "root";
const defaultApplicationDto: ApplicationDto = { diagramInfos: {} };
const defaultDiagramDto: DiagramDto = { id: "", name: "", canvases: {} };
@singleton(IStoreKey)
export class Store implements IStore {
private currentDiagramId: string = "";
private config: Configuration = {
onRemoteChanged: () => {},
onSyncChanged: () => {},
isSyncEnabled: false,
};
constructor(
// private localData: ILocalData = di(ILocalDataKey),
private localFiles: ILocalFiles = di(ILocalFilesKey),
private db: IStoreDB = di(IStoreDBKey)
) {}
public configure(config: Partial<Configuration>): void {
this.config = { ...this.config, ...config };
this.db.configure({
onConflict: (local: LocalEntity, remote: RemoteEntity) =>
this.onEntityConflict(local, remote),
...config,
onRemoteChanged: (keys: string[]) => this.onRemoteChange(keys),
});
}
public triggerSync(): Promise<Result<void>> {
return this.db.triggerSync();
}
public openNewDiagram(): DiagramDto {
const now = Date.now();
const id = cuid();
const name = this.getUniqueName();
console.log("new diagram", id, name);
const diagramDto: DiagramDto = {
id: id,
name: name,
canvases: {},
};
const applicationDto = this.getApplicationDto();
applicationDto.diagramInfos[id] = {
id: id,
name: name,
accessed: now,
};
this.db.monitorRemoteEntities([id, applicationKey]);
this.db.writeBatch([
{ key: applicationKey, value: applicationDto },
{ key: id, value: diagramDto },
]);
this.currentDiagramId = id;
return diagramDto;
}
public async tryOpenMostResentDiagram(): Promise<Result<DiagramDto>> {
const id = this.getMostResentDiagramId();
if (isError(id)) {
return id as Error;
}
const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id);
if (isError(diagramDto)) {
return diagramDto;
}
this.db.monitorRemoteEntities([id, applicationKey]);
this.currentDiagramId = id;
return diagramDto;
}
public async tryOpenDiagram(id: string): Promise<Result<DiagramDto>> {
const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id);
if (isError(diagramDto)) {
return diagramDto;
}
this.db.monitorRemoteEntities([id, applicationKey]);
this.currentDiagramId = id;
// Too support most recently used diagram feature, we update accessed time
const applicationDto = this.getApplicationDto();
const diagramInfo = applicationDto.diagramInfos[id];
applicationDto.diagramInfos[id] = { ...diagramInfo, accessed: Date.now() };
this.db.writeBatch([{ key: applicationKey, value: applicationDto }]);
return diagramDto;
}
public getRootCanvas(): CanvasDto {
return this.getCanvas(rootCanvasId);
}
public getCanvas(canvasId: string): CanvasDto {
const diagramDto = this.getDiagramDto();
const canvasDto = diagramDto.canvases[canvasId];
assert(canvasDto);
return canvasDto;
}
public writeCanvas(canvasDto: CanvasDto): void {
const diagramDto = this.getDiagramDto();
const id = diagramDto.id;
diagramDto.canvases[canvasDto.id] = canvasDto;
this.db.writeBatch([{ key: id, value: diagramDto }]);
}
public getRecentDiagrams(): DiagramInfoDto[] {
return Object.values(this.getApplicationDto().diagramInfos).sort((i1, i2) =>
i1.accessed < i2.accessed ? 1 : i1.accessed > i2.accessed ? -1 : 0
);
}
// For printing/export
public exportDiagram(): DiagramDto {
return this.getDiagramDto();
}
public deleteDiagram(id: string): void {
console.log("Delete diagram", id);
const applicationDto = this.getApplicationDto();
delete applicationDto.diagramInfos[id];
this.db.writeBatch([{ key: applicationKey, value: applicationDto }]);
this.db.removeBatch([id]);
}
public setDiagramName(name: string): void {
const diagramDto = this.getDiagramDto();
const id = diagramDto.id;
diagramDto.name = name;
const applicationDto = this.getApplicationDto();
applicationDto.diagramInfos[id] = {
...applicationDto.diagramInfos[id],
name: name,
accessed: Date.now(),
};
this.db.writeBatch([
{ key: applicationKey, value: applicationDto },
{ key: id, value: diagramDto },
]);
}
public async loadDiagramFromFile(): Promise<Result<string>> {
const fileText = await this.localFiles.loadFile();
const fileDto: FileDto = JSON.parse(fileText);
// if (!(await this.sync.uploadDiagrams(fileDto.diagrams))) {
// // save locally
// fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d));
// }
//fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d));
const firstDiagramId = fileDto.diagrams[0]?.id;
if (!firstDiagramId) {
return new Error("No valid diagram in file");
}
return firstDiagramId;
}
public saveDiagramToFile(): void {
const diagramDto = this.getDiagramDto();
const fileDto: FileDto = { diagrams: [diagramDto] };
const fileText = JSON.stringify(fileDto, null, 2);
this.localFiles.saveFile(`${diagramDto.name}.json`, fileText);
}
public async saveAllDiagramsToFile(): Promise<void> {
// let diagrams = await this.sync.downloadAllDiagrams();
// if (!diagrams) {
// // Read from local
// diagrams = this.local.readAllDiagrams();
// }
// let diagrams = this.local.readAllDiagrams();
// const fileDto = { diagrams: diagrams };
// const fileText = JSON.stringify(fileDto, null, 2);
// this.localFiles.saveFile(`diagrams.json`, fileText);
}
public getMostResentDiagramId(): Result<string> {
const resentDiagrams = this.getRecentDiagrams();
if (resentDiagrams.length === 0) {
return new RangeError("not found");
}
return resentDiagrams[0].id;
}
public getApplicationDto(): ApplicationDto {
return this.db.readLocal<ApplicationDto>(
applicationKey,
defaultApplicationDto
);
}
private onRemoteChange(keys: string[]) {
this.config.onRemoteChanged(keys);
}
private onEntityConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
if ("diagramInfos" in local.value) {
return this.onApplicationConflict(local, remote);
}
return this.onDiagramConflict(local, remote);
}
private onApplicationConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
console.warn("Application conflict", local, remote);
const mergeDiagramInfos = (
newerDiagrams: DiagramInfoDtos,
olderDiagrams: DiagramInfoDtos
): DiagramInfoDtos => {
let mergedDiagrams = { ...olderDiagrams, ...newerDiagrams };
Object.keys(newerDiagrams).forEach((key) => {
if (!(key in newerDiagrams)) {
delete mergedDiagrams[key];
}
});
return mergedDiagrams;
};
if (local.version >= remote.version) {
// Local entity has more edits, merge diagram infos, but priorities remote
const applicationDto: ApplicationDto = {
diagramInfos: mergeDiagramInfos(
local.value.diagramInfos,
remote.value.diagramInfos
),
};
return {
key: local.key,
value: applicationDto,
version: local.version,
};
}
// Remote entity since that has more edits, merge diagram infos, but priorities local
const applicationDto: ApplicationDto = {
diagramInfos: mergeDiagramInfos(
remote.value.diagramInfos,
local.value.diagramInfos
),
};
return {
key: remote.key,
value: applicationDto,
version: remote.version,
};
}
private onDiagramConflict(
local: LocalEntity,
remote: RemoteEntity
): MergeEntity {
console.warn("Diagram conflict", local, remote);
if (local.version >= remote.version) {
// use local since it has more edits
return {
key: local.key,
value: local.value,
version: local.version,
};
}
// Use remote entity since that has more edits
return {
key: remote.key,
value: remote.value,
version: remote.version,
};
}
private getDiagramDto(): DiagramDto {
return this.db.readLocal<DiagramDto>(
this.currentDiagramId,
defaultDiagramDto
);
}
private getUniqueName(): string {
const diagrams = Object.values(this.getApplicationDto().diagramInfos);
for (let i = 0; i < 99; i++) {
const name = "Name" + (i > 0 ? ` (${i})` : "");
if (!diagrams.find((d) => d.name === name)) {
return name;
}
}
return "Name";
}
}
| Java |
<html>
<head>
<title>Julian Fellows's panel show appearances</title>
<script type="text/javascript" src="../common.js"></script>
<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>
<script type="text/javascript" src="../people.js"></script>
<!--#include virtual="head.txt" -->
</head>
<body>
<!--#include virtual="nav.txt" -->
<div class="page">
<h1>Julian Fellows's panel show appearances</h1>
<p>Julian Fellows has appeared in <span class="total">1</span> episodes between 2003-2003. Note that these appearances may be for more than one person if multiple people have the same name.</p>
<div class="performerholder">
<table class="performer">
<tr style="vertical-align:bottom;">
<td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2003</span></td>
</tr>
</table>
</div>
<ol class="episodes">
<li><strong>2003-05-22</strong> / <a href="../shows/call-my-bluff.html">Call My Bluff</a></li>
</ol>
</div>
</body>
</html>
| Java |
var createSubmit = function(name, primus, keyDict) {
return function(event) {
var message = $('#message').val();
if (message.length === 0) {
event.preventDefault();
return;
}
$('#message').val('');
$('#message').focus();
var BigInteger = forge.jsbn.BigInteger;
var data = JSON.parse(sessionStorage[name]);
var pem = data.pem;
var privateKey = forge.pki.privateKeyFromPem(pem);
var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e));
var keys = [];
var iv = forge.random.getBytesSync(16);
var key = forge.random.getBytesSync(16);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();
var encryptedMessage = cipher.output.getBytes();
var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': name,
'key': encryptedKey
});
var md = forge.md.sha1.create();
md.update(message, 'utf8');
var signature = privateKey.sign(md);
var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;});
var deferredRequests = [];
for (var i = 0; i < recipients.length; i++) {
(function (index) {
var retrieveKey = function(pk) {
if (pk === false) {
return;
}
if (keyDict[recipients[i]] === undefined) {
keyDict[recipients[i]] = pk;
}
var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e));
var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': recipients[index],
'key': encryptedKey
});
}
if (keyDict[recipients[i]] === undefined) {
deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey));
} else {
retrieveKey(keyDict[recipients[i]]);
}
})(i);
}
$.when.apply(null, deferredRequests).done(function() {
primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv,
'signature': signature, 'recipients': recipients});
});
event.preventDefault();
};
};
| Java |
<?php
namespace action\sub;
use net\shawn_huang\pretty\Action;
class Index extends Action {
protected function run() {
$this->put([
'holy' => 'shit'
]);
}
} | Java |
<?php
namespace keeko\account\action;
use keeko\framework\foundation\AbstractAction;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use keeko\framework\domain\payload\Success;
/**
* User Widget
*
* This code is automatically created. Modifications will probably be overwritten.
*
* @author gossi
*/
class AccountWidgetAction extends AbstractAction {
/**
* Automatically generated run method
*
* @param Request $request
* @return Response
*/
public function run(Request $request) {
$prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences();
$translator = $this->getServiceContainer()->getTranslator();
return $this->responder->run($request, new Success([
'account_url' => $prefs->getAccountUrl(),
'destination' => $prefs->getAccountUrl() . '/' . $translator->trans('slug.login'),
'redirect' => $request->getUri(),
'login_label' => $prefs->getUserLogin()
]));
}
}
| Java |
// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <zmq/zmqabstractnotifier.h>
#include <util.h>
CZMQAbstractNotifier::~CZMQAbstractNotifier()
{
assert(!psocket);
}
bool CZMQAbstractNotifier::NotifyBlock(const CBlockIndex * /*CBlockIndex*/)
{
return true;
}
bool CZMQAbstractNotifier::NotifyTransaction(const CTransaction &/*transaction*/)
{
return true;
}
bool CZMQAbstractNotifier::NotifyTransactionLock(const CTransactionRef &/*transaction*/)
{
return true;
} | Java |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.21-2-15
description: Array.prototype.reduce - 'length' is property of the global object
includes:
- runTestCase.js
- fnGlobalObject.js
---*/
function testcase() {
function callbackfn(prevVal, curVal, idx, obj) {
return (obj.length === 2);
}
try {
var oldLen = fnGlobalObject().length;
fnGlobalObject()[0] = 12;
fnGlobalObject()[1] = 11;
fnGlobalObject()[2] = 9;
fnGlobalObject().length = 2;
return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true;
} finally {
delete fnGlobalObject()[0];
delete fnGlobalObject()[1];
delete fnGlobalObject()[2];
fnGlobalObject().length = oldLen;
}
}
runTestCase(testcase);
| Java |
import builder = require('botbuilder');
export module Helpers {
export class API {
public static async DownloadJson(url:string, post:boolean=false, options:any=undefined): Promise<string>{
return new Promise<string>(resolve => {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.onload = function (){
try {
resolve(xhr.responseText);
}
catch(e){
console.log("Error while calling api: " + e.message);
}
};
xhr.open(options ? "POST" : "GET", url, true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(options));
});
}
}
export enum SearchType { "code", "documentation" };
} | Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WingtipToys.Models;
namespace WingtipToys.Logic
{
public class AddProducts
{
public bool AddProduct(string ProductName, string ProductDesc, string ProductPrice, string ProductCategory, string ProductImagePath)
{
var myProduct = new Product();
myProduct.ProductName = ProductName;
myProduct.Description = ProductDesc;
myProduct.UnitPrice = Convert.ToDouble(ProductPrice);
myProduct.ImagePath = ProductImagePath;
myProduct.CategoryID = Convert.ToInt32(ProductCategory);
using (ProductContext _db = new ProductContext())
{
// Add product to DB.
_db.Products.Add(myProduct);
_db.SaveChanges();
}
// Success.
return true;
}
}
} | Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.security.fluent.models.SecureScoreControlDefinitionItemInner;
/** An instance of this class provides access to all the operations defined in SecureScoreControlDefinitionsClient. */
public interface SecureScoreControlDefinitionsClient {
/**
* List the available security controls, their assessments, and the max score.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SecureScoreControlDefinitionItemInner> list();
/**
* List the available security controls, their assessments, and the max score.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SecureScoreControlDefinitionItemInner> list(Context context);
/**
* For a specified subscription, list the available security controls, their assessments, and the max score.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription();
/**
* For a specified subscription, list the available security controls, their assessments, and the max score.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of security controls definition.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(Context context);
}
| Java |
<?php
namespace Seahinet\Catalog\Indexer;
use Seahinet\Catalog\Model\Collection\Product;
use Seahinet\Catalog\Model\Product as ProductModel;
use Seahinet\Catalog\Model\Collection\Category;
use Seahinet\Lib\Db\Sql\Ddl\Column\UnsignedInteger;
use Seahinet\Lib\Indexer\Handler\AbstractHandler;
use Seahinet\Lib\Indexer\Handler\Database;
use Seahinet\Lib\Indexer\Provider;
use Seahinet\Lib\Model\Collection\Language;
use Zend\Db\Sql\Ddl;
class Url implements Provider
{
use \Seahinet\Lib\Traits\Container;
protected $path = [];
public function provideStructure(AbstractHandler $handler)
{
if ($handler instanceof Database) {
$adapter = $this->getContainer()->get('dbAdapter');
$platform = $adapter->getPlatform();
$languages = new Language;
$languages->columns(['id']);
foreach ($languages as $language) {
$table = 'catalog_url_' . $language['id'] . '_index';
$adapter->query(
'DROP TABLE IF EXISTS ' . $table, $adapter::QUERY_MODE_EXECUTE
);
$ddl = new Ddl\CreateTable($table);
$ddl->addColumn(new UnsignedInteger('product_id', true, 0))
->addColumn(new UnsignedInteger('category_id', false, 0))
->addColumn(new Ddl\Column\Varchar('path', 512, false))
->addConstraint(new Ddl\Constraint\UniqueKey(['category_id', 'product_id'], 'UNQ_' . strtoupper($table) . '_CATEGORY_ID_PRODUCT_ID'))
->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_PRODUCT_ENTITY_ID', 'product_id', 'product_entity', 'id', 'CASCADE', 'CASCADE'))
->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_CATEGORY_ENTITY_ID', 'category_id', 'category_entity', 'id', 'CASCADE', 'CASCADE'))
->addConstraint(new Ddl\Index\Index('path', 'IDX_' . strtoupper($table) . '_PATH'));
$adapter->query(
$ddl->getSqlString($platform), $adapter::QUERY_MODE_EXECUTE
);
}
} else {
$handler->buildStructure([['attr' => 'path', 'is_unique' => 1]]);
}
return true;
}
public function provideData(AbstractHandler $handler)
{
$languages = new Language;
$languages->columns(['id']);
foreach ($languages as $language) {
$categories = new Category($language['id']);
$categories->where(['status' => 1]);
$categories->load(false);
$data = [$language['id'] => []];
$tree = [];
foreach ($categories as $category) {
$tree[$category['id']] = [
'object' => $category,
'pid' => (int) $category['parent_id']
];
}
foreach ($categories as $category) {
if ($path = $this->getPath($category, $tree)) {
$data[$language['id']][$category['id']] = [
'product_id' => null,
'category_id' => $category['id'],
'path' => $path
];
}
}
$handler->buildData($data);
$products = new Product($language['id']);
$products->where(['status' => 1])->limit(50);
$init = $data;
for ($i = 0;; $i++) {
$data = [$language['id'] => []];
$products->reset('offset')->offset(50 * $i);
$products->load(false, true);
if (!$products->count()) {
break;
}
foreach ($products as $product) {
$product = new ProductModel($language['id'], $product);
$categories = $product->getCategories();
foreach ($categories as $category) {
$data[$language['id']][] = [
'product_id' => $product['id'],
'category_id' => $category['id'],
'path' => (isset($init[$language['id']][$category['id']]['path']) ?
($init[$language['id']][$category['id']]['path'] . '/') : '') .
$product['uri_key']
];
}
}
$data[$language['id']] = array_values($data[$language['id']]);
$handler->buildData($data);
}
}
return true;
}
private function getPath($category, $tree)
{
if (isset($this->path[$category['id'] . '#' . $category['uri_key']])) {
return $this->path[$category['id'] . '#' . $category['uri_key']];
}
if (!isset($category['uri_key'])) {
return '';
}
$path = $category['uri_key'];
$pid = (int) $category['parent_id'];
if ($pid && isset($tree[$pid])) {
$path = trim($this->getPath($tree[$pid]['object'], $tree) . '/' . $path, '/');
}
$this->path[$category['id'] . '#' . $category['uri_key']] = $path;
return $path;
}
}
| Java |
package org.superboot.service;
import com.querydsl.core.types.Predicate;
import org.springframework.data.domain.Pageable;
import org.superboot.base.BaseException;
import org.superboot.base.BaseResponse;
/**
* <b> 错误日志服务接口 </b>
* <p>
* 功能描述:
* </p>
*/
public interface ErrorLogService {
/**
* 按照微服务模块进行分组统计
*
* @return
* @throws BaseException
*/
BaseResponse getErrorLogGroupByAppName() throws BaseException;
/**
* 获取错误日志列表信息
*
* @param pageable 分页信息
* @param predicate 查询参数
* @return
* @throws BaseException
*/
BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException;
/**
* 获取错误日志记录数
*
* @return
* @throws BaseException
*/
BaseResponse getErrorLogCount(Predicate predicate) throws BaseException;
/**
* 查询错误日志详细信息
*
* @param id
* @return
* @throws BaseException
*/
BaseResponse getErrorLogItem(String id) throws BaseException;
}
| Java |
UNIX BUILD NOTES
================
Build Instructions: Ubuntu & Debian
Build requirements:
-------------------
```bash
sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils
```
BOOST
-----
```bash
sudo apt-get install libboost-all-dev
```
BDB
---
For Ubuntu only: db4.8 packages are available here. You can add the repository and install using the following commands:
```bash
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install libdb4.8-dev libdb4.8++-dev
```
Ubuntu and Debian have their own libdb-dev and libdb++-dev packages, but these will install BerkeleyDB 5.1 or later, which break binary wallet compatibility with the distributed executables which are based on BerkeleyDB 4.8
MINIUPNPC
---------
```bash
sudo apt-get install libminiupnpc-dev
```
QT5
---
```bash
sudo apt-get install libqt5gui5 libqt5core5a libqt5dbus5 qttools5-dev qttools5-dev-tools libprotobuf-dev protobuf-compiler
sudo apt-get install qt5-default -y
```
QRENCODE
--------
```bash
sudo apt-get install libqrencode-dev (optional)
```
secp256k1
---------
```bash
sudo apt-get install libsecp256k1-dev
```
OR
```bash
git clone https://github.com/bitcoin/bitcoin
cd /path/to/bitcoin-sources/src/sect256k1
./autogen.sh
./configure --enable-static --disable-shared --enable-module-recovery
make
sudo make install
```
BUILD
=====
```bash
git clone https://github.com/atcsecure/blocknet.git
cd /path/to/blocknet
git checkout xbridge-new-2
cp config.orig.pri config.pri
/path/to/qmake blocknet-qt.pro (etc. /usr/lib/x86_64-linux-gnu/qt5/bin on ubuntu)
make
```
| Java |
$(function () {
var $container = $('#container');
var certificatesInfo = $container.data('certinfo');
var runDate = $container.data('rundate');
$('#created_date').html(runDate);
var sorted_certificates = Object.keys(certificatesInfo)
.sort(function( a, b ) {
return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left;
}).map(function(sortedKey) {
return certificatesInfo[sortedKey];
});
var card_html = String()
+'<div class="col-xs-12 col-md-6 col-xl-4">'
+' <div class="card text-xs-center" style="border-color:#333;">'
+' <div class="card-header" style="overflow:hidden;">'
+' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>'
+' </div>'
+' <div class="card-block {{background}}">'
+' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>'
+' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>'
+' </div>'
+' <div class="card-footer">'
+' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>'
+' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>'
+' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>'
+' </div>'
+' </div>'
+'</div>';
function insert_card(json) {
var card_template = Handlebars.compile(card_html),
html = card_template(json);
$('#panel').append(html);
};
sorted_certificates.forEach(function(element, index, array){
var json = {
'server': element.server,
'days_left': element.info.days_left,
'issuer': element.issuer.org,
'common_name': element.subject.common_name,
'issuer_cn': element.issuer.common_name
}
if (element.info.days_left <= 30 ){
json.background = 'card-inverse card-danger';
} else if (element.info.days_left > 30 && element.info.days_left <= 60 ) {
json.background = 'card-inverse card-warning';
} else if (element.info.days_left === "??") {
json.background = 'card-inverse card-info';
} else {
json.background = 'card-inverse card-success';
}
insert_card(json);
});
});
| Java |
---
title: "Configuring the Terminal on a New Macbook"
date: 2016-06-01 21:12:00
category: post
tags: [efficiency, osx, shell, sublime]
---
I bought a new Macbook Pro Retina today for personal use, and spent most of the day re-configuring the terminal and development environment to match my old machine. This post is both a reference for my future self (to save some time with future environment configuration) and a set of recommendations for anyone looking for some time saving tricks.
## [Changing `ls` Colors][ls]{:target="_blank"}
The default colors displayed in the output of the `ls` command in the terminal don't make any differentiation between folders or file types. The guide above highlights a few environment variables to set in your `~/.bash_profile` that allow for customization of the colors of `ls` output. This is exceedingly helpful when trying to navigate foreign folder structures, or trying to find that one executable in a sea of non executables.
The variables are as follows:
{% highlight shell %}
export CLICOLOR=1 # tells the shell to apply coloring to command output (just needs to be set)
export LSCOLORS=exfxcxdxbxegedabagacad # configuration of colors for particular file types
# NOTE: see the article linked above for detail on LSCOLORS values
{% endhighlight %}
## [Sublime Text Symlink][subl]{:target="_blank"}
My text editor of preference is Sublime, so the article linked above is applicable for creating a symlink for its CLI and adding it to your path. This is convenient since it allows you to open a file (or folder) in your text editor of choice ***from the command line***, instead of having to open files manually from the editor itself. Once you create the symlink, make sure you add the location of the link to your path and put it in your `~/.bash_profile`.
{% highlight shell %}
export PATH=$PATH:~/.bin # augments PATH with location of sublime symlink
{% endhighlight %}
## Additional Sublime Configuration
On the topic of Sublime, I recommend enabling the following options in `Preferences > Settings - User`:
{%highlight json%}
{
"trim_trailing_white_space_on_save": true,
"ensure_newline_at_eof_on_save": true,
"scroll_past_end": true
}
{%endhighlight%}
`trim_trailing_white_space_on_save` will do just that, making your diffs in github easier to parse through.
`ensure_newline_at_eof_on_save` is also self explanatory, and keeps your files consistent with the expectation of many unix based text editing utilities that non-empty files have a newline `\n` at the end. Github also tracks this in files, so having it enabled ensures all of your files remain consistent and do not show up in diffs because newlines were removed.
`scroll_past_end` lets the editor scroll further down than the last line of the file. This is useful to bring text at the end of a file higher up in the editor, without needing to add a bunch of unnecessary blank lines.
## [Current Git Branch in Your PS1][gbps1]{:target="_blank"}
This one blew my mind when I enabled it, and also taught me how to configure the "Prompt String 1" (PS1) that displays by default in the terminal. Just follow the instructions in the post above, which involves adding a shell function to your `~/.bash_profile` that checks for the presence of a git repository and parses the text of the current branch. If a branch was found, the name of the branch will be added to your `PS1`, right before your cursor! Knowing what branch you're on is critical when working on a complex project with multiple branches, preventing inadvertent work in / commits to the wrong branch.
## [Tab Completion of Git Branches][tab]{:target="_blank"}
Another trick that saves me a lot of time is tab completion of git branches. Without this, you are forced to type out the full branch name to which you are switching, which slows you down. See the SO post linked above for details on enabling this. It involves downloading a script that performs the tab completion logic (credit to Shawn O. Pearce <spearce@spearce.org>) and sourcing it in your `~/.bash_profile`. In all honestly I haven't looked through the script in much detail... but works like a charm!
Let me know in the comments if you have any additional time saving tricks that you think I've missed. I'm always interested in improving my personal development process.
[ls]: http://osxdaily.com/2012/02/21/add-color-to-the-terminal-in-mac-os-x/
[subl]: http://stackoverflow.com/questions/16199581/opening-sublime-text-on-command-line-as-subl-on-mac-os#answer-16495202
[gbps1]: https://coderwall.com/p/fasnya/add-git-branch-name-to-bash-prompt
[tab]: http://apple.stackexchange.com/a/55886
| Java |
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1')
fig1 = plt.figure(1)
img1.seek(0)
# for i in range(250):
# pixA11 = img1.getpixel((1,i))
# print(pixA11)
f1 = list(img1.getdata())
print(f1[1000])
plt.imshow(img1)
fig1.show()
input()
# Plots eleventh frame
# print('Frame 11')
# fig2 = plt.figure(2)
# img1.seek(10)
# # for i in range(250):
# # pixB11 = img1.getpixel((1,i))
# # print(pixB11)
# f2 = list(img1.getdata())
# print(f2[10000])
# plt.imshow(img1)
# fig2.show()
# input()
# Create a new image
fig3 = plt.figure(3)
imgAvg = Image.new(img1.mode, img1.size)
print(img1.mode)
print(img1.size)
fAvg = list()
pix = imgAvg.load()
for i in range(512):
for j in range(512):
pixVal = (f1[i*512+j] + f1[i*512+j]) / 2
# fAvg.append(pixVal)
fAvg.insert(i*512+j,pixVal)
imgAvg.putdata(fAvg)
imgAvg.save('avg.tiff')
plt.imshow(imgAvg)
fig3.show()
print('Average')
# The following is necessary to keep the above figures 'alive'
input()
# data = random.random((256, 256))
# img1 = Image.fromarray(data)
# img1.save('test.tiff')
| Java |
FROM nginx
MAINTAINER Konstantin Volodin, volodin.konstantin@gmail.com
COPY nginx.conf /etc/nginx
EXPOSE 80
EXPOSE 5500
ENTRYPOINT nginx -g "daemon off;"
| Java |
FROM golang:alpine as build
WORKDIR /go/src
COPY main.go .
RUN go build -o /go/bin/memhogger .
FROM alpine
LABEL maintainer="Michael Gasch <embano1@live.com>"
COPY --from=build /go/bin/memhogger /bin/memhogger
ENTRYPOINT ["memhogger"] | Java |
-- phpMyAdmin SQL Dump
-- version 4.0.9
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: May 11, 2014 at 07:52 AM
-- Server version: 5.6.14
-- PHP Version: 5.5.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `apdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `bm2`
--
CREATE TABLE IF NOT EXISTS `bm2` (
`date` int(11) NOT NULL,
`att` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `bm2`
--
INSERT INTO `bm2` (`date`, `att`) VALUES
(1, 90),
(2, 88),
(3, 0),
(4, 88),
(5, 90),
(6, 92),
(7, 88),
(8, 90),
(9, 86),
(10, 0),
(11, 86),
(12, 0),
(13, 85),
(14, 90),
(15, 92),
(16, 88),
(17, 0),
(18, 86),
(19, 92),
(20, 93),
(21, 90),
(22, 90),
(23, 92),
(24, 0),
(25, 93),
(26, 93),
(27, 93),
(28, 93),
(29, 93),
(30, 0),
(31, 0);
-- --------------------------------------------------------
--
-- Table structure for table `fan`
--
CREATE TABLE IF NOT EXISTS `fan` (
`date` date NOT NULL,
`ta` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `school_name`
--
CREATE TABLE IF NOT EXISTS `school_name` (
`sid` varchar(5) NOT NULL,
`sname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `school_name`
--
INSERT INTO `school_name` (`sid`, `sname`) VALUES
('s1', 'GLPS- NELGULI'),
('', ''),
('s2', 'GLPS SEETHARAMAM PALYA '),
('s3', 'RBANMS - HPS - DICKENSON ROAD '),
('s4', 'GHPS - BASAVANNA NAGARA'),
('s5', 'GLPS - SADANA PALYA');
-- --------------------------------------------------------
--
-- Table structure for table `superv`
--
CREATE TABLE IF NOT EXISTS `superv` (
`date` date NOT NULL,
`te` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `superv2`
--
CREATE TABLE IF NOT EXISTS `superv2` (
`date` int(11) NOT NULL,
`te` int(11) NOT NULL,
`fb` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `superv2`
--
INSERT INTO `superv2` (`date`, `te`, `fb`) VALUES
(1, 90, ''),
(2, 84, ''),
(3, 0, ''),
(4, 86, ''),
(5, 91, ''),
(6, 92, ''),
(7, 89, ''),
(8, 88, ''),
(9, 87, ''),
(10, 0, ''),
(11, 88, ''),
(12, 0, ''),
(13, 86, ''),
(14, 92, ''),
(15, 92, ''),
(16, 90, ''),
(17, 0, ''),
(18, 88, ''),
(19, 92, ''),
(20, 94, ''),
(21, 90, ''),
(22, 91, ''),
(23, 92, ''),
(24, 0, ''),
(25, 92, ''),
(26, 92, ''),
(27, 92, ''),
(28, 90, ''),
(29, 92, ''),
(30, 0, ''),
(31, 0, '');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| Java |
package com.InfinityRaider.AgriCraft.utility;
import com.InfinityRaider.AgriCraft.items.ItemAgricraft;
import com.InfinityRaider.AgriCraft.items.ItemNugget;
import com.InfinityRaider.AgriCraft.reference.Data;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class OreDictHelper {
private static final Map<String, Block> oreBlocks = new HashMap<String, Block>();
private static final Map<String, Integer> oreBlockMeta = new HashMap<String, Integer>();
private static final Map<String, Item> nuggets = new HashMap<String, Item>();
private static final Map<String, Integer> nuggetMeta = new HashMap<String, Integer>();
public static Block getOreBlockForName(String name) {
return oreBlocks.get(name);
}
public static int getOreMetaForName(String name) {
return oreBlockMeta.get(name);
}
public static Item getNuggetForName(String name) {
return nuggets.get(name);
}
public static int getNuggetMetaForName(String name) {
return nuggetMeta.get(name);
}
//checks if an itemstack has this ore dictionary entry
public static boolean hasOreId(ItemStack stack, String tag) {
if(stack==null || stack.getItem()==null) {
return false;
}
int[] ids = OreDictionary.getOreIDs(stack);
for(int id:ids) {
if(OreDictionary.getOreName(id).equals(tag)) {
return true;
}
}
return false;
}
public static boolean hasOreId(Block block, String tag) {
return block != null && hasOreId(new ItemStack(block), tag);
}
//checks if two blocks have the same ore dictionary entry
public static boolean isSameOre(Block block1, int meta1, Block block2, int meta2) {
if(block1==block2 && meta1==meta2) {
return true;
}
if(block1==null || block2==null) {
return false;
}
int[] ids1 = OreDictionary.getOreIDs(new ItemStack(block1, 1, meta1));
int[] ids2 = OreDictionary.getOreIDs(new ItemStack(block2, 1, meta2));
for (int id1:ids1) {
for (int id2:ids2) {
if (id1==id2) {
return true;
}
}
}
return false;
}
//finds the ingot for a nugget ore dictionary entry
public static ItemStack getIngot(String ore) {
ItemStack ingot = null;
ArrayList<ItemStack> entries = OreDictionary.getOres("ingot" + ore);
if (entries.size() > 0 && entries.get(0).getItem() != null) {
ingot = entries.get(0);
}
return ingot;
}
//finds what ores and nuggets are already registered in the ore dictionary
public static void getRegisteredOres() {
//Vanilla
for (String oreName : Data.vanillaNuggets) {
getOreBlock(oreName);
if(oreBlocks.get(oreName)!=null) {
getNugget(oreName);
}
}
//Modded
for (String[] data : Data.modResources) {
String oreName = data[0];
getOreBlock(oreName);
if(oreBlocks.get(oreName)!=null) {
getNugget(oreName);
}
}
}
private static void getOreBlock(String oreName) {
for (ItemStack itemStack : OreDictionary.getOres("ore"+oreName)) {
if (itemStack.getItem() instanceof ItemBlock) {
ItemBlock block = (ItemBlock) itemStack.getItem();
oreBlocks.put(oreName, block.field_150939_a);
oreBlockMeta.put(oreName, itemStack.getItemDamage());
break;
}
}
}
private static void getNugget(String oreName) {
List<ItemStack> nuggets = OreDictionary.getOres("nugget" + oreName);
if (!nuggets.isEmpty()) {
Item nugget = nuggets.get(0).getItem();
OreDictHelper.nuggets.put(oreName, nugget);
nuggetMeta.put(oreName, nuggets.get(0).getItemDamage());
} else {
ItemAgricraft nugget = new ItemNugget(oreName);
OreDictionary.registerOre("nugget"+oreName, nugget);
OreDictHelper.nuggets.put(oreName, nugget);
nuggetMeta.put(oreName, 0);
}
}
public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed) {
return getFruitsFromOreDict(seed, true);
}
public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed, boolean sameMod) {
String seedModId = IOHelper.getModId(seed);
ArrayList<ItemStack> fruits = new ArrayList<ItemStack>();
for(int id:OreDictionary.getOreIDs(seed)) {
if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) {
String name = OreDictionary.getOreName(id).substring(4);
ArrayList<ItemStack> fromOredict = OreDictionary.getOres("crop"+name);
for(ItemStack stack:fromOredict) {
if(stack==null || stack.getItem()==null) {
continue;
}
String stackModId = IOHelper.getModId(stack);
if((!sameMod) || stackModId.equals(seedModId)) {
fruits.add(stack);
}
}
}
}
return fruits;
}
}
| Java |
'use strict';
//Setting up route
angular.module('socketio-area').config(['$stateProvider',
function($stateProvider) {
// Socketio area state routing
$stateProvider.
state('socketio-area', {
url: '/socketio',
templateUrl: 'modules/socketio-area/views/socketio-area.client.view.html'
});
}
]); | Java |
#include "utlua.h"
#ifdef __linux__
#include <limits.h>
#include <linux/netfilter_ipv4.h>
#endif
#include <net/if.h>
#define LUA_TCPD_CONNECTION_TYPE "<tcpd.connect>"
#define LUA_TCPD_SERVER_TYPE "<tcpd.bind %s %d>"
#define LUA_TCPD_ACCEPT_TYPE "<tcpd.accept %s %d>"
#if FAN_HAS_OPENSSL
typedef struct
{
SSL_CTX *ssl_ctx;
char *key;
int retainCount;
} SSLCTX;
#endif
typedef struct
{
struct bufferevent *buf;
#if FAN_HAS_OPENSSL
SSLCTX *sslctx;
int ssl_verifyhost;
int ssl_verifypeer;
const char *ssl_error;
#endif
lua_State *mainthread;
int onReadRef;
int onSendReadyRef;
int onDisconnectedRef;
int onConnectedRef;
char *host;
char *ssl_host;
int port;
int send_buffer_size;
int receive_buffer_size;
int interface;
lua_Number read_timeout;
lua_Number write_timeout;
} Conn;
#if FAN_HAS_OPENSSL
#define VERIFY_DEPTH 5
static int conn_index = 0;
#endif
typedef struct
{
struct evconnlistener *listener;
lua_State *mainthread;
int onAcceptRef;
int onSSLHostNameRef;
char *host;
int port;
int ipv6;
#if FAN_HAS_OPENSSL
int ssl;
SSL_CTX *ctx;
EC_KEY *ecdh;
#endif
int send_buffer_size;
int receive_buffer_size;
} SERVER;
typedef struct
{
struct bufferevent *buf;
lua_State *mainthread;
int onReadRef;
int onSendReadyRef;
int selfRef;
char ip[INET6_ADDRSTRLEN];
int port;
int onDisconnectedRef;
} ACCEPT;
#define TCPD_ACCEPT_UNREF(accept) \
CLEAR_REF(accept->mainthread, accept->onSendReadyRef) \
CLEAR_REF(accept->mainthread, accept->onReadRef) \
CLEAR_REF(accept->mainthread, accept->onDisconnectedRef) \
CLEAR_REF(accept->mainthread, accept->selfRef)
LUA_API int lua_tcpd_server_close(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE);
CLEAR_REF(L, serv->onAcceptRef)
CLEAR_REF(L, serv->onSSLHostNameRef)
if (serv->host)
{
free(serv->host);
serv->host = NULL;
}
if (event_mgr_base_current() && serv->listener)
{
evconnlistener_free(serv->listener);
serv->listener = NULL;
}
#if FAN_HAS_OPENSSL
if (serv->ctx)
{
SSL_CTX_free(serv->ctx);
EC_KEY_free(serv->ecdh);
serv->ctx = NULL;
serv->ecdh = NULL;
}
#endif
return 0;
}
LUA_API int lua_tcpd_server_gc(lua_State *L)
{
return lua_tcpd_server_close(L);
}
LUA_API int lua_tcpd_accept_tostring(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
lua_pushfstring(L, LUA_TCPD_ACCEPT_TYPE, accept->ip, accept->port);
return 1;
}
LUA_API int lua_tcpd_server_tostring(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE);
if (serv->listener)
{
char host[INET6_ADDRSTRLEN];
regress_get_socket_host(evconnlistener_get_fd(serv->listener), host);
lua_pushfstring(
L, LUA_TCPD_SERVER_TYPE, host,
regress_get_socket_port(evconnlistener_get_fd(serv->listener)));
}
else
{
lua_pushfstring(L, LUA_TCPD_SERVER_TYPE, 0);
}
return 1;
}
static void tcpd_accept_eventcb(struct bufferevent *bev, short events,
void *arg)
{
ACCEPT *accept = (ACCEPT *)arg;
if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF ||
events & BEV_EVENT_TIMEOUT)
{
if (events & BEV_EVENT_ERROR)
{
#if DEBUG
printf("BEV_EVENT_ERROR %s\n",
evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
#endif
}
bufferevent_free(bev);
accept->buf = NULL;
if (accept->onDisconnectedRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onDisconnectedRef);
if (events & BEV_EVENT_ERROR && EVUTIL_SOCKET_ERROR())
{
lua_pushstring(co,
evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
}
else if (events & BEV_EVENT_TIMEOUT)
{
lua_pushstring(co, "timeout");
}
else if (events & BEV_EVENT_EOF)
{
lua_pushstring(co, "client disconnected");
}
else
{
lua_pushnil(co);
}
CLEAR_REF(mainthread, accept->onDisconnectedRef)
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
TCPD_ACCEPT_UNREF(accept)
}
else
{
}
}
#define BUFLEN 1024
static void tcpd_accept_readcb(struct bufferevent *bev, void *ctx)
{
ACCEPT *accept = (ACCEPT *)ctx;
char buf[BUFLEN];
int n;
BYTEARRAY ba = {0};
bytearray_alloc(&ba, BUFLEN * 2);
struct evbuffer *input = bufferevent_get_input(bev);
while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0)
{
bytearray_writebuffer(&ba, buf, n);
}
bytearray_read_ready(&ba);
if (accept->onReadRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onReadRef);
lua_pushlstring(co, (const char *)ba.buffer, ba.total);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
bytearray_dealloc(&ba);
}
static void tcpd_accept_writecb(struct bufferevent *bev, void *ctx)
{
ACCEPT *accept = (ACCEPT *)ctx;
if (evbuffer_get_length(bufferevent_get_output(bev)) == 0)
{
if (accept->onSendReadyRef != LUA_NOREF)
{
lua_State *mainthread = accept->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onSendReadyRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
}
void connlistener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *addr, int socklen, void *arg)
{
SERVER *serv = (SERVER *)arg;
if (serv->onAcceptRef != LUA_NOREF)
{
lua_State *mainthread = serv->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onAcceptRef);
ACCEPT *accept = lua_newuserdata(co, sizeof(ACCEPT));
memset(accept, 0, sizeof(ACCEPT));
accept->buf = NULL;
accept->mainthread = mainthread;
accept->selfRef = LUA_NOREF;
accept->onReadRef = LUA_NOREF;
accept->onSendReadyRef = LUA_NOREF;
accept->onDisconnectedRef = LUA_NOREF;
luaL_getmetatable(co, LUA_TCPD_ACCEPT_TYPE);
lua_setmetatable(co, -2);
struct event_base *base = evconnlistener_get_base(listener);
struct bufferevent *bev;
#if FAN_HAS_OPENSSL
if (serv->ssl && serv->ctx)
{
bev = bufferevent_openssl_socket_new(
base, fd, SSL_new(serv->ctx), BUFFEREVENT_SSL_ACCEPTING,
BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
}
else
{
#endif
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
#if FAN_HAS_OPENSSL
}
#endif
bufferevent_setcb(bev, tcpd_accept_readcb, tcpd_accept_writecb,
tcpd_accept_eventcb, accept);
bufferevent_enable(bev, EV_READ | EV_WRITE);
if (serv->send_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &serv->send_buffer_size,
sizeof(serv->send_buffer_size));
}
if (serv->receive_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &serv->receive_buffer_size,
sizeof(serv->receive_buffer_size));
}
memset(accept->ip, 0, INET6_ADDRSTRLEN);
if (addr->sa_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), accept->ip,
INET_ADDRSTRLEN);
accept->port = ntohs(addr_in->sin_port);
}
else
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)addr;
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), accept->ip,
INET6_ADDRSTRLEN);
accept->port = ntohs(addr_in->sin6_port);
}
accept->buf = bev;
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
}
LUA_API int tcpd_accept_bind(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
luaL_checktype(L, 2, LUA_TTABLE);
lua_settop(L, 2);
lua_pushvalue(L, 1);
accept->selfRef = luaL_ref(L, LUA_REGISTRYINDEX);
SET_FUNC_REF_FROM_TABLE(L, accept->onReadRef, 2, "onread")
SET_FUNC_REF_FROM_TABLE(L, accept->onSendReadyRef, 2, "onsendready")
SET_FUNC_REF_FROM_TABLE(L, accept->onDisconnectedRef, 2, "ondisconnected")
lua_pushstring(L, accept->ip);
lua_pushinteger(L, accept->port);
return 2;
}
#if FAN_HAS_OPENSSL
static int ssl_servername_cb(SSL *s, int *ad, void *arg)
{
const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
// if (hostname)
// printf("Hostname in TLS extension: \"%s\"\n", hostname);
SERVER *serv = (SERVER *)arg;
if (hostname && serv->onSSLHostNameRef != LUA_NOREF)
{
lua_State *mainthread = serv->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onSSLHostNameRef);
lua_pushstring(co, hostname);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
// if (!p->servername)
// return SSL_TLSEXT_ERR_NOACK;
// if (servername) {
// if (strcasecmp(servername, p->servername))
// return p->extension_error;
// }
return SSL_TLSEXT_ERR_OK;
}
#endif
static void tcpd_server_rebind(lua_State *L, SERVER *serv)
{
if (serv->listener)
{
evconnlistener_free(serv->listener);
serv->listener = NULL;
}
if (serv->host)
{
char portbuf[6];
evutil_snprintf(portbuf, sizeof(portbuf), "%d", serv->port);
struct evutil_addrinfo hints = {0};
struct evutil_addrinfo *answer = NULL;
hints.ai_family = serv->ipv6 ? AF_INET6 : AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = EVUTIL_AI_ADDRCONFIG;
int err = evutil_getaddrinfo(serv->host, portbuf, &hints, &answer);
if (err < 0 || !answer)
{
luaL_error(L, "invaild bind address %s:%d", serv->host, serv->port);
}
serv->listener =
evconnlistener_new_bind(event_mgr_base(), connlistener_cb, serv,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
answer->ai_addr, answer->ai_addrlen);
evutil_freeaddrinfo(answer);
}
else
{
struct sockaddr *addr = NULL;
size_t addr_size = 0;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
memset(&sin, 0, sizeof(sin));
memset(&sin6, 0, sizeof(sin6));
if (!serv->ipv6)
{
addr = (struct sockaddr *)&sin;
addr_size = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(0);
sin.sin_port = htons(serv->port);
}
else
{
addr = (struct sockaddr *)&sin6;
addr_size = sizeof(sin6);
sin6.sin6_family = AF_INET6;
// sin6.sin6_addr.s6_addr
sin6.sin6_port = htons(serv->port);
}
serv->listener = evconnlistener_new_bind(
event_mgr_base(), connlistener_cb, serv,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, addr, addr_size);
}
}
LUA_API int lua_tcpd_server_rebind(lua_State *L)
{
SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE);
tcpd_server_rebind(L, serv);
return 0;
}
LUA_API int tcpd_bind(lua_State *L)
{
event_mgr_init();
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1);
SERVER *serv = lua_newuserdata(L, sizeof(SERVER));
memset(serv, 0, sizeof(SERVER));
luaL_getmetatable(L, LUA_TCPD_SERVER_TYPE);
lua_setmetatable(L, -2);
serv->mainthread = utlua_mainthread(L);
SET_FUNC_REF_FROM_TABLE(L, serv->onAcceptRef, 1, "onaccept")
SET_FUNC_REF_FROM_TABLE(L, serv->onSSLHostNameRef, 1, "onsslhostname")
DUP_STR_FROM_TABLE(L, serv->host, 1, "host")
SET_INT_FROM_TABLE(L, serv->port, 1, "port")
lua_getfield(L, 1, "ssl");
int ssl = lua_toboolean(L, -1);
lua_pop(L, 1);
#if FAN_HAS_OPENSSL
serv->ssl = ssl;
if (serv->ssl)
{
lua_getfield(L, 1, "cert");
const char *cert = lua_tostring(L, -1);
lua_getfield(L, 1, "key");
const char *key = lua_tostring(L, -1);
if (cert && key)
{
SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
SSL_CTX_set_tlsext_servername_arg(ctx, serv);
serv->ctx = ctx;
SSL_CTX_set_options(ctx,
SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE |
0); // SSL_OP_NO_SSLv2
serv->ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!serv->ecdh)
{
die_most_horribly_from_openssl_error("EC_KEY_new_by_curve_name");
}
if (1 != SSL_CTX_set_tmp_ecdh(ctx, serv->ecdh))
{
die_most_horribly_from_openssl_error("SSL_CTX_set_tmp_ecdh");
}
server_setup_certs(ctx, cert, key);
}
lua_pop(L, 2);
}
#else
if (ssl)
{
luaL_error(L, "ssl is not supported on micro version.");
}
#endif
SET_INT_FROM_TABLE(L, serv->send_buffer_size, 1, "send_buffer_size")
SET_INT_FROM_TABLE(L, serv->receive_buffer_size, 1, "receive_buffer_size")
lua_getfield(L, 1, "ipv6");
serv->ipv6 = lua_toboolean(L, -1);
lua_pop(L, 1);
tcpd_server_rebind(L, serv);
if (!serv->listener)
{
return 0;
}
else
{
if (!serv->port)
{
serv->port = regress_get_socket_port(evconnlistener_get_fd(serv->listener));
}
lua_pushinteger(L, serv->port);
return 2;
}
}
static void tcpd_conn_readcb(struct bufferevent *bev, void *ctx)
{
Conn *conn = (Conn *)ctx;
char buf[BUFLEN];
int n;
BYTEARRAY ba;
bytearray_alloc(&ba, BUFLEN * 2);
struct evbuffer *input = bufferevent_get_input(bev);
while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0)
{
bytearray_writebuffer(&ba, buf, n);
}
bytearray_read_ready(&ba);
if (conn->onReadRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_rawgeti(mainthread, LUA_REGISTRYINDEX, conn->onReadRef);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_xmove(mainthread, co, 1);
lua_unlock(mainthread);
lua_pushlstring(co, (const char *)ba.buffer, ba.total);
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
bytearray_dealloc(&ba);
}
static void tcpd_conn_writecb(struct bufferevent *bev, void *ctx)
{
Conn *conn = (Conn *)ctx;
if (evbuffer_get_length(bufferevent_get_output(bev)) == 0)
{
if (conn->onSendReadyRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onSendReadyRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
}
static void tcpd_conn_eventcb(struct bufferevent *bev, short events,
void *arg)
{
Conn *conn = (Conn *)arg;
if (events & BEV_EVENT_CONNECTED)
{
// printf("tcp connected.\n");
if (conn->onConnectedRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onConnectedRef);
FAN_RESUME(co, mainthread, 0);
POP_REF(mainthread);
}
}
else if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF ||
events & BEV_EVENT_TIMEOUT)
{
#if FAN_HAS_OPENSSL
SSL *ssl = bufferevent_openssl_get_ssl(bev);
if (ssl)
{
SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
SSL_shutdown(ssl);
}
#endif
bufferevent_free(bev);
conn->buf = NULL;
if (conn->onDisconnectedRef != LUA_NOREF)
{
lua_State *mainthread = conn->mainthread;
lua_lock(mainthread);
lua_State *co = lua_newthread(mainthread);
PUSH_REF(mainthread);
lua_unlock(mainthread);
lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onDisconnectedRef);
if (events & BEV_EVENT_TIMEOUT)
{
if (events & BEV_EVENT_READING)
{
lua_pushliteral(co, "read timeout");
}
else if (events & BEV_EVENT_WRITING)
{
lua_pushliteral(co, "write timeout");
}
else
{
lua_pushliteral(co, "unknown timeout");
}
}
else if (events & BEV_EVENT_ERROR)
{
#if FAN_HAS_OPENSSL
if (conn->ssl_error)
{
lua_pushfstring(co, "SSLError: %s", conn->ssl_error);
}
else
{
#endif
int err = bufferevent_socket_get_dns_error(bev);
if (err)
{
lua_pushstring(co, evutil_gai_strerror(err));
}
else if (EVUTIL_SOCKET_ERROR())
{
lua_pushstring(
co, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
}
else
{
lua_pushnil(co);
}
#if FAN_HAS_OPENSSL
}
#endif
}
else if (events & BEV_EVENT_EOF)
{
lua_pushliteral(co, "server disconnected");
}
else
{
lua_pushnil(co);
}
FAN_RESUME(co, mainthread, 1);
POP_REF(mainthread);
}
}
}
#if FAN_HAS_OPENSSL
static int ssl_verifypeer_cb(int preverify_ok, X509_STORE_CTX *ctx)
{
if (!preverify_ok)
{
SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
Conn *conn = SSL_get_ex_data(ssl, conn_index);
int err = X509_STORE_CTX_get_error(ctx);
conn->ssl_error = strdup(X509_verify_cert_error_string(err));
}
return preverify_ok;
}
#endif
static void luatcpd_reconnect(Conn *conn)
{
if (conn->buf)
{
bufferevent_free(conn->buf);
conn->buf = NULL;
}
#if FAN_HAS_OPENSSL
conn->ssl_error = 0;
if (conn->sslctx)
{
SSL *ssl = SSL_new(conn->sslctx->ssl_ctx);
SSL_set_ex_data(ssl, conn_index, conn);
if (conn->ssl_verifyhost && (conn->ssl_host ?: conn->host))
{
SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
if (!SSL_set1_host(ssl, conn->ssl_host ?: conn->host))
{
printf("SSL_set1_host '%s' failed!\n", conn->ssl_host ?: conn->host);
}
}
/* Enable peer verification (with a non-null callback if desired) */
if (conn->ssl_verifypeer)
{
SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
}
else
{
SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
}
SSL_set_tlsext_host_name(ssl, conn->ssl_host ?: conn->host);
conn->buf = bufferevent_openssl_socket_new(
event_mgr_base(), -1, ssl, BUFFEREVENT_SSL_CONNECTING,
BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
#ifdef EVENT__NUMERIC_VERSION
#if (EVENT__NUMERIC_VERSION >= 0x02010500)
bufferevent_openssl_set_allow_dirty_shutdown(conn->buf, 1);
#endif
#endif
}
else
{
#endif
conn->buf = bufferevent_socket_new(
event_mgr_base(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
#if FAN_HAS_OPENSSL
}
#endif
int rc = bufferevent_socket_connect_hostname(conn->buf, event_mgr_dnsbase(),
AF_UNSPEC,
conn->host, conn->port);
evutil_socket_t fd = bufferevent_getfd(conn->buf);
if (conn->send_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &conn->send_buffer_size,
sizeof(conn->send_buffer_size));
}
if (conn->receive_buffer_size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &conn->receive_buffer_size,
sizeof(conn->receive_buffer_size));
}
#ifdef IP_BOUND_IF
if (conn->interface)
{
setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &conn->interface, sizeof(conn->interface));
}
#endif
if (rc < 0)
{
LOGE("could not connect to %s:%d %s", conn->host, conn->port,
evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
bufferevent_free(conn->buf);
conn->buf = NULL;
return;
}
bufferevent_enable(conn->buf, EV_WRITE | EV_READ);
bufferevent_setcb(conn->buf, tcpd_conn_readcb, tcpd_conn_writecb,
tcpd_conn_eventcb, conn);
}
LUA_API int tcpd_connect(lua_State *L)
{
event_mgr_init();
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1);
Conn *conn = lua_newuserdata(L, sizeof(Conn));
memset(conn, 0, sizeof(Conn));
luaL_getmetatable(L, LUA_TCPD_CONNECTION_TYPE);
lua_setmetatable(L, -2);
conn->mainthread = utlua_mainthread(L);
conn->buf = NULL;
#if FAN_HAS_OPENSSL
conn->sslctx = NULL;
conn->ssl_error = 0;
#endif
conn->send_buffer_size = 0;
conn->receive_buffer_size = 0;
SET_FUNC_REF_FROM_TABLE(L, conn->onReadRef, 1, "onread")
SET_FUNC_REF_FROM_TABLE(L, conn->onSendReadyRef, 1, "onsendready")
SET_FUNC_REF_FROM_TABLE(L, conn->onDisconnectedRef, 1, "ondisconnected")
SET_FUNC_REF_FROM_TABLE(L, conn->onConnectedRef, 1, "onconnected")
DUP_STR_FROM_TABLE(L, conn->host, 1, "host")
SET_INT_FROM_TABLE(L, conn->port, 1, "port")
lua_getfield(L, 1, "ssl");
int ssl = lua_toboolean(L, -1);
lua_pop(L, 1);
#if FAN_HAS_OPENSSL
lua_getfield(L, 1, "ssl_verifyhost");
conn->ssl_verifyhost = (int)luaL_optinteger(L, -1, 1);
lua_pop(L, 1);
lua_getfield(L, 1, "ssl_verifypeer");
conn->ssl_verifypeer = (int)luaL_optinteger(L, -1, 1);
lua_pop(L, 1);
DUP_STR_FROM_TABLE(L, conn->ssl_host, 1, "ssl_host")
if (ssl)
{
lua_getfield(L, 1, "cainfo");
const char *cainfo = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "capath");
const char *capath = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "pkcs12.path");
const char *p12path = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
lua_getfield(L, 1, "pkcs12.password");
const char *p12password = luaL_optstring(L, -1, NULL);
lua_pop(L, 1);
if (!cainfo && !capath)
{
cainfo = "cert.pem";
}
BYTEARRAY ba = {0};
bytearray_alloc(&ba, BUFLEN);
bytearray_writebuffer(&ba, "SSL_CTX:", strlen("SSL_CTX_"));
if (cainfo)
{
bytearray_writebuffer(&ba, cainfo, strlen(cainfo));
}
if (capath)
{
bytearray_writebuffer(&ba, capath, strlen(capath));
}
if (p12path)
{
bytearray_writebuffer(&ba, p12path, strlen(p12path));
}
if (p12password)
{
bytearray_writebuffer(&ba, p12password, strlen(p12password));
}
bytearray_write8(&ba, 0);
bytearray_read_ready(&ba);
char *cache_key = strdup((const char *)ba.buffer);
bytearray_dealloc(&ba);
lua_getfield(L, LUA_REGISTRYINDEX, cache_key);
if (lua_isnil(L, -1))
{
SSLCTX *sslctx = lua_newuserdata(L, sizeof(SSLCTX));
sslctx->key = strdup(cache_key);
sslctx->ssl_ctx = SSL_CTX_new(TLS_method());
conn->sslctx = sslctx;
sslctx->retainCount = 1;
lua_setfield(L, LUA_REGISTRYINDEX, cache_key);
if (!SSL_CTX_load_verify_locations(sslctx->ssl_ctx, cainfo, capath))
{
printf("SSL_CTX_load_verify_locations failed: cainfo=%s capath=%s\n", cainfo, capath);
}
#ifdef SSL_MODE_RELEASE_BUFFERS
SSL_CTX_set_mode(sslctx->ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
#endif
SSL_CTX_set_options(sslctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
SSL_CTX_set_verify(sslctx->ssl_ctx, SSL_VERIFY_PEER, ssl_verifypeer_cb);
while (p12path)
{
FILE *fp = NULL;
EVP_PKEY *pkey = NULL;
X509 *cert = NULL;
STACK_OF(X509) *ca = NULL;
PKCS12 *p12 = NULL;
if ((fp = fopen(p12path, "rb")) == NULL)
{
fprintf(stderr, "Error opening file %s\n", p12path);
break;
}
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (!p12)
{
fprintf(stderr, "Error reading PKCS#12 file\n");
ERR_print_errors_fp(stderr);
break;
}
if (!PKCS12_parse(p12, p12password, &pkey, &cert, &ca))
{
fprintf(stderr, "Error parsing PKCS#12 file\n");
ERR_print_errors_fp(stderr);
}
else
{
SSL_CTX_use_certificate(sslctx->ssl_ctx, cert);
if (ca && sk_X509_num(ca))
{
int i = 0;
for (i = 0; i < sk_X509_num(ca); i++)
{
SSL_CTX_use_certificate(sslctx->ssl_ctx, sk_X509_value(ca, i));
}
}
SSL_CTX_use_PrivateKey(sslctx->ssl_ctx, pkey);
sk_X509_pop_free(ca, X509_free);
X509_free(cert);
EVP_PKEY_free(pkey);
}
PKCS12_free(p12);
p12 = NULL;
break;
}
}
else
{
SSLCTX *sslctx = lua_touserdata(L, -1);
sslctx->retainCount++;
conn->sslctx = sslctx;
}
lua_pop(L, 1);
FREE_STR(cache_key);
}
#else
if (ssl)
{
luaL_error(L, "ssl is not supported on micro version.");
}
#endif
SET_INT_FROM_TABLE(L, conn->send_buffer_size, 1, "send_buffer_size")
SET_INT_FROM_TABLE(L, conn->receive_buffer_size, 1, "receive_buffer_size")
lua_getfield(L, 1, "read_timeout");
lua_Number read_timeout = (int)luaL_optnumber(L, -1, 0);
conn->read_timeout = read_timeout;
lua_pop(L, 1);
lua_getfield(L, 1, "write_timeout");
lua_Number write_timeout = (int)luaL_optnumber(L, -1, 0);
conn->write_timeout = write_timeout;
lua_pop(L, 1);
lua_getfield(L, 1, "interface");
if (lua_type(L, -1) == LUA_TSTRING)
{
const char *interface = lua_tostring(L, -1);
conn->interface = if_nametoindex(interface);
}
lua_pop(L, 1);
luatcpd_reconnect(conn);
return 1;
}
static const luaL_Reg tcpdlib[] = {
{"bind", tcpd_bind}, {"connect", tcpd_connect}, {NULL, NULL}};
LUA_API int tcpd_conn_close(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE);
if (event_mgr_base_current() && conn->buf)
{
bufferevent_free(conn->buf);
conn->buf = NULL;
}
CLEAR_REF(L, conn->onReadRef)
CLEAR_REF(L, conn->onSendReadyRef)
CLEAR_REF(L, conn->onDisconnectedRef)
CLEAR_REF(L, conn->onConnectedRef)
FREE_STR(conn->host)
FREE_STR(conn->ssl_host)
#if FAN_HAS_OPENSSL
if (conn->sslctx)
{
conn->sslctx->retainCount--;
if (conn->sslctx->retainCount <= 0)
{
lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, conn->sslctx->key);
SSL_CTX_free(conn->sslctx->ssl_ctx);
free(conn->sslctx->key);
}
conn->sslctx = NULL;
}
#endif
return 0;
}
LUA_API int tcpd_conn_gc(lua_State *L) { return tcpd_conn_close(L); }
LUA_API int tcpd_accept_remote(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
lua_newtable(L);
lua_pushstring(L, accept->ip);
lua_setfield(L, -2, "ip");
lua_pushinteger(L, accept->port);
lua_setfield(L, -2, "port");
return 1;
}
#ifdef __linux__
LUA_API int tcpd_accept_original_dst(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
evutil_socket_t fd = bufferevent_getfd(accept->buf);
struct sockaddr_storage ss;
socklen_t len = sizeof(struct sockaddr_storage);
if (getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &ss, &len))
{
lua_pushnil(L);
lua_pushfstring(L, "getsockopt: %s", strerror(errno));
return 2;
}
char host[INET6_ADDRSTRLEN];
int port = 0;
if (ss.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss;
port = ntohs(((struct sockaddr_in *)&ss)->sin_port);
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host,
INET_ADDRSTRLEN);
}
else if (ss.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss;
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host,
INET6_ADDRSTRLEN);
}
lua_pushstring(L, host);
lua_pushinteger(L, port);
return 2;
}
#endif
LUA_API int tcpd_accept_getsockname(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
evutil_socket_t fd = bufferevent_getfd(accept->buf);
struct sockaddr_storage ss;
socklen_t len = sizeof(struct sockaddr_storage);
if (getsockname(fd, (struct sockaddr *)&ss, &len))
{
lua_pushnil(L);
lua_pushfstring(L, "getsockname: %s", strerror(errno));
return 2;
}
char host[INET6_ADDRSTRLEN];
int port = 0;
if (ss.ss_family == AF_INET)
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss;
port = ntohs(((struct sockaddr_in *)&ss)->sin_port);
inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host,
INET_ADDRSTRLEN);
}
else if (ss.ss_family == AF_INET6)
{
struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss;
port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port);
inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host,
INET6_ADDRSTRLEN);
}
lua_pushstring(L, host);
lua_pushinteger(L, port);
return 2;
}
LUA_API int tcpd_accept_close(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
if (event_mgr_base_current() && accept->buf)
{
bufferevent_free(accept->buf);
accept->buf = NULL;
}
TCPD_ACCEPT_UNREF(accept)
return 0;
}
LUA_API int lua_tcpd_accept_gc(lua_State *L) { return tcpd_accept_close(L); }
LUA_API int tcpd_accept_read_pause(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
if (accept->buf)
{
bufferevent_disable(accept->buf, EV_READ);
}
return 0;
}
LUA_API int tcpd_accept_read_resume(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
if (accept->buf)
{
bufferevent_enable(accept->buf, EV_READ);
}
return 0;
}
LUA_API int tcpd_conn_read_pause(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE);
if (conn->buf)
{
bufferevent_disable(conn->buf, EV_READ);
}
return 0;
}
LUA_API int tcpd_conn_read_resume(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE);
if (conn->buf)
{
bufferevent_enable(conn->buf, EV_READ);
}
return 0;
}
LUA_API int tcpd_conn_send(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE);
size_t len = 0;
const char *data = luaL_checklstring(L, 2, &len);
if (data && len > 0 && conn->buf)
{
if (conn->read_timeout > 0)
{
struct timeval tv1;
d2tv(conn->read_timeout, &tv1);
if (conn->write_timeout > 0)
{
struct timeval tv2;
d2tv(conn->write_timeout, &tv2);
bufferevent_set_timeouts(conn->buf, &tv1, &tv2);
}
else
{
bufferevent_set_timeouts(conn->buf, &tv1, NULL);
}
}
else
{
if (conn->write_timeout > 0)
{
struct timeval tv2;
d2tv(conn->write_timeout, &tv2);
bufferevent_set_timeouts(conn->buf, NULL, &tv2);
}
}
bufferevent_write(conn->buf, data, len);
size_t total = evbuffer_get_length(bufferevent_get_output(conn->buf));
lua_pushinteger(L, total);
}
else
{
lua_pushinteger(L, -1);
}
return 1;
}
LUA_API int tcpd_conn_reconnect(lua_State *L)
{
Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE);
luatcpd_reconnect(conn);
return 0;
}
LUA_API int tcpd_accept_flush(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
int mode = luaL_optinteger(L, 2, BEV_NORMAL);
lua_pushinteger(L, bufferevent_flush(accept->buf, EV_WRITE, mode));
return 1;
}
LUA_API int tcpd_accept_send(lua_State *L)
{
ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE);
size_t len = 0;
const char *data = luaL_checklstring(L, 2, &len);
if (data && len > 0 && accept->buf)
{
bufferevent_write(accept->buf, data, len);
size_t total = evbuffer_get_length(bufferevent_get_output(accept->buf));
lua_pushinteger(L, total);
}
else
{
lua_pushinteger(L, -1);
}
return 1;
}
LUA_API int luaopen_fan_tcpd(lua_State *L)
{
#if FAN_HAS_OPENSSL
conn_index = SSL_get_ex_new_index(0, "conn_index", NULL, NULL, NULL);
#endif
luaL_newmetatable(L, LUA_TCPD_CONNECTION_TYPE);
lua_pushcfunction(L, &tcpd_conn_send);
lua_setfield(L, -2, "send");
lua_pushcfunction(L, &tcpd_conn_read_pause);
lua_setfield(L, -2, "pause_read");
lua_pushcfunction(L, &tcpd_conn_read_resume);
lua_setfield(L, -2, "resume_read");
lua_pushcfunction(L, &tcpd_conn_close);
lua_setfield(L, -2, "close");
lua_pushcfunction(L, &tcpd_conn_reconnect);
lua_setfield(L, -2, "reconnect");
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &tcpd_conn_gc);
lua_rawset(L, -3);
lua_pop(L, 1);
luaL_newmetatable(L, LUA_TCPD_ACCEPT_TYPE);
lua_pushcfunction(L, &tcpd_accept_send);
lua_setfield(L, -2, "send");
lua_pushcfunction(L, &tcpd_accept_flush);
lua_setfield(L, -2, "flush");
lua_pushcfunction(L, &tcpd_accept_close);
lua_setfield(L, -2, "close");
lua_pushcfunction(L, &tcpd_accept_read_pause);
lua_setfield(L, -2, "pause_read");
lua_pushcfunction(L, &tcpd_accept_read_resume);
lua_setfield(L, -2, "resume_read");
lua_pushcfunction(L, &tcpd_accept_bind);
lua_setfield(L, -2, "bind");
lua_pushcfunction(L, &tcpd_accept_remote);
lua_setfield(L, -2, "remoteinfo");
lua_pushcfunction(L, &tcpd_accept_getsockname);
lua_setfield(L, -2, "getsockname");
#ifdef __linux__
lua_pushcfunction(L, &tcpd_accept_original_dst);
lua_setfield(L, -2, "original_dst");
#endif
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pushstring(L, "__tostring");
lua_pushcfunction(L, &lua_tcpd_accept_tostring);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &lua_tcpd_accept_gc);
lua_rawset(L, -3);
lua_pop(L, 1);
luaL_newmetatable(L, LUA_TCPD_SERVER_TYPE);
lua_pushstring(L, "close");
lua_pushcfunction(L, &lua_tcpd_server_close);
lua_rawset(L, -3);
lua_pushcfunction(L, &lua_tcpd_server_rebind);
lua_setfield(L, -2, "rebind");
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &lua_tcpd_server_gc);
lua_rawset(L, -3);
lua_pushstring(L, "__tostring");
lua_pushcfunction(L, &lua_tcpd_server_tostring);
lua_rawset(L, -3);
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_rawset(L, -3);
lua_pop(L, 1);
lua_newtable(L);
luaL_register(L, "tcpd", tcpdlib);
return 1;
}
| Java |
/**
* configuration for grunt tasks
* @module Gruntfile
*/
module.exports = function(grunt) {
/** load tasks */
require('load-grunt-tasks')(grunt);
/** config for build paths */
var config = {
dist: {
dir: 'dist/',
StoreFactory: 'dist/StoreFactory.js',
ngStoreFactory: 'dist/ngStore.js'
},
src: {
dir: 'src/'
},
tmp: {
dir: 'tmp/'
}
};
/** paths to files */
var files = {
/** src files */
Factory: [
'StoreFactory.js'
],
/** src files */
Store: [
'Store.js'
],
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/** config for grunt tasks */
var taskConfig = {
/** concatentation tasks for building the source files */
concat: {
StoreFactory: {
options: {
// stripBanners: true
banner: '',
footer: '',
},
src: (function() {
var
cwd = config.src.dir,
queue = [].concat(files.Factory, files.Store);
return queue.map(function(path) {
return cwd + path;
});
})(),
dest: config.dist.StoreFactory,
},
ngSession: {
options: {
banner: 'angular.module("ngStore", [])\n' +
'.service("ngStore", [\n' +
'function() {\n\n',
footer: '\n\n' +
'return new StoreFactory();\n\n}' +
'\n]);'
},
src: (function() {
return [
config.dist.StoreFactory,
];
})(),
dest: config.dist.ngStoreFactory
}
},
/** uglify (javascript minification) config */
uglify: {
StoreFactory: {
options: {},
files: [
{
src: config.dist.StoreFactory,
dest: (function() {
var split = config.dist.StoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
},
ngStoreFactory: {
options: {},
files: [
{
src: config.dist.ngStoreFactory,
dest: (function() {
var split = config.dist.ngStoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
}
}
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
// register default & custom tasks
grunt.initConfig(taskConfig);
grunt.registerTask('default', [
'build'
]);
grunt.registerTask('build', [
'concat',
'uglify'
]);
}; | Java |
#requires -Modules InvokeBuild
[CmdletBinding()]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingWriteHost', '')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingEmptyCatchBlock', '')]
param(
[String[]]$Tag,
[String[]]$ExcludeTag = @("Integration"),
[String]$PSGalleryAPIKey,
[String]$GithubAccessToken
)
$WarningPreference = "Continue"
if ($PSBoundParameters.ContainsKey('Verbose')) {
$VerbosePreference = "Continue"
}
if ($PSBoundParameters.ContainsKey('Debug')) {
$DebugPreference = "Continue"
}
try {
$script:IsWindows = (-not (Get-Variable -Name IsWindows -ErrorAction Ignore)) -or $IsWindows
$script:IsLinux = (Get-Variable -Name IsLinux -ErrorAction Ignore) -and $IsLinux
$script:IsMacOS = (Get-Variable -Name IsMacOS -ErrorAction Ignore) -and $IsMacOS
$script:IsCoreCLR = $PSVersionTable.ContainsKey('PSEdition') -and $PSVersionTable.PSEdition -eq 'Core'
}
catch { }
Set-StrictMode -Version Latest
Import-Module "$PSScriptRoot/Tools/BuildTools.psm1" -Force -ErrorAction Stop
if ($BuildTask -notin @("SetUp", "InstallDependencies")) {
Import-Module BuildHelpers -Force -ErrorAction Stop
Invoke-Init
}
#region SetUp
# Synopsis: Proxy task
task Init { Invoke-Init }
# Synopsis: Get the next version for the build
task GetNextVersion {
$manifestVersion = [Version](Get-Metadata -Path $env:BHPSModuleManifest)
try {
$env:CurrentOnlineVersion = [Version](Find-Module -Name $env:BHProjectName).Version
$nextOnlineVersion = Get-NextNugetPackageVersion -Name $env:BHProjectName
if ( ($manifestVersion.Major -gt $nextOnlineVersion.Major) -or
($manifestVersion.Minor -gt $nextOnlineVersion.Minor)
# -or ($manifestVersion.Build -gt $nextOnlineVersion.Build)
) {
$env:NextBuildVersion = [Version]::New($manifestVersion.Major, $manifestVersion.Minor, 0)
}
else {
$env:NextBuildVersion = $nextOnlineVersion
}
}
catch {
$env:NextBuildVersion = $manifestVersion
}
}
#endregion Setup
#region HarmonizeVariables
switch ($true) {
{ $IsWindows } {
$OS = "Windows"
if (-not ($IsCoreCLR)) {
$OSVersion = $PSVersionTable.BuildVersion.ToString()
}
}
{ $IsLinux } {
$OS = "Linux"
}
{ $IsMacOs } {
$OS = "OSX"
}
{ $IsCoreCLR } {
$OSVersion = $PSVersionTable.OS
}
}
#endregion HarmonizeVariables
#region DebugInformation
task ShowInfo Init, GetNextVersion, {
Write-Build Gray
Write-Build Gray ('Running in: {0}' -f $env:BHBuildSystem)
Write-Build Gray '-------------------------------------------------------'
Write-Build Gray
Write-Build Gray ('Project name: {0}' -f $env:BHProjectName)
Write-Build Gray ('Project root: {0}' -f $env:BHProjectPath)
Write-Build Gray ('Build Path: {0}' -f $env:BHBuildOutput)
Write-Build Gray ('Current (online) Version: {0}' -f $env:CurrentOnlineVersion)
Write-Build Gray '-------------------------------------------------------'
Write-Build Gray
Write-Build Gray ('Branch: {0}' -f $env:BHBranchName)
Write-Build Gray ('Commit: {0}' -f $env:BHCommitMessage)
Write-Build Gray ('Build #: {0}' -f $env:BHBuildNumber)
Write-Build Gray ('Next Version: {0}' -f $env:NextBuildVersion)
Write-Build Gray '-------------------------------------------------------'
Write-Build Gray
Write-Build Gray ('PowerShell version: {0}' -f $PSVersionTable.PSVersion.ToString())
Write-Build Gray ('OS: {0}' -f $OS)
Write-Build Gray ('OS Version: {0}' -f $OSVersion)
Write-Build Gray
}
#endregion DebugInformation
#region BuildRelease
# Synopsis: Build a shippable release
task Build Init, GenerateExternalHelp, CopyModuleFiles, UpdateManifest, CompileModule, PrepareTests
# Synopsis: Generate ./Release structure
task CopyModuleFiles {
# Setup
if (-not (Test-Path "$env:BHBuildOutput/$env:BHProjectName")) {
$null = New-Item -Path "$env:BHBuildOutput/$env:BHProjectName" -ItemType Directory
}
# Copy module
Copy-Item -Path "$env:BHModulePath/*" -Destination "$env:BHBuildOutput/$env:BHProjectName" -Recurse -Force
# Copy additional files
Copy-Item -Path @(
"$env:BHProjectPath/CHANGELOG.md"
"$env:BHProjectPath/LICENSE"
"$env:BHProjectPath/README.md"
) -Destination "$env:BHBuildOutput/$env:BHProjectName" -Force
}
# Synopsis: Prepare tests for ./Release
task PrepareTests Init, {
$null = New-Item -Path "$env:BHBuildOutput/Tests" -ItemType Directory -ErrorAction SilentlyContinue
Copy-Item -Path "$env:BHProjectPath/Tests" -Destination $env:BHBuildOutput -Recurse -Force
Copy-Item -Path "$env:BHProjectPath/PSScriptAnalyzerSettings.psd1" -Destination $env:BHBuildOutput -Force
}
# Synopsis: Compile all functions into the .psm1 file
task CompileModule Init, {
$regionsToKeep = @('Dependencies', 'Configuration')
$targetFile = "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psm1"
$content = Get-Content -Encoding UTF8 -LiteralPath $targetFile
$capture = $false
$compiled = ""
foreach ($line in $content) {
if ($line -match "^#region ($($regionsToKeep -join "|"))$") {
$capture = $true
}
if (($capture -eq $true) -and ($line -match "^#endregion")) {
$capture = $false
}
if ($capture) {
$compiled += "$line`r`n"
}
}
$PublicFunctions = @( Get-ChildItem -Path "$env:BHBuildOutput/$env:BHProjectName/Public/*.ps1" -ErrorAction SilentlyContinue )
$PrivateFunctions = @( Get-ChildItem -Path "$env:BHBuildOutput/$env:BHProjectName/Private/*.ps1" -ErrorAction SilentlyContinue )
foreach ($function in @($PublicFunctions + $PrivateFunctions)) {
$compiled += (Get-Content -Path $function.FullName -Raw)
$compiled += "`r`n"
}
Set-Content -LiteralPath $targetFile -Value $compiled -Encoding UTF8 -Force
Remove-Utf8Bom -Path $targetFile
"Private", "Public" | Foreach-Object { Remove-Item -Path "$env:BHBuildOutput/$env:BHProjectName/$_" -Recurse -Force }
}
# Synopsis: Use PlatyPS to generate External-Help
task GenerateExternalHelp Init, {
Import-Module platyPS -Force
foreach ($locale in (Get-ChildItem "$env:BHProjectPath/docs" -Attribute Directory)) {
New-ExternalHelp -Path "$($locale.FullName)" -OutputPath "$env:BHModulePath/$($locale.Basename)" -Force
New-ExternalHelp -Path "$($locale.FullName)/commands" -OutputPath "$env:BHModulePath/$($locale.Basename)" -Force
}
Remove-Module platyPS
}
# Synopsis: Update the manifest of the module
task UpdateManifest GetNextVersion, {
Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue
Import-Module $env:BHPSModuleManifest -Force
$ModuleAlias = @(Get-Alias | Where-Object { $_.ModuleName -eq "$env:BHProjectName" })
BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName ModuleVersion -Value $env:NextBuildVersion
# BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName FileList -Value (Get-ChildItem "$env:BHBuildOutput/$env:BHProjectName" -Recurse).Name
BuildHelpers\Set-ModuleFunctions -Name "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -FunctionsToExport ([string[]](Get-ChildItem "$env:BHBuildOutput/$env:BHProjectName/Public/*.ps1").BaseName)
BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName AliasesToExport -Value ''
if ($ModuleAlias) {
BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName AliasesToExport -Value @($ModuleAlias.Name)
}
}
# Synopsis: Create a ZIP file with this build
task Package Init, {
Assert-True { Test-Path "$env:BHBuildOutput\$env:BHProjectName" } "Missing files to package"
Remove-Item "$env:BHBuildOutput\$env:BHProjectName.zip" -ErrorAction SilentlyContinue
$null = Compress-Archive -Path "$env:BHBuildOutput\$env:BHProjectName" -DestinationPath "$env:BHBuildOutput\$env:BHProjectName.zip"
}
#endregion BuildRelease
#region Test
task Test Init, {
Assert-True { Test-Path $env:BHBuildOutput -PathType Container } "Release path must exist"
Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue
<# $params = @{
Path = "$env:BHBuildOutput/$env:BHProjectName"
Include = '*.ps1', '*.psm1'
Recurse = $True
Exclude = $CodeCoverageExclude
}
$codeCoverageFiles = Get-ChildItem @params #>
try {
$parameter = @{
Script = "$env:BHBuildOutput/Tests/*"
Tag = $Tag
ExcludeTag = $ExcludeTag
Show = "Fails"
PassThru = $true
OutputFile = "$env:BHProjectPath/Test-$OS-$($PSVersionTable.PSVersion.ToString()).xml"
OutputFormat = "NUnitXml"
# CodeCoverage = $codeCoverageFiles
}
$testResults = Invoke-Pester @parameter
Assert-True ($testResults.FailedCount -eq 0) "$($testResults.FailedCount) Pester test(s) failed."
}
catch {
throw $_
}
}, { Init }
#endregion
#region Publish
# Synopsis: Publish a new release on github and the PSGallery
task Deploy Init, PublishToGallery, TagReplository, UpdateHomepage
# Synpsis: Publish the $release to the PSGallery
task PublishToGallery {
Assert-True (-not [String]::IsNullOrEmpty($PSGalleryAPIKey)) "No key for the PSGallery"
Assert-True { Get-Module $env:BHProjectName -ListAvailable } "Module $env:BHProjectName is not available"
Remove-Module $env:BHProjectName -ErrorAction Ignore
Publish-Module -Name $env:BHProjectName -NuGetApiKey $PSGalleryAPIKey
}
# Synopsis: push a tag with the version to the git repository
task TagReplository GetNextVersion, Package, {
$releaseText = "Release version $env:NextBuildVersion"
Set-GitUser
# Push a tag to the repository
Write-Build Gray "git checkout $ENV:BHBranchName"
cmd /c "git checkout $ENV:BHBranchName 2>&1"
Write-Build Gray "git tag -a v$env:NextBuildVersion -m `"$releaseText`""
cmd /c "git tag -a v$env:NextBuildVersion -m `"$releaseText`" 2>&1"
Write-Build Gray "git push origin v$env:NextBuildVersion"
cmd /c "git push origin v$env:NextBuildVersion 2>&1"
Write-Build Gray "Publish v$env:NextBuildVersion as a GitHub release"
$release = @{
AccessToken = $GithubAccessToken
TagName = "v$env:NextBuildVersion"
Name = "Version $env:NextBuildVersion"
ReleaseText = $releaseText
RepositoryOwner = "AtlassianPS"
Artifact = "$env:BHBuildOutput\$env:BHProjectName.zip"
}
Publish-GithubRelease @release
}
# Synopsis: Update the version of this module that the homepage uses
task UpdateHomepage {
try {
Set-GitUser
Write-Build Gray "git close .../AtlassianPS.github.io --recursive"
$null = cmd /c "git clone https://github.com/AtlassianPS/AtlassianPS.github.io --recursive 2>&1"
Push-Location "AtlassianPS.github.io/"
Write-Build Gray "git submodule foreach git pull origin master"
$null = cmd /c "git submodule foreach git pull origin master 2>&1"
Write-Build Gray "git status -s"
$status = cmd /c "git status -s 2>&1"
if ($status -contains " M modules/$env:BHProjectName") {
Write-Build Gray "git add modules/$env:BHProjectName"
$null = cmd /c "git add modules/$env:BHProjectName 2>&1"
Write-Build Gray "git commit -m `"Update module $env:BHProjectName`""
cmd /c "git commit -m `"Update module $env:BHProjectName`" 2>&1"
Write-Build Gray "git push"
cmd /c "git push 2>&1"
}
Pop-Location
}
catch { Write-Warning "Failed to deploy to homepage" }
}
#endregion Publish
#region Cleaning tasks
# Synopsis: Clean the working dir
task Clean Init, RemoveGeneratedFiles, RemoveTestResults
# Synopsis: Remove generated and temp files.
task RemoveGeneratedFiles {
Remove-Item "$env:BHModulePath/en-US/*" -Force -ErrorAction SilentlyContinue
Remove-Item $env:BHBuildOutput -Force -Recurse -ErrorAction SilentlyContinue
}
# Synopsis: Remove Pester results
task RemoveTestResults {
Remove-Item "Test-*.xml" -Force -ErrorAction SilentlyContinue
}
#endregion
task . ShowInfo, Clean, Build, Test
Remove-Item -Path Env:\BH*
| Java |
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var seo = require('./lib/seo');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(seo);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
app.get('/loaderio-995e64d5aae415e1f10d60c9391e37ac/', function(req, res, next) {
res.send('loaderio-995e64d5aae415e1f10d60c9391e37ac');
});
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
var cacheBuster = function(req, res, next){
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
};
// @todo isolate to api routes...
app.use(cacheBuster);
// catch all which sends all urls to index page, thus starting our app
// @note that because Express routes are registered in order, and we already defined our api routes
// this catch all will not effect prior routes.
app.use(function(req, res, next) {
app.get('*', function(req, res, next) {
//return res.ok('catch all');
res.redirect('/#!' + req.url);
});
});
| Java |
# KnockGame
This sketch is responsible for the **Handshake** and **Knock** interfaces.
# External Libraries
## SerialCommand
https://github.com/kroimon/Arduino-SerialCommand
| Java |
#include <iostream>
#include <string>
#include <forward_list>
using namespace std;
void insert(forward_list<string>& fst, const string& to_find, const string& to_add);
int main() {
forward_list<string> fst{ "pen", "pineapple", "apple", "pen" };
insert(fst, "pen", "and");
for (auto& i : fst)
cout << i << " ";
cout << endl;
return 0;
}
void insert(forward_list<string>& fst, const string& to_find, const string& to_add) {
auto prev = fst.before_begin();
for (auto iter = fst.begin(); iter != fst.end(); prev = iter++) {
if (*iter == to_find) {
fst.insert_after(iter, to_add);
return;
}
}
fst.insert_after(prev, to_add);
return;
} | Java |
/*
* MIT License
*
* Copyright (c) 2017 Alessandro Arcangeli <alessandroarcangeli.rm@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mrkoopa.jfbx;
public interface FbxCameraStereo extends FbxCamera {
}
| Java |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToDB.Data
{
using Linq;
using Common;
using SqlProvider;
using SqlQuery;
public partial class DataConnection
{
IQueryRunner IDataContext.GetQueryRunner(Query query, int queryNumber, Expression expression, object[] parameters)
{
CheckAndThrowOnDisposed();
return new QueryRunner(query, queryNumber, this, expression, parameters);
}
internal class QueryRunner : QueryRunnerBase
{
public QueryRunner(Query query, int queryNumber, DataConnection dataConnection, Expression expression, object[] parameters)
: base(query, queryNumber, dataConnection, expression, parameters)
{
_dataConnection = dataConnection;
}
readonly DataConnection _dataConnection;
readonly DateTime _startedOn = DateTime.UtcNow;
readonly Stopwatch _stopwatch = Stopwatch.StartNew();
bool _isAsync;
Expression _mapperExpression;
public override Expression MapperExpression
{
get => _mapperExpression;
set
{
_mapperExpression = value;
if (value != null && Common.Configuration.Linq.TraceMapperExpression &&
TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.MapperCreated)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
IsAsync = _isAsync,
});
}
}
}
public override string GetSqlText()
{
SetCommand(false);
var sqlProvider = _preparedQuery.SqlProvider ?? _dataConnection.DataProvider.CreateSqlBuilder();
var sb = new StringBuilder();
sb.Append("-- ").Append(_dataConnection.ConfigurationString);
if (_dataConnection.ConfigurationString != _dataConnection.DataProvider.Name)
sb.Append(' ').Append(_dataConnection.DataProvider.Name);
if (_dataConnection.DataProvider.Name != sqlProvider.Name)
sb.Append(' ').Append(sqlProvider.Name);
sb.AppendLine();
sqlProvider.PrintParameters(sb, _preparedQuery.Parameters);
var isFirst = true;
foreach (var command in _preparedQuery.Commands)
{
sb.AppendLine(command);
if (isFirst && _preparedQuery.QueryHints != null && _preparedQuery.QueryHints.Count > 0)
{
isFirst = false;
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length--;
sb.AppendLine();
var sql = sb.ToString();
var sqlBuilder = _dataConnection.DataProvider.CreateSqlBuilder();
sql = sqlBuilder.ApplyQueryHints(sql, _preparedQuery.QueryHints);
sb = new StringBuilder(sql);
}
}
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length--;
sb.AppendLine();
return sb.ToString();
}
public override void Dispose()
{
if (TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.Completed)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
Command = _dataConnection.Command,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
RecordsAffected = RowsCount,
IsAsync = _isAsync,
});
}
base.Dispose();
}
public class PreparedQuery
{
public string[] Commands;
public List<SqlParameter> SqlParameters;
public IDbDataParameter[] Parameters;
public SqlStatement Statement;
public ISqlBuilder SqlProvider;
public List<string> QueryHints;
}
PreparedQuery _preparedQuery;
static PreparedQuery GetCommand(DataConnection dataConnection, IQueryContext query, int startIndent = 0)
{
if (query.Context != null)
{
return new PreparedQuery
{
Commands = (string[])query.Context,
SqlParameters = query.Statement.Parameters,
Statement = query.Statement,
QueryHints = query.QueryHints,
};
}
var sql = query.Statement.ProcessParameters(dataConnection.MappingSchema);
var newSql = dataConnection.ProcessQuery(sql);
if (!object.ReferenceEquals(sql, newSql))
{
sql = newSql;
sql.IsParameterDependent = true;
}
var sqlProvider = dataConnection.DataProvider.CreateSqlBuilder();
var cc = sqlProvider.CommandCount(sql);
var sb = new StringBuilder();
var commands = new string[cc];
for (var i = 0; i < cc; i++)
{
sb.Length = 0;
sqlProvider.BuildSql(i, sql, sb, startIndent);
commands[i] = sb.ToString();
}
if (!sql.IsParameterDependent)
query.Context = commands;
return new PreparedQuery
{
Commands = commands,
SqlParameters = sql.Parameters,
Statement = sql,
SqlProvider = sqlProvider,
QueryHints = query.QueryHints,
};
}
static void GetParameters(DataConnection dataConnection, IQueryContext query, PreparedQuery pq)
{
var parameters = query.GetParameters();
if (parameters.Length == 0 && pq.SqlParameters.Count == 0)
return;
var ordered = dataConnection.DataProvider.SqlProviderFlags.IsParameterOrderDependent;
var c = ordered ? pq.SqlParameters.Count : parameters.Length;
var parms = new List<IDbDataParameter>(c);
if (ordered)
{
for (var i = 0; i < pq.SqlParameters.Count; i++)
{
var sqlp = pq.SqlParameters[i];
if (sqlp.IsQueryParameter)
{
var parm = parameters.Length > i && object.ReferenceEquals(parameters[i], sqlp) ?
parameters[i] :
parameters.First(p => object.ReferenceEquals(p, sqlp));
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
}
else
{
foreach (var parm in parameters)
{
if (parm.IsQueryParameter && pq.SqlParameters.Contains(parm))
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
pq.Parameters = parms.ToArray();
}
static void AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm)
{
var p = dataConnection.Command.CreateParameter();
var systemType = parm.SystemType;
var dataType = parm.DataType;
var dbType = parm.DbType;
var dbSize = parm.DbSize;
var paramValue = parm.Value;
if (systemType == null)
{
if (paramValue != null)
systemType = paramValue.GetType();
}
if (dataType == DataType.Undefined)
{
dataType = dataConnection.MappingSchema.GetDataType(
parm.SystemType == typeof(object) && paramValue != null ?
paramValue.GetType() :
systemType).DataType;
}
dataConnection.DataProvider.SetParameter(p, name, new DbDataType(systemType, dataType, dbType, dbSize), paramValue);
parms.Add(p);
}
public static PreparedQuery SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent = 0)
{
var preparedQuery = GetCommand(dataConnection, queryContext, startIndent);
GetParameters(dataConnection, queryContext, preparedQuery);
return preparedQuery;
}
protected override void SetQuery()
{
_preparedQuery = SetQuery(_dataConnection, Query.Queries[QueryNumber]);
}
void SetCommand()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
}
#region ExecuteNonQuery
static int ExecuteNonQueryImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
if (preparedQuery.Commands.Length == 1)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteNonQuery();
}
var rowsAffected = -1;
for (var i = 0; i < preparedQuery.Commands.Length; i++)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[i], null, i == 0 ? preparedQuery.QueryHints : null);
if (i == 0 && preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
if (i < preparedQuery.Commands.Length - 1 && preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
dataConnection.ExecuteNonQuery();
}
catch (Exception)
{
}
}
else
{
var n = dataConnection.ExecuteNonQuery();
if (i == 0)
rowsAffected = n;
}
}
return rowsAffected;
}
public override int ExecuteNonQuery()
{
SetCommand(true);
return ExecuteNonQueryImpl(_dataConnection, _preparedQuery);
}
public static int ExecuteNonQuery(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
return ExecuteNonQueryImpl(dataConnection, preparedQuery);
}
#endregion
#region ExecuteScalar
static object ExecuteScalarImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
IDbDataParameter idParam = null;
if (dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired)
{
if (preparedQuery.Statement.NeedsIdentity())
{
idParam = dataConnection.Command.CreateParameter();
idParam.ParameterName = "IDENTITY_PARAMETER";
idParam.Direction = ParameterDirection.Output;
idParam.DbType = DbType.Decimal;
dataConnection.Command.Parameters.Add(idParam);
}
}
if (preparedQuery.Commands.Length == 1)
{
if (idParam != null)
{
// This is because the firebird provider does not return any parameters via ExecuteReader
// the rest of the providers must support this mode
dataConnection.ExecuteNonQuery();
return idParam.Value;
}
return dataConnection.ExecuteScalar();
}
dataConnection.ExecuteNonQuery();
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[1], null, null);
return dataConnection.ExecuteScalar();
}
public static object ExecuteScalar(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return ExecuteScalarImpl(dataConnection, preparedQuery);
}
public override object ExecuteScalar()
{
SetCommand();
return ExecuteScalarImpl(_dataConnection, _preparedQuery);
}
#endregion
#region ExecuteReader
public static IDataReader ExecuteReader(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteReader();
}
public override IDataReader ExecuteReader()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return _dataConnection.ExecuteReader();
}
#endregion
class DataReaderAsync : IDataReaderAsync
{
public DataReaderAsync(DbDataReader dataReader)
{
_dataReader = dataReader;
}
readonly DbDataReader _dataReader;
public IDataReader DataReader => _dataReader;
public Task<bool> ReadAsync(CancellationToken cancellationToken)
{
return _dataReader.ReadAsync(cancellationToken);
}
public void Dispose()
{
// call interface method, because at least MySQL provider incorrectly override
// methods for .net core 1x
DataReader.Dispose();
}
}
public override async Task<IDataReaderAsync> ExecuteReaderAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
base.SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
var dataReader = await _dataConnection.ExecuteReaderAsync(_dataConnection.GetCommandBehavior(CommandBehavior.Default), cancellationToken);
return new DataReaderAsync(dataReader);
}
public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
base.SetCommand(true);
if (_preparedQuery.Commands.Length == 1)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[0], null, _preparedQuery.QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
for (var i = 0; i < _preparedQuery.Commands.Length; i++)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[i], null, i == 0 ? _preparedQuery.QueryHints : null);
if (i == 0 && _preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
if (i < _preparedQuery.Commands.Length - 1 && _preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
catch
{
}
}
else
{
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
}
return -1;
}
public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
SetCommand();
IDbDataParameter idparam = null;
if (_dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired)
{
if (_preparedQuery.Statement.NeedsIdentity())
{
idparam = _dataConnection.Command.CreateParameter();
idparam.ParameterName = "IDENTITY_PARAMETER";
idparam.Direction = ParameterDirection.Output;
idparam.DbType = DbType.Decimal;
_dataConnection.Command.Parameters.Add(idparam);
}
}
if (_preparedQuery.Commands.Length == 1)
{
if (idparam != null)
{
// так сделано потому, что фаерберд провайдер не возвращает никаких параметров через ExecuteReader
// остальные провайдеры должны поддерживать такой режим
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
return idparam.Value;
}
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[1], null, null);
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
}
}
}
| Java |
# Swagger JSON
This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.

| Java |
/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include BOSS_WEBRTC_U_rtc_base__win32socketserver_h //original-code:"rtc_base/win32socketserver.h"
#include <ws2tcpip.h> // NOLINT
#include <algorithm>
#include BOSS_WEBRTC_U_rtc_base__byteorder_h //original-code:"rtc_base/byteorder.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
#include BOSS_WEBRTC_U_rtc_base__win32window_h //original-code:"rtc_base/win32window.h"
namespace rtc {
///////////////////////////////////////////////////////////////////////////////
// Win32Socket
///////////////////////////////////////////////////////////////////////////////
// TODO: Enable for production builds also? Use FormatMessage?
#if !defined(NDEBUG)
LPCSTR WSAErrorToString(int error, LPCSTR* description_result) {
LPCSTR string = "Unspecified";
LPCSTR description = "Unspecified description";
switch (error) {
case ERROR_SUCCESS:
string = "SUCCESS";
description = "Operation succeeded";
break;
case WSAEWOULDBLOCK:
string = "WSAEWOULDBLOCK";
description = "Using a non-blocking socket, will notify later";
break;
case WSAEACCES:
string = "WSAEACCES";
description = "Access denied, or sharing violation";
break;
case WSAEADDRNOTAVAIL:
string = "WSAEADDRNOTAVAIL";
description = "Address is not valid in this context";
break;
case WSAENETDOWN:
string = "WSAENETDOWN";
description = "Network is down";
break;
case WSAENETUNREACH:
string = "WSAENETUNREACH";
description = "Network is up, but unreachable";
break;
case WSAENETRESET:
string = "WSANETRESET";
description = "Connection has been reset due to keep-alive activity";
break;
case WSAECONNABORTED:
string = "WSAECONNABORTED";
description = "Aborted by host";
break;
case WSAECONNRESET:
string = "WSAECONNRESET";
description = "Connection reset by host";
break;
case WSAETIMEDOUT:
string = "WSAETIMEDOUT";
description = "Timed out, host failed to respond";
break;
case WSAECONNREFUSED:
string = "WSAECONNREFUSED";
description = "Host actively refused connection";
break;
case WSAEHOSTDOWN:
string = "WSAEHOSTDOWN";
description = "Host is down";
break;
case WSAEHOSTUNREACH:
string = "WSAEHOSTUNREACH";
description = "Host is unreachable";
break;
case WSAHOST_NOT_FOUND:
string = "WSAHOST_NOT_FOUND";
description = "No such host is known";
break;
}
if (description_result) {
*description_result = description;
}
return string;
}
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
LPCSTR description_string;
LPCSTR error_string = WSAErrorToString(error, &description_string);
RTC_LOG(LS_INFO) << context << " = " << error << " (" << error_string << ":"
<< description_string << ") [" << address.ToString() << "]";
}
#else
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
#endif
/////////////////////////////////////////////////////////////////////////////
// Win32Socket::EventSink
/////////////////////////////////////////////////////////////////////////////
#define WM_SOCKETNOTIFY (WM_USER + 50)
#define WM_DNSNOTIFY (WM_USER + 51)
struct Win32Socket::DnsLookup {
HANDLE handle;
uint16_t port;
char buffer[MAXGETHOSTSTRUCT];
};
class Win32Socket::EventSink : public Win32Window {
public:
explicit EventSink(Win32Socket* parent) : parent_(parent) {}
void Dispose();
bool OnMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) override;
void OnNcDestroy() override;
private:
bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
Win32Socket* parent_;
};
void Win32Socket::EventSink::Dispose() {
parent_ = nullptr;
if (::IsWindow(handle())) {
::DestroyWindow(handle());
} else {
delete this;
}
}
bool Win32Socket::EventSink::OnMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
switch (uMsg) {
case WM_SOCKETNOTIFY:
case WM_TIMER:
return OnSocketNotify(uMsg, wParam, lParam, result);
case WM_DNSNOTIFY:
return OnDnsNotify(wParam, lParam, result);
}
return false;
}
bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg,
WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
result = 0;
int wsa_event = WSAGETSELECTEVENT(lParam);
int wsa_error = WSAGETSELECTERROR(lParam);
// Treat connect timeouts as close notifications
if (uMsg == WM_TIMER) {
wsa_event = FD_CLOSE;
wsa_error = WSAETIMEDOUT;
}
if (parent_)
parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
return true;
}
bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam,
LPARAM lParam,
LRESULT& result) {
result = 0;
int error = WSAGETASYNCERROR(lParam);
if (parent_)
parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
return true;
}
void Win32Socket::EventSink::OnNcDestroy() {
if (parent_) {
RTC_LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
" hasn't yet been disposed.";
} else {
delete this;
}
}
/////////////////////////////////////////////////////////////////////////////
// Win32Socket
/////////////////////////////////////////////////////////////////////////////
Win32Socket::Win32Socket()
: socket_(INVALID_SOCKET),
error_(0),
state_(CS_CLOSED),
connect_time_(0),
closing_(false),
close_error_(0),
sink_(nullptr),
dns_(nullptr) {}
Win32Socket::~Win32Socket() {
Close();
}
bool Win32Socket::CreateT(int family, int type) {
Close();
int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0);
if (socket_ == INVALID_SOCKET) {
UpdateLastError();
return false;
}
if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
return false;
}
return true;
}
int Win32Socket::Attach(SOCKET s) {
RTC_DCHECK(socket_ == INVALID_SOCKET);
if (socket_ != INVALID_SOCKET)
return SOCKET_ERROR;
RTC_DCHECK(s != INVALID_SOCKET);
if (s == INVALID_SOCKET)
return SOCKET_ERROR;
socket_ = s;
state_ = CS_CONNECTED;
if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
return SOCKET_ERROR;
return 0;
}
void Win32Socket::SetTimeout(int ms) {
if (sink_)
::SetTimer(sink_->handle(), 1, ms, 0);
}
SocketAddress Win32Socket::GetLocalAddress() const {
sockaddr_storage addr = {0};
socklen_t addrlen = sizeof(addr);
int result =
::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen);
SocketAddress address;
if (result >= 0) {
SocketAddressFromSockAddrStorage(addr, &address);
} else {
RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
<< socket_;
}
return address;
}
SocketAddress Win32Socket::GetRemoteAddress() const {
sockaddr_storage addr = {0};
socklen_t addrlen = sizeof(addr);
int result =
::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen);
SocketAddress address;
if (result >= 0) {
SocketAddressFromSockAddrStorage(addr, &address);
} else {
RTC_LOG(LS_WARNING)
<< "GetRemoteAddress: unable to get remote addr, socket=" << socket_;
}
return address;
}
int Win32Socket::Bind(const SocketAddress& addr) {
RTC_DCHECK(socket_ != INVALID_SOCKET);
if (socket_ == INVALID_SOCKET)
return SOCKET_ERROR;
sockaddr_storage saddr;
size_t len = addr.ToSockAddrStorage(&saddr);
int err = ::bind(socket_, reinterpret_cast<sockaddr*>(&saddr),
static_cast<int>(len));
UpdateLastError();
return err;
}
int Win32Socket::Connect(const SocketAddress& addr) {
if (state_ != CS_CLOSED) {
SetError(EALREADY);
return SOCKET_ERROR;
}
if (!addr.IsUnresolvedIP()) {
return DoConnect(addr);
}
RTC_LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
DnsLookup* dns = new DnsLookup;
if (!sink_) {
// Explicitly create the sink ourselves here; we can't rely on SetAsync
// because we don't have a socket_ yet.
CreateSink();
}
// TODO: Replace with IPv6 compatible lookup.
dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
addr.hostname().c_str(), dns->buffer,
sizeof(dns->buffer));
if (!dns->handle) {
RTC_LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
delete dns;
UpdateLastError();
Close();
return SOCKET_ERROR;
}
dns->port = addr.port();
dns_ = dns;
state_ = CS_CONNECTING;
return 0;
}
int Win32Socket::DoConnect(const SocketAddress& addr) {
if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
return SOCKET_ERROR;
}
if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
return SOCKET_ERROR;
}
sockaddr_storage saddr = {0};
size_t len = addr.ToSockAddrStorage(&saddr);
connect_time_ = Time();
int result = connect(socket_, reinterpret_cast<SOCKADDR*>(&saddr),
static_cast<int>(len));
if (result != SOCKET_ERROR) {
state_ = CS_CONNECTED;
} else {
int code = WSAGetLastError();
if (code == WSAEWOULDBLOCK) {
state_ = CS_CONNECTING;
} else {
ReportWSAError("WSAAsync:connect", code, addr);
error_ = code;
Close();
return SOCKET_ERROR;
}
}
addr_ = addr;
return 0;
}
int Win32Socket::GetError() const {
return error_;
}
void Win32Socket::SetError(int error) {
error_ = error;
}
Socket::ConnState Win32Socket::GetState() const {
return state_;
}
int Win32Socket::GetOption(Option opt, int* value) {
int slevel;
int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1)
return -1;
char* p = reinterpret_cast<char*>(value);
int optlen = sizeof(value);
return ::getsockopt(socket_, slevel, sopt, p, &optlen);
}
int Win32Socket::SetOption(Option opt, int value) {
int slevel;
int sopt;
if (TranslateOption(opt, &slevel, &sopt) == -1)
return -1;
const char* p = reinterpret_cast<const char*>(&value);
return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
}
int Win32Socket::Send(const void* buffer, size_t length) {
int sent = ::send(socket_, reinterpret_cast<const char*>(buffer),
static_cast<int>(length), 0);
UpdateLastError();
return sent;
}
int Win32Socket::SendTo(const void* buffer,
size_t length,
const SocketAddress& addr) {
sockaddr_storage saddr;
size_t addr_len = addr.ToSockAddrStorage(&saddr);
int sent = ::sendto(
socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length),
0, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(addr_len));
UpdateLastError();
return sent;
}
int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) {
if (timestamp) {
*timestamp = -1;
}
int received =
::recv(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0);
UpdateLastError();
if (closing_ && received <= static_cast<int>(length))
PostClosed();
return received;
}
int Win32Socket::RecvFrom(void* buffer,
size_t length,
SocketAddress* out_addr,
int64_t* timestamp) {
if (timestamp) {
*timestamp = -1;
}
sockaddr_storage saddr;
socklen_t addr_len = sizeof(saddr);
int received =
::recvfrom(socket_, static_cast<char*>(buffer), static_cast<int>(length),
0, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
UpdateLastError();
if (received != SOCKET_ERROR)
SocketAddressFromSockAddrStorage(saddr, out_addr);
if (closing_ && received <= static_cast<int>(length))
PostClosed();
return received;
}
int Win32Socket::Listen(int backlog) {
int err = ::listen(socket_, backlog);
if (!SetAsync(FD_ACCEPT))
return SOCKET_ERROR;
UpdateLastError();
if (err == 0)
state_ = CS_CONNECTING;
return err;
}
Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
sockaddr_storage saddr;
socklen_t addr_len = sizeof(saddr);
SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
UpdateLastError();
if (s == INVALID_SOCKET)
return nullptr;
if (out_addr)
SocketAddressFromSockAddrStorage(saddr, out_addr);
Win32Socket* socket = new Win32Socket;
if (0 == socket->Attach(s))
return socket;
delete socket;
return nullptr;
}
int Win32Socket::Close() {
int err = 0;
if (socket_ != INVALID_SOCKET) {
err = ::closesocket(socket_);
socket_ = INVALID_SOCKET;
closing_ = false;
close_error_ = 0;
UpdateLastError();
}
if (dns_) {
WSACancelAsyncRequest(dns_->handle);
delete dns_;
dns_ = nullptr;
}
if (sink_) {
sink_->Dispose();
sink_ = nullptr;
}
addr_.Clear();
state_ = CS_CLOSED;
return err;
}
void Win32Socket::CreateSink() {
RTC_DCHECK(nullptr == sink_);
// Create window
sink_ = new EventSink(this);
sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10);
}
bool Win32Socket::SetAsync(int events) {
if (nullptr == sink_) {
CreateSink();
RTC_DCHECK(nullptr != sink_);
}
// start the async select
if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events) ==
SOCKET_ERROR) {
UpdateLastError();
Close();
return false;
}
return true;
}
bool Win32Socket::HandleClosed(int close_error) {
// WM_CLOSE will be received before all data has been read, so we need to
// hold on to it until the read buffer has been drained.
char ch;
closing_ = true;
close_error_ = close_error;
return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
}
void Win32Socket::PostClosed() {
// If we see that the buffer is indeed drained, then send the close.
closing_ = false;
::PostMessage(sink_->handle(), WM_SOCKETNOTIFY, socket_,
WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
}
void Win32Socket::UpdateLastError() {
error_ = WSAGetLastError();
}
int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
switch (opt) {
case OPT_DONTFRAGMENT:
*slevel = IPPROTO_IP;
*sopt = IP_DONTFRAGMENT;
break;
case OPT_RCVBUF:
*slevel = SOL_SOCKET;
*sopt = SO_RCVBUF;
break;
case OPT_SNDBUF:
*slevel = SOL_SOCKET;
*sopt = SO_SNDBUF;
break;
case OPT_NODELAY:
*slevel = IPPROTO_TCP;
*sopt = TCP_NODELAY;
break;
case OPT_DSCP:
RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
return -1;
default:
RTC_NOTREACHED();
return -1;
}
return 0;
}
void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
// Ignore events if we're already closed.
if (socket != socket_)
return;
error_ = error;
switch (event) {
case FD_CONNECT:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:connect notify", error, addr_);
#if !defined(NDEBUG)
int64_t duration = TimeSince(connect_time_);
RTC_LOG(LS_INFO) << "WSAAsync:connect error (" << duration
<< " ms), faking close";
#endif
state_ = CS_CLOSED;
// If you get an error connecting, close doesn't really do anything
// and it certainly doesn't send back any close notification, but
// we really only maintain a few states, so it is easiest to get
// back into a known state by pretending that a close happened, even
// though the connect event never did occur.
SignalCloseEvent(this, error);
} else {
#if !defined(NDEBUG)
int64_t duration = TimeSince(connect_time_);
RTC_LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
#endif
state_ = CS_CONNECTED;
SignalConnectEvent(this);
}
break;
case FD_ACCEPT:
case FD_READ:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:read notify", error, addr_);
} else {
SignalReadEvent(this);
}
break;
case FD_WRITE:
if (error != ERROR_SUCCESS) {
ReportWSAError("WSAAsync:write notify", error, addr_);
} else {
SignalWriteEvent(this);
}
break;
case FD_CLOSE:
if (HandleClosed(error)) {
ReportWSAError("WSAAsync:close notify", error, addr_);
state_ = CS_CLOSED;
SignalCloseEvent(this, error);
}
break;
}
}
void Win32Socket::OnDnsNotify(HANDLE task, int error) {
if (!dns_ || dns_->handle != task)
return;
uint32_t ip = 0;
if (error == 0) {
hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]);
ip = NetworkToHost32(net_ip);
}
RTC_LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString() << ", "
<< error << ")";
if (error == 0) {
SocketAddress address(ip, dns_->port);
error = DoConnect(address);
} else {
Close();
}
if (error) {
error_ = error;
SignalCloseEvent(this, error_);
} else {
delete dns_;
dns_ = nullptr;
}
}
///////////////////////////////////////////////////////////////////////////////
// Win32SocketServer
// Provides cricket base services on top of a win32 gui thread
///////////////////////////////////////////////////////////////////////////////
static UINT s_wm_wakeup_id = 0;
const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
Win32SocketServer::Win32SocketServer()
: wnd_(this), posted_(false), hdlg_(nullptr) {
if (s_wm_wakeup_id == 0)
s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) {
RTC_LOG_GLE(LS_ERROR) << "Failed to create message window.";
}
}
Win32SocketServer::~Win32SocketServer() {
if (wnd_.handle() != nullptr) {
KillTimer(wnd_.handle(), 1);
wnd_.Destroy();
}
}
Socket* Win32SocketServer::CreateSocket(int family, int type) {
return CreateAsyncSocket(family, type);
}
AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
Win32Socket* socket = new Win32Socket;
if (socket->CreateT(family, type)) {
return socket;
}
delete socket;
return nullptr;
}
void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
message_queue_ = queue;
}
bool Win32SocketServer::Wait(int cms, bool process_io) {
BOOL b;
if (process_io) {
// Spin the Win32 message pump at least once, and as long as requested.
// This is the Thread::ProcessMessages case.
uint32_t start = Time();
do {
MSG msg;
SetTimer(wnd_.handle(), 0, cms, nullptr);
// Get the next available message. If we have a modeless dialog, give
// give the message to IsDialogMessage, which will return true if it
// was a message for the dialog that it handled internally.
// Otherwise, dispatch as usual via Translate/DispatchMessage.
b = GetMessage(&msg, nullptr, 0, 0);
if (b == -1) {
RTC_LOG_GLE(LS_ERROR) << "GetMessage failed.";
return false;
} else if (b) {
if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(wnd_.handle(), 0);
} while (b && TimeSince(start) < cms);
} else if (cms != 0) {
// Sit and wait forever for a WakeUp. This is the Thread::Send case.
RTC_DCHECK(cms == -1);
MSG msg;
b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id);
{
CritScope scope(&cs_);
posted_ = false;
}
} else {
// No-op (cms == 0 && !process_io). This is the Pump case.
b = TRUE;
}
return (b != FALSE);
}
void Win32SocketServer::WakeUp() {
if (wnd_.handle()) {
// Set the "message pending" flag, if not already set.
{
CritScope scope(&cs_);
if (posted_)
return;
posted_ = true;
}
PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
}
}
void Win32SocketServer::Pump() {
// Clear the "message pending" flag.
{
CritScope scope(&cs_);
posted_ = false;
}
// Dispatch all the messages that are currently in our queue. If new messages
// are posted during the dispatch, they will be handled in the next Pump.
// We use max(1, ...) to make sure we try to dispatch at least once, since
// this allow us to process "sent" messages, not included in the size() count.
Message msg;
for (size_t max_messages_to_process =
std::max<size_t>(1, message_queue_->size());
max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
--max_messages_to_process) {
message_queue_->Dispatch(&msg);
}
// Anything remaining?
int delay = message_queue_->GetDelay();
if (delay == -1) {
KillTimer(wnd_.handle(), 1);
} else {
SetTimer(wnd_.handle(), 1, delay, nullptr);
}
}
bool Win32SocketServer::MessageWindow::OnMessage(UINT wm,
WPARAM wp,
LPARAM lp,
LRESULT& lr) {
bool handled = false;
if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
ss_->Pump();
lr = 0;
handled = true;
}
return handled;
}
Win32Thread::Win32Thread(SocketServer* ss) : Thread(ss), id_(0) {}
Win32Thread::~Win32Thread() {
Stop();
}
void Win32Thread::Run() {
id_ = GetCurrentThreadId();
Thread::Run();
id_ = 0;
}
void Win32Thread::Quit() {
PostThreadMessage(id_, WM_QUIT, 0, 0);
}
} // namespace rtc
| Java |
class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
""":type: list[R]"""
for c in p:
if c == '*':
rs[-1].is_star = True
else:
rs.append(R(c))
lr = len(rs)
ls = len(s)
s += '\0'
dp = [[False] * (ls + 1) for _ in range(lr + 1)]
dp[0][0] = True
for i, r in enumerate(rs):
for j in range(ls + 1):
c = s[j - 1]
if r.is_star:
dp[i + 1][j] = dp[i][j]
if j and r.match(c):
dp[i + 1][j] |= dp[i + 1][j - 1]
else:
if j and r.match(c):
dp[i + 1][j] = dp[i][j - 1]
return dp[-1][-1]
| Java |
# escape=`
FROM mcr.microsoft.com/windows/servercore as msi
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ENV MONGO_VERSION 3.4.5
ENV MONGO_DOWNLOAD_URL https://downloads.mongodb.com/win32/mongodb-win32-x86_64-enterprise-windows-64-${MONGO_VERSION}-signed.msi
ENV MONGO_DOWNLOAD_SHA256 cda1c8d547fc6051d7bbe2953f9a75bced846ac64a733726f8443835db5b2901
RUN Write-Host ('Downloading {0} ...' -f $env:MONGO_DOWNLOAD_URL)
RUN Invoke-WebRequest -Uri $env:MONGO_DOWNLOAD_URL -OutFile 'mongodb.msi'
RUN Write-Host ('Verifying sha256 ({0}) ...' -f $env:MONGO_DOWNLOAD_SHA256)
RUN if ((Get-FileHash mongodb.msi -Algorithm sha256).Hash -ne $env:MONGO_DOWNLOAD_SHA256) { `
Write-Host 'FAILED!'; `
exit 1; `
}
RUN Start-Process msiexec.exe -ArgumentList '/i', 'mongodb.msi', '/quiet', '/norestart', 'INSTALLLOCATION=C:\mongodb', 'ADDLOCAL=Server,Client,MonitoringTools,ImportExportTools,MiscellaneousTools' -NoNewWindow -Wait
RUN Remove-Item C:\mongodb\bin\*.pdb
FROM mcr.microsoft.com/windows/nanoserver:sac2016
COPY --from=msi C:\mongodb\ C:\mongodb\
COPY --from=msi C:\windows\system32\msvcp140.dll C:\windows\system32
COPY --from=msi C:\windows\system32\vcruntime140.dll C:\windows\system32
COPY --from=msi C:\windows\system32\wininet.dll C:\windows\system32
RUN mkdir C:\data\db & setx /m PATH %PATH%;C:\mongodb\bin
VOLUME C:\data\db
EXPOSE 27017
CMD ["mongod.exe"]
| Java |
namespace GameBoySharp.Domain.Contracts
{
public interface IContiguousMemory : IReadableMemory, IWriteableMemory
{
}
} | Java |
public class App {
public static void main(String[] args) {
System.out.println("Old man, look at my life...");
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Thu Jan 05 15:34:48 PST 2017 -->
<title>Uses of Class main.CurrentDateAndTime</title>
<meta name="date" content="2017-01-05">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class main.CurrentDateAndTime";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../main/package-summary.html">Package</a></li>
<li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li>
<li><a href="CurrentDateAndTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class main.CurrentDateAndTime" class="title">Uses of Class<br>main.CurrentDateAndTime</h2>
</div>
<div class="classUseContainer">No usage of main.CurrentDateAndTime</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../main/package-summary.html">Package</a></li>
<li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li>
<li><a href="CurrentDateAndTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
version https://git-lfs.github.com/spec/v1
oid sha256:83b131c4d8b0acf16d0579e177572a462b114180f95c7444ebae08cb7370e68f
size 3656
| Java |
var score = 0;
var scoreText;
var map_x = 14;
var map_y = 10;
var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update });
function preload() {
// game.scale.maxWidth = 600;
// game.scale.maxHeight = 600;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.setScreenSize();
game.load.image('cat', 'assets/cat.png', 16, 16);
game.load.image('ground', 'assets/darkfloor.png', 16, 16);
game.load.image('l_wall', 'assets/l_wall.png', 16, 16);
game.load.image('r_wall', 'assets/r_wall.png', 16, 16);
game.load.image('t_wall', 'assets/t_wall.png', 16, 16);
game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16);
game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16);
game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16);
game.load.image('br_wall', 'assets/br_wall.png', 16, 16);
game.load.image('stone_door', 'assets/door_stone.png', 16, 16);
game.load.image('star', 'assets/star.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
// the game world
gmap = game.add.tilemap();
gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0);
gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1);
gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2);
gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3);
gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4);
gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5);
gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6);
gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7);
gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8);
ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16);
wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16);
for (var i=0; i<map_x; i++) {
for(var j=0; j<map_y; j++) {
if (i==0 && j==0) {
gmap.putTile(4, i, j, wall_layer);
} else if (i==map_x/2 && j==0) {
gmap.putTile(8, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(5, i, j, wall_layer);
} else if (i==0 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==map_x-1 && j == 0) {
gmap.putTile(3, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==0) {
gmap.putTile(1, i, j, wall_layer);
} else if(i==map_x-1) {
gmap.putTile(2, i, j, wall_layer);
} else if(j==map_y-1) {
gmap.putTile(7, i, j, wall_layer);
} else if(j==0) {
gmap.putTile(7, i, j, wall_layer);
} else {
gmap.putTile(0, i, j, ground_layer);
}
}
}
wall_layer.resizeWorld();
game.physics.arcade.enable(wall_layer);
gmap.setCollision(wall_layer);
// the player
player = game.add.sprite(32, 32, 'cat');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
// gmap.setCollisionBetween(0, 100, true, wall_layer);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collide(player, wall_layer);
player.body.velocity.x = 0;
player.body.velocity.y = 0;
if (cursors.left.isDown) {
player.body.velocity.x = -150;
} else if (cursors.right.isDown) {
player.body.velocity.x = 150;
} else if (cursors.down.isDown) {
player.body.velocity.y = 150;
} else if (cursors.up.isDown) {
player.body.velocity.y = -150;
} else {
}
}
| Java |
package com.thebluealliance.androidclient.gcm.notifications;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.activities.ViewMatchActivity;
import com.thebluealliance.androidclient.datafeed.JSONManager;
import com.thebluealliance.androidclient.helpers.EventHelper;
import com.thebluealliance.androidclient.helpers.MatchHelper;
import com.thebluealliance.androidclient.helpers.MyTBAHelper;
import com.thebluealliance.androidclient.listeners.GamedayTickerClickListener;
import com.thebluealliance.androidclient.models.BasicModel;
import com.thebluealliance.androidclient.models.Match;
import com.thebluealliance.androidclient.models.StoredNotification;
import com.thebluealliance.androidclient.views.MatchView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Nathan on 7/24/2014.
*/
public class ScoreNotification extends BaseNotification {
private String eventName, eventKey, matchKey;
private Match match;
public ScoreNotification(String messageData) {
super("score", messageData);
}
@Override
public void parseMessageData() throws JsonParseException {
JsonObject jsonData = JSONManager.getasJsonObject(messageData);
if (!jsonData.has("match")) {
throw new JsonParseException("Notification data does not contain 'match");
}
JsonObject match = jsonData.get("match").getAsJsonObject();
this.match = gson.fromJson(match, Match.class);
try {
this.matchKey = this.match.getKey();
} catch (BasicModel.FieldNotDefinedException e) {
e.printStackTrace();
}
this.eventKey = MatchHelper.getEventKeyFromMatchKey(matchKey);
if (!jsonData.has("event_name")) {
throw new JsonParseException("Notification data does not contain 'event_name");
}
eventName = jsonData.get("event_name").getAsString();
}
@Override
public Notification buildNotification(Context context) {
Resources r = context.getResources();
String matchKey;
try {
matchKey = match.getKey();
this.matchKey = matchKey;
} catch (BasicModel.FieldNotDefinedException e) {
Log.e(getLogTag(), "Incoming Match object does not have a key. Can't post score update");
e.printStackTrace();
return null;
}
String matchTitle = MatchHelper.getMatchTitleFromMatchKey(context, matchKey);
String matchAbbrevTitle = MatchHelper.getAbbrevMatchTitleFromMatchKey(context, matchKey);
JsonObject alliances;
try {
alliances = match.getAlliances();
} catch (BasicModel.FieldNotDefinedException e) {
Log.e(getLogTag(), "Incoming match object does not contain alliance data. Can't post score update");
e.printStackTrace();
return null;
}
int redScore = Match.getRedScore(alliances);
ArrayList<String> redTeamKeys = new ArrayList<>();
JsonArray redTeamsJson = Match.getRedTeams(alliances);
for (int i = 0; i < redTeamsJson.size(); i++) {
redTeamKeys.add(redTeamsJson.get(i).getAsString());
}
int blueScore = Match.getBlueScore(alliances);
ArrayList<String> blueTeamKeys = new ArrayList<>();
JsonArray blueTeamsJson = Match.getBlueTeams(alliances);
for (int i = 0; i < blueTeamsJson.size(); i++) {
blueTeamKeys.add(blueTeamsJson.get(i).getAsString());
}
// TODO filter out teams that the user doesn't want notifications about
// These arrays hold the numbers of teams that the user cares about
ArrayList<String> redTeams = new ArrayList<>();
ArrayList<String> blueTeams = new ArrayList<>();
for (String key : redTeamKeys) {
redTeams.add(key.replace("frc", ""));
}
for (String key : blueTeamKeys) {
blueTeams.add(key.replace("frc", ""));
}
// Make sure the score string is formatted properly with the winning score first
String scoreString;
if (redScore > blueScore) {
scoreString = redScore + "-" + blueScore;
} else if (redScore < blueScore) {
scoreString = blueScore + "-" + redScore;
} else {
scoreString = redScore + "-" + redScore;
}
String redTeamString = Utilities.stringifyListOfStrings(context, redTeams);
String blueTeamString = Utilities.stringifyListOfStrings(context, blueTeams);
boolean useSpecial2015Format;
try {
useSpecial2015Format = match.getYear() == 2015 && match.getType() != MatchHelper.TYPE.FINAL;
} catch (BasicModel.FieldNotDefinedException e) {
useSpecial2015Format = false;
Log.w(Constants.LOG_TAG, "Couldn't determine if we should use 2015 score format. Defaulting to no");
}
String eventShortName = EventHelper.shortName(eventName);
String notificationString;
if (redTeams.size() == 0 && blueTeams.size() == 0) {
// We must have gotten this GCM message by mistake
return null;
} else if (useSpecial2015Format) {
/* Only for 2015 non-finals matches. Ugh */
notificationString = context.getString(R.string.notification_score_2015_no_winner, eventShortName, matchTitle, redTeamString, redScore, blueTeamString, blueScore);
} else if ((redTeams.size() > 0 && blueTeams.size() == 0)) {
// The user only cares about some teams on the red alliance
if (redScore > blueScore) {
// Red won
notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, redTeamString, matchTitle, scoreString);
} else if (redScore < blueScore) {
// Red lost
notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, redTeamString, matchTitle, scoreString);
} else {
// Red tied
notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, redTeamString, matchTitle, scoreString);
}
} else if ((blueTeams.size() > 0 && redTeams.size() == 0)) {
// The user only cares about some teams on the blue alliance
if (blueScore > redScore) {
// Blue won
notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, blueTeamString, matchTitle, scoreString);
} else if (blueScore < redScore) {
// Blue lost
notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, blueTeamString, matchTitle, scoreString);
} else {
// Blue tied
notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, blueTeamString, matchTitle, scoreString);
}
} else if ((blueTeams.size() > 0 && redTeams.size() > 0)) {
// The user cares about teams on both alliances
if (blueScore > redScore) {
// Blue won
notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, blueTeamString, redTeamString, matchTitle, scoreString);
} else if (blueScore < redScore) {
// Blue lost
notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString);
} else {
// Blue tied
notificationString = context.getString(R.string.notification_score_teams_tied_with_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString);
}
} else {
// We should never, ever get here but if we do...
return null;
}
// We can finally build the notification!
Intent instance = getIntent(context);
stored = new StoredNotification();
stored.setType(getNotificationType());
String eventCode = EventHelper.getEventCode(matchKey);
String notificationTitle = r.getString(R.string.notification_score_title, eventCode, matchAbbrevTitle);
stored.setTitle(notificationTitle);
stored.setBody(notificationString);
stored.setIntent(MyTBAHelper.serializeIntent(instance));
stored.setTime(Calendar.getInstance().getTime());
NotificationCompat.Builder builder = getBaseBuilder(context, instance)
.setContentTitle(notificationTitle)
.setContentText(notificationString)
.setLargeIcon(getLargeIconFormattedForPlatform(context, R.drawable.ic_info_outline_white_24dp));
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle().bigText(notificationString);
builder.setStyle(style);
return builder.build();
}
@Override
public void updateDataLocally(Context c) {
if (match != null) {
match.write(c);
}
}
@Override
public Intent getIntent(Context c) {
return ViewMatchActivity.newInstance(c, matchKey);
}
@Override
public int getNotificationId() {
return (new Date().getTime() + ":" + getNotificationType() + ":" + matchKey).hashCode();
}
@Override
public View getView(Context c, LayoutInflater inflater, View convertView) {
ViewHolder holder;
if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) {
convertView = inflater.inflate(R.layout.list_item_notification_score, null, false);
holder = new ViewHolder();
holder.header = (TextView) convertView.findViewById(R.id.card_header);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.matchView = (MatchView) convertView.findViewById(R.id.match_details);
holder.time = (TextView) convertView.findViewById(R.id.notification_time);
holder.summaryContainer = convertView.findViewById(R.id.summary_container);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.header.setText(c.getString(R.string.gameday_ticker_event_title_format, EventHelper.shortName(eventName), EventHelper.getShortCodeForEventKey(eventKey).toUpperCase()));
holder.title.setText(c.getString(R.string.notification_score_gameday_title, MatchHelper.getMatchTitleFromMatchKey(c, matchKey)));
holder.time.setText(getNotificationTimeString(c));
holder.summaryContainer.setOnClickListener(new GamedayTickerClickListener(c, this));
match.render(false, false, false, true).getView(c, inflater, holder.matchView);
return convertView;
}
private class ViewHolder {
public TextView header;
public TextView title;
public MatchView matchView;
public TextView time;
private View summaryContainer;
}
}
| Java |
import { expect } from 'chai';
import { Curry } from './curry';
describe('curry', () => {
it('should curry the method with default arity', () => {
class MyClass {
@Curry()
add(a: any, b?: any) {
return a + b;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10)).to.equal(15);
});
it('should curry the method with default arity (paramless)', () => {
class MyClass {
@Curry
add(a: any, b?: any) {
return a + b;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10)).to.equal(15);
});
it('should curry the method with fixed arity', () => {
class MyClass {
@Curry(2)
add(a: any, b?: any, c?: any) {
return a + b * c;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5).to.be.an.instanceOf(Function);
expect(add5(10, 2)).to.equal(25);
});
it('should retain the class context', () => {
class MyClass {
value = 10;
@Curry()
add(a: any, b?: any): any {
return (a + b) * this.value;
}
}
const myClass = new MyClass();
const add5 = myClass.add(5);
expect(add5(2)).to.equal(70);
});
});
| Java |
module Fog
module XenServer
class Compute
module Models
class CrashDumps < Collection
model Fog::XenServer::Compute::Models::CrashDump
end
end
end
end
end | Java |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DebugWindow : MonoBehaviour {
public Text textWindow;
string freshInput;
// Use this for initialization
void Start () {
if (textWindow == null)
throw new UnityException ("Debug Window has no text box to output to.");
}
// Update is called once per frame
void Update () {
textWindow.text = "Debug:\n" + freshInput;
freshInput = "";
}
public void LOG(string Text)
{
freshInput += Text + '\n';
}
}
| Java |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionTranslators.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.Internal;
namespace Pomelo.EntityFrameworkCore.MySql.Json.Microsoft.Query.Internal
{
public class MySqlJsonMicrosoftMemberTranslatorPlugin : IMemberTranslatorPlugin
{
public MySqlJsonMicrosoftMemberTranslatorPlugin(
IRelationalTypeMappingSource typeMappingSource,
ISqlExpressionFactory sqlExpressionFactory,
IMySqlJsonPocoTranslator jsonPocoTranslator)
{
var mySqlSqlExpressionFactory = (MySqlSqlExpressionFactory)sqlExpressionFactory;
var mySqlJsonPocoTranslator = (MySqlJsonPocoTranslator)jsonPocoTranslator;
Translators = new IMemberTranslator[]
{
new MySqlJsonMicrosoftDomTranslator(
mySqlSqlExpressionFactory,
typeMappingSource,
mySqlJsonPocoTranslator),
jsonPocoTranslator,
};
}
public virtual IEnumerable<IMemberTranslator> Translators { get; }
}
}
| Java |
export { default } from 'ember-flexberry-gis/services/map-store';
| Java |
from flask import Flask, render_template, flash
from flask_material_lite import Material_Lite
from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from flask_wtf.file import FileField
from wtforms import TextField, HiddenField, ValidationError, RadioField,\
BooleanField, SubmitField, IntegerField, FormField, validators
from wtforms.validators import Required
# straight from the wtforms docs:
class TelephoneForm(Form):
country_code = IntegerField('Country Code', [validators.required()])
area_code = IntegerField('Area Code/Exchange', [validators.required()])
number = TextField('Number')
class ExampleForm(Form):
field1 = TextField('First Field', description='This is field one.')
field2 = TextField('Second Field', description='This is field two.',
validators=[Required()])
hidden_field = HiddenField('You cannot see this', description='Nope')
recaptcha = RecaptchaField('A sample recaptcha field')
radio_field = RadioField('This is a radio field', choices=[
('head_radio', 'Head radio'),
('radio_76fm', "Radio '76 FM"),
('lips_106', 'Lips 106'),
('wctr', 'WCTR'),
])
checkbox_field = BooleanField('This is a checkbox',
description='Checkboxes can be tricky.')
# subforms
mobile_phone = FormField(TelephoneForm)
# you can change the label as well
office_phone = FormField(TelephoneForm, label='Your office phone')
ff = FileField('Sample upload')
submit_button = SubmitField('Submit Form')
def validate_hidden_field(form, field):
raise ValidationError('Always wrong')
def create_app(configfile=None):
app = Flask(__name__)
AppConfig(app, configfile) # Flask-Appconfig is not necessary, but
# highly recommend =)
# https://github.com/mbr/flask-appconfig
Material_Lite(app)
# in a real app, these should be configured through Flask-Appconfig
app.config['SECRET_KEY'] = 'devkey'
app.config['RECAPTCHA_PUBLIC_KEY'] = \
'6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw'
@app.route('/', methods=('GET', 'POST'))
def index():
form = ExampleForm()
form.validate_on_submit() # to get error messages to the browser
flash('critical message', 'critical')
flash('error message', 'error')
flash('warning message', 'warning')
flash('info message', 'info')
flash('debug message', 'debug')
flash('different message', 'different')
flash('uncategorized message')
return render_template('index.html', form=form)
return app
if __name__ == '__main__':
create_app().run(debug=True)
| Java |
#!/usr/bin/env python3
from __future__ import print_function, division
import numpy as np
from sht.grids import standard_grid, get_cartesian_grid
def test_grids():
L = 10
thetas, phis = standard_grid(L)
# Can't really test much here
assert thetas.size == L
assert phis.size == L**2
grid = get_cartesian_grid(thetas, phis)
assert grid.shape == (L**2, 3)
| Java |
This is an older post
| Java |
var Keyboard_Space = new function(){
this.initKeyboard = function(testing){
testmode = testing;
return new Keyboard();
}
var Keyboard = function(){
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
var this_obj = this;
Zip_Space.loadZip(currentSongData["filename"], function() {
this_obj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
this_obj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
this_obj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
this_obj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
this_obj.backend = BackendSpace.init();
this_obj.keyboardUI = Keyboard_UI_Space.initKeyboardUI();
console.log("New keyboard created");
})
}
// link the keyboard and the editor
Keyboard.prototype.linkEditor = function(editor){
this.editor = editor;
var mainObj = this;
setTimeout(function(){mainObj.editor.setBPM(currentSongData.bpm)},500);
}
Keyboard.prototype.getCurrentSounds = function(){
return currentSounds;
}
// loads sounds from srcArray for given chain into soundArr
Keyboard.prototype.loadSounds = function(srcArr, soundArr, chain){
for(var i = 0; i < srcArr.length; i++)
soundArr.push(null);
for(var i = 0; i < srcArr.length; i++){
if(srcArr[i] == "")
this.checkLoaded();
else
this.requestSound(i, srcArr, soundArr, chain);
}
}
// makes request for sounds
// if offline version, gets from local files
// if online version, gets from public folder
Keyboard.prototype.requestSound = function(i, srcArr, soundArr, chain){
var thisObj = this;
soundArr[i] = new Howl({
// for online version
urls: [Zip_Space.dataArray['sounds/chain'+chain+'/'+srcArr[i]+'.mp3']],
// old
// urls: [currentSongData["soundUrls"]["chain"+chain][srcArr[i]].replace("www.dropbox.com","dl.dropboxusercontent.com").replace("?dl=0","")],
// for offline version
// urls: ["audio/chain"+chain+"/"+srcArr[i]+".mp3"],
onload: function(){
thisObj.checkLoaded();
},
onloaderror: function(id, error){
console.log('error: '+id)
console.log(error);
console.log('sounds/chain'+chain+'/'+srcArr[i]+'.mp3');
$("#error_msg").html("There was an error. Please try clearing your browser's cache and reload the page.");
}
});
}
// checks if all of the sounds have loaded
// if they have, load the keyboard
Keyboard.prototype.checkLoaded = function(){
numSoundsLoaded++;
$(".soundPack").html("Loading sounds ("+numSoundsLoaded+"/"+(4*12*numChains)+")");
if(numSoundsLoaded == 4*12*numChains){
loadingSongs = false;
this.keyboardUI.loadKeyboard(this, currentSongData, currentSoundPack);
}
}
Keyboard.prototype.getKeyInd = function(kc){
var keyInd = keyPairs.indexOf(kc);
if(keyInd == -1)
keyInd = backupPairs.indexOf(kc);
return keyInd;
}
Keyboard.prototype.switchSoundPackCheck = function(kc){
// up
if(kc == 39){
this.switchSoundPack(3);
return true;
}
// left
else if(kc == 37){
this.switchSoundPack(0);
return true;
}
// down
else if(kc == 38){
this.switchSoundPack(1);
return true;
}
// right
else if(kc == 40){
this.switchSoundPack(2);
return true;
}
}
// switch sound pack and update pressures
Keyboard.prototype.switchSoundPack = function(sp){
// release all keys
for(var i = 0; i < 4; i++)
for(var j = 0; j < 12; j++)
if($(".button-"+(i*12+j)+"").attr("released") == "false")
this.releaseKey(keyPairs[i*12+j]);
// set the new soundpack
currentSoundPack = sp;
$(".sound_pack_button").css("background-color","white");
$(".sound_pack_button_"+(currentSoundPack+1)).css("background-color","rgb(255,160,0)");
$(".soundPack").html("Sound Pack: "+(currentSoundPack+1));
// set pressures for buttons in new sound pack
for(var i = 0; i < 4; i++){
for(var j = 0; j < 12; j++){
var press = false;
if(currentSongData["holdToPlay"]["chain"+(currentSoundPack+1)].indexOf((i*12+j)) != -1)
press = true;
$('.button-'+(i*12+j)+'').attr("pressure", ""+press+"");
// holdToPlay coloring, turned off for now
//$('.button-'+(i*12+j)+'').css("background-color", $('.button-'+(i*12+j)+'').attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// key released
// stop playing sound if holdToPlay
Keyboard.prototype.releaseKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyUp(kc);
// send key code to MIDI editor
this.editor.recordKeyUp(kc);
}
}
Keyboard.prototype.midiKeyUp = function(kc){
if(this.switchSoundPackCheck(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
if($(".button-"+(kcInd)+"").attr("pressure") == "true")
currentSounds[currentSoundPack][kcInd].stop();
$(".button-"+(kcInd)+"").attr("released","true");
// holdToPlay coloring, turned off for now
// Removes Style Attribute to clean up HTML
$(".button-"+(kcInd)+"").removeAttr("style");
if($(".button-"+(kcInd)+"").hasClass("pressed") == true)
$(".button-"+(kcInd)+"").removeClass("pressed");
//$(".button-"+(kcInd)+"").css("background-color", $(".button-"+(kcInd)+"").attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// play the key by finding the mapping,
// stopping all sounds in key's linkedArea
// and then playing sound
Keyboard.prototype.playKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyDown(kc);
// send key code to midi editor
this.editor.recordKeyDown(kc);
}
}
Keyboard.prototype.midiKeyDown = function(kc){
if(this.switchSoundPackCheck(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
currentSounds[currentSoundPack][kcInd].stop();
currentSounds[currentSoundPack][kcInd].play();
// go through all linked Areas in current chain
currentSongData["linkedAreas"]["chain"+(currentSoundPack+1)].forEach(function(el, ind, arr){
// for ever linked area array
for(var j = 0; j < el.length; j++){
// if key code is in linked area array
if(kcInd == el[j]){
// stop all other sounds in linked area array
for(var k = 0; k < el.length; k++){
if(k != j)
currentSounds[currentSoundPack][el[k]].stop();
}
break;
}
}
});
// set button color and attribute
$(".button-"+(kcInd)+"").addClass("pressed");
$(".button-"+(kcInd)+"").attr("released","false");
//$(".button-"+(kcInd)+"").css("background-color","rgb(255,160,0)");
}
}
}
// shows and formats all of the UI elements
Keyboard.prototype.initUI = function(){
// create new editor and append it to the body element
if(testmode)
BasicMIDI.init("#editor_container_div", this, 170);
else
MIDI_Editor.init("#editor_container_div", this, 170);
// info and links buttons
// $(".click_button").css("display", "inline-block");
for(var s in songDatas)
$("#songs_container").append("<div class='song_selection' songInd='"+s+"'>"+songDatas[s].song_name+"</div>");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
var mainObj = this;
$(".song_selection").click(function() {
var tempS = parseInt($(this).attr("songInd"));
if(tempS != currentSongInd && !loadingSongs){
loadingSongs = true;
currentSongInd = tempS
currentSongData = songDatas[currentSongInd];
$(".song_selection").css("background-color","white");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
$(".button-row").remove();
for(var i = 0; i < currentSounds.length; i++){
for(var k = 0; k < currentSounds[i].length; k++){
if(currentSounds[i][k] != null)
currentSounds[i][k].unload();
}
}
currentSounds = [];
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
mainObj.editor.notesLoaded([],-1);
mainObj.editor.setBPM(currentSongData.bpm)
numSoundsLoaded = 0;
Zip_Space.loadZip(currentSongData["filename"], function() {
mainObj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
mainObj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
mainObj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
mainObj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
})
}
});
}
// send request to server to save the notes to the corresponding projectId (pid)
Keyboard.prototype.saveNotes = function(notes, pid){
var saveNote = [];
for(var n in notes)
saveNote.push({"note":notes[n].note, "beat":notes[n].beat, "length":notes[n].length});
//console.log(saveNote);
this.backend.saveSong(JSON.stringify(saveNote), pid, this.editor, currentSongData.song_number);
}
// ask the user for the project they would like to load and then load that project from the server
// send back a notes array of the loaded project with note,beat,and length and the project id
Keyboard.prototype.loadNotes = function(){
this.backend.loadSongs(this.editor, currentSongData.song_number);
}
// current soundpack (0-3)
var currentSoundPack = 0;
// number of sounds loaded
var numSoundsLoaded = 0;
// howl objects for current song
var currentSounds = [];
// reference to current song data
var songDatas = [equinoxData, animalsData, electroData, ghetData, kyotoData, aeroData];
var currentSongInd = 0;
var currentSongData = equinoxData;
// number of chains
var numChains = 4;
var testmode = false;
var loadingSongs = true;
}
// Global Variables
// ascii key mappings to array index
var keyPairs = [49,50,51,52,53,54,55,56,57,48,189,187,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,186,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// alternate keys for firefox
var backupPairs = [49,50,51,52,53,54,55,56,57,48,173,61,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,59,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// letter to show in each button
var letterPairs = ["1","2","3","4","5","6","7","8","9","0","-","=",
"Q","W","E","R","T","Y","U","I","O","P","[","]",
"A","S","D","F","G","H","J","K","L",";","'","\\n",
"Z","X","C","V","B","N","M",",",".","/","\\s","NA"]; | Java |
angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books-table.html'
};
})
.directive('userTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-table.html'
};
})
.directive('userProfileInfo', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-profile-info.html'
};
})
.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}]); | Java |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<div th:fragment="common-header">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>WickedThymeleafDemo</title>
<link th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet" media="screen"/>
<link type="text/css" th:href="@{/css/styles.css}" rel="stylesheet" media="screen"/>
</div>
</head>
<body>
<div th:fragment="end-scripts">
<script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
</div>
</body>
</html> | Java |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all
helper_method :current_user_session, :current_user
filter_parameter_logging :password, :password_confirmation
layout 'application'
protected
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def require_user
unless current_user
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to login_url
return false
end
end
def require_no_user
if current_user
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to account_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
end
| Java |
<?php
namespace App\AAS_Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\AAS_Bundle\Utils\AAS as AAS;
/**
* Person
*/
class Person
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $surname;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $patronymic;
/**
* @var string
*/
private $position;
/**
* @var \App\AAS_Bundle\Entity\Witness
*/
private $witness;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $phone_numbers;
/**
* @var \App\AAS_Bundle\Entity\Team
*/
private $team;
/**
* @var \DateTime
*/
private $created_at;
/**
* @var \DateTime
*/
private $updated_at;
/**
* Constructor
*/
public function __construct()
{
$this->phone_numbers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set surname
*
* @param string $surname
* @return Person
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
public function getSurnameSlug()
{
return AAS::slugify($this->getSurname());
}
/**
* Set name
*
* @param string $name
* @return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
public function getNameSlug()
{
return AAS::slugify($this->getName());
}
/**
* Set patronymic
*
* @param string $patronymic
* @return Person
*/
public function setPatronymic($patronymic)
{
$this->patronymic = $patronymic;
return $this;
}
/**
* Get patronymic
*
* @return string
*/
public function getPatronymic()
{
return $this->patronymic;
}
public function getPatronymicSlug()
{
return AAS::slugify($this->getPatronymic());
}
/**
* Set created_at
*
* @param \DateTime $createdAt
* @return Person
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* @param \DateTime $updatedAt
* @return Person
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* @ORM\PrePersist
*/
public function setCreatedAtValue()
{
if(!$this->getCreatedAt())
{
$this->created_at = new \DateTime();
}
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedAtValue()
{
$this->updated_at = new \DateTime();
}
/**
* @var \App\AAS_Bundle\Entity\SecurityPerson
*/
private $security_person;
/**
* Set security_person
*
* @param \App\AAS_Bundle\Entity\SecurityPerson $securityPerson
* @return Person
*/
public function setSecurityPerson(\App\AAS_Bundle\Entity\SecurityPerson $securityPerson = null)
{
$this->security_person = $securityPerson;
return $this;
}
/**
* Get security_person
*
* @return \App\AAS_Bundle\Entity\SecurityPerson
*/
public function getSecurityPerson()
{
return $this->security_person;
}
/**
* Set position
*
* @param string $position
* @return Person
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* @return string
*/
public function getPosition()
{
return $this->position;
}
/**
* Set witness
*
* @param \App\AAS_Bundle\Entity\Witness $witness
* @return Person
*/
public function setWitness(\App\AAS_Bundle\Entity\Witness $witness = null)
{
$this->witness = $witness;
return $this;
}
/**
* Get witness
*
* @return \App\AAS_Bundle\Entity\Witness
*/
public function getWitness()
{
return $this->witness;
}
/**
* Add phone_numbers
*
* @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers
* @return Person
*/
public function addPhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers)
{
$this->phone_numbers[] = $phoneNumbers;
return $this;
}
/**
* Remove phone_numbers
*
* @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers
*/
public function removePhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers)
{
$this->phone_numbers->removeElement($phoneNumbers);
}
/**
* Get phone_numbers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getPhoneNumbers()
{
return $this->phone_numbers;
}
/**
* Set team
*
* @param \App\AAS_Bundle\Entity\Team $team
* @return Person
*/
public function setTeam(\App\AAS_Bundle\Entity\Team $team = null)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* @return \App\AAS_Bundle\Entity\Team
*/
public function getTeam()
{
return $this->team;
}
/**
* @var \App\AAS_Bundle\Entity\MedicalCommission
*/
private $medical_commission;
/**
* Set medical_commission
*
* @param \App\AAS_Bundle\Entity\MedicalCommission $medicalCommission
* @return Person
*/
public function setMedicalCommission(\App\AAS_Bundle\Entity\MedicalCommission $medicalCommission = null)
{
$this->medical_commission = $medicalCommission;
return $this;
}
/**
* Get medical_commission
*
* @return \App\AAS_Bundle\Entity\MedicalCommission
*/
public function getMedicalCommission()
{
return $this->medical_commission;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $admissions;
/**
* Add admissions
*
* @param \App\AAS_Bundle\Entity\Admission $admissions
* @return Person
*/
public function addAdmission(\App\AAS_Bundle\Entity\Admission $admissions)
{
$this->admissions[] = $admissions;
return $this;
}
/**
* Remove admissions
*
* @param \App\AAS_Bundle\Entity\Admission $admissions
*/
public function removeAdmission(\App\AAS_Bundle\Entity\Admission $admissions)
{
$this->admissions->removeElement($admissions);
}
/**
* Get admissions
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAdmissions()
{
return $this->admissions;
}
/**
* @var \App\AAS_Bundle\Entity\BusinessTripGroup
*/
private $business_trip_group;
/**
* Set business_trip_group
*
* @param \App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup
* @return Person
*/
public function setBusinessTripGroup(\App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup = null)
{
$this->business_trip_group = $businessTripGroup;
return $this;
}
/**
* Get business_trip_group
*
* @return \App\AAS_Bundle\Entity\BusinessTripGroup
*/
public function getBusinessTripGroup()
{
return $this->business_trip_group;
}
}
| Java |
package me.streib.janis.nanhotline.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class Launcher {
public static void main(String[] args) throws Exception {
NANHotlineConfiguration conf;
if (args.length != 1) {
InputStream ins;
File confFile = new File("conf/nanhotline.properties");
if (confFile.exists()) {
ins = new FileInputStream(confFile);
} else {
ins = Launcher.class
.getResourceAsStream("nanhotline.properties");
}
conf = new NANHotlineConfiguration(ins);
} else {
conf = new NANHotlineConfiguration(new FileInputStream(new File(
args[0])));
}
DatabaseConnection.init(conf);
Server s = new Server(new InetSocketAddress(conf.getHostName(),
conf.getPort()));
((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20);
ServletContextHandler h = new ServletContextHandler(
ServletContextHandler.SESSIONS);
h.setInitParameter(SessionManager.__SessionCookieProperty, "DB-Session");
h.addServlet(NANHotline.class, "/*");
HandlerList hl = new HandlerList();
hl.setHandlers(new Handler[] { generateStaticContext(), h });
s.setHandler(hl);
s.start();
}
private static Handler generateStaticContext() {
final ResourceHandler rh = new ResourceHandler();
rh.setResourceBase("static/");
ContextHandler ch = new ContextHandler("/static");
ch.setHandler(rh);
return ch;
}
}
| Java |
const test = require('tap').test
const GF = require('core/galois-field')
test('Galois Field', function (t) {
t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1')
for (let i = 1; i < 255; i++) {
t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other')
t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other')
}
t.equal(GF.mul(0, 1), 0, 'Should return 0 if first param is 0')
t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0')
t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0')
for (let j = 1; j < 255; j++) {
t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative')
}
t.end()
})
| Java |
import chalk = require("chalk");
import { take, select } from "redux-saga/effects";
import path = require("path");
import moment = require("moment");
import { titleize } from "inflection";
import { parallel } from "mesh";
import { weakMemo } from "../memo";
import AnsiUp from "ansi_up";
import { reader } from "../monad";
import { noop } from "lodash";
import { ImmutableObject, createImmutableObject } from "../immutable";
import { LogLevel, LogAction, LogActionTypes, Logger } from "./base";
// beat TS type checking
chalk.enabled = true;
function createLogColorizer(tester: RegExp, replaceValue: any) {
return function(input: string) {
if (!tester.test(input)) return input;
return input.replace(tester, replaceValue);
}
}
export type ConsoleLogState = {
argv?: {
color?: boolean,
hlog?: boolean
},
log?: {
level: LogLevel,
prefix?: string
}
}
const cwd = process.cwd();
const highlighters = [
createLogColorizer(/^INF/, (match) => chalk.bgCyan(match)),
createLogColorizer(/^ERR/, (match) => chalk.bgRed(match)),
createLogColorizer(/^DBG/, (match) => chalk.grey.bgBlack(match)),
createLogColorizer(/^WRN/, (match) => chalk.bgYellow(match)),
// timestamp
createLogColorizer(/\[\d+\.\d+\.\d+\]/, (match, inner) => `[${chalk.grey(inner)}]`),
// URL
createLogColorizer(/((\w{3,}\:\/\/)|([^\/\s\("':]+)?\/)([^\/\)\s"':]+\/?)+/g, (match) => {
return chalk.yellow(/\w+:\/\//.test(match) ? match : match.replace(cwd + "/", ""))
}),
// duration
createLogColorizer(/\s\d+(\.\d+)?(s|ms|m|h|d)(\s|$)/g, (match) => chalk.bold.cyan(match)),
// numbers
createLogColorizer(/\b\d+(\.\d+)?\b/g, (match, inner) => `${chalk.cyan(match)}`),
// strings
createLogColorizer(/"(.*?)"/g, (match, inner) => `"${chalk.blue(inner)}"`),
// tokens
createLogColorizer(/([\:\{\}",\(\)]|->|null|undefined|Infinity)/g, (match) => chalk.grey(match)),
// <<output - green (from audio again)
createLogColorizer(/<<(.*)/g, (match, word) => chalk.green(word)),
// >>input - magenta (from audio)
createLogColorizer(/>>(.*)/g, (match, word) => chalk.magenta(word)),
// **BIG EMPHASIS**
createLogColorizer(/\*\*(.*?)\*\*/, (match, word) => chalk.bgBlue(word)),
// *emphasis*
createLogColorizer(/\*(.*?)\*/g, (match, word) => chalk.bold(word)),
// ___underline___
createLogColorizer(/___(.*?)___/g, (match, word) => chalk.underline(word)),
// ~de emphasis~
createLogColorizer(/~(.*?)~/g, (match, word) => chalk.grey(word)),
];
function colorize(input: string) {
let output = input;
for (let i = 0, n = highlighters.length; i < n; i++) output = highlighters[i](output);
return output;
}
function styledConsoleLog(...args: any[]) {
var argArray = [];
if (args.length) {
var startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi;
var endTagRe = /<\/span>/gi;
var reResultArray;
argArray.push(arguments[0].replace(startTagRe, '%c').replace(endTagRe, '%c'));
while (reResultArray = startTagRe.exec(arguments[0])) {
argArray.push(reResultArray[2]);
argArray.push('');
}
// pass through subsequent args since chrome dev tools does not (yet) support console.log styling of the following form: console.log('%cBlue!', 'color: blue;', '%cRed!', 'color: red;');
for (var j = 1; j < arguments.length; j++) {
argArray.push(arguments[j]);
}
}
console.log.apply(console, argArray);
}
// I'm against abbreviations, but it's happening here
// since all of these are the same length -- saves space in stdout, and makes
// logs easier to read.
const PREFIXES = {
[LogLevel.DEBUG]: "DBG ",
[LogLevel.INFO]: "INF ",
[LogLevel.WARNING]: "WRN ",
[LogLevel.ERROR]: "ERR ",
};
const defaultState = { level: LogLevel.ALL, prefix: "" };
export function* consoleLogSaga() {
while(true) {
const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState;
let { text, level }: LogAction = (yield take(LogActionTypes.LOG));
if (!(acceptedLevel & level)) continue;
const log = {
[LogLevel.DEBUG]: console.log.bind(console),
[LogLevel.LOG]: console.log.bind(console),
[LogLevel.INFO]: console.info.bind(console),
[LogLevel.WARNING]: console.warn.bind(console),
[LogLevel.ERROR]: console.error.bind(console)
}[level];
text = PREFIXES[level] + (prefix || "") + text;
text = colorize(text);
if (typeof window !== "undefined" && !window["$synthetic"]) {
return styledConsoleLog(new AnsiUp().ansi_to_html(text));
}
log(text);
}
}
| Java |
<?php
namespace Payname\Security;
use Payname\Exception\ApiCryptoException;
/**
* Class Crypto
* Extract from https://github.com/illuminate/encryption
*/
class Crypto
{
/**
* The algorithm used for encryption.
*
* @var string
*/
private static $cipher = 'AES-128-CBC';
/**
* Encrypt the given value.
*
* @param string $value
* @param string $key
* @return string
*/
public static function encrypt($value, $key)
{
$iv = openssl_random_pseudo_bytes(self::getIvSize());
$value = openssl_encrypt(serialize($value), self::$cipher, $key, 0, $iv);
if ($value === false) {
throw new ApiCryptoException('Could not encrypt the data.');
}
$mac = self::hash($iv = base64_encode($iv), $value, $key);
return base64_encode(json_encode(compact('iv', 'value', 'mac')));
}
/**
* Decrypt the given value.
*
* @param string $payload
* @param string $key
* @return string
*/
public static function decrypt($value, $key)
{
$payload = self::getJsonPayload($value, $key);
$iv = base64_decode($payload['iv']);
$decrypted = openssl_decrypt($payload['value'], self::$cipher, $key, 0, $iv);
if ($decrypted === false) {
throw new ApiCryptoException('Could not decrypt the data.');
}
return unserialize($decrypted);
}
/**
* Get the JSON array from the given payload.
*
* @param string $payload
* @param string $key
* @return array
*/
private static function getJsonPayload($payload, $key)
{
$payload = json_decode(base64_decode($payload), true);
if (!$payload || (!is_array($payload) || !isset($payload['iv']) || !isset($payload['value']) || !isset($payload['mac']))) {
throw new ApiCryptoException('The payload is invalid.');
}
if (!self::validMac($payload, $key)) {
throw new ApiCryptoException('The MAC is invalid.');
}
return $payload;
}
/**
* Determine if the MAC for the given payload is valid.
*
* @param array $payload
* @param string $key
* @return bool
*/
private static function validMac(array $payload, $key)
{
$bytes = null;
if (function_exists('random_bytes')) {
$bytes = random_bytes(16);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes(16, $strong);
if ($bytes === false || $strong === false) {
throw new ApiCryptoException('Unable to generate random string.');
}
} else {
throw new ApiCryptoException('OpenSSL extension is required for PHP 5 users.');
}
$calcMac = hash_hmac('sha256', self::hash($payload['iv'], $payload['value'], $key), $bytes, true);
return hash_hmac('sha256', $payload['mac'], $bytes, true) === $calcMac;
}
/**
* Create a MAC for the given value.
*
* @param string $iv
* @param string $value
* @return string
*/
private static function hash($iv, $value, $key)
{
return hash_hmac('sha256', $iv.$value, $key);
}
/**
* Get the IV size for the cipher.
*
* @return int
*/
private static function getIvSize()
{
return 16;
}
}
| Java |
# Wildcard string matcher
## Requirements
- PHP 5.4 or greater (recommended).
## Installation
1. [Download all libraries](https://github.com/pedzed/libs/archive/master.zip)
or [specifically download this one](https://raw.githubusercontent.com/pedzed/libs/master/src/pedzed/libs/WildcardStringMatcher.php).
2. Move the file(s) to your server.
3. Include the file(s). *It's recommended to autoload them.*
## Examples
```php
$strList = [
'*',
'*.ipsum',
'lorem.ipsum.dolor',
'lorem.ipsum.sit.amet',
'lorem.*.amet',
'lorem.*'
];
$match = 'lorem.ipsum.sit.amet';
echo $match.'<br /><br />';
foreach($strList as $str){
echo 'String: '.$str.':<br />';
var_dump(WildcardStringMatcher::match($str, $match));
}
/* OUTPUT:
lorem.ipsum.sit.amet
String: *:
boolean true
String: *.ipsum:
boolean false
String: lorem.ipsum.dolor:
boolean false
String: lorem.ipsum.sit.amet:
boolean true
String: lorem.*.amet:
boolean true
String: lorem.*:
boolean true
*/
```
Case-sensitivity is supported. On default, it is disabled. To enable
case-sensitivity, pass a third parameter.
```php
WildcardStringMatcher::match($str1, $str2, true);
```
| Java |
---
layout: page
title: Island Networks Seminar
date: 2016-05-24
author: Sharon Gamble
tags: weekly links, java
status: published
summary: Duis posuere erat eu orci faucibus, ac.
banner: images/banner/leisure-05.jpg
booking:
startDate: 05/27/2017
endDate: 05/29/2017
ctyhocn: OKCBTHX
groupCode: INS
published: true
---
Ut at tempus purus. Suspendisse potenti. Pellentesque pulvinar metus ac urna tincidunt condimentum. In hac habitasse platea dictumst. Vestibulum sollicitudin justo id metus dapibus blandit. Vestibulum sed ipsum interdum odio ultricies tristique vitae quis urna. Quisque consequat massa sit amet nunc tempus viverra. Proin lacinia condimentum interdum. Aenean ut dui dui. Phasellus ut lorem non sem viverra pellentesque et id nunc. Pellentesque fringilla eros sed erat luctus, in volutpat quam finibus.
Pellentesque luctus sit amet enim vel fermentum. Aenean mollis elit libero, at porttitor turpis posuere in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam ac ante et purus convallis feugiat. Vestibulum ornare porta aliquet. Aliquam erat volutpat. Proin ac lectus id lectus pharetra facilisis. Mauris sagittis sit amet turpis eget mattis. Donec bibendum eget mauris quis pulvinar. Sed tincidunt leo in nibh iaculis tempor. Sed sit amet laoreet mauris, et sollicitudin leo. Praesent sed auctor leo, eget dictum elit.
* Cras sit amet arcu in erat vulputate iaculis ac in enim
* Praesent et neque volutpat, sollicitudin erat nec, ullamcorper urna
* Phasellus posuere nisi sed est venenatis placerat
* Nam eleifend velit eget tristique faucibus.
Donec sit amet leo a tortor fermentum lobortis nec in sapien. Quisque porta enim lorem, eu eleifend elit condimentum non. Phasellus vitae pretium velit. Suspendisse accumsan nunc vitae varius auctor. Suspendisse et sem nulla. Etiam cursus, quam eu dictum vestibulum, diam nulla malesuada mauris, et euismod erat sapien non sapien. Fusce egestas mi id volutpat laoreet.
Praesent egestas, eros mollis tincidunt euismod, lorem augue feugiat ligula, ut venenatis ex purus id eros. Pellentesque vitae mauris vestibulum, auctor mauris nec, laoreet nunc. Mauris varius, tortor id eleifend fringilla, tellus tortor volutpat nibh, in elementum neque mi at ex. Phasellus ornare dui sed enim imperdiet, in porta quam interdum. Morbi a ornare velit. Quisque mollis vitae libero et rutrum. In bibendum faucibus metus at volutpat. Sed pretium ex et libero finibus, at pharetra lorem finibus. Duis venenatis laoreet sapien sit amet pharetra. Maecenas varius varius ipsum, sit amet porttitor justo consequat non. Pellentesque viverra fringilla tincidunt. Nulla turpis libero, venenatis vel magna at, finibus gravida eros. Quisque mollis mollis ante, in convallis metus consequat imperdiet. Pellentesque quis nisl at massa commodo vestibulum quis eu metus. Donec sollicitudin sed tortor et egestas.
| Java |
'use strict';
// Test dependencies are required and exposed in common/bootstrap.js
require('../../common/bootstrap');
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
var codeContents = 'console.log("testing deploy");';
var reference = new Buffer(codeContents);
var lists = deployment.js.lists;
var listRuleLength = lists.includes.length + lists.ignores.length + lists.blacklist.length;
var sandbox = sinon.sandbox.create();
var FIXTURE_PATH = path.join(__dirname, '/../../../test/unit/fixtures');
exports['Deployment: JavaScript'] = {
setUp(done) {
this.deploy = sandbox.spy(Tessel.prototype, 'deploy');
this.appStop = sandbox.spy(commands.app, 'stop');
this.appStart = sandbox.spy(commands.app, 'start');
this.deleteFolder = sandbox.spy(commands, 'deleteFolder');
this.createFolder = sandbox.spy(commands, 'createFolder');
this.untarStdin = sandbox.spy(commands, 'untarStdin');
this.execute = sandbox.spy(commands.js, 'execute');
this.openStdinToFile = sandbox.spy(commands, 'openStdinToFile');
this.chmod = sandbox.spy(commands, 'chmod');
this.push = sandbox.spy(deploy, 'push');
this.createShellScript = sandbox.spy(deploy, 'createShellScript');
this.injectBinaryModules = sandbox.stub(deployment.js, 'injectBinaryModules').callsFake(() => Promise.resolve());
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.resolve(reference));
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
this.end = sandbox.spy(this.tessel._rps.stdin, 'end');
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pWrite = sandbox.stub(Preferences, 'write').returns(Promise.resolve());
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
deleteTemporaryDeployCode()
.then(done);
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
deleteTemporaryDeployCode()
.then(done)
.catch(function(err) {
throw err;
});
},
bundling(test) {
test.expect(1);
this.tarBundle.restore();
createTemporaryDeployCode().then(() => {
var tb = deployment.js.tarBundle({
target: DEPLOY_DIR_JS
});
tb.then(bundle => {
/*
$ t2 run app.js
INFO Looking for your Tessel...
INFO Connected to arnold over LAN
INFO Writing app.js to RAM on arnold (2.048 kB)...
INFO Deployed.
INFO Running app.js...
testing deploy
INFO Stopping script...
*/
test.equal(bundle.length, 2048);
test.done();
})
.catch(error => {
test.ok(false, error.toString());
test.done();
});
});
},
createShellScriptDefaultEntryPoint(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptDefaultEntryPointNoSubargs(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptDefaultEntryPointNoExtraargs(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptSendsCorrectEntryPoint(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
processCompletionOrder(test) {
// Array of processes we've started but haven't completed yet
var processesAwaitingCompletion = [];
this.tessel._rps.on('control', (data) => {
// Push new commands into the queue
processesAwaitingCompletion.push(data);
});
// Create the temporary folder with example code
createTemporaryDeployCode()
.then(() => {
var closeAdvance = (event) => {
// If we get an event listener for the close event of a process
if (event === 'close') {
// Wait some time before actually closing it
setTimeout(() => {
// We should only have one process waiting for completion
test.equal(processesAwaitingCompletion.length, 1);
// Pop that process off
processesAwaitingCompletion.shift();
// Emit the close event to keep it going
this.tessel._rps.emit('close');
}, 200);
}
};
// When we get a listener that the Tessel process needs to close before advancing
this.tessel._rps.on('newListener', closeAdvance);
// Actually deploy the script
this.tessel.deploy({
entryPoint: path.relative(process.cwd(), DEPLOY_FILE_JS),
compress: true,
push: false,
single: false
})
// If it finishes, it was successful
.then(() => {
this.tessel._rps.removeListener('newListener', closeAdvance);
test.done();
})
// If not, there was an issue
.catch(function(err) {
test.equal(err, undefined, 'We hit a catch statement that we should not have.');
});
});
}
};
exports['deployment.js.compress with uglify.es.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.es, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('es', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
minifyFailureReturnsOriginalSource(test) {
test.expect(2);
const result = deployment.js.compress('es', '#$%^');
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '#$%^');
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('es', '#$%^');
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(23);
const optionsCompress = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
// ------
dead_code: true,
unsafe_math: true,
keep_infinity: true,
// ------
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('es', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(23);
const ourExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
// ------
dead_code: true,
unsafe_math: true,
keep_infinity: true,
// ------
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
deployment.js.compress('es', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
theirOptionsCompress(test) {
test.expect(20);
var theirExplicitSettings = {
// ------
booleans: false,
cascade: false,
conditionals: false,
comparisons: false,
evaluate: false,
hoist_funs: false,
hoist_vars: false,
if_return: false,
join_vars: false,
loops: false,
properties: false,
sequences: false,
unsafe: false,
// ------
dead_code: false,
unsafe_math: false,
keep_infinity: false,
// ------
keep_fargs: true,
keep_fnames: true,
warnings: true,
drop_console: true,
};
var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings);
deployment.js.compress('es', 'var a = 1;', {
compress: theirExplicitSettings
});
const optionsSeen = this.minify.lastCall.args[1].compress;
theirExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], theirExplicitSettings[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('es', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('es', codeContents), codeContents);
test.done();
},
minifyWithBareReturns(test) {
test.expect(1);
deployment.js.compress('es', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
avoidCompleteFailure(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
test.equal(deployment.js.compress('es', 'return;'), 'return;');
test.done();
},
};
exports['deployment.js.compress with uglify.js.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.js, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('js', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
minifyFailureReturnsOriginalSource(test) {
test.expect(2);
const result = deployment.js.compress('js', '#$%^');
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '#$%^');
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('js', '#$%^');
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(15);
const optionsCompress = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('js', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(15);
const ourExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
deployment.js.compress('js', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
theirOptionsCompress(test) {
test.expect(15);
var theirExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings);
deployment.js.compress('js', 'var a = 1;', {
compress: theirExplicitSettings
});
const optionsSeen = this.minify.lastCall.args[1].compress;
theirExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], theirExplicitSettings[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('js', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('js', codeContents), codeContents);
test.done();
},
minifyWithBareReturns(test) {
test.expect(1);
deployment.js.compress('js', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
avoidCompleteFailure(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
const result = deployment.js.compress('js', 'return;');
test.equal(result, 'return;');
test.done();
},
theReasonForUsingBothVersionsOfUglify(test) {
test.expect(2);
this.minify.restore();
this.es = sandbox.spy(uglify.es, 'minify');
this.js = sandbox.spy(uglify.js, 'minify');
const code = tags.stripIndents `
var Class = function() {};
Class.prototype.method = function() {};
module.exports = Class;
`;
deployment.js.compress('es', code);
deployment.js.compress('js', code);
test.equal(this.es.callCount, 1);
test.equal(this.js.callCount, 1);
test.done();
},
};
exports['deployment.js.tarBundle'] = {
setUp(done) {
this.copySync = sandbox.spy(fs, 'copySync');
this.outputFileSync = sandbox.spy(fs, 'outputFileSync');
this.writeFileSync = sandbox.spy(fs, 'writeFileSync');
this.remove = sandbox.spy(fs, 'remove');
this.readdirSync = sandbox.spy(fs, 'readdirSync');
this.globSync = sandbox.spy(glob, 'sync');
this.collect = sandbox.spy(Project.prototype, 'collect');
this.exclude = sandbox.spy(Project.prototype, 'exclude');
this.mkdirSync = sandbox.spy(fsTemp, 'mkdirSync');
this.addIgnoreRules = sandbox.spy(Ignore.prototype, 'addIgnoreRules');
this.project = sandbox.spy(deployment.js, 'project');
this.compress = sandbox.spy(deployment.js, 'compress');
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
actionsGlobRules(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
test.deepEqual(
rules.map(path.normalize), [
// Found in "test/unit/fixtures/ignore/.tesselignore"
'a/**/*.*',
'mock-foo.js',
// Found in "test/unit/fixtures/ignore/nested/.tesselignore"
'nested/b/**/*.*',
'nested/file.js'
].map(path.normalize)
);
test.done();
},
actionsGlobFiles(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
const files = glob.files(target, rules);
test.deepEqual(files, ['mock-foo.js']);
test.done();
},
actionsGlobFilesNested(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['**/.tesselignore']);
test.deepEqual(files, [
'.tesselignore',
'nested/.tesselignore'
]);
test.done();
},
actionsGlobFilesNonNested(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['.tesselignore']);
test.deepEqual(files, ['.tesselignore']);
test.done();
},
noOptionsTargetFallbackToCWD(test) {
test.expect(2);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
sandbox.spy(path, 'relative');
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
compress: true,
full: true,
}).then(() => {
test.equal(path.relative.firstCall.args[0], path.normalize('test/unit/fixtures/project'));
test.equal(path.relative.firstCall.args[1], path.normalize('test/unit/fixtures/project'));
test.done();
});
},
full(test) {
test.expect(8);
const target = 'test/unit/fixtures/project';
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
// One call for .tesselinclude
// One call for the single rule found within
// Three calls for the deploy lists
// * 2 (We need all ignore rules ahead of time for ignoring binaries)
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.exclude.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'nested/another.js',
'node_modules/foo/index.js',
'package.json',
]);
test.done();
});
});
},
fullHitsErrorFromFstreamIgnore(test) {
test.expect(1);
// Need to stub function in _actual_ fs (but we use fs-extra)
const fs = require('fs');
sandbox.stub(fs, 'readFile').callsFake((file, callback) => {
callback('foo');
});
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'foo');
test.done();
});
},
slim(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
// These things happen in the --slim path
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
test.equal(this.mkdirSync.callCount, 1);
test.equal(this.outputFileSync.callCount, 3);
// End
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 1);
test.deepEqual(this.exclude.lastCall.args[0], [
'mock-foo.js',
'test/unit/fixtures/project/mock-foo.js',
'other.js',
'test/unit/fixtures/project/other.js',
'node_modules/foo/package.json',
'test/unit/fixtures/project/node_modules/foo/package.json'
].map(path.normalize));
const minified = this.compress.lastCall.returnValue;
test.equal(this.compress.callCount, 2);
test.equal(minified.indexOf('!!mock-foo!!') === -1, true);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'node_modules/foo/index.js',
'package.json'
]);
test.done();
});
});
},
slimHitsErrorFromFstreamReader(test) {
test.expect(1);
const pipe = fstream.Reader.prototype.pipe;
// Need to stub function in _actual_ fs (but we use fs-extra)
this.readerPipe = sandbox.stub(fstream.Reader.prototype, 'pipe').callsFake(function() {
this.emit('error', new Error('foo'));
return pipe.apply(this, arguments);
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorInfsRemove(test) {
test.expect(1);
this.remove.restore();
this.remove = sandbox.stub(fs, 'remove').callsFake((temp, handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
this.remove.reset();
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromCompress(test) {
test.expect(1);
this.compress.restore();
this.compress = sandbox.stub(deployment.js, 'compress').callsFake(() => {
throw new Error('foo');
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromProjectCollect(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake((handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromProject(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake(function() {
this.emit('error', new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
compressionProducesNoErrors(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
compressionIsSkipped(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: false,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// compression mechanism is never called when --compress=false
test.equal(this.compress.callCount, 0);
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
slimTesselInit(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/init';
/*
init
├── index.js
└── package.json
0 directories, 2 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(this.mkdirSync.callCount, 1);
const minified = this.compress.lastCall.returnValue;
test.equal(minified, 'const e=require("tessel"),{2:o,3:l}=e.led;o.on(),setInterval(()=>{o.toggle(),l.toggle()},100),console.log("I\'m blinking! (Press CTRL + C to stop)");');
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js', 'package.json']);
test.done();
});
});
},
slimSingle(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
slimSingleNested(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
fullSingle(test) {
test.expect(3);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
full: true,
}).then(bundle => {
test.equal(this.addIgnoreRules.callCount, 3);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
fullSingleNested(test) {
test.expect(2);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
full: true,
}).then(bundle => {
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
slimIncludeOverridesIgnore(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-overrides-ignore';
/*
project-include-overrides-ignore
├── .tesselignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
/*
All .tesselignore rules are negated by all .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
test.equal(this.project.callCount, 1);
// 3 js files are compressed
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Since the .tesselignore rules are ALL negated by .tesselinclude rules,
// the additional files are copied into the temporary bundle dir, and
// then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
fullIncludeOverridesIgnore(test) {
test.expect(8);
const target = 'test/unit/fixtures/project-include-overrides-ignore';
/*
project-include-overrides-ignore
├── .tesselignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// The .tesselignore rules are ALL overridden by .tesselinclude rules
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimIncludeWithoutIgnore(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
fullIncludeWithoutIgnore(test) {
test.expect(8);
/*
!! TAKE NOTE!!
This is actually the default behavior. That is to say:
these files would be included, whether they are listed
in the .tesselinclude file or not.
*/
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimIncludeHasNegateRules(test) {
test.expect(8);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-has-negate-rules';
/*
project-include-has-negate-rules
.
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
test.equal(this.exclude.callCount, 1);
// Called once for the extra file matching
// the .tesselinclude rules
test.equal(this.copySync.callCount, 1);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
// The 4 files discovered and listed in the dependency graph
// See bundle extraction below.
test.equal(this.outputFileSync.callCount, 4);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, but the .tesselinclude rules
// include a negated pattern. The additional, non-negated files
// are copied into the temporary bundle dir, and then included
// in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js MUST NOT BE PRESENT
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
fullIncludeHasNegateRules(test) {
test.expect(8);
const target = 'test/unit/fixtures/project-include-has-negate-rules';
/*
project-include-has-negate-rules
.
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// This is where the negated rule is transferred.
test.deepEqual(this.addIgnoreRules.getCall(1).args[0], [
// Note that the "!" was stripped from the rule
'mock-foo.js',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js is NOT present
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimSingleInclude(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
single: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are .tesselinclude rules, but the single flag is present
so they don't matter. The only file sent must be the file specified.
*/
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Only the explicitly specified `index.js` will
// be included in the deployed code.
test.deepEqual(entries, [
'index.js',
]);
test.done();
});
});
},
detectAssetsWithoutInclude(test) {
test.expect(4);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-assets-without-include';
/*
project-assets-without-include
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 7 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 1);
test.equal(this.warn.firstCall.args[0], 'Some assets in this project were not deployed (see: t2 run --help)');
test.done();
});
},
detectAssetsWithoutIncludeEliminatedByDepGraph(test) {
test.expect(3);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-assets-without-include-eliminated-by-dep-graph';
/*
project-assets-without-include
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── index.js
│ └── package.json
└── package.json
3 directories, 6 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 0);
// Ultimately, all assets were accounted for, even though
// no tesselinclude existed.
test.done();
});
},
alwaysExplicitlyProvideProjectDirname(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.deepEqual(this.project.lastCall.args[0], {
entry: path.join(target, entryPoint),
dirname: path.normalize(target),
});
test.done();
});
},
detectAndEliminateBlacklistedAssets(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-ignore-blacklisted';
/*
project-ignore-blacklisted
├── index.js
├── node_modules
│ └── tessel
│ ├── index.js
│ └── package.json
└── package.json
2 directories, 4 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then((bundle) => {
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'package.json'
]);
test.done();
});
});
},
iteratesBinaryModulesUsed(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
const details = {
modulePath: ''
};
this.minimatch = sandbox.stub(deployment.js, 'minimatch').returns(true);
this.rules = sandbox.stub(glob, 'rules').callsFake(() => {
return [
'a', 'b',
];
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler(details);
});
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.equal(this.forEach.callCount, 2);
test.equal(this.minimatch.callCount, 3);
test.deepEqual(this.minimatch.getCall(0).args, ['', 'a', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(1).args, ['', 'b', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(2).args, ['', 'node_modules/**/tessel/**/*', {
matchBase: true,
dot: true
}]);
test.done();
});
},
};
var fixtures = {
project: path.join(FIXTURE_PATH, '/find-project'),
explicit: path.join(FIXTURE_PATH, '/find-project-explicit-main')
};
exports['deploy.findProject'] = {
setUp(done) {
done();
},
tearDown(done) {
sandbox.restore();
done();
},
home(test) {
test.expect(1);
var fake = path.normalize('/fake/test/home/dir');
this.homedir = sandbox.stub(os, 'homedir').returns(fake);
this.lstatSync = sandbox.stub(fs, 'lstatSync').callsFake((file) => {
return {
isDirectory: () => {
// naive for testing.
return file.slice(-1) === '/';
}
};
});
this.realpathSync = sandbox.stub(fs, 'realpathSync').callsFake((arg) => {
// Ensure that "~" was transformed
test.equal(arg, path.normalize('/fake/test/home/dir/foo'));
test.done();
return '';
});
deploy.findProject({
lang: deployment.js,
entryPoint: '~/foo/',
compress: true,
});
},
byFile(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target,
compress: true,
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
byDirectory(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
byDirectoryBWExplicitMain(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project-explicit-main/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.explicit,
program: path.join(fixtures.explicit, 'app.js'),
entryPoint: 'app.js'
});
test.done();
});
},
byDirectoryMissingIndex(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project-no-index/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(() => {
test.ok(false, 'findProject should not find a valid project here');
test.done();
}).catch(error => {
test.ok(error.includes('ENOENT'));
test.done();
});
},
byFileInSubDirectory(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/test/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'test/index.js'),
entryPoint: path.normalize('test/index.js')
});
test.done();
});
},
noPackageJsonSingle(test) {
test.expect(1);
var pushdir = path.normalize('test/unit/fixtures/project-no-package.json/');
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
single: true,
slim: true,
lang: deployment.js,
};
deploy.findProject(opts).then(project => {
// Without the `single` flag, this would've continued upward
// until it found a directory with a package.json.
test.equal(project.pushdir, fs.realpathSync(pushdir));
test.done();
});
},
noPackageJsonUseProgramDirname(test) {
test.expect(1);
// This is no package.json here
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
lang: deployment.js,
single: false,
};
this.endOfLookup = sandbox.stub(deploy, 'endOfLookup').returns(true);
deploy.findProject(opts).then(project => {
test.equal(project.pushdir, path.dirname(path.join(process.cwd(), entryPoint)));
test.done();
});
},
};
exports['deploy.sendBundle, error handling'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pathResolve = sandbox.stub(path, 'resolve');
this.failure = 'FAIL';
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
findProject(test) {
test.expect(1);
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
resolveBinaryModules(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
tarBundle(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
};
exports['deployment.js.preBundle'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.info = sandbox.stub(log, 'info');
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
});
this.receive = sandbox.stub(this.tessel, 'receive').callsFake((rps, callback) => {
rps.emit('close');
callback();
});
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.findProject = sandbox.stub(deploy, 'findProject').returns(Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').returns(Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').returns(Promise.resolve(new Buffer([0x00])));
this.pathResolve = sandbox.stub(path, 'resolve');
this.preBundle = sandbox.spy(deployment.js, 'preBundle');
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
preBundleChecksForNpmrc(test) {
test.expect(1);
const warning = tags.stripIndents `This project is missing an ".npmrc" file!
To prepare your project for deployment, use the command:
t2 init
Once complete, retry:`;
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(false));
deployment.js.preBundle({
target: '/',
}).catch(error => {
test.equal(error.startsWith(warning), true);
test.done();
});
},
preBundleReceivesTessel(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
deploy.sendBundle(this.tessel, {
target: '/',
entryPoint: 'foo.js',
lang: deployment.js
}).then(() => {
test.equal(this.preBundle.lastCall.args[0].tessel, this.tessel);
test.done();
});
},
// // We need to find a way to provde the build version directly from the
// // Tessel 2 itself. This approach makes deployment slow with a network
// // connection, or impossible without one.
// preBundleCallsfetchCurrentBuildInfoAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.fetchCurrentBuildInfo.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
// preBundleCallsrequestBuildListAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.requestBuildList.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
// preBundleCallsfetchNodeProcessVersionsAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.fetchNodeProcessVersions.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
};
exports['deployment.js.resolveBinaryModules'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/project-binary-modules');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing"}]}';
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => Promise.resolve());
done();
},
tearDown(done) {
sandbox.restore();
done();
},
bailOnSkipBinary(test) {
test.expect(2);
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 1);
// test/unit/fixtures/skip-binary/ has the corresponding
// dependencies for the following binary modules:
//
// debug-1.1.1-Debug-node-v46-linux-mipsel
// release-1.1.1-Release-node-v46-linux-mipsel
//
// However, the latter has a "tessel.skipBinary = true" key in its package.json
//
//
test.equal(this.exists.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel')), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
buildPathExpWindow(test) {
test.expect(1);
let descriptor = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', {
value: 'win32'
});
this.match = sandbox.spy(String.prototype, 'match');
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(
this.match.lastCall.args[0].toString(),
'/(?:build\\\\(Debug|Release|bindings)\\\\)/'
);
// Restore this descriptor
Object.defineProperty(process, 'platform', descriptor);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
noOptionsTargetFallbackToCWD(test) {
test.expect(3);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.relative.callCount, 1);
test.equal(this.relative.lastCall.args[0], target);
test.equal(this.relative.lastCall.args[1], target);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
noOptionsTargetFallbackToCWDNoRelative(test) {
test.expect(1);
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').returns('');
this.cwd = sandbox.stub(process, 'cwd').returns('');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.ok(false, 'resolveBinaryModules should not resolve');
test.done();
}).catch(error => {
// The thing to be found:
//
// node_modules/release/package.json
//
// Will not be found, because it doesn't exist,
// but in this case, that's exactly what we want.
test.equal(error.toString(), `Error: Cannot find module '${path.normalize('node_modules/release/package.json')}'`);
test.done();
});
},
findsModulesMissingBinaryNodeFiles(test) {
test.expect(2);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
spawnPythonScriptReturnsNull(test) {
test.expect(1);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: null
};
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.readGypFileSync.lastCall.returnValue, '');
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
spawnPythonScript(test) {
test.expect(7);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: [
null, new Buffer('{"targets": [{"target_name": "missing","sources": ["capture.c", "missing.cc"]}]}', 'utf8')
]
};
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.equal(this.spawnSync.callCount, 1);
test.equal(this.spawnSync.lastCall.args[0], 'python');
var python = this.spawnSync.lastCall.args[1][1];
test.equal(python.startsWith('import ast, json; print json.dumps(ast.literal_eval(open('), true);
test.equal(python.endsWith(').read()));'), true);
test.equal(python.includes('missing'), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
failsWithMessage(test) {
test.expect(1);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing",}]}';
// ^
// That's intentional.
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
test.equal(binaryModulesUsed.get('missing@1.1.1').resolved, false);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
existsInLocalCache(test) {
test.expect(2);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
existsInLocalCacheNodeGypLinkedBinPath(test) {
test.expect(1);
this.readGypFileSync.restore();
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 2);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
resolveFromRealDirFixtures(test) {
test.expect(5);
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
// To avoid making an actual network request,
// make the program think these things are already
// cached. The test to pass is that it calls fs.existsSync
// with the correct things from the project directory (this.target)
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 4);
// test/unit/fixtures/project-binary-modules/ has the corresponding
// dependencies for the following binary modules:
var cachedBinaryPaths = [
'.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel',
'.tessel/binaries/linked-1.1.1-Release-node-v46-linux-mipsel',
'.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel',
'.tessel/binaries/missing-1.1.1-Release-node-v46-linux-mipsel',
];
cachedBinaryPaths.forEach((cbp, callIndex) => {
test.equal(this.exists.getCall(callIndex).args[0].endsWith(path.normalize(cbp)), true);
});
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
requestsRemote(test) {
test.expect(12);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
test.equal(this.request.callCount, 1);
var requestArgs = this.request.lastCall.args[0];
test.equal(requestArgs.url, 'http://packages.tessel.io/npm/release-1.1.1-Release-node-v46-linux-mipsel.tgz');
test.equal(requestArgs.gzip, true);
test.equal(this.pipe.callCount, 2);
test.equal(this.createGunzip.callCount, 1);
test.equal(this.Extract.callCount, 1);
test.equal(this.transform.stubsUsed.length, 2);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
requestsRemoteGunzipErrors(test) {
test.expect(9);
this.removeSync = sandbox.stub(fs, 'removeSync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
// Hook into the ifReachable call to trigger an error at the gunzip stream
this.ifReachable.restore();
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => {
this.transform.emit('error', {
code: 'Z_DATA_ERROR',
});
return Promise.resolve();
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
// The result of gunzip emitting an error:
test.equal(this.removeSync.callCount, 1);
test.equal(this.removeSync.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
test.equal(this.request.callCount, 1);
test.equal(this.createGunzip.callCount, 1);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
};
exports['deployment.js.injectBinaryModules'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/project-binary-modules');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.globRoot = path.join(FIXTURE_PATH, '/project-binary-modules/');
this.copySync = sandbox.stub(fs, 'copySync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
done();
},
tearDown(done) {
sandbox.restore();
done();
},
copies(test) {
test.expect(17);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
test.equal(this.copySync.callCount, 8);
var args = this.copySync.args;
/*
This is an abbreviated view of what should be copied by this operation:
[
[
'debug-1.1.1-Release-node-v46-linux-mipsel/Debug/debug.node',
'debug/build/Debug/debug.node'
],
[
'debug/package.json',
'debug/package.json'
],
[
'linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node',
'linked/build/bindings/linked.node'
],
[
'linked/package.json',
'linked/package.json'
],
[
'missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node',
'missing/build/Release/missing.node'
],
[
'missing/package.json',
'missing/package.json'
],
[
'release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node',
'release/build/Release/release.node'
],
[
'release/package.json',
'release/package.json'
]
]
*/
// ----- fixtures/project-binary-modules/node_modules/debug
test.equal(
args[0][0].endsWith(path.normalize('debug-1.1.1-Debug-node-v46-linux-mipsel/Debug/debug.node')),
true
);
test.equal(
args[0][1].endsWith(path.normalize('debug/build/Debug/debug.node')),
true
);
test.equal(
args[1][0].endsWith(path.normalize('debug/package.json')),
true
);
test.equal(
args[1][1].endsWith(path.normalize('debug/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/linked
test.equal(
args[2][0].endsWith(path.normalize('linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node')),
true
);
test.equal(
args[2][1].endsWith(path.normalize('linked/build/bindings/linked.node')),
true
);
test.equal(
args[3][0].endsWith(path.normalize('linked/package.json')),
true
);
test.equal(
args[3][1].endsWith(path.normalize('linked/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/missing
test.equal(
args[4][0].endsWith(path.normalize('missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node')),
true
);
test.equal(
args[4][1].endsWith(path.normalize('missing/build/Release/missing.node')),
true
);
test.equal(
args[5][0].endsWith(path.normalize('missing/package.json')),
true
);
test.equal(
args[5][1].endsWith(path.normalize('missing/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/release
test.equal(
args[6][0].endsWith(path.normalize('release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node')),
true
);
test.equal(
args[6][1].endsWith(path.normalize('release/build/Release/release.node')),
true
);
test.equal(
args[7][0].endsWith(path.normalize('release/package.json')),
true
);
test.equal(
args[7][1].endsWith(path.normalize('release/package.json')),
true
);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
doesNotCopyIgnoredBinaries(test) {
test.expect(1);
this.target = path.normalize('test/unit/fixtures/project-ignore-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-ignore-binary/');
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
usesBinaryHighestInTreeWhenEncounteringDuplicates(test) {
test.expect(6);
this.target = path.normalize('test/unit/fixtures/project-binary-modules-duplicate-lower-deps');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules-duplicate-lower-deps/');
});
// We WANT to glob the actual target directory
this.globSync.restore();
this.mapHas = sandbox.spy(Map.prototype, 'has');
this.mapGet = sandbox.spy(Map.prototype, 'get');
this.mapSet = sandbox.spy(Map.prototype, 'set');
this.arrayMap = sandbox.spy(Array.prototype, 'map');
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
// Ensure that 2 modules with the same name and version were found!
for (var i = 0; i < this.arrayMap.callCount; i++) {
let call = this.arrayMap.getCall(i);
if (call.thisValue.UNRESOLVED_BINARY_LIST) {
test.equal(call.thisValue.length, 2);
}
}
test.equal(this.mapHas.callCount, 2);
test.equal(this.mapHas.getCall(0).args[0], 'release@1.1.1');
test.equal(this.mapHas.getCall(1).args[0], 'release@1.1.1');
// Ensure that only one of the two were included in the
// final list of binary modules to bundle
test.equal(binaryModulesUsed.size, 1);
// Ensure that the swap has occurred
test.equal(
path.normalize(binaryModulesUsed.get('release@1.1.1').globPath),
path.normalize('node_modules/release/build/Release/release.node')
);
test.done();
});
},
fallbackWhenOptionsMissing(test) {
test.expect(1);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
binaryModulesUsed.clear();
// We need something to look at...
sandbox.stub(binaryModulesUsed, 'forEach');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync()).then(() => {
test.equal(binaryModulesUsed.forEach.callCount, 1);
test.done();
});
});
},
doesNotCopyWhenOptionsSingleTrue(test) {
test.expect(1);
// This would normally result in 8 calls to this.copySync
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {
single: true
}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
rewriteBinaryBuildPlatformPaths(test) {
test.expect(2);
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'serialport.node',
buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'),
buildType: 'Release',
globPath: path.normalize('node_modules/serialport/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/serialport.node'),
ignored: false,
name: 'serialport',
modulePath: path.normalize('node_modules/serialport'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/serialport-2.0.6-Release-node-v46-linux-mipsel')
});
});
var find = lists.binaryPathTranslations['*'][0].find;
lists.binaryPathTranslations['*'][0].find = 'FAKE_PLATFORM-FAKE_ARCH';
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// If the replacement operation did not work, these would still be
// "FAKE_PLATFORM-FAKE_ARCH"
test.equal(this.copySync.firstCall.args[0].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
test.equal(this.copySync.firstCall.args[1].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
// Restore the path translation...
lists.binaryPathTranslations['*'][0].find = find;
test.done();
});
},
tryTheirPathAndOurPath(test) {
test.expect(3);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
// Fail the first try/catch on THEIR PATH
if (this.copySync.callCount === 1) {
throw new Error('ENOENT: no such file or directory');
}
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'node_sqlite3.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/sqlite3-3.1.4-Release/node-v46-something-else/node_sqlite3.node'
buildPath: path.normalize('/lib/binding/node-v46-something-else/'),
buildType: 'Release',
globPath: path.normalize('node_modules/sqlite3/lib/binding/node-v46-something-else/node_sqlite3.node'),
ignored: false,
name: 'sqlite3',
modulePath: path.normalize('node_modules/sqlite3'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/sqlite3-3.1.4-Release'),
});
});
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
// 1 call: copy the package.json
test.equal(fs.copySync.callCount, 3);
// THEIR PATH
test.equal(this.copySync.getCall(0).args[0].endsWith(path.normalize('node-v46-something-else/node_sqlite3.node')), true);
// OUR PATH
test.equal(this.copySync.getCall(1).args[0].endsWith(path.normalize('Release/node_sqlite3.node')), true);
test.done();
});
},
tryCatchTwiceAndFailGracefullyWithMissingBinaryMessage(test) {
test.expect(4);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
throw new Error('E_THIS_IS_NOT_REAL');
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'not-a-thing.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/not-a-thing-3.1.4-Release/node-v46-something-else/not-a-thing.node'
buildPath: path.normalize('/lib/binding/node-v46-something-else/'),
buildType: 'Release',
globPath: path.normalize('node_modules/not-a-thing/lib/binding/node-v46-something-else/not-a-thing.node'),
ignored: false,
name: 'not-a-thing',
modulePath: path.normalize('node_modules/not-a-thing'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/not-a-thing-3.1.4-Release'),
});
});
this.error = sandbox.stub(log, 'error');
this.logMissingBinaryModuleWarning = sandbox.stub(deployment.js, 'logMissingBinaryModuleWarning');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
test.equal(this.copySync.callCount, 2);
// Result of failing both attempts to copy
test.equal(this.logMissingBinaryModuleWarning.callCount, 1);
test.equal(this.error.callCount, 1);
test.equal(String(this.error.lastCall.args[0]).includes('E_THIS_IS_NOT_REAL'), true);
test.done();
});
}
};
exports['deploy.createShellScript'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
remoteShellScriptPathIsNotPathNormalized(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: [],
subargs: [],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
},
remoteShellScriptPathIsNotPathNormalizedWithSubargs(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
}
};
// Test dependencies are required and exposed in common/bootstrap.js
exports['deployment.js.lists'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
checkIncludes(test) {
test.expect(1);
var includes = [
'node_modules/**/aws-sdk/apis/*.json',
'node_modules/**/mime/types/*.types',
'node_modules/**/negotiator/**/*.js',
'node_modules/**/socket.io-client/socket.io.js',
'node_modules/**/socket.io-client/dist/socket.io.min.js',
'node_modules/**/socket.io-client/dist/socket.io.js',
];
test.deepEqual(lists.includes, includes);
test.done();
},
checkIgnores(test) {
test.expect(1);
var ignores = [
'node_modules/**/tessel/**/*',
];
test.deepEqual(lists.ignores, ignores);
test.done();
},
checkCompression(test) {
test.expect(1);
/*
This test just ensures that no one accidentally
messes up the contents of the deploy-lists file,
specifically for the compression options field
*/
var compressionOptions = {
extend: {
compress: {
keep_fnames: true
},
mangle: {}
},
};
test.deepEqual(lists.compressionOptions, compressionOptions);
test.done();
}
};
exports['deployment.js.postRun'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.originalProcessStdinProperties = {
pipe: process.stdin.pipe,
setRawMode: process.stdin.setRawMode,
};
this.stdinPipe = sandbox.spy();
this.setRawMode = sandbox.spy();
process.stdin.pipe = this.stdinPipe;
process.stdin.setRawMode = this.setRawMode;
this.notRealTessel = {
connection: {
connectionType: 'LAN',
},
};
done();
},
tearDown(done) {
process.stdin.pipe = this.originalProcessStdinProperties.pipe;
process.stdin.setRawMode = this.originalProcessStdinProperties.setRawMode;
sandbox.restore();
done();
},
postRunLAN(test) {
test.expect(2);
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 1);
test.equal(process.stdin.setRawMode.callCount, 1);
test.done();
});
},
postRunUSB(test) {
test.expect(2);
this.notRealTessel.connection.connectionType = 'USB';
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 0);
test.equal(process.stdin.setRawMode.callCount, 0);
test.done();
});
},
};
exports['deployment.js.logMissingBinaryModuleWarning'] = {
setUp(done) {
this.warn = sandbox.stub(log, 'warn');
this.details = {
binName: 'compiled-binary.node',
buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'),
buildType: 'Release',
globPath: path.normalize('node_modules/compiled-binary/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/compiled-binary.node'),
ignored: false,
name: 'compiled-binary',
modulePath: path.normalize('node_modules/compiled-binary'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/compiled-binary-2.0.6-Release-node-v46-linux-mipsel')
};
done();
},
tearDown(done) {
sandbox.restore();
done();
},
callsThroughToLogWarn(test) {
test.expect(1);
deployment.js.logMissingBinaryModuleWarning(this.details);
test.equal(this.warn.callCount, 1);
test.done();
},
includesModuleNameAndVersion(test) {
test.expect(1);
deployment.js.logMissingBinaryModuleWarning(this.details);
var output = this.warn.lastCall.args[0];
test.equal(output.includes('Pre-compiled module is missing: compiled-binary@2.0.6'), true);
test.done();
},
};
exports['deployment.js.minimatch'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
callsThroughToMinimatch(test) {
test.expect(1);
const result = deployment.js.minimatch('', '', {});
test.equal(result, true);
test.done();
},
};
| Java |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, titles, prog='neato', size=None,
type_format=None, filename=None):
"""
Display the results using matplotlib.
"""
if not size:
size = _get_size(len(graphs))
fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10))
fig.set_facecolor('white')
x_val = 0
y_val = 0
index = 0
if size[0] == 1:
axarr = np.array(axarr).reshape((1, size[1]))
for candidate in graphs:
# axarr[x_val, y_val].axis('off')
axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter())
axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter())
axarr[x_val, y_val].xaxis.set_ticks([])
axarr[x_val, y_val].yaxis.set_ticks([])
axarr[x_val, y_val].set_title(titles[index])
# axarr[x_val, y_val].set_axis_bgcolor("white")
if not type_format:
type_format = TYPE_FORMAT
_plot_subplot(candidate, request.nodes(), prog, type_format,
axarr[x_val, y_val])
y_val += 1
if y_val > size[1] - 1:
y_val = 0
x_val += 1
index += 1
fig.tight_layout()
if filename is not None:
plt.savefig(filename)
else:
plt.show()
plt.close()
def _plot_subplot(graph, new_nodes, prog, type_format, axes):
"""
Plot a single candidate graph.
"""
pos = nx.nx_agraph.graphviz_layout(graph, prog=prog)
# draw the nodes
for node, values in graph.nodes(data=True):
shape = 'o'
if values[stitcher.TYPE_ATTR] in type_format:
shape = type_format[values[stitcher.TYPE_ATTR]]
color = 'g'
alpha = 0.8
if node in new_nodes:
color = 'b'
alpha = 0.2
elif 'rank' in values and values['rank'] > 7:
color = 'r'
elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3:
color = 'y'
nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color,
node_shape=shape, alpha=alpha, ax=axes)
# draw the edges
dotted_line = []
normal_line = []
for src, trg in graph.edges():
if src in new_nodes and trg not in new_nodes:
dotted_line.append((src, trg))
else:
normal_line.append((src, trg))
nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted',
ax=axes)
nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes)
# draw labels
nx.draw_networkx_labels(graph, pos, ax=axes)
def show_3d(graphs, request, titles, prog='neato', filename=None):
"""
Show the candidates in 3d - the request elevated above the container.
"""
fig = plt.figure(figsize=(18, 10))
fig.set_facecolor('white')
i = 0
size = _get_size(len(graphs))
for graph in graphs:
axes = fig.add_subplot(size[0], size[1], i+1,
projection=Axes3D.name)
axes.set_title(titles[i])
axes._axis3don = False
_plot_3d_subplot(graph, request, prog, axes)
i += 1
fig.tight_layout()
if filename is not None:
plt.savefig(filename)
else:
plt.show()
plt.close()
def _plot_3d_subplot(graph, request, prog, axes):
"""
Plot a single candidate graph in 3d.
"""
cache = {}
tmp = graph.copy()
for node in request.nodes():
tmp.remove_node(node)
pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog)
# the container
for item in tmp.nodes():
axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None",
marker="o", color='gray')
axes.text(pos[item][0], pos[item][1], 0, item)
for src, trg in tmp.edges():
axes.plot([pos[src][0], pos[trg][0]],
[pos[src][1], pos[trg][1]],
[0, 0], color='gray')
# the new nodes
for item in graph.nodes():
if item in request.nodes():
for nghb in graph.neighbors(item):
if nghb in tmp.nodes():
x_val = pos[nghb][0]
y_val = pos[nghb][1]
if (x_val, y_val) in list(cache.values()):
x_val = pos[nghb][0] + random.randint(10, SPACE)
y_val = pos[nghb][0] + random.randint(10, SPACE)
cache[item] = (x_val, y_val)
# edge
axes.plot([x_val, pos[nghb][0]],
[y_val, pos[nghb][1]],
[SPACE, 0], color='blue')
axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o",
color='blue')
axes.text(x_val, y_val, SPACE, item)
for src, trg in request.edges():
if trg in cache and src in cache:
axes.plot([cache[src][0], cache[trg][0]],
[cache[src][1], cache[trg][1]],
[SPACE, SPACE], color='blue')
def _get_size(n_items):
"""
Calculate the size of the subplot layouts based on number of items.
"""
n_cols = math.ceil(math.sqrt(n_items))
n_rows = math.floor(math.sqrt(n_items))
if n_cols * n_rows < n_items:
n_cols += 1
return int(n_rows), int(n_cols)
| Java |
package de.verygame.surface.screen.base;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.Map;
/**
* @author Rico Schrage
*
* Context which can contain several subscreens.
*/
public class SubScreenContext implements ScreenContext {
/** List of subScreen's plus visibility flag */
protected final ScreenSwitch screenSwitch;
/** viewport of the screen (manages the glViewport) */
protected final Viewport viewport;
/** True if a subScreen is visible */
protected boolean showSubScreen = false;
/**
* Constructs a context with the given viewport.
*
* @param viewport viewport viewport of the screen
*/
public SubScreenContext(Viewport viewport) {
super();
this.viewport = viewport;
this.screenSwitch = new ScreenSwitch();
}
/**
* Sets the dependency map of the screen switch.
*
* @param dependencies map of dependencies
*/
public void setDependencies(Map<String, Object> dependencies) {
screenSwitch.setDependencyMap(dependencies);
}
/**
* Sets the batch of the context.
*
* @param polygonSpriteBatch batch
*/
public void setBatch(PolygonSpriteBatch polygonSpriteBatch) {
screenSwitch.setBatch(polygonSpriteBatch);
}
/**
* Sets the inputHandler of the context.
*
* @param inputHandler inputHandler
*/
public void setInputHandler(InputMultiplexer inputHandler) {
screenSwitch.setInputHandler(inputHandler);
}
public InputMultiplexer getInputHandler() {
return screenSwitch.getInputHandler();
}
public void onActivate(ScreenId screenKey) {
if (screenSwitch.getActiveScreen() != null) {
screenSwitch.getActiveScreen().onActivate(screenKey);
}
}
public float onDeactivate(ScreenId screenKey) {
if (screenSwitch.getActiveScreen() != null) {
return screenSwitch.getActiveScreen().onDeactivate(screenKey);
}
return 0;
}
/**
* Applies the viewport of the context. Calls {@link Viewport#apply(boolean)}.
*/
public void applyViewport() {
viewport.apply(true);
}
/**
* Updates the viewport of the context. Calls {@link Viewport#update(int, int, boolean)}.
*
* @param width width of the frame
* @param height height of the frame
*/
public void updateViewport(int width, int height) {
viewport.update(width, height, true);
}
public void update() {
screenSwitch.updateSwitch();
screenSwitch.updateScreen();
}
public void renderScreen() {
if (showSubScreen) {
screenSwitch.renderScreen();
}
}
public void resizeSubScreen(int width, int height) {
screenSwitch.resize(width, height);
}
public void pauseSubScreen() {
screenSwitch.pause();
}
public void resumeSubScreen() {
screenSwitch.resume();
}
public void dispose() {
screenSwitch.dispose();
}
@Override
public Viewport getViewport() {
return viewport;
}
@Override
public PolygonSpriteBatch getBatch() {
return screenSwitch.getBatch();
}
@Override
public void addSubScreen(SubScreenId id, SubScreen subScreen) {
if (screenSwitch.getBatch() == null) {
throw new IllegalStateException("Parent screen have to be attached to a screen switch!");
}
this.screenSwitch.addScreen(id, subScreen);
}
@Override
public SubScreen getActiveSubScreen() {
return (SubScreen) screenSwitch.getActiveScreen();
}
@Override
public void showScreen(SubScreenId id) {
showSubScreen = true;
screenSwitch.setActive(id);
}
@Override
public void initialize(SubScreenId id) {
showSubScreen = true;
screenSwitch.setScreenSimple(id);
}
@Override
public void hideScreen() {
showSubScreen = false;
}
}
| Java |
package x7c1.linen.scene.updater
import android.app.Service
import x7c1.linen.database.control.DatabaseHelper
import x7c1.linen.glue.service.ServiceControl
import x7c1.linen.repository.date.Date
import x7c1.linen.repository.dummy.DummyFactory
import x7c1.linen.repository.preset.PresetFactory
import x7c1.wheat.macros.logger.Log
import x7c1.wheat.modern.patch.TaskAsync.async
class UpdaterMethods(
service: Service with ServiceControl,
helper: DatabaseHelper,
startId: Int){
def createDummies(max: Int): Unit = async {
Log info "[init]"
val notifier = new UpdaterServiceNotifier(service, max, Date.current(), startId)
DummyFactory.createDummies0(service)(max){ n =>
notifier.notifyProgress(n)
}
notifier.notifyDone()
service stopSelf startId
}
def createPresetJp(): Unit = async {
Log info "[init]"
new PresetFactory(helper).setupJapanesePresets()
}
def createDummySources(channelIds: Seq[Long]) = async {
Log info s"$channelIds"
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Dec 03 20:33:24 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)</title>
<meta name="date" content="2014-12-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package net.sourceforge.pmd.lang.xsl.rule.xpath</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../net/sourceforge/pmd/lang/xsl/rule/xpath/XPathRulesTest.html" title="class in net.sourceforge.pmd.lang.xsl.rule.xpath">XPathRulesTest</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li>
<li>Next Package</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2002–2014 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p>
</body>
</html>
| Java |
import test from 'ava';
import escapeStringRegexp from './index.js';
test('main', t => {
t.is(
escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'),
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]'
);
});
test('escapes `-` in a way compatible with PCRE', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\x2d bar'
);
});
test('escapes `-` in a way compatible with the Unicode flag', t => {
t.regex(
'-',
new RegExp(escapeStringRegexp('-'), 'u')
);
});
| Java |
---
layout: post
title: 《青铜时代》
date: 2015-04-03
categories:
- 一书
tags: [book]
status: publish
type: post
published: true
author_copyright: true
author_footer: false
---
>他要是发现自己对着时空作思想工作,一定以为是对牛弹琴,除了时空,还有诗意──妈的,他怎么会懂得什么叫做诗意。除了诗意,还有恶意。这个他一定能懂。这是他唯一懂得的东西。
>不过我倒因此知道了文明是什么。照我看,文明就是人们告别了原始的游猎生活,搬到一起来住。从此抬头不见低头见,大家都产生了一些共同的想法。在这些想法里,最常见的是觉得别人「欠」,自己亏了。
>王仙客到长安城里找无双,长安城是这么一个地方:从空中俯瞰,它是个四四方方的大院子。在大院子里,套着很多小院子,那就是长安七十二坊,横八竖九,大小都一样。每个坊都有四道门,每个坊都和每个坊一样,每个坊也都像缩小了的长安城一样,而且每个坊都四四方方。坊周围是三丈高的土坯墙,每块土坯都是十三斤重,上下差不了一两。坊里有一些四四方方的院子,没院子的人家房子也盖得四四方方。每座房子都朝着正南方,左右差不了一度。长安城里真正的君子,都长着四方脸,迈着四方步。真正的淑女,长的是四方的屁股,四方的乳房,给孩子喂奶时好像拿了块砖头要拍死他一样。在长安城里,谁敢说「派」,或者是3.14,都是不赦之罪。
>这是因为过去我虽然不缺少下流的想象力,但是不够多愁善感,不能长久地迷恋一个梦。
>王仙客临终时说,他始终也没搞清楚什么是现实,什么是梦。在他看来,苦苦地思索无双去了哪里,就像是现实,因为现实总是具有一种苦涩味。而篱笆上的两层花,迎面走来的穿紫棠木屐的妓女,四面是窗户的小亭子,刺鼻子的粗肥皂味,以及在心中萦绕不去的鱼玄机,等等,就像是一个梦。梦具有一种荒诞的真实性,而真实有一种真实的荒诞性。除了这种感觉上的差异,他说不出这两者之间有什么区别。
>你这坏蛋真的不知道吗?我爱你呀!!
>这个故事就像李先生告诉我的他的故事一样:他年轻的时候,看过一本有关古文字释读的书,知道了世界上还有不少未释读的文字;然后他就想知道这些未读懂的文字是什么,于是就见到了西夏文。再后来他 又想知道西夏文讲了些什么,于是就把一辈子都陷在里面了。像这样的事结果总是很不幸,所以人家基督徒祷告时总说:主哇,请不要使我受诱惑。这话的意思就是说:请不要使我知道任何故事的开头,除非那故事已经结束了。
>当众受阉前他告诉刽子手说:我有疝气病,小的那个才是卵泡,可别割错了。他还请教刽子手说:我是像猪挨阉时一样呦呦叫比较好呢,还是像狗一样汪汪叫好。不要老想着自己是个什么,要想想别人想让咱当个什么,这种态度就叫虚心啦。
>我表哥对我说,每个人一辈子必有一件事是他一生的主题。比方说王仙客罢,他一生的主题就是寻找无双,因为他活着时在寻找无双,到死时还要说:现在我才知道,原来我是为寻找无双而生的。
>鱼玄机在临终时骂起人来,这样很不雅。但是假设有人用绳子勒你脖子,你会有何感触呢?是什么就说什么,是一件需要极大勇气的事;但是假定你生来就很乖,后来又当了模范犯人,你会说什么呢?我们经常感到有一些话早该有人讲出来,但始终不见有人讲。我想,这大概是因为少了一个合适的人去受三绞毙命之刑罢。
>当你无休无止地想一件事时,时间也就无休无止的延长。这两件事是如此的相辅相成,叫人总忘不了冥冥中似有天意那句老话。
>罗素说,假如有个人说,我说的话全是假话,那你就不知拿他怎么办好了:假如你相信他这句话,就是把他当成好人,但他分明是个骗子。假如你不相信他的话,把他当骗子,但是哪有骗子说自己是骗子的?你又只好当他是好人了。罗素他老人家建议我们出门要带手枪,见到这种人就一枪打死他。
>在此以后很短一段时间里,宣阳坊里的人们管长安兵乱,官兵入城,镇压从逆分子等等,叫做闹自卫队。我小时候,认识一个老头子,记得老佛爷闹义和团。正如我插队那个地方管文化大革命叫闹红卫兵。那个地方也有闹自卫队这个词,却是指一九三七年。当时听说日本人要来,当官的就都跑 了。村里忽然冒出一伙人来,手里拿着大刀片,说他们要抗日,让村里出白面,给他们炸油条吃。等到日本人真来了,他们也跑了。据老乡们讲,时候不长,前后也就是半个月。 | Java |
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon(s) in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/myJqueryTimeline.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container" style="padding-top: 30px;">
<div class="row-fluid">
<div id="mike" class="span12">
Timeline
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div id="myTimeline"></div>
</div>
<div class="teste">
</div>
</div>
</div>
<!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>-->
<script src="js/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!--<script src="js/classT.js"></script>-->
<script src="js/myJquery.Timeline.js"></script>
<script src="js/jquery.hoverIntent.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<!--
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
</script>
-->
</body>
</html>
| Java |
require File.dirname(__FILE__) + '/../lib/ruby_js'
require 'test/unit'
require 'active_support/test_case'
RubyJS::Translator.load_paths << File.join(File.dirname(__FILE__), "mock")
RubyJS::Translator.load
| Java |
---
layout: post
title: 課業|蒙文通的經史觀
date: 2018-10-29
categories: blog
tags: 功課
description: 蒙文通的經史觀
---
20160627。大一下朞專必《歷史學理論與方法》作業。主題是「我心目中的歷史學」。當時班主任過來給我說「老師們覺㝵你那篇作業寫㝵不錯,我來轉達一下。」後來成績確實挺髙,不過我覺㝵也沒多好啊。㝡中二的是最後一節,當時剛接觸經學,就有這些中二想法,實際上多是別人的想法。䋣簡自動轉換,改了一些,可能還有錯。
------
> `摘要` 本札記旨在槩述蒙文通對經學與史學關係的認識,這也是他治經的主要成就之一。蒙文通之治經,繞過西漢直抵晚周,主張今古文之分在於諸子時期地域學術的分流。孔子在繼承「舊法丗傳之史」的基礎上刪述六經,寄寓了平等之理想,𢒈成儒學。儒學在西漢之所以取㝵獨尊地位,是因爲其吸收諸子思想,𢒈成了恢弘廣大的學術體系。漢代經師根據當時的政治狀況,對儒家思想進行變革,一改儒學而成經學。本文亦對當今學術分科體系以及經學的處境做出了一些思攷。
>
> `關鍵詞` 蒙文通 經史 今古文 三晉 齊魯 學科
本文分爲六箇部分,第一部分闡述蒙文通對晚周學術狀況的認識,他認爲其時學術按地域分爲三系,均具有各自的特點,今、古學的淵源就在於各自的地域文化特點。第二部分闡述了儒學實本魯舊史以刪述,竝加入完整的理想制度以成。此爲今學的基礎。第三部分闡述在各地域特點的基礎上,儒學受到諸子之學的影響,遂成廣博精深之新儒學。此𢒈成了今文內部的差異。第四部分則推至漢代,晚周學術至炎漢經歷了三箇發展階段,愈變而去先秦儒學愈遠,鮮活的舊史傳記之學變爲了乾枯的平章攷據之學。從經出於史變爲史出於經。第五部分在前者的基礎上,對蒙文通對「託古改制」「六經皆史」的看法進行梳理。㝡後,筆者闡述了自己對經學硏究現狀的思攷。
# 一、晚周地域之學
## (一)統說
井硏廖氏與儀徵劉氏皆以地域畫分今古,雖二人觀點不同,廖氏以爲齊魯爲今,燕趙爲古,劉氏以爲魯學爲古,齊學爲今,但捨今古以進地域,則給了蒙文通很大的啓發。[①]其繼承廖季平餘緒,繞過漢師,直抵晚周,條剖縷析,抉經學之原,將晚周學術畫分爲東、南、北三系,以齊魯之學爲今學,晉䠂之學爲古學,且今古學內部也竝非統一,而是各有淵源。
首先,畫分的標準不是地理意義上的地域,而是文化意義上的地域。合於魯人旨趣者謂魯學,合於齊人旨趣者爲齊學,不限於其是魯人還是齊人。所謂旨趣其實指各國學術是如何受到這箇國家文化傳統、政治制度的影響的。
> 夫《周官》爲孔氏未見之書,丘朙不在弟子之籍,《佚書》《佚禮》出魯壁,當刪餘之經,《費易》《毛詩》出孔門,爲民閒之學,其本非一途,其說非一致,合群書爲之說,建《周官》以爲宗,而古學立。《公羊》、轅固本於齊,《穀梁》、申培出於魯,鄒、夾、韓嬰其源又異,刺六經爲《王制》,合殊科爲今文。古學爲源異而流合,今學亦源異而流合,欲竝胡越爲一家,貯冰炭於同器,自扞隔不可㝵通。……剖析今古家所據之典籍,分別硏討,以求其眞,則漢人今古學之藩籬立卽動搖,徒究心於今古已成之後,而不思求之於今古未建之前……而事則猶疏。[②]
兩漢傳經之學,奇說孔多,奚止四派,豈區區今古兩宗所能盡括?[③]
蒙氏主今古但漢人強制牽合而成,分制《王制》《周官》以攝今、古,廖氏之業雖朙,肰兩漢傳經,奇說孔多,遠非二者所能盡括。今、古內部,亦絕非統一,今古之閒非有堅固不可破之壁壘,若喋喋於今古之辨,於學猶疏。當結兩漢之局,開晚周之緒,緣之以求晚周之學,而成諦論。
## (二)分說
《經學抉原》之《魯學齊學》《晉學䠂學》章辨章列國學術,勾陳四地文海,下將極爲簡略地加以槩括。
魯學精醇謹篤,洙泗儒生,丗守師說。《穀梁》魯學,言禮合於孟子。
齊學雜駁恢弘。齊威王宣王之時,稷下學宮備百家,儒學其一耳。七國之分,法制禮儀竝殊異,故齊學亦兼取各國。《公羊》乃齊學,雜於淳於髡、鄒衍之言。
三晉之學以史見長。《毛詩》傳於趙國毛萇,《左氏》傳於趙國貫長卿,《周官》爲河閒獻王所㝵,魏文侯《孝經傳》爲《周官》之《大司樂》章,河閒,故趙地,則古文爲梁趙之學。又舉例稱,汲冢書中,《紀年》扶同《左氏》,異於《公羊》《穀梁》,《逸周書》多晉史之辭,《師春》全取《左氏》言卜筮事,更可見古文猶梁趙之學。韓非、荀子所言之周公立國,國之不服雲雲,皆齊魯之學所不聞,則三晉之史學視齊魯爲備。
䠂學多神怪。《天問》、《山經》,爭涉神話,語多靈怪,民神糅雜,皆爲樸略之人,知《天問》《山經》所述,自爲䠂之史文;《九歌》所詠雲中君、少司命之類,乃䠂之神鬼。[④]
魯人以經學爲正宗,三晉以史學爲正宗,䠂人以辭賦爲正宗。東方儒墨之學,傳之南北,亦遂分途,莫不受地域之影響。「魯人宿敦禮義,故說湯、武俱爲聖智;晉人宿崇功利,故說舜、禹皆同篡竊;䠂人宿好鬼神,故稱虞、夏極其靈怪。」[⑤]各國史蹟紛亂,乃至首出之王,繼丗之王皆不同。
# 二、據舊史以刪述六經
蒙氏以爲,六經皆本舊法丗傳之史以刪述,灌注理想制度以成。
首先,蒙文通肯定了六國舊史皆在,孔子據舊史以刪述六經是完全可能的。孔子制作《春秋》時求觀於周史記,又求百二十國寶書,是各國典章具存之證。又舉《詩》的例子,孔子之《詩》篇目與《禮記·投壺》不同,《周禮》六義又與孔子《詩》《禮記》均不同,墨子三百篇之說與孔子同,墨子爲魯人,故「《投壺》《周官》所談,儻皆異國之詩耶」。足可見各國史籍紛繁複雜,「列國圖史科類不一,多寡懸殊」,如各國皆有春秋,晉䠂之春秋曰《乘》曰《檮杌》,魯之春秋曰《春秋》。此皆六國史策具在之證。[⑥]
朙確了這一點後,蒙文通進一步指出,孔子大小六蓺之十二經,咸據魯舊史,而非「凡稱先王之法言陳跡者,竝諸子孔氏託古之爲」。「孔子據魯史定六經,肰三年之喪,魯先君莫之行,宰予亦以爲久。」[⑦]宰予、子貢爲孔門大儒,尚疑之,則此必非魯或周之舊禮。
> 自衛反魯,肰後樂正,《雅》《頌》各㝵其所,則樂不復魯之舊也。於《坊記》見《魯春秋》,於《公羊》見《不修春秋》,……則《春秋》之辭微而指博者,亦非魯之舊也。《序卦》《系》《象》,則《易》亦非魯之舊也。[⑧]
樂㝵其正,是樂不再是魯之舊樂。《坊記》《公羊》中有所謂不修春秋之名,則春秋之微言大義乃孔子刪述後方纔具備。《易》有孔子所作之《繫辭》《象傳》,則亦非魯之舊《易》。
他又指出,刪述六經的過程是加入儒家的政治理想的過程,以使其具有微言大義。他通過經學制度和當時漢代現實政治制度的矛盾來進行說朙。井田制和豪強兼竝相矛盾,辟雍選賢和任子爲郎相矛盾,封禪禪讓和天子傳子相矛盾,大射選諸侯和恩澤諸侯相矛盾,朙堂議政和專制獨裁相矛盾。儒者不敢鮮朙地提出作爲反抗綱領,而託之於古聖先賢以避難免禍,不可以書見之,乃以口傳微言大義。六經都是「舊法丗傳之史」,之所以能上升爲「聖經賢傳」,發展成爲具有完整體系的思想系統,正是由於儒生依附六經灌注了自己的整套理想制度。[⑨]「晚周之學重於議政,多與君權不相容,而依託之書遂猥起戰國之季。……曲說偽書者,皆於時理想之所寄、而所謂微言大義者也。此儒家之發展造於極峰。」[⑩]之所以寄以曲說,乃社會環境使肰。
「肰則六經之刪合爲一,未必出於孔子。」這也就是說,蒙文通認爲六經之刪述經歷了一箇較長的過程,表現𢒈式是傳記的逐漸發展。六經爲古文獻,而漢人所言者爲新的理想制度,乃舊文獻與此新制度无抵觸者,正是因爲儒生逐漸對六經進行修改,使之符合新理想制度。
未刪述之六經,猶齊䠂舊史,巫史猶爲之;刪定之書,則大義微言,粲肰朙備,儒家之理想寄託於此,唯七十子之徒、搢紳先生能言之。
# 三、儒學與諸子的關係
蒙文通以爲,在西漢,儒學之所以能取㝵獨尊地位,爲其匯集諸子百家之思想,至爲恢弘廣大,非一家之百氏所能抗衡者。
> 《史記》言:「自孔子卒後,七十子之徒散游諸侯,子路居魏,子張居陳,淡臺子羽居䠂,子夏居西河,子貢終於齊。」則孔氏之學,於時已散在中國。[11]
孔子弟子散於九流,經傳皆互取爲書,儒學因此㝵以不斷發揚。
> 《禮記》則又有取之《逸曲禮》者,《奔喪》、《投壺》是也。有取之《子思子》者,《中庸》《表記》《坊記》是也。有取之《曾子》者,《大孝》《立孝》等十篇是也。有取之《三朝記》者,《千乘》《四代》等也。《三年問》《勸學》取之荀卿,《保傅》取之賈誼,《月令》取之呂不韋,《朙堂》取之《朙堂陰陽》,《緇衣》取之《公孫尼子》,《王度》取之淳於髡。[12]
>
> 漢代經師有法殷法夏之說,繼周損益,二代孰宜,於此不免自爲矛盾。及究論之,法家自託於從殷,儒之言法殷者爲《春秋》家,實取法家以爲義也;墨家自託於法夏,儒之言法夏者爲《禮》家,實取墨家以爲義也。[13]
上爲諸子經傳互取之例。《禮記》有取之《逸曲禮》、子思子、曾子、荀子、呂不韋、賈誼等者,《春秋》取法家義而法殷,《禮》家取墨家義而法夏。傳記之學乃晚周學術之精華,儒學之傳記海納諸子,遂成雄視百家之執,入漢以後㝵獨尊之位理亦宜肰。
> 經與傳記,輔車相依,是入漢而儒者於百家之學、六蓺之文,棄駁而集其醇,益推致其說於精渺,持異已超絕於諸子,獨爲漢之新儒學,論且有優於孟荀,詎先秦百氏所能抗行者哉?百川沸騰,朝宗於海,殊途於事,納於同歸……殆以諸子之義旣萃於經術,則經術爲根底,而百氏其條柯。……其導源於諸子之跡,亦灼肰可朙。誠以今文之約,求諸子之約,以諸子之博,尋今文之博。[14]
經和傳記相互依存,經爲傳之理論依據,傳爲理想之寄託,爲諸子發朙經之大義之所存。入漢以後,儒家於諸子之學擇醇而錄,推演至微,孟荀尚猶不及,遑論百氏百言。諸子百川,畢匯於經學之後海,以儒家爲根基,以百家爲枝蔓,遂成博約爲一之美。以經學之精煉,探求諸子之廣博,以諸子之廣博,解經學之深意。「究諸子之義理,始覺千奇百異畢有統攝,畢有歸宿。六經與百家,必循環反復,乃見相㝵而益彰。」[15]二者互見,乃有大朙,轉相發朙,斯㝵至理。
> 其他各家重在理論的創樹而忽視傳統文獻,儒家則旣重理論又重文獻,諸子以創樹理論爲經,儒家則以傳統文獻爲經,……認識了「六蓺經傳」是諸子思想的發展,纔能認識漢代經學自有其思想體系,纔不會把六蓺經傳當作史料看待。在肯定了經學自有其思想體系後,再來分析經學家所講的禮制,纔能看出這些禮制所體現的思想內容。朙確了經學自有其思想體系,再結合諸子學派作「經」的事來看經師們所傳的六經,就可知衟六經雖是舊史,但經學家不可能絲毫不動地把舊史全盤接受下來,必肰要刪去舊史中和新的思想體系相矛盾扞格的部分,這樣纔能經傳自相吻合。[16]
簡言之,諸子以各自的思想刪述六經,使經變爲自己傳記體系中的一箇部分。經學爲百家言之結論,六經其根基,而精深廣義在傳記,「經其表而傳記爲之裏也」。經學深意,在於傳記,捨傳記而毋論微言大義。
# 四、漢代儒學變爲經學
晚週百家三地學術,在秦漢時走向合流。秦排三晉之學,其時齊魯竝進以漸合,晉學以獨排而別行。故言今古,皆秦漢以後之事,而非晚周之旨。孔孟以降,是爲儒學,儒學一變爲章句之學,是爲今學,今文一變爲訓詁之學,是爲古學。
## (一)大儒學變爲小儒學
蒙氏以爲,自漢武抑絀百家而立學校之官,六經傳記次第刪削,而僅存儒家之一言,六經自此囿於儒家,孔學遂失傳記之學之廣大,儒者之書一變爲經生之業。
「儒之日益精卓者,以其善取於諸子百家之言而大義以恢弘也;儒之日益塞陋者,以其不善取於舊法丗傳之史而以章句訓詁蔀之也。」[17]儒學之所以日益固陋,是因爲它拋棄了晚周時期㝡具生命力的舊法丗傳之史這一核心。失此要義,則諸子精神无所託,儒學風采无以新。捨去諸子,囿於儒家,是爲因,見遮章句,是爲果。此爲第一變。
## (二)儒學變爲今學
> 石渠、白虎以降,委曲枝派之事盛,破碎大衟,孟、荀以來之緒殆幾乎息矣。始之,傳記之學尚存週末之風,終也,射策之科專以解說爲事;自儒學漸變而爲經學,洙泗之業,由發展變而爲停滯。……孟、荀之衟熄,而梁丘、夏侯之說張。[18]
石渠白虎以降,章句之學興而洙泗之業偃,解說之法盛而傳記之蓺息。先漢經說據晚周之故事以爲典要,貴在陳義而非解經,在述志而非闡釋。
師說者,周秦儒生之餘緒也,卽前文所述之集百家之言,捨短取長而成之儒學者也。蒙氏以爲先漢師說相承,儒者之墜緒猶賴以存,故經生之業雖不足貴,而今文學所以猶有足取者也。此爲第二變。
## (三)今學變爲古學
> 自儒者不㝵竟其用於漢,而王莽依之以改革,……逮莽之紛更煩擾而天下不安,新室傾覆,儒者亦嗒焉喪其所主,宏義髙論不爲丗重,而古文家因之以興,刊落精要,反於索寞,惟以訓詁攷證爲學,肰後孔氏之學於以大晦。……東亰之學不爲方言髙論,謹固之風起而恢弘之致衰,士趨於篤行而減於精思理想。[19]
終始先漢,儒生无所用其改制之理想,於是捨棄傳記而沈潛於訓詁攷據,於是古學漸盛,以治史之途治經,「於經師舊說胥加擯斥,亦於鄒魯縉紳之傳直以舊法丗傳之史視之、以舊法丗傳之史攷論之」,經學變爲史學,東亰之學遂與晚周異術。此爲第三變,之後「儒衟喪、微言絕、大義乖,皆漢師之罪也」。[20]
今文傳自晚周儒家,其傳承各有師授,古文學創自西亰末年,其講論篤守舊典,故今文者理想所寄,古文者史蹟所陳也。
# 五、對託古改制、六經皆史的批判
在《古史甄微自序》中,他批判了清人互相攻訐以分今古。劉宋龔魏之流,譏訕康成,詆訐子駿,卽以是爲今文;而古文家徒詆讖緯,矜《蒼》《雅》,人自以爲能宗鄭,而實鮮究其條貫。交口贊康成、毀笵寧,於其旨義之爲一爲二,乃未之詳察。[21]徒以口舌爲勞,乃不究家法丗傳,何裨於今古之辯。今古之分不嚴,又何談託古改制、六經皆史。清季經生之業但門戶之見、黨林之爭耳。
他據《左傳》《國語》的例子,對託古改制說提出質疑。此二書多於孔子義合,難衟不正說朙瞭是祖於孔子嗎。如果說它們不是祖於孔子,那如何解釋其中的制度義理多於孔義相符。如果它們的確是魯國舊史,那麼自肰和孔義合,與晉䠂之學異。劉歆偽造之說則存疑。況且改制說的依據在於隱公改元,肰而《左》紀惠公之元,《國》晉依獻公、文公紀元,《春秋》皆有所記,那麼唯獨魯就是當新王了?素王之說難以成立,那麼改制說亦不攻而破。[22]
於六經皆史,通過前文的敘述,我們可以清䠂地猜測到蒙文通的看法。儒學在舊法丗傳之史的基礎上寄託自己的政治理想,則𢒈成的新儒學已遠去舊史,六經皆史說乃牽強苟合。其亦言:「余舊撰《經學導言》,推論三晉之學,史學實其正宗;則六經、《天問》所陳,翻不免於理想虛構;則六經皆史之談,顯非諦說。……晚近六經皆史之談,旣暗於史,尤病於史。……此六經皆史、託古改制兩說之所不易朙,而追尋今、古之家法,求晉、䠂之師說,或有當也。」[23]他認爲六經皆史之說只會使眞實的古史暗淡失色,經史需分途,猶涇渭之不可相混。「有素樸之三代,史蹟也;有蔚煥之三代,理想也;以理想爲行實,則輕信;等史蹟於設論,則妄疑;輕信、妄疑而學兩傷,……古以史質勝,今以理想髙,混不之辨,」[24]經與史之分乃理想與史蹟之分,分之則兩美,合之則兩傷,今與古之爭變爲了經與史之爭。
從蒙文通對託古改制、六經皆史的質疑中可以看到,他是超越了今古的立場的,而獨主自己的三系說。經學𢒈成的更深層次的過程,在於百家三地學術的匯流,經學的𢒈成不僅受儒學、魯學的影響,不單單是周公之跡、春秋歷史或素王託言、王魯新周那麼簡單。
# 六、餘論
## (一)
蒙氏更提到了保護經學、守護傳統的問題。
> 記注、撰述,判若淵雲,豈可同語,濫竽良史,卽班述《漢書》,唐修五史,蒐羅非不博,比校非不朙,肰漫无紀要,未睹風裁,謂之整齊故事則可,揆諸《春秋》所以爲《春秋》之義,寧无歉肰。[25]
上面這段話,他借用章學誠「記注」與「撰述」的槩念,表朙瞭對義理之史和史料之史的態度。班書唐史雖蒐羅廣大,肰不過整齊故事,整理史料,其中无以見㝵大義與精神,歷史捨微言則成斷爛朝報耳,《春秋》之義,至馬而息。這一態度構成了他看待現代歷史學的一大基礎。
約作於1949年的一篇遺稿這樣寫衟:
> 自秦漢至朙清,經學爲中國民族无上之法典,思想與行爲、政治與風習,皆不能出其軌笵。……其力量之恢弘、影響之深遠,遠非子史文蓺可與抗衡。自清末改制以來,惜學校之經學一科遂分裂而入於數科,以《易》入悊學,《詩》入文學,《尚書》《春秋》《禮》入史學,原本宏偉獨特之經學遂至若存若亡,殆妄以西方學術之分類衡量中國學術,而不顧經學在民族文化中之巨大力量、巨大成就之故也。[26]
他極力反對將中國傳統學術套入西方學科分科體系,完整恢弘之經學入於各科,則支離破碎,學者欲探求聖人大義,則如盲人摸象。他的擔心早已成爲現實。
近年來,學界主張重新回歸經學的呼聲越來越髙。彭林在2008年「經學與中國悊學」國際學術硏討會的會議論文中提倡,復興經學亟待解決三箇問題:一是成立經學系,二是重建經學硏究的課程體系,三是培養專經硏究的青年才俊。但這一構想在當今中國的髙等教育體系中要想實現,實爲困難。人大、武大做出了積極的嘗試,設立國學院,效果如何,尚有待檢驗。是否經學硏究一入髙等教育之門,便成了作爲歷史學的經學,就像傳統音樂一入音樂學院之門,便成了丗界音樂的一箇組成部分,實在不敢㝵出結論。如果不在㝡髙的學科設計、理念上打破現有體系,那麼經學系必定會被歷史系同化。
陳壁生猶爲應重新回歸經學的力倡者。
> 一箇成熟的文朙體,每當遭逢巨變,必回首其文朙的源頭,從發源之處再出發,以此文朙的價値回應遭遇的挑戰,實現眞正的「文蓺復興」。但是,西來新學蜂起……在胡適等人倡導「整理國故」,建立現代分科學術之後,中國學術全面摧毀古典文朙體系,而成爲「丗界學術」的一箇部分。……中華文朙,自漢丗尊奉五經,以爲政治社會之核心價値,二千餘年閒,宅國在茲土,立教在斯人,容有一時之神州激蕩,一代之宗廟丘墟,而疆土、文朙、人種,百丗不絕,此實全賴經學大義之相傳,以保禮樂文朙之不墜。……中國文朙的核心,卽在經學,在經學瓦解百年之後的今天,重新回到經學,纔能深層次地認識歷史,在歷史中尋找未來的方向。[27]
其實陳壁生的主要觀點,蒙氏皆有,只是半箇丗紀過去,在21丗紀的今天,傳統文化的價値重新突現出來,他的認識㝵以隨著時代更深一步。如果說蒙文通反對西方分科體系是因爲无奈地見證了經學在眼下逐漸瓦解的過程,那麼陳壁生反對則是因爲當今在西方學科體系的主導下,傳統文化的發展出現了一些偏離正軌的問題,更因爲當今社會價値的缺失。
經學入於史學,則僅剩史蹟之所陳;入悊學,則僅有儒家倫理之探究,易學之辯證法;入文學,則僅存賦比興之修辭。何以入?以馬克思主義探究史蹟,以西方悊學體系匡正倫理,以西方文學理論架構詩三百。肰經學之要,在制度,在理想,在義理。捨制度无以談理想,捨理想而制度无所歸;捨理想而義理无所現,捨義理而理想爲空言。歷史學欲求制度,文學欲求訓詁修辭,悊學欲求義理,但分別求之,實不能求㝵欲求之物,如「中國悊學」一科,以西方之思辨法推演儒家之衟𢛳倫理,所㝵者不過「己所不欲勿施於人」之𢒈下勸誡,亦或「仁學的𢒈而上學原理」之不倫不類者,儒家的內聖外王理想在西悊看來不過是政治經驗、修身教導,中國文化之價値在西方體系下只能被俯視。經學爲中國文化之大系,是中國文化重綜合的思維方式㝡重要的體現,若框以重分析的西方體系,豈不謬哉。又如之於歷史學,一方面,經學爲硏究史學之工具,亦猶小學爲經學之工具。治經乃治史之階,不朙今古家法,於史料之六經如何取捨,不知理想與史蹟之辨,則雜取攛掇之史料何以求眞。若志在治史,此種態度完全値㝵提倡。但另一方面,經學所含儒家之理想義理,若僅這樣被對待,那將永久地被存封在故紙堆裏,傳統文化的眞正價値何以被挖掘。
如果百年之前是一箇需要破的時代,那麼現在,則是一箇需要重新立的時代。每代人有每代人要做的事,五四先賢之業令人㬌仰,而今天,我們要做和他們「相反」的事。
## (二)
古史辨摧毀一切,新漢學重估一切,而鹽亭蒙氏在時代洪流中獨守西蜀一隅,以飽滿的精神捍衛著華夏文學之尊嚴,實在不易。讀蒙氏之文章,余喟嘆扼腕之處不可勝數,猶念夫聖人之髙渺如日月,杳肰不可階。蒙氏言「餘生雖晚,猶幸㝵聞先𢛳之緒餘,略窺經學之戶牖,則又今之喜而不寐」,吾亦狂喜。而晚年之悲慘境遇,發人唏噓。斯人一去,廖氏餘緒滅,經學大義絕。
蒙氏抉經學之原,以地域畫分晚周學術流派,闡朙今古之淵源,他分析的是「王魯新周」的來龍去脈,而非「王魯新周」本身的含義。此差可算作學術史的硏究笵圍,而不單單是傳統經學所觸及處。經學哉,抑史學哉?大槩他後期由經入史也是必肰。炳麟爲與南海對抗,夷六蓺於古史,視孔子爲古之良史,在消解今學的價値的同時消解了經學的價値,緊接著古史辨、新漢學遂一發不可收拾。蒙氏之業何其相似。六蓺各規整其源流,改制說謬,皆史說陋,經學的神秘性進一步破除,作爲史料學的歷史學亦可趁機而入,將經學的古堡攻佔,插上「史學」的光輝旗幟,竝聲稱站在了科學精神的㝡髙點。全球教主降爲古之良史,素王之享格爲賢師之敬。
這是經學內在邏輯發展的必肰嗎?它自身包含著消解自身的規定性嗎?發展到現代,它眞的足以被文學史學悊學瓜分嗎?退一步講,文學史學悊學聯合起來就可以構成一箇完整的經學嗎?經學眞的足以解決當今中國的弊病嗎?經學是中國自己的學術話語體系的未來嗎?這些仍是値㝵我們思攷和探索的問題。
# 註腳
[①]參見蒙文通:《經學抉原》,《經學抉原》,上海:上海人民出版社,2006年,第55頁。
[②]《井硏廖季平師與近代今文學》,《經學抉原》,第101頁。
[③]《井硏廖師與漢代今古文學》,《經學抉原》,第114頁。
[④]參見《經學抉原》,《經學抉原》,第84—91頁。
[⑤]蒙文通:《古史甄微自序》,《川大史學•蒙文通卷》,成都:四川大學出版社,2006年,第397頁。
[⑥]參見《經學抉原》,《經學抉原》,第57頁。
[⑦]《經學抉原》,《經學抉原》,第58頁。
[⑧]參見《經學抉原》,《經學抉原》,第58—59頁。
[⑨]參見《孔子和今文學》,《經學抉原》,第250頁。
[⑩]《論經學遺稿甲》,《經學抉原》,第206頁。
[11]《經學抉原》,《經學抉原》,第88頁。
[12]《經學抉原》,《經學抉原》,第66頁。
[13]《論經學遺稿丙》,《經學抉原》,第211頁。
[14]《儒學五論題辭》,《經學抉原》,第202—203頁。
[15]《論經學遺稿乙》,《經學抉原》,第208頁。
[16]《孔子和今文學》,《經學抉原》,第262頁。
[17]《論經學遺稿甲》,《經學抉原》,第206頁。
[18]《論經學遺稿甲》,《經學抉原》,第206頁。
[19]《論經學遺稿乙》,《經學抉原》,第208頁。
[20]《論經學遺稿甲》,《經學抉原》,第206頁。
[21]《古史甄微自序》,《川大史學•蒙文通卷》,第396頁。
[22]參見《古史甄微自序》,《川大史學•蒙文通卷》,第398頁。
[23]《古史甄微自序》,《川大史學•蒙文通卷》,第398頁。
[24]《儒家政治思想之發展》,《經學抉原》,第152頁。
[25]蒙文通:《中國史學史•緒言》,《川大史學•蒙文通卷》,第575頁。
[26]《論經學遺稿丙》,《經學抉原》,第209頁。
[27]陳壁生:《經學的瓦解》,上海:華東師笵大學出版社,2014年,第168—169頁。
| Java |
const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, { tableName: 'pokemons' })
Pokemon.getByIdWithLock = function (pokemonId, transaction) {
return Pokemon.findOne({
where: {
id: pokemonId
},
lock: {
level: transaction.LOCK.UPDATE
}
})
}
Pokemon.getByName = function (name) {
return Pokemon.findOne({
where: {
name
}
}).then(checkExists(name))
}
Pokemon.prototype.decreaseStock = function (quantity) {
if (this.stock < quantity) {
return Promise.reject(new InventoryError(this.name, this.stock))
}
this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
}
| Java |
// File auto generated by STUHashTool
using static STULib.Types.Generic.Common;
namespace STULib.Types.Dump {
[STU(0x6250465B)]
public class STU_6250465B : STUInstance {
[STUField(0x6674CA34)]
public string m_6674CA34;
[STUField(0xDC05EA3B)]
public ulong m_DC05EA3B;
[STUField(0x781349E1)]
public byte m_781349E1;
}
}
| Java |
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('advanced-form/integer', {
integration: true
});
test('Render component with attributes', function(assert) {
this.render(
hbs`{{advanced-form/integer min=10 max=20 value=5}}`
);
var $componentInput = this.$('.integer input');
assert.equal($componentInput.val(), '10');
});
| Java |
class DeluxePublisher::Settings < ActiveRecord::Base
set_table_name 'deluxe_publisher_settings'
end | Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.http.policy;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.logging.LogLevel;
import reactor.core.publisher.Mono;
/**
* Manages logging HTTP requests in {@link HttpLoggingPolicy}.
*/
@FunctionalInterface
public interface HttpRequestLogger {
/**
* Gets the {@link LogLevel} used to log the HTTP request.
* <p>
* By default this will return {@link LogLevel#INFORMATIONAL}.
*
* @param loggingOptions The information available during request logging.
* @return The {@link LogLevel} used to log the HTTP request.
*/
default LogLevel getLogLevel(HttpRequestLoggingContext loggingOptions) {
return LogLevel.INFORMATIONAL;
}
/**
* Logs the HTTP request.
* <p>
* To get the {@link LogLevel} used to log the HTTP request use {@link #getLogLevel(HttpRequestLoggingContext)}.
*
* @param logger The {@link ClientLogger} used to log the HTTP request.
* @param loggingOptions The information available during request logging.
* @return A reactive response that indicates that the HTTP request has been logged.
*/
Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions);
}
| Java |
import React from 'react'
import { Hero } from '../../components'
const HeroContainer = () => (
<Hero />
)
export default HeroContainer
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.