text stringlengths 2 99k | meta dict |
|---|---|
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net35;net471</TargetFrameworks>
<RootNamespace>com.spacepuppyeditor</RootNamespace>
<AssemblyName>SPUtilsEditor</AssemblyName>
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\SpacepuppyUnityFramework\Properties\AssemblyVersionInfo.cs" Link="Properties\AssemblyVersionInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="UnityEditor">
<HintPath>..\Resources\UnityEditor.dll</HintPath>
</Reference>
<Reference Include="UnityEditor.Graphs">
<HintPath>..\Resources\UnityEditor.Graphs.dll</HintPath>
</Reference>
<Reference Include="UnityEngine">
<HintPath>..\Resources\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UI">
<HintPath>..\Resources\UnityEngine.UI.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SpacepuppyUnityFramework\SpacepuppyUnityFramework.csproj" />
<ProjectReference Include="..\SpacepuppyUnityFrameworkEditor\SpacepuppyUnityFrameworkEditor.csproj" />
<ProjectReference Include="..\SPUtils\SPUtils.csproj" />
</ItemGroup>
</Project> | {
"pile_set_name": "Github"
} |
The MIT License (MIT)
Copyright (c) 2013 TOML authors
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.
| {
"pile_set_name": "Github"
} |
@charset "UTF-8";
//---------------------------------------------------
// actionsheet.scss
//---------------------------------------------------
$actionsheetFullSwitch: false !default;
.panel--actionsheet {
background: $colorF;
display: none;
.active & {
display: block;
}
@if $actionsheetFullSwitch{
padding: 10px;
.line-list{
border-radius: $radiusBase;
}
} @else {
.line-list{
position: relative;
&::after{
content: "";
@include retina-one-px-border(bottom);
}
&:last-of-type{
&::after{
top: 0;
bottom: auto;
}
}
}
}
} | {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
* (c) 2009 Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Twig_Node_Expression_Binary_Concat extends Twig_Node_Expression_Binary
{
public function operator(Twig_Compiler $compiler)
{
return $compiler->raw('.');
}
}
| {
"pile_set_name": "Github"
} |
---
-api-id: P:Windows.Media.Audio.IAudioNodeWithListener.Listener
-api-type: winrt property
---
<!-- Property syntax
public Windows.Media.Audio.AudioNodeListener Listener { get; set; }
-->
# Windows.Media.Audio.IAudioNodeWithListener.Listener
## -description
Gets or sets the [AudioNodeListener](audionodelistener.md) that describes the position and other characteristics of the listener from which the node's audio is heard when spatial audio processing is used.
## -property-value
The listener for the audio node.
## -remarks
## -examples
## -see-also
| {
"pile_set_name": "Github"
} |
# SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB)
# Copyright (c) 2019 Mellanox Technologies, Inc. All rights reserved.
#cython: language_level=3
from pyverbs.base cimport PyverbsObject, PyverbsCM
cimport pyverbs.libibverbs as v
cdef class QPCap(PyverbsObject):
cdef v.ibv_qp_cap cap
cdef class QPInitAttr(PyverbsObject):
cdef v.ibv_qp_init_attr attr
cdef object scq
cdef object rcq
cdef object srq
cdef class QPInitAttrEx(PyverbsObject):
cdef v.ibv_qp_init_attr_ex attr
cdef object scq
cdef object rcq
cdef object _pd
cdef object xrcd
cdef object srq
cdef class QPAttr(PyverbsObject):
cdef v.ibv_qp_attr attr
cdef class QP(PyverbsCM):
cdef v.ibv_qp *qp
cdef int type
cdef int state
cdef object pd
cdef object context
cdef object xrcd
cpdef close(self)
cdef update_cqs(self, init_attr)
cdef object scq
cdef object rcq
cdef object mws
cdef object srq
cdef add_ref(self, obj)
cdef class DataBuffer(PyverbsCM):
cdef v.ibv_data_buf data
cdef class QPEx(QP):
cdef v.ibv_qp_ex *qp_ex
cdef class ECE(PyverbsCM):
cdef v.ibv_ece ece
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>FooterText</key>
<string>This application makes use of the following third party libraries:</string>
<key>Title</key>
<string>Acknowledgements</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Copyright (c) 2015-2019 Vincent Tourraine (http://www.vtourraine.net)
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>AcknowList</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>The MIT License (MIT)
Copyright (c) 2015-present Yannick Loriot
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>DynamicColor</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>The MIT License (MIT)
Copyright (c) 2018 Wei Wang
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>Kingfisher</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>The MIT License (MIT)
Copyright (c) 2014 Naoto Kaneko
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>Timepiece</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Copyright (c) 2017 Alvin Varghese <alvinvarghese@live.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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>TrySwiftData</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>The MIT License (MIT)
Copyright (c) 2017 Xmartlabs SRL
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.
</string>
<key>License</key>
<string>MIT</string>
<key>Title</key>
<string>XLPagerTabStrip</string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>FooterText</key>
<string>Generated by CocoaPods - https://cocoapods.org</string>
<key>Title</key>
<string></string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
</array>
<key>StringsTable</key>
<string>Acknowledgements</string>
<key>Title</key>
<string>Acknowledgements</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/*global module process*/
(function withNode() {
module.exports = (mainWindow, updateWindow, shell, packageJSON, app) => {
let menuTemplate;
const aboutMenuItem = {
'submenu': [
{
'role': 'about'
},
{
'label': `Version ${packageJSON.version}`,
'enabled': false
},
{
'label': 'Check for Updates...',
click() {
mainWindow.webContents.send('loading:freeze-app');
updateWindow.setMenu(null);
updateWindow.show();
}
},
{
'type': 'separator'
},
{
'label': 'Visit Website',
click() {
shell.openExternal(packageJSON.homepage);
}
}
]
}
, fileMenuItem = {
'label': 'File',
'submenu': [
{
'label': 'Add Project...',
'accelerator': 'CmdOrCtrl+O',
click() {
mainWindow.webContents.send('menu:add-project-folder');
}
}
]
}
, editMenuItem = {
'label': 'Edit',
'submenu': [
{
'role': 'undo'
},
{
'role': 'redo'
},
{
'type': 'separator'
},
{
'role': 'cut'
},
{
'role': 'copy'
},
{
'role': 'paste'
},
{
'role': 'pasteandmatchstyle'
},
{
'role': 'delete'
},
{
'role': 'selectall'
}
]
}
, viewMenuItem = {
'label': 'View',
'submenu': [
{
'role': 'togglefullscreen'
},
{
'type': 'separator'
},
{
'label': 'Developer',
'submenu': [{
'label': 'Open DevTools',
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.openDevTools();
}
}
}]
}
]
}
, windowMenuItem = {
'role': 'window',
'submenu': [
{
'role': 'minimize'
},
{
'role': 'close'
}
]
}
, helpMenuItem = {
'role': 'help',
'submenu': [
{
'label': 'More About',
click() {
shell.openExternal(`${packageJSON.github}`);
}
},
{
'label': 'Report an issue',
click() {
shell.openExternal(`${packageJSON.bugs.url}`);
}
},
{
'type': 'separator'
},
{
'label': 'Donate',
click() {
shell.openExternal(packageJSON.donate.opencollective);
}
},
{
'type': 'separator'
},
{
'label': 'Join Chat',
click() {
shell.openExternal(`${packageJSON.social.gitter.url}`);
}
},
{
'label': 'Follow on Twitter',
click() {
shell.openExternal(`${packageJSON.social.twitter.url}`);
}
}
]
};
if (process.platform !== 'darwin' &&
process.platform !== 'win32') {
//if linux no need for "check for updates"
aboutMenuItem.submenu.splice(2, 1);
}
if (process.platform &&
process.platform === 'darwin') {
aboutMenuItem.label = packageJSON.name;
aboutMenuItem.submenu.push({
'type': 'separator'
});
aboutMenuItem.submenu.push({
'role': 'hide'
});
aboutMenuItem.submenu.push({
'role': 'hideothers'
});
aboutMenuItem.submenu.push({
'role': 'unhide'
});
aboutMenuItem.submenu.push({
'type': 'separator'
});
aboutMenuItem.submenu.push({
'label': 'Restart',
'accelerator': 'CmdOrCtrl+R',
click() {
app.relaunch();
app.quit();
}
});
aboutMenuItem.submenu.push({
'role': 'quit'
});
menuTemplate = [
aboutMenuItem,
fileMenuItem,
editMenuItem,
viewMenuItem,
windowMenuItem,
helpMenuItem
];
} else {
aboutMenuItem.label = 'About';
viewMenuItem.submenu.unshift({
'label': 'Toggle menu',
click() {
mainWindow.setAutoHideMenuBar(true);
if (mainWindow.isMenuBarVisible()) {
mainWindow.setMenuBarVisibility(false);
} else {
mainWindow.setMenuBarVisibility(true);
}
}
});
menuTemplate = [
fileMenuItem,
editMenuItem,
viewMenuItem,
helpMenuItem,
aboutMenuItem
];
}
return menuTemplate;
};
}());
| {
"pile_set_name": "Github"
} |
predicate jacop_lex_lesseq_int(array [int] of var int: x,array [int] of var int: y);
array [1..3] of int: X_INTRODUCED_63 = [1,-1,-1];
array [1..30] of int: X_INTRODUCED_67 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
array [1..2] of int: X_INTRODUCED_74 = [-1,-1];
array [1..2] of int: X_INTRODUCED_196 = [1,-42];
array [1..3] of int: X_INTRODUCED_201 = [1,1,-1];
array [1..5] of int: X_INTRODUCED_291 = [1,1,1,1,-1];
array [1..7] of int: X_INTRODUCED_293 = [1,1,1,1,1,1,-1];
array [1..9] of int: X_INTRODUCED_295 = [1,1,1,1,1,1,1,1,-1];
array [1..11] of int: X_INTRODUCED_298 = [1,1,1,1,1,1,1,1,1,1,-1];
array [1..13] of int: X_INTRODUCED_302 = [1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..15] of int: X_INTRODUCED_306 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..17] of int: X_INTRODUCED_310 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..19] of int: X_INTRODUCED_314 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..21] of int: X_INTRODUCED_318 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..23] of int: X_INTRODUCED_322 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..25] of int: X_INTRODUCED_326 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..27] of int: X_INTRODUCED_330 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..29] of int: X_INTRODUCED_334 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..31] of int: X_INTRODUCED_338 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..33] of int: X_INTRODUCED_342 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..35] of int: X_INTRODUCED_346 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..37] of int: X_INTRODUCED_350 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..39] of int: X_INTRODUCED_354 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..41] of int: X_INTRODUCED_358 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..43] of int: X_INTRODUCED_362 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..45] of int: X_INTRODUCED_366 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..47] of int: X_INTRODUCED_370 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..49] of int: X_INTRODUCED_374 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..51] of int: X_INTRODUCED_378 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..53] of int: X_INTRODUCED_382 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..55] of int: X_INTRODUCED_386 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..57] of int: X_INTRODUCED_390 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..59] of int: X_INTRODUCED_394 = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1];
array [1..2] of int: X_INTRODUCED_398 = [-1,1];
array [1..2] of int: X_INTRODUCED_399 = [1,-1];
var 0..42: X_INTRODUCED_0;
var 0..42: X_INTRODUCED_1;
var 0..42: X_INTRODUCED_2;
var 0..42: X_INTRODUCED_3;
var 0..42: X_INTRODUCED_4;
var 0..42: X_INTRODUCED_5;
var 0..42: X_INTRODUCED_6;
var 0..42: X_INTRODUCED_7;
var 0..42: X_INTRODUCED_8;
var 0..42: X_INTRODUCED_9;
var 0..42: X_INTRODUCED_10;
var 0..42: X_INTRODUCED_11;
var 0..42: X_INTRODUCED_12;
var 0..42: X_INTRODUCED_13;
var 0..42: X_INTRODUCED_14;
var 0..42: X_INTRODUCED_15;
var 0..42: X_INTRODUCED_16;
var 0..42: X_INTRODUCED_17;
var 0..42: X_INTRODUCED_18;
var 0..42: X_INTRODUCED_19;
var 0..42: X_INTRODUCED_20;
var 0..42: X_INTRODUCED_21;
var 0..42: X_INTRODUCED_22;
var 0..42: X_INTRODUCED_23;
var 0..42: X_INTRODUCED_24;
var 0..42: X_INTRODUCED_25;
var 0..42: X_INTRODUCED_26;
var 0..42: X_INTRODUCED_27;
var 0..42: X_INTRODUCED_28;
var 0..42: X_INTRODUCED_29;
var 0..42: X_INTRODUCED_30;
var 0..42: X_INTRODUCED_31;
var 0..42: X_INTRODUCED_32;
var 0..42: X_INTRODUCED_33;
var 0..42: X_INTRODUCED_34;
var 0..42: X_INTRODUCED_35;
var 0..42: X_INTRODUCED_36;
var 0..42: X_INTRODUCED_37;
var 0..42: X_INTRODUCED_38;
var 0..42: X_INTRODUCED_39;
var 0..42: X_INTRODUCED_40;
var 0..42: X_INTRODUCED_41;
var 0..42: X_INTRODUCED_42;
var 0..42: X_INTRODUCED_43;
var 0..42: X_INTRODUCED_44;
var 0..42: X_INTRODUCED_45;
var 0..42: X_INTRODUCED_46;
var 0..42: X_INTRODUCED_47;
var 0..42: X_INTRODUCED_48;
var 0..42: X_INTRODUCED_49;
var 0..42: X_INTRODUCED_50;
var 0..42: X_INTRODUCED_51;
var 0..42: X_INTRODUCED_52;
var 0..42: X_INTRODUCED_53;
var 0..42: X_INTRODUCED_54;
var 0..42: X_INTRODUCED_55;
var 0..42: X_INTRODUCED_56;
var 0..42: X_INTRODUCED_57;
var 0..42: X_INTRODUCED_58;
var 0..42: X_INTRODUCED_59;
var 1..168: X_INTRODUCED_60;
var 1..168: X_INTRODUCED_61;
var 84..168: Production:: output_var:: is_defined_var;
var 28..84: Surplus:: is_defined_var;
var 0..7056: X_INTRODUCED_71 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_72 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_75 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_76 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_78 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_79 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_81 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_82 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_84 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_85 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_87 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_88 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_90 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_91 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_93 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_94 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_96 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_97 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_99 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_100 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_102 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_103 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_105 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_106 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_108 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_109 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_111 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_112 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_114 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_115 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_117 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_118 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_120 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_121 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_123 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_124 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_126 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_127 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_129 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_130 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_132 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_133 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_135 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_136 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_138 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_139 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_141 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_142 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_144 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_145 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_147 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_148 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_150 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_151 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_153 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_154 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_156 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_157 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_159 ::var_is_introduced :: is_defined_var;
var 0..7056: X_INTRODUCED_160 ::var_is_introduced :: is_defined_var;
var 42..84: X_INTRODUCED_397 ::var_is_introduced :: is_defined_var;
array [1..60] of var int: p:: output_array([1..30,1..2]) = [X_INTRODUCED_0,X_INTRODUCED_1,X_INTRODUCED_2,X_INTRODUCED_3,X_INTRODUCED_4,X_INTRODUCED_5,X_INTRODUCED_6,X_INTRODUCED_7,X_INTRODUCED_8,X_INTRODUCED_9,X_INTRODUCED_10,X_INTRODUCED_11,X_INTRODUCED_12,X_INTRODUCED_13,X_INTRODUCED_14,X_INTRODUCED_15,X_INTRODUCED_16,X_INTRODUCED_17,X_INTRODUCED_18,X_INTRODUCED_19,X_INTRODUCED_20,X_INTRODUCED_21,X_INTRODUCED_22,X_INTRODUCED_23,X_INTRODUCED_24,X_INTRODUCED_25,X_INTRODUCED_26,X_INTRODUCED_27,X_INTRODUCED_28,X_INTRODUCED_29,X_INTRODUCED_30,X_INTRODUCED_31,X_INTRODUCED_32,X_INTRODUCED_33,X_INTRODUCED_34,X_INTRODUCED_35,X_INTRODUCED_36,X_INTRODUCED_37,X_INTRODUCED_38,X_INTRODUCED_39,X_INTRODUCED_40,X_INTRODUCED_41,X_INTRODUCED_42,X_INTRODUCED_43,X_INTRODUCED_44,X_INTRODUCED_45,X_INTRODUCED_46,X_INTRODUCED_47,X_INTRODUCED_48,X_INTRODUCED_49,X_INTRODUCED_50,X_INTRODUCED_51,X_INTRODUCED_52,X_INTRODUCED_53,X_INTRODUCED_54,X_INTRODUCED_55,X_INTRODUCED_56,X_INTRODUCED_57,X_INTRODUCED_58,X_INTRODUCED_59];
array [1..2] of var int: R:: output_array([1..2]) = [X_INTRODUCED_60,X_INTRODUCED_61];
array [1..30] of var int: X_INTRODUCED_66 ::var_is_introduced = [X_INTRODUCED_0,X_INTRODUCED_2,X_INTRODUCED_4,X_INTRODUCED_6,X_INTRODUCED_8,X_INTRODUCED_10,X_INTRODUCED_12,X_INTRODUCED_14,X_INTRODUCED_16,X_INTRODUCED_18,X_INTRODUCED_20,X_INTRODUCED_22,X_INTRODUCED_24,X_INTRODUCED_26,X_INTRODUCED_28,X_INTRODUCED_30,X_INTRODUCED_32,X_INTRODUCED_34,X_INTRODUCED_36,X_INTRODUCED_38,X_INTRODUCED_40,X_INTRODUCED_42,X_INTRODUCED_44,X_INTRODUCED_46,X_INTRODUCED_48,X_INTRODUCED_50,X_INTRODUCED_52,X_INTRODUCED_54,X_INTRODUCED_56,X_INTRODUCED_58];
array [1..30] of var int: X_INTRODUCED_70 ::var_is_introduced = [X_INTRODUCED_1,X_INTRODUCED_3,X_INTRODUCED_5,X_INTRODUCED_7,X_INTRODUCED_9,X_INTRODUCED_11,X_INTRODUCED_13,X_INTRODUCED_15,X_INTRODUCED_17,X_INTRODUCED_19,X_INTRODUCED_21,X_INTRODUCED_23,X_INTRODUCED_25,X_INTRODUCED_27,X_INTRODUCED_29,X_INTRODUCED_31,X_INTRODUCED_33,X_INTRODUCED_35,X_INTRODUCED_37,X_INTRODUCED_39,X_INTRODUCED_41,X_INTRODUCED_43,X_INTRODUCED_45,X_INTRODUCED_47,X_INTRODUCED_49,X_INTRODUCED_51,X_INTRODUCED_53,X_INTRODUCED_55,X_INTRODUCED_57,X_INTRODUCED_59];
array [1..2] of var int: X_INTRODUCED_163 ::var_is_introduced = [X_INTRODUCED_2,X_INTRODUCED_3];
array [1..2] of var int: X_INTRODUCED_164 ::var_is_introduced = [X_INTRODUCED_0,X_INTRODUCED_1];
array [1..2] of var int: X_INTRODUCED_165 ::var_is_introduced = [X_INTRODUCED_6,X_INTRODUCED_7];
array [1..2] of var int: X_INTRODUCED_166 ::var_is_introduced = [X_INTRODUCED_4,X_INTRODUCED_5];
array [1..2] of var int: X_INTRODUCED_167 ::var_is_introduced = [X_INTRODUCED_8,X_INTRODUCED_9];
array [1..2] of var int: X_INTRODUCED_168 ::var_is_introduced = [X_INTRODUCED_10,X_INTRODUCED_11];
array [1..2] of var int: X_INTRODUCED_169 ::var_is_introduced = [X_INTRODUCED_16,X_INTRODUCED_17];
array [1..2] of var int: X_INTRODUCED_170 ::var_is_introduced = [X_INTRODUCED_14,X_INTRODUCED_15];
array [1..2] of var int: X_INTRODUCED_171 ::var_is_introduced = [X_INTRODUCED_18,X_INTRODUCED_19];
array [1..2] of var int: X_INTRODUCED_172 ::var_is_introduced = [X_INTRODUCED_20,X_INTRODUCED_21];
array [1..2] of var int: X_INTRODUCED_173 ::var_is_introduced = [X_INTRODUCED_24,X_INTRODUCED_25];
array [1..2] of var int: X_INTRODUCED_174 ::var_is_introduced = [X_INTRODUCED_22,X_INTRODUCED_23];
array [1..2] of var int: X_INTRODUCED_175 ::var_is_introduced = [X_INTRODUCED_26,X_INTRODUCED_27];
array [1..2] of var int: X_INTRODUCED_176 ::var_is_introduced = [X_INTRODUCED_28,X_INTRODUCED_29];
array [1..2] of var int: X_INTRODUCED_177 ::var_is_introduced = [X_INTRODUCED_30,X_INTRODUCED_31];
array [1..2] of var int: X_INTRODUCED_178 ::var_is_introduced = [X_INTRODUCED_32,X_INTRODUCED_33];
array [1..2] of var int: X_INTRODUCED_179 ::var_is_introduced = [X_INTRODUCED_36,X_INTRODUCED_37];
array [1..2] of var int: X_INTRODUCED_180 ::var_is_introduced = [X_INTRODUCED_34,X_INTRODUCED_35];
array [1..2] of var int: X_INTRODUCED_181 ::var_is_introduced = [X_INTRODUCED_38,X_INTRODUCED_39];
array [1..2] of var int: X_INTRODUCED_182 ::var_is_introduced = [X_INTRODUCED_40,X_INTRODUCED_41];
array [1..2] of var int: X_INTRODUCED_183 ::var_is_introduced = [X_INTRODUCED_44,X_INTRODUCED_45];
array [1..2] of var int: X_INTRODUCED_184 ::var_is_introduced = [X_INTRODUCED_42,X_INTRODUCED_43];
array [1..2] of var int: X_INTRODUCED_185 ::var_is_introduced = [X_INTRODUCED_46,X_INTRODUCED_47];
array [1..2] of var int: X_INTRODUCED_186 ::var_is_introduced = [X_INTRODUCED_48,X_INTRODUCED_49];
array [1..2] of var int: X_INTRODUCED_187 ::var_is_introduced = [X_INTRODUCED_50,X_INTRODUCED_51];
array [1..2] of var int: X_INTRODUCED_188 ::var_is_introduced = [X_INTRODUCED_52,X_INTRODUCED_53];
array [1..2] of var int: X_INTRODUCED_189 ::var_is_introduced = [X_INTRODUCED_54,X_INTRODUCED_55];
array [1..2] of var int: X_INTRODUCED_190 ::var_is_introduced = [X_INTRODUCED_58,X_INTRODUCED_59];
array [1..2] of var int: X_INTRODUCED_191 ::var_is_introduced = [X_INTRODUCED_56,X_INTRODUCED_57];
array [1..11] of var int: X_INTRODUCED_297 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,Surplus];
array [1..13] of var int: X_INTRODUCED_301 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,Surplus];
array [1..15] of var int: X_INTRODUCED_305 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,Surplus];
array [1..17] of var int: X_INTRODUCED_309 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,Surplus];
array [1..19] of var int: X_INTRODUCED_313 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,Surplus];
array [1..21] of var int: X_INTRODUCED_317 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,Surplus];
array [1..23] of var int: X_INTRODUCED_321 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,Surplus];
array [1..25] of var int: X_INTRODUCED_325 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,Surplus];
array [1..27] of var int: X_INTRODUCED_329 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,Surplus];
array [1..29] of var int: X_INTRODUCED_333 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,Surplus];
array [1..31] of var int: X_INTRODUCED_337 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,Surplus];
array [1..33] of var int: X_INTRODUCED_341 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,Surplus];
array [1..35] of var int: X_INTRODUCED_345 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,Surplus];
array [1..37] of var int: X_INTRODUCED_349 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,Surplus];
array [1..39] of var int: X_INTRODUCED_353 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,Surplus];
array [1..41] of var int: X_INTRODUCED_357 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,Surplus];
array [1..43] of var int: X_INTRODUCED_361 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,Surplus];
array [1..45] of var int: X_INTRODUCED_365 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,Surplus];
array [1..47] of var int: X_INTRODUCED_369 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,Surplus];
array [1..49] of var int: X_INTRODUCED_373 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,Surplus];
array [1..51] of var int: X_INTRODUCED_377 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_144,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,X_INTRODUCED_145,Surplus];
array [1..53] of var int: X_INTRODUCED_381 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_144,X_INTRODUCED_147,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,X_INTRODUCED_145,X_INTRODUCED_148,Surplus];
array [1..55] of var int: X_INTRODUCED_385 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_144,X_INTRODUCED_147,X_INTRODUCED_150,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,X_INTRODUCED_145,X_INTRODUCED_148,X_INTRODUCED_151,Surplus];
array [1..57] of var int: X_INTRODUCED_389 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_144,X_INTRODUCED_147,X_INTRODUCED_150,X_INTRODUCED_153,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,X_INTRODUCED_145,X_INTRODUCED_148,X_INTRODUCED_151,X_INTRODUCED_154,Surplus];
array [1..59] of var int: X_INTRODUCED_393 ::var_is_introduced = [X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_84,X_INTRODUCED_87,X_INTRODUCED_90,X_INTRODUCED_93,X_INTRODUCED_96,X_INTRODUCED_99,X_INTRODUCED_102,X_INTRODUCED_105,X_INTRODUCED_108,X_INTRODUCED_111,X_INTRODUCED_114,X_INTRODUCED_117,X_INTRODUCED_120,X_INTRODUCED_123,X_INTRODUCED_126,X_INTRODUCED_129,X_INTRODUCED_132,X_INTRODUCED_135,X_INTRODUCED_138,X_INTRODUCED_141,X_INTRODUCED_144,X_INTRODUCED_147,X_INTRODUCED_150,X_INTRODUCED_153,X_INTRODUCED_156,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,X_INTRODUCED_85,X_INTRODUCED_88,X_INTRODUCED_91,X_INTRODUCED_94,X_INTRODUCED_97,X_INTRODUCED_100,X_INTRODUCED_103,X_INTRODUCED_106,X_INTRODUCED_109,X_INTRODUCED_112,X_INTRODUCED_115,X_INTRODUCED_118,X_INTRODUCED_121,X_INTRODUCED_124,X_INTRODUCED_127,X_INTRODUCED_130,X_INTRODUCED_133,X_INTRODUCED_136,X_INTRODUCED_139,X_INTRODUCED_142,X_INTRODUCED_145,X_INTRODUCED_148,X_INTRODUCED_151,X_INTRODUCED_154,X_INTRODUCED_157,Surplus];
array [1..62] of var int: X_INTRODUCED_401 ::var_is_introduced = [X_INTRODUCED_0,X_INTRODUCED_1,X_INTRODUCED_2,X_INTRODUCED_3,X_INTRODUCED_4,X_INTRODUCED_5,X_INTRODUCED_6,X_INTRODUCED_7,X_INTRODUCED_8,X_INTRODUCED_9,X_INTRODUCED_10,X_INTRODUCED_11,X_INTRODUCED_12,X_INTRODUCED_13,X_INTRODUCED_14,X_INTRODUCED_15,X_INTRODUCED_16,X_INTRODUCED_17,X_INTRODUCED_18,X_INTRODUCED_19,X_INTRODUCED_20,X_INTRODUCED_21,X_INTRODUCED_22,X_INTRODUCED_23,X_INTRODUCED_24,X_INTRODUCED_25,X_INTRODUCED_26,X_INTRODUCED_27,X_INTRODUCED_28,X_INTRODUCED_29,X_INTRODUCED_30,X_INTRODUCED_31,X_INTRODUCED_32,X_INTRODUCED_33,X_INTRODUCED_34,X_INTRODUCED_35,X_INTRODUCED_36,X_INTRODUCED_37,X_INTRODUCED_38,X_INTRODUCED_39,X_INTRODUCED_40,X_INTRODUCED_41,X_INTRODUCED_42,X_INTRODUCED_43,X_INTRODUCED_44,X_INTRODUCED_45,X_INTRODUCED_46,X_INTRODUCED_47,X_INTRODUCED_48,X_INTRODUCED_49,X_INTRODUCED_50,X_INTRODUCED_51,X_INTRODUCED_52,X_INTRODUCED_53,X_INTRODUCED_54,X_INTRODUCED_55,X_INTRODUCED_56,X_INTRODUCED_57,X_INTRODUCED_58,X_INTRODUCED_59,X_INTRODUCED_60,X_INTRODUCED_61];
constraint int_lin_eq(X_INTRODUCED_63,[Production,X_INTRODUCED_60,X_INTRODUCED_61],0):: defines_var(Production);
constraint int_lin_eq(X_INTRODUCED_67,X_INTRODUCED_66,42);
constraint int_lin_eq(X_INTRODUCED_67,X_INTRODUCED_70,42);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_71,X_INTRODUCED_72],-280);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_75,X_INTRODUCED_76],-280);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_78,X_INTRODUCED_79],-230);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_81,X_INTRODUCED_82],-230);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_84,X_INTRODUCED_85],-230);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_87,X_INTRODUCED_88],-230);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_90,X_INTRODUCED_91],-150);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_93,X_INTRODUCED_94],-100);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_96,X_INTRODUCED_97],-100);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_99,X_INTRODUCED_100],-100);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_102,X_INTRODUCED_103],-100);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_105,X_INTRODUCED_106],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_108,X_INTRODUCED_109],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_111,X_INTRODUCED_112],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_114,X_INTRODUCED_115],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_117,X_INTRODUCED_118],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_120,X_INTRODUCED_121],-90);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_123,X_INTRODUCED_124],-80);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_126,X_INTRODUCED_127],-80);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_129,X_INTRODUCED_130],-80);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_132,X_INTRODUCED_133],-80);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_135,X_INTRODUCED_136],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_138,X_INTRODUCED_139],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_141,X_INTRODUCED_142],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_144,X_INTRODUCED_145],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_147,X_INTRODUCED_148],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_150,X_INTRODUCED_151],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_153,X_INTRODUCED_154],-70);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_156,X_INTRODUCED_157],-60);
constraint int_lin_le(X_INTRODUCED_74,[X_INTRODUCED_159,X_INTRODUCED_160],-60);
constraint jacop_lex_lesseq_int(X_INTRODUCED_164,X_INTRODUCED_163);
constraint jacop_lex_lesseq_int(X_INTRODUCED_166,X_INTRODUCED_165);
constraint jacop_lex_lesseq_int(X_INTRODUCED_165,X_INTRODUCED_167);
constraint jacop_lex_lesseq_int(X_INTRODUCED_167,X_INTRODUCED_168);
constraint jacop_lex_lesseq_int(X_INTRODUCED_170,X_INTRODUCED_169);
constraint jacop_lex_lesseq_int(X_INTRODUCED_169,X_INTRODUCED_171);
constraint jacop_lex_lesseq_int(X_INTRODUCED_171,X_INTRODUCED_172);
constraint jacop_lex_lesseq_int(X_INTRODUCED_174,X_INTRODUCED_173);
constraint jacop_lex_lesseq_int(X_INTRODUCED_173,X_INTRODUCED_175);
constraint jacop_lex_lesseq_int(X_INTRODUCED_175,X_INTRODUCED_176);
constraint jacop_lex_lesseq_int(X_INTRODUCED_176,X_INTRODUCED_177);
constraint jacop_lex_lesseq_int(X_INTRODUCED_177,X_INTRODUCED_178);
constraint jacop_lex_lesseq_int(X_INTRODUCED_180,X_INTRODUCED_179);
constraint jacop_lex_lesseq_int(X_INTRODUCED_179,X_INTRODUCED_181);
constraint jacop_lex_lesseq_int(X_INTRODUCED_181,X_INTRODUCED_182);
constraint jacop_lex_lesseq_int(X_INTRODUCED_184,X_INTRODUCED_183);
constraint jacop_lex_lesseq_int(X_INTRODUCED_183,X_INTRODUCED_185);
constraint jacop_lex_lesseq_int(X_INTRODUCED_185,X_INTRODUCED_186);
constraint jacop_lex_lesseq_int(X_INTRODUCED_186,X_INTRODUCED_187);
constraint jacop_lex_lesseq_int(X_INTRODUCED_187,X_INTRODUCED_188);
constraint jacop_lex_lesseq_int(X_INTRODUCED_188,X_INTRODUCED_189);
constraint jacop_lex_lesseq_int(X_INTRODUCED_191,X_INTRODUCED_190);
constraint int_lin_eq(X_INTRODUCED_196,[Surplus,Production],-3500):: defines_var(Surplus);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_71,X_INTRODUCED_72,Surplus],560);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_75,X_INTRODUCED_76,Surplus],560);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_78,X_INTRODUCED_79,Surplus],460);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_81,X_INTRODUCED_82,Surplus],460);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_84,X_INTRODUCED_85,Surplus],460);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_87,X_INTRODUCED_88,Surplus],460);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_90,X_INTRODUCED_91,Surplus],300);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_93,X_INTRODUCED_94,Surplus],200);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_96,X_INTRODUCED_97,Surplus],200);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_99,X_INTRODUCED_100,Surplus],200);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_102,X_INTRODUCED_103,Surplus],200);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_105,X_INTRODUCED_106,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_108,X_INTRODUCED_109,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_111,X_INTRODUCED_112,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_114,X_INTRODUCED_115,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_117,X_INTRODUCED_118,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_120,X_INTRODUCED_121,Surplus],180);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_123,X_INTRODUCED_124,Surplus],160);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_126,X_INTRODUCED_127,Surplus],160);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_129,X_INTRODUCED_130,Surplus],160);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_132,X_INTRODUCED_133,Surplus],160);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_135,X_INTRODUCED_136,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_138,X_INTRODUCED_139,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_141,X_INTRODUCED_142,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_144,X_INTRODUCED_145,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_147,X_INTRODUCED_148,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_150,X_INTRODUCED_151,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_153,X_INTRODUCED_154,Surplus],140);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_156,X_INTRODUCED_157,Surplus],120);
constraint int_lin_le(X_INTRODUCED_201,[X_INTRODUCED_159,X_INTRODUCED_160,Surplus],120);
constraint int_lin_le(X_INTRODUCED_291,[X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_72,X_INTRODUCED_76,Surplus],1120);
constraint int_lin_le(X_INTRODUCED_293,[X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,Surplus],1580);
constraint int_lin_le(X_INTRODUCED_295,[X_INTRODUCED_71,X_INTRODUCED_75,X_INTRODUCED_78,X_INTRODUCED_81,X_INTRODUCED_72,X_INTRODUCED_76,X_INTRODUCED_79,X_INTRODUCED_82,Surplus],2040);
constraint int_lin_le(X_INTRODUCED_298,X_INTRODUCED_297,2500);
constraint int_lin_le(X_INTRODUCED_302,X_INTRODUCED_301,2960);
constraint int_lin_le(X_INTRODUCED_306,X_INTRODUCED_305,3260);
constraint int_lin_le(X_INTRODUCED_310,X_INTRODUCED_309,3460);
constraint int_lin_le(X_INTRODUCED_314,X_INTRODUCED_313,3660);
constraint int_lin_le(X_INTRODUCED_318,X_INTRODUCED_317,3860);
constraint int_lin_le(X_INTRODUCED_322,X_INTRODUCED_321,4060);
constraint int_lin_le(X_INTRODUCED_326,X_INTRODUCED_325,4240);
constraint int_lin_le(X_INTRODUCED_330,X_INTRODUCED_329,4420);
constraint int_lin_le(X_INTRODUCED_334,X_INTRODUCED_333,4600);
constraint int_lin_le(X_INTRODUCED_338,X_INTRODUCED_337,4780);
constraint int_lin_le(X_INTRODUCED_342,X_INTRODUCED_341,4960);
constraint int_lin_le(X_INTRODUCED_346,X_INTRODUCED_345,5140);
constraint int_lin_le(X_INTRODUCED_350,X_INTRODUCED_349,5300);
constraint int_lin_le(X_INTRODUCED_354,X_INTRODUCED_353,5460);
constraint int_lin_le(X_INTRODUCED_358,X_INTRODUCED_357,5620);
constraint int_lin_le(X_INTRODUCED_362,X_INTRODUCED_361,5780);
constraint int_lin_le(X_INTRODUCED_366,X_INTRODUCED_365,5920);
constraint int_lin_le(X_INTRODUCED_370,X_INTRODUCED_369,6060);
constraint int_lin_le(X_INTRODUCED_374,X_INTRODUCED_373,6200);
constraint int_lin_le(X_INTRODUCED_378,X_INTRODUCED_377,6340);
constraint int_lin_le(X_INTRODUCED_382,X_INTRODUCED_381,6480);
constraint int_lin_le(X_INTRODUCED_386,X_INTRODUCED_385,6620);
constraint int_lin_le(X_INTRODUCED_390,X_INTRODUCED_389,6760);
constraint int_lin_le(X_INTRODUCED_394,X_INTRODUCED_393,6880);
constraint int_div(Production,2,X_INTRODUCED_397):: defines_var(X_INTRODUCED_397);
constraint int_lin_le(X_INTRODUCED_398,[X_INTRODUCED_61,X_INTRODUCED_397],0);
constraint int_lin_le(X_INTRODUCED_399,[X_INTRODUCED_60,X_INTRODUCED_397],0);
constraint int_times(X_INTRODUCED_0,X_INTRODUCED_60,X_INTRODUCED_71):: defines_var(X_INTRODUCED_71);
constraint int_times(X_INTRODUCED_1,X_INTRODUCED_61,X_INTRODUCED_72):: defines_var(X_INTRODUCED_72);
constraint int_times(X_INTRODUCED_2,X_INTRODUCED_60,X_INTRODUCED_75):: defines_var(X_INTRODUCED_75);
constraint int_times(X_INTRODUCED_3,X_INTRODUCED_61,X_INTRODUCED_76):: defines_var(X_INTRODUCED_76);
constraint int_times(X_INTRODUCED_4,X_INTRODUCED_60,X_INTRODUCED_78):: defines_var(X_INTRODUCED_78);
constraint int_times(X_INTRODUCED_5,X_INTRODUCED_61,X_INTRODUCED_79):: defines_var(X_INTRODUCED_79);
constraint int_times(X_INTRODUCED_6,X_INTRODUCED_60,X_INTRODUCED_81):: defines_var(X_INTRODUCED_81);
constraint int_times(X_INTRODUCED_7,X_INTRODUCED_61,X_INTRODUCED_82):: defines_var(X_INTRODUCED_82);
constraint int_times(X_INTRODUCED_8,X_INTRODUCED_60,X_INTRODUCED_84):: defines_var(X_INTRODUCED_84);
constraint int_times(X_INTRODUCED_9,X_INTRODUCED_61,X_INTRODUCED_85):: defines_var(X_INTRODUCED_85);
constraint int_times(X_INTRODUCED_10,X_INTRODUCED_60,X_INTRODUCED_87):: defines_var(X_INTRODUCED_87);
constraint int_times(X_INTRODUCED_11,X_INTRODUCED_61,X_INTRODUCED_88):: defines_var(X_INTRODUCED_88);
constraint int_times(X_INTRODUCED_12,X_INTRODUCED_60,X_INTRODUCED_90):: defines_var(X_INTRODUCED_90);
constraint int_times(X_INTRODUCED_13,X_INTRODUCED_61,X_INTRODUCED_91):: defines_var(X_INTRODUCED_91);
constraint int_times(X_INTRODUCED_14,X_INTRODUCED_60,X_INTRODUCED_93):: defines_var(X_INTRODUCED_93);
constraint int_times(X_INTRODUCED_15,X_INTRODUCED_61,X_INTRODUCED_94):: defines_var(X_INTRODUCED_94);
constraint int_times(X_INTRODUCED_16,X_INTRODUCED_60,X_INTRODUCED_96):: defines_var(X_INTRODUCED_96);
constraint int_times(X_INTRODUCED_17,X_INTRODUCED_61,X_INTRODUCED_97):: defines_var(X_INTRODUCED_97);
constraint int_times(X_INTRODUCED_18,X_INTRODUCED_60,X_INTRODUCED_99):: defines_var(X_INTRODUCED_99);
constraint int_times(X_INTRODUCED_19,X_INTRODUCED_61,X_INTRODUCED_100):: defines_var(X_INTRODUCED_100);
constraint int_times(X_INTRODUCED_20,X_INTRODUCED_60,X_INTRODUCED_102):: defines_var(X_INTRODUCED_102);
constraint int_times(X_INTRODUCED_21,X_INTRODUCED_61,X_INTRODUCED_103):: defines_var(X_INTRODUCED_103);
constraint int_times(X_INTRODUCED_22,X_INTRODUCED_60,X_INTRODUCED_105):: defines_var(X_INTRODUCED_105);
constraint int_times(X_INTRODUCED_23,X_INTRODUCED_61,X_INTRODUCED_106):: defines_var(X_INTRODUCED_106);
constraint int_times(X_INTRODUCED_24,X_INTRODUCED_60,X_INTRODUCED_108):: defines_var(X_INTRODUCED_108);
constraint int_times(X_INTRODUCED_25,X_INTRODUCED_61,X_INTRODUCED_109):: defines_var(X_INTRODUCED_109);
constraint int_times(X_INTRODUCED_26,X_INTRODUCED_60,X_INTRODUCED_111):: defines_var(X_INTRODUCED_111);
constraint int_times(X_INTRODUCED_27,X_INTRODUCED_61,X_INTRODUCED_112):: defines_var(X_INTRODUCED_112);
constraint int_times(X_INTRODUCED_28,X_INTRODUCED_60,X_INTRODUCED_114):: defines_var(X_INTRODUCED_114);
constraint int_times(X_INTRODUCED_29,X_INTRODUCED_61,X_INTRODUCED_115):: defines_var(X_INTRODUCED_115);
constraint int_times(X_INTRODUCED_30,X_INTRODUCED_60,X_INTRODUCED_117):: defines_var(X_INTRODUCED_117);
constraint int_times(X_INTRODUCED_31,X_INTRODUCED_61,X_INTRODUCED_118):: defines_var(X_INTRODUCED_118);
constraint int_times(X_INTRODUCED_32,X_INTRODUCED_60,X_INTRODUCED_120):: defines_var(X_INTRODUCED_120);
constraint int_times(X_INTRODUCED_33,X_INTRODUCED_61,X_INTRODUCED_121):: defines_var(X_INTRODUCED_121);
constraint int_times(X_INTRODUCED_34,X_INTRODUCED_60,X_INTRODUCED_123):: defines_var(X_INTRODUCED_123);
constraint int_times(X_INTRODUCED_35,X_INTRODUCED_61,X_INTRODUCED_124):: defines_var(X_INTRODUCED_124);
constraint int_times(X_INTRODUCED_36,X_INTRODUCED_60,X_INTRODUCED_126):: defines_var(X_INTRODUCED_126);
constraint int_times(X_INTRODUCED_37,X_INTRODUCED_61,X_INTRODUCED_127):: defines_var(X_INTRODUCED_127);
constraint int_times(X_INTRODUCED_38,X_INTRODUCED_60,X_INTRODUCED_129):: defines_var(X_INTRODUCED_129);
constraint int_times(X_INTRODUCED_39,X_INTRODUCED_61,X_INTRODUCED_130):: defines_var(X_INTRODUCED_130);
constraint int_times(X_INTRODUCED_40,X_INTRODUCED_60,X_INTRODUCED_132):: defines_var(X_INTRODUCED_132);
constraint int_times(X_INTRODUCED_41,X_INTRODUCED_61,X_INTRODUCED_133):: defines_var(X_INTRODUCED_133);
constraint int_times(X_INTRODUCED_42,X_INTRODUCED_60,X_INTRODUCED_135):: defines_var(X_INTRODUCED_135);
constraint int_times(X_INTRODUCED_43,X_INTRODUCED_61,X_INTRODUCED_136):: defines_var(X_INTRODUCED_136);
constraint int_times(X_INTRODUCED_44,X_INTRODUCED_60,X_INTRODUCED_138):: defines_var(X_INTRODUCED_138);
constraint int_times(X_INTRODUCED_45,X_INTRODUCED_61,X_INTRODUCED_139):: defines_var(X_INTRODUCED_139);
constraint int_times(X_INTRODUCED_46,X_INTRODUCED_60,X_INTRODUCED_141):: defines_var(X_INTRODUCED_141);
constraint int_times(X_INTRODUCED_47,X_INTRODUCED_61,X_INTRODUCED_142):: defines_var(X_INTRODUCED_142);
constraint int_times(X_INTRODUCED_48,X_INTRODUCED_60,X_INTRODUCED_144):: defines_var(X_INTRODUCED_144);
constraint int_times(X_INTRODUCED_49,X_INTRODUCED_61,X_INTRODUCED_145):: defines_var(X_INTRODUCED_145);
constraint int_times(X_INTRODUCED_50,X_INTRODUCED_60,X_INTRODUCED_147):: defines_var(X_INTRODUCED_147);
constraint int_times(X_INTRODUCED_51,X_INTRODUCED_61,X_INTRODUCED_148):: defines_var(X_INTRODUCED_148);
constraint int_times(X_INTRODUCED_52,X_INTRODUCED_60,X_INTRODUCED_150):: defines_var(X_INTRODUCED_150);
constraint int_times(X_INTRODUCED_53,X_INTRODUCED_61,X_INTRODUCED_151):: defines_var(X_INTRODUCED_151);
constraint int_times(X_INTRODUCED_54,X_INTRODUCED_60,X_INTRODUCED_153):: defines_var(X_INTRODUCED_153);
constraint int_times(X_INTRODUCED_55,X_INTRODUCED_61,X_INTRODUCED_154):: defines_var(X_INTRODUCED_154);
constraint int_times(X_INTRODUCED_56,X_INTRODUCED_60,X_INTRODUCED_156):: defines_var(X_INTRODUCED_156);
constraint int_times(X_INTRODUCED_57,X_INTRODUCED_61,X_INTRODUCED_157):: defines_var(X_INTRODUCED_157);
constraint int_times(X_INTRODUCED_58,X_INTRODUCED_60,X_INTRODUCED_159):: defines_var(X_INTRODUCED_159);
constraint int_times(X_INTRODUCED_59,X_INTRODUCED_61,X_INTRODUCED_160):: defines_var(X_INTRODUCED_160);
solve :: int_search(X_INTRODUCED_401,input_order,indomain_min,complete) minimize Production;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2008, 2010, 2011, 2016 Otto Moerbeek <otto@drijf.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "includes.h"
#include <stdlib.h>
#include <string.h>
#ifndef HAVE_FREEZERO
void
freezero(void *ptr, size_t sz)
{
if (ptr == NULL)
return;
explicit_bzero(ptr, sz);
free(ptr);
}
#endif /* HAVE_FREEZERO */
| {
"pile_set_name": "Github"
} |
/*************************************************************************************
Toolkit for WPF
Copyright (C) 2007-2020 Xceed Software Inc.
This program is provided to you under the terms of the XCEED SOFTWARE, INC.
COMMUNITY LICENSE AGREEMENT (for non-commercial use) as published at
https://github.com/xceedsoftware/wpftoolkit/blob/master/license.md
For more features, controls, and fast professional support,
pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !VS2008
using System.ComponentModel.DataAnnotations;
#endif
using System.Diagnostics;
using System.Linq;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace Xceed.Wpf.Toolkit.PropertyGrid
{
internal class ObjectContainerHelper : ObjectContainerHelperBase
{
private object _selectedObject;
public ObjectContainerHelper( IPropertyContainer propertyContainer, object selectedObject )
: base( propertyContainer )
{
_selectedObject = selectedObject;
}
private object SelectedObject
{
get
{
return _selectedObject;
}
}
protected override string GetDefaultPropertyName()
{
object selectedObject = SelectedObject;
return ( selectedObject != null ) ? ObjectContainerHelperBase.GetDefaultPropertyName( SelectedObject ) : ( string )null;
}
protected override void GenerateSubPropertiesCore( Action<IEnumerable<PropertyItem>> updatePropertyItemsCallback )
{
var propertyItems = new List<PropertyItem>();
if( SelectedObject != null )
{
try
{
var descriptors = new List<PropertyDescriptor>();
{
descriptors = ObjectContainerHelperBase.GetPropertyDescriptors( SelectedObject, this.PropertyContainer.HideInheritedProperties );
}
foreach( var descriptor in descriptors )
{
var propertyDef = this.GetPropertyDefinition( descriptor );
bool isBrowsable = false;
var isPropertyBrowsable = this.PropertyContainer.IsPropertyVisible( descriptor );
if( isPropertyBrowsable.HasValue )
{
isBrowsable = isPropertyBrowsable.Value;
}
else
{
#if !VS2008
var displayAttribute = PropertyGridUtilities.GetAttribute<DisplayAttribute>( descriptor );
if( displayAttribute != null )
{
var autoGenerateField = displayAttribute.GetAutoGenerateField();
isBrowsable = this.PropertyContainer.AutoGenerateProperties
&& ((autoGenerateField.HasValue && autoGenerateField.Value) || !autoGenerateField.HasValue);
}
else
#endif
{
isBrowsable = descriptor.IsBrowsable && this.PropertyContainer.AutoGenerateProperties;
}
if( propertyDef != null )
{
isBrowsable = propertyDef.IsBrowsable.GetValueOrDefault( isBrowsable );
}
}
if( isBrowsable )
{
var prop = this.CreatePropertyItem( descriptor, propertyDef );
if( prop != null )
{
propertyItems.Add( prop );
}
}
}
}
catch( Exception e )
{
//TODO: handle this some how
Debug.WriteLine( "Property creation failed." );
Debug.WriteLine( e.StackTrace );
}
}
updatePropertyItemsCallback.Invoke( propertyItems );
}
private PropertyItem CreatePropertyItem( PropertyDescriptor property, PropertyDefinition propertyDef )
{
DescriptorPropertyDefinition definition = new DescriptorPropertyDefinition( property, SelectedObject, this.PropertyContainer );
definition.InitProperties();
this.InitializeDescriptorDefinition( definition, propertyDef );
PropertyItem propertyItem = new PropertyItem( definition );
Debug.Assert( SelectedObject != null );
propertyItem.Instance = SelectedObject;
propertyItem.CategoryOrder = this.GetCategoryOrder( definition.CategoryValue );
propertyItem.WillRefreshPropertyGrid = this.GetWillRefreshPropertyGrid( property );
return propertyItem;
}
private int GetCategoryOrder( object categoryValue )
{
Debug.Assert( this.SelectedObject != null );
if( categoryValue == null )
return int.MaxValue;
int order = int.MaxValue;
var orderAttribute = TypeDescriptor.GetAttributes( this.SelectedObject )
.OfType<CategoryOrderAttribute>()
.FirstOrDefault( attribute => Equals( attribute.CategoryValue, categoryValue ) );
if( orderAttribute != null )
{
order = orderAttribute.Order;
}
return order;
}
}
}
| {
"pile_set_name": "Github"
} |
package net.ttddyy.dsproxy.proxy;
/**
* Provide a method to unwrap the original jdbc object from proxy object.
*
* <p>Proxy object created by {@link JdbcProxyFactory} implements this interface.
*
* @author Tadaya Tsuyukubo
* @see JdbcProxyFactory
* @see net.ttddyy.dsproxy.proxy.jdk.ConnectionInvocationHandler
* @see net.ttddyy.dsproxy.proxy.jdk.StatementInvocationHandler
* @see net.ttddyy.dsproxy.proxy.jdk.PreparedStatementInvocationHandler
* @see net.ttddyy.dsproxy.proxy.jdk.CallableStatementInvocationHandler
* @see net.ttddyy.dsproxy.proxy.jdk.ResultSetInvocationHandler
*/
public interface ProxyJdbcObject {
/**
* Method to return wrapped source object(Connection, Statement, PreparedStatement, CallableStatement).
*
* @return source object
*/
Object getTarget();
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="135"
android:endColor="@color/gradient_middle_1"
android:startColor="@color/gradient_middle_2" />
</shape>
| {
"pile_set_name": "Github"
} |
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD 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.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file rail_gui.cpp %File for dealing with rail construction user interface */
#include "stdafx.h"
#include "gui.h"
#include "window_gui.h"
#include "station_gui.h"
#include "terraform_gui.h"
#include "viewport_func.h"
#include "command_func.h"
#include "waypoint_func.h"
#include "newgrf_station.h"
#include "company_base.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "sound_func.h"
#include "company_func.h"
#include "widgets/dropdown_type.h"
#include "tunnelbridge.h"
#include "tilehighlight_func.h"
#include "spritecache.h"
#include "core/geometry_func.hpp"
#include "hotkeys.h"
#include "engine_base.h"
#include "vehicle_func.h"
#include "zoom_func.h"
#include "rail_gui.h"
#include "station_map.h"
#include "tunnelbridge_map.h"
#include "widgets/rail_widget.h"
#include "safeguards.h"
static RailType _cur_railtype; ///< Rail type of the current build-rail toolbar.
static bool _remove_button_clicked; ///< Flag whether 'remove' toggle-button is currently enabled
static DiagDirection _build_depot_direction; ///< Currently selected depot direction
static byte _waypoint_count = 1; ///< Number of waypoint types
static byte _cur_waypoint_type; ///< Currently selected waypoint type
static bool _convert_signal_button; ///< convert signal button in the signal GUI pressed
static SignalVariant _cur_signal_variant; ///< set the signal variant (for signal GUI)
static SignalType _cur_signal_type; ///< set the signal type (for signal GUI)
/* Map the setting: default_signal_type to the corresponding signal type */
static const SignalType _default_signal_type[] = {SIGTYPE_NORMAL, SIGTYPE_PBS, SIGTYPE_PBS_ONEWAY};
struct RailStationGUISettings {
Axis orientation; ///< Currently selected rail station orientation
bool newstations; ///< Are custom station definitions available?
StationClassID station_class; ///< Currently selected custom station class (if newstations is \c true )
byte station_type; ///< %Station type within the currently selected custom station class (if newstations is \c true )
byte station_count; ///< Number of custom stations (if newstations is \c true )
};
static RailStationGUISettings _railstation; ///< Settings of the station builder GUI
static void HandleStationPlacement(TileIndex start, TileIndex end);
static void ShowBuildTrainDepotPicker(Window *parent);
static void ShowBuildWaypointPicker(Window *parent);
static void ShowStationBuilder(Window *parent);
static void ShowSignalBuilder(Window *parent);
/**
* Check whether a station type can be build.
* @return true if building is allowed.
*/
static bool IsStationAvailable(const StationSpec *statspec)
{
if (statspec == nullptr || !HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) return true;
uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
if (cb_res == CALLBACK_FAILED) return true;
return Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res);
}
void CcPlaySound_SPLAT_RAIL(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
{
if (result.Succeeded() && _settings_client.sound.confirm) SndPlayTileFx(SND_20_SPLAT_RAIL, tile);
}
static void GenericPlaceRail(TileIndex tile, int cmd)
{
DoCommandP(tile, _cur_railtype, cmd,
_remove_button_clicked ?
CMD_REMOVE_SINGLE_RAIL | CMD_MSG(STR_ERROR_CAN_T_REMOVE_RAILROAD_TRACK) :
CMD_BUILD_SINGLE_RAIL | CMD_MSG(STR_ERROR_CAN_T_BUILD_RAILROAD_TRACK),
CcPlaySound_SPLAT_RAIL);
}
/**
* Try to add an additional rail-track at the entrance of a depot
* @param tile Tile to use for adding the rail-track
* @param dir Direction to check for already present tracks
* @param track Track to add
* @see CcRailDepot()
*/
static void PlaceExtraDepotRail(TileIndex tile, DiagDirection dir, Track track)
{
if (GetRailTileType(tile) != RAIL_TILE_NORMAL) return;
if ((GetTrackBits(tile) & DiagdirReachesTracks(dir)) == 0) return;
DoCommandP(tile, _cur_railtype, track, CMD_BUILD_SINGLE_RAIL);
}
/** Additional pieces of track to add at the entrance of a depot. */
static const Track _place_depot_extra_track[12] = {
TRACK_LEFT, TRACK_UPPER, TRACK_UPPER, TRACK_RIGHT, // First additional track for directions 0..3
TRACK_X, TRACK_Y, TRACK_X, TRACK_Y, // Second additional track
TRACK_LOWER, TRACK_LEFT, TRACK_RIGHT, TRACK_LOWER, // Third additional track
};
/** Direction to check for existing track pieces. */
static const DiagDirection _place_depot_extra_dir[12] = {
DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_SE, DIAGDIR_SW,
DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_NE, DIAGDIR_SE,
DIAGDIR_NW, DIAGDIR_NE, DIAGDIR_NW, DIAGDIR_NE,
};
void CcRailDepot(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
{
if (result.Failed()) return;
DiagDirection dir = (DiagDirection)p2;
if (_settings_client.sound.confirm) SndPlayTileFx(SND_20_SPLAT_RAIL, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
tile += TileOffsByDiagDir(dir);
if (IsTileType(tile, MP_RAILWAY)) {
PlaceExtraDepotRail(tile, _place_depot_extra_dir[dir], _place_depot_extra_track[dir]);
PlaceExtraDepotRail(tile, _place_depot_extra_dir[dir + 4], _place_depot_extra_track[dir + 4]);
PlaceExtraDepotRail(tile, _place_depot_extra_dir[dir + 8], _place_depot_extra_track[dir + 8]);
}
}
/**
* Place a rail waypoint.
* @param tile Position to start dragging a waypoint.
*/
static void PlaceRail_Waypoint(TileIndex tile)
{
if (_remove_button_clicked) {
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_REMOVE_STATION);
return;
}
Axis axis = GetAxisForNewWaypoint(tile);
if (IsValidAxis(axis)) {
/* Valid tile for waypoints */
VpStartPlaceSizing(tile, axis == AXIS_X ? VPM_X_LIMITED : VPM_Y_LIMITED, DDSP_BUILD_STATION);
VpSetPlaceSizingLimit(_settings_game.station.station_spread);
} else {
/* Tile where we can't build rail waypoints. This is always going to fail,
* but provides the user with a proper error message. */
DoCommandP(tile, 1 << 8 | 1 << 16, STAT_CLASS_WAYP | INVALID_STATION << 16, CMD_BUILD_RAIL_WAYPOINT | CMD_MSG(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT));
}
}
void CcStation(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
{
if (result.Failed()) return;
if (_settings_client.sound.confirm) SndPlayTileFx(SND_20_SPLAT_RAIL, tile);
/* Only close the station builder window if the default station and non persistent building is chosen. */
if (_railstation.station_class == STAT_CLASS_DFLT && _railstation.station_type == 0 && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
}
/**
* Place a rail station.
* @param tile Position to place or start dragging a station.
*/
static void PlaceRail_Station(TileIndex tile)
{
if (_remove_button_clicked) {
VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_REMOVE_STATION);
VpSetPlaceSizingLimit(-1);
} else if (_settings_client.gui.station_dragdrop) {
VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_BUILD_STATION);
VpSetPlaceSizingLimit(_settings_game.station.station_spread);
} else {
uint32 p1 = _cur_railtype | _railstation.orientation << 6 | _settings_client.gui.station_numtracks << 8 | _settings_client.gui.station_platlength << 16 | _ctrl_pressed << 24;
uint32 p2 = _railstation.station_class | _railstation.station_type << 8 | INVALID_STATION << 16;
int w = _settings_client.gui.station_numtracks;
int h = _settings_client.gui.station_platlength;
if (!_railstation.orientation) Swap(w, h);
CommandContainer cmdcont = { tile, p1, p2, CMD_BUILD_RAIL_STATION | CMD_MSG(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION), CcStation, "" };
ShowSelectStationIfNeeded(cmdcont, TileArea(tile, w, h));
}
}
/**
* Build a new signal or edit/remove a present signal, use CmdBuildSingleSignal() or CmdRemoveSingleSignal() in rail_cmd.cpp
*
* @param tile The tile where the signal will build or edit
*/
static void GenericPlaceSignals(TileIndex tile)
{
TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
if (trackbits & TRACK_BIT_VERT) { // N-S direction
trackbits = (_tile_fract_coords.x <= _tile_fract_coords.y) ? TRACK_BIT_RIGHT : TRACK_BIT_LEFT;
}
if (trackbits & TRACK_BIT_HORZ) { // E-W direction
trackbits = (_tile_fract_coords.x + _tile_fract_coords.y <= 15) ? TRACK_BIT_UPPER : TRACK_BIT_LOWER;
}
Track track = FindFirstTrack(trackbits);
if (_remove_button_clicked) {
DoCommandP(tile, track, 0, CMD_REMOVE_SIGNALS | CMD_MSG(STR_ERROR_CAN_T_REMOVE_SIGNALS_FROM), CcPlaySound_SPLAT_RAIL);
} else {
const Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
/* Map the setting cycle_signal_types to the lower and upper allowed signal type. */
static const uint cycle_bounds[] = {SIGTYPE_NORMAL | (SIGTYPE_LAST_NOPBS << 3), SIGTYPE_PBS | (SIGTYPE_LAST << 3), SIGTYPE_NORMAL | (SIGTYPE_LAST << 3)};
/* various bitstuffed elements for CmdBuildSingleSignal() */
uint32 p1 = track;
if (w != nullptr) {
/* signal GUI is used */
SB(p1, 3, 1, _ctrl_pressed);
SB(p1, 4, 1, _cur_signal_variant);
SB(p1, 5, 3, _cur_signal_type);
SB(p1, 8, 1, _convert_signal_button);
SB(p1, 9, 6, cycle_bounds[_settings_client.gui.cycle_signal_types]);
} else {
SB(p1, 3, 1, _ctrl_pressed);
SB(p1, 4, 1, (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC));
SB(p1, 5, 3, _default_signal_type[_settings_client.gui.default_signal_type]);
SB(p1, 8, 1, 0);
SB(p1, 9, 6, cycle_bounds[_settings_client.gui.cycle_signal_types]);
}
DoCommandP(tile, p1, 0, CMD_BUILD_SIGNALS |
CMD_MSG((w != nullptr && _convert_signal_button) ? STR_ERROR_SIGNAL_CAN_T_CONVERT_SIGNALS_HERE : STR_ERROR_CAN_T_BUILD_SIGNALS_HERE),
CcPlaySound_SPLAT_RAIL);
}
}
/**
* Start placing a rail bridge.
* @param tile Position of the first tile of the bridge.
* @param w Rail toolbar window.
*/
static void PlaceRail_Bridge(TileIndex tile, Window *w)
{
if (IsBridgeTile(tile)) {
TileIndex other_tile = GetOtherTunnelBridgeEnd(tile);
Point pt = {0, 0};
w->OnPlaceMouseUp(VPM_X_OR_Y, DDSP_BUILD_BRIDGE, pt, other_tile, tile);
} else {
VpStartPlaceSizing(tile, VPM_X_OR_Y, DDSP_BUILD_BRIDGE);
}
}
/** Command callback for building a tunnel */
void CcBuildRailTunnel(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
{
if (result.Succeeded()) {
if (_settings_client.sound.confirm) SndPlayTileFx(SND_20_SPLAT_RAIL, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
} else {
SetRedErrorSquare(_build_tunnel_endtile);
}
}
/**
* Toggles state of the Remove button of Build rail toolbar
* @param w window the button belongs to
*/
static void ToggleRailButton_Remove(Window *w)
{
DeleteWindowById(WC_SELECT_STATION, 0);
w->ToggleWidgetLoweredState(WID_RAT_REMOVE);
w->SetWidgetDirty(WID_RAT_REMOVE);
_remove_button_clicked = w->IsWidgetLowered(WID_RAT_REMOVE);
SetSelectionRed(_remove_button_clicked);
}
/**
* Updates the Remove button because of Ctrl state change
* @param w window the button belongs to
* @return true iff the remove button was changed
*/
static bool RailToolbar_CtrlChanged(Window *w)
{
if (w->IsWidgetDisabled(WID_RAT_REMOVE)) return false;
/* allow ctrl to switch remove mode only for these widgets */
for (uint i = WID_RAT_BUILD_NS; i <= WID_RAT_BUILD_STATION; i++) {
if ((i <= WID_RAT_AUTORAIL || i >= WID_RAT_BUILD_WAYPOINT) && w->IsWidgetLowered(i)) {
ToggleRailButton_Remove(w);
return true;
}
}
return false;
}
/**
* The "remove"-button click proc of the build-rail toolbar.
* @param w Build-rail toolbar window
* @see BuildRailToolbarWindow::OnClick()
*/
static void BuildRailClick_Remove(Window *w)
{
if (w->IsWidgetDisabled(WID_RAT_REMOVE)) return;
ToggleRailButton_Remove(w);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
/* handle station builder */
if (w->IsWidgetLowered(WID_RAT_BUILD_STATION)) {
if (_remove_button_clicked) {
/* starting drag & drop remove */
if (!_settings_client.gui.station_dragdrop) {
SetTileSelectSize(1, 1);
} else {
VpSetPlaceSizingLimit(-1);
}
} else {
/* starting station build mode */
if (!_settings_client.gui.station_dragdrop) {
int x = _settings_client.gui.station_numtracks;
int y = _settings_client.gui.station_platlength;
if (_railstation.orientation == 0) Swap(x, y);
SetTileSelectSize(x, y);
} else {
VpSetPlaceSizingLimit(_settings_game.station.station_spread);
}
}
}
}
static void DoRailroadTrack(int mode)
{
DoCommandP(TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y), _cur_railtype | (mode << 6),
_remove_button_clicked ?
CMD_REMOVE_RAILROAD_TRACK | CMD_MSG(STR_ERROR_CAN_T_REMOVE_RAILROAD_TRACK) :
CMD_BUILD_RAILROAD_TRACK | CMD_MSG(STR_ERROR_CAN_T_BUILD_RAILROAD_TRACK),
CcPlaySound_SPLAT_RAIL);
}
static void HandleAutodirPlacement()
{
int trackstat = _thd.drawstyle & HT_DIR_MASK; // 0..5
if (_thd.drawstyle & HT_RAIL) { // one tile case
GenericPlaceRail(TileVirtXY(_thd.selend.x, _thd.selend.y), trackstat);
return;
}
DoRailroadTrack(trackstat);
}
/**
* Build new signals or remove signals or (if only one tile marked) edit a signal.
*
* If one tile marked abort and use GenericPlaceSignals()
* else use CmdBuildSingleSignal() or CmdRemoveSingleSignal() in rail_cmd.cpp to build many signals
*/
static void HandleAutoSignalPlacement()
{
uint32 p2 = GB(_thd.drawstyle, 0, 3); // 0..5
if ((_thd.drawstyle & HT_DRAG_MASK) == HT_RECT) { // one tile case
GenericPlaceSignals(TileVirtXY(_thd.selend.x, _thd.selend.y));
return;
}
const Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
if (w != nullptr) {
/* signal GUI is used */
SB(p2, 3, 1, 0);
SB(p2, 4, 1, _cur_signal_variant);
SB(p2, 6, 1, _ctrl_pressed);
SB(p2, 7, 3, _cur_signal_type);
SB(p2, 24, 8, _settings_client.gui.drag_signals_density);
SB(p2, 10, 1, !_settings_client.gui.drag_signals_fixed_distance);
} else {
SB(p2, 3, 1, 0);
SB(p2, 4, 1, (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC));
SB(p2, 6, 1, _ctrl_pressed);
SB(p2, 7, 3, _default_signal_type[_settings_client.gui.default_signal_type]);
SB(p2, 24, 8, _settings_client.gui.drag_signals_density);
SB(p2, 10, 1, !_settings_client.gui.drag_signals_fixed_distance);
}
/* _settings_client.gui.drag_signals_density is given as a parameter such that each user
* in a network game can specify his/her own signal density */
DoCommandP(TileVirtXY(_thd.selstart.x, _thd.selstart.y), TileVirtXY(_thd.selend.x, _thd.selend.y), p2,
_remove_button_clicked ?
CMD_REMOVE_SIGNAL_TRACK | CMD_MSG(STR_ERROR_CAN_T_REMOVE_SIGNALS_FROM) :
CMD_BUILD_SIGNAL_TRACK | CMD_MSG(STR_ERROR_CAN_T_BUILD_SIGNALS_HERE),
CcPlaySound_SPLAT_RAIL);
}
/** Rail toolbar management class. */
struct BuildRailToolbarWindow : Window {
RailType railtype; ///< Rail type to build.
int last_user_action; ///< Last started user action.
BuildRailToolbarWindow(WindowDesc *desc, RailType railtype) : Window(desc)
{
this->InitNested(TRANSPORT_RAIL);
this->SetupRailToolbar(railtype);
this->DisableWidget(WID_RAT_REMOVE);
this->last_user_action = WIDGET_LIST_END;
if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this);
}
~BuildRailToolbarWindow()
{
if (this->IsWidgetLowered(WID_RAT_BUILD_STATION)) SetViewportCatchmentStation(nullptr, true);
if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false);
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (!gui_scope) return;
if (!CanBuildVehicleInfrastructure(VEH_TRAIN)) delete this;
}
/**
* Configures the rail toolbar for railtype given
* @param railtype the railtype to display
*/
void SetupRailToolbar(RailType railtype)
{
this->railtype = railtype;
const RailtypeInfo *rti = GetRailTypeInfo(railtype);
assert(railtype < RAILTYPE_END);
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_NS)->widget_data = rti->gui_sprites.build_ns_rail;
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_X)->widget_data = rti->gui_sprites.build_x_rail;
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_EW)->widget_data = rti->gui_sprites.build_ew_rail;
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_Y)->widget_data = rti->gui_sprites.build_y_rail;
this->GetWidget<NWidgetCore>(WID_RAT_AUTORAIL)->widget_data = rti->gui_sprites.auto_rail;
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_DEPOT)->widget_data = rti->gui_sprites.build_depot;
this->GetWidget<NWidgetCore>(WID_RAT_CONVERT_RAIL)->widget_data = rti->gui_sprites.convert_rail;
this->GetWidget<NWidgetCore>(WID_RAT_BUILD_TUNNEL)->widget_data = rti->gui_sprites.build_tunnel;
}
/**
* Switch to another rail type.
* @param railtype New rail type.
*/
void ModifyRailType(RailType railtype)
{
this->SetupRailToolbar(railtype);
this->ReInit();
}
void UpdateRemoveWidgetStatus(int clicked_widget)
{
switch (clicked_widget) {
case WID_RAT_REMOVE:
/* If it is the removal button that has been clicked, do nothing,
* as it is up to the other buttons to drive removal status */
return;
case WID_RAT_BUILD_NS:
case WID_RAT_BUILD_X:
case WID_RAT_BUILD_EW:
case WID_RAT_BUILD_Y:
case WID_RAT_AUTORAIL:
case WID_RAT_BUILD_WAYPOINT:
case WID_RAT_BUILD_STATION:
case WID_RAT_BUILD_SIGNALS:
/* Removal button is enabled only if the rail/signal/waypoint/station
* button is still lowered. Once raised, it has to be disabled */
this->SetWidgetDisabledState(WID_RAT_REMOVE, !this->IsWidgetLowered(clicked_widget));
break;
default:
/* When any other buttons than rail/signal/waypoint/station, raise and
* disable the removal button */
this->DisableWidget(WID_RAT_REMOVE);
this->RaiseWidget(WID_RAT_REMOVE);
break;
}
}
void SetStringParameters(int widget) const override
{
if (widget == WID_RAT_CAPTION) {
const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
if (rti->max_speed > 0) {
SetDParam(0, STR_TOOLBAR_RAILTYPE_VELOCITY);
SetDParam(1, rti->strings.toolbar_caption);
SetDParam(2, rti->max_speed);
} else {
SetDParam(0, rti->strings.toolbar_caption);
}
}
}
void OnClick(Point pt, int widget, int click_count) override
{
if (widget < WID_RAT_BUILD_NS) return;
_remove_button_clicked = false;
switch (widget) {
case WID_RAT_BUILD_NS:
HandlePlacePushButton(this, WID_RAT_BUILD_NS, GetRailTypeInfo(_cur_railtype)->cursor.rail_ns, HT_LINE | HT_DIR_VL);
this->last_user_action = widget;
break;
case WID_RAT_BUILD_X:
HandlePlacePushButton(this, WID_RAT_BUILD_X, GetRailTypeInfo(_cur_railtype)->cursor.rail_swne, HT_LINE | HT_DIR_X);
this->last_user_action = widget;
break;
case WID_RAT_BUILD_EW:
HandlePlacePushButton(this, WID_RAT_BUILD_EW, GetRailTypeInfo(_cur_railtype)->cursor.rail_ew, HT_LINE | HT_DIR_HL);
this->last_user_action = widget;
break;
case WID_RAT_BUILD_Y:
HandlePlacePushButton(this, WID_RAT_BUILD_Y, GetRailTypeInfo(_cur_railtype)->cursor.rail_nwse, HT_LINE | HT_DIR_Y);
this->last_user_action = widget;
break;
case WID_RAT_AUTORAIL:
HandlePlacePushButton(this, WID_RAT_AUTORAIL, GetRailTypeInfo(_cur_railtype)->cursor.autorail, HT_RAIL);
this->last_user_action = widget;
break;
case WID_RAT_DEMOLISH:
HandlePlacePushButton(this, WID_RAT_DEMOLISH, ANIMCURSOR_DEMOLISH, HT_RECT | HT_DIAGONAL);
this->last_user_action = widget;
break;
case WID_RAT_BUILD_DEPOT:
if (HandlePlacePushButton(this, WID_RAT_BUILD_DEPOT, GetRailTypeInfo(_cur_railtype)->cursor.depot, HT_RECT)) {
ShowBuildTrainDepotPicker(this);
this->last_user_action = widget;
}
break;
case WID_RAT_BUILD_WAYPOINT:
this->last_user_action = widget;
_waypoint_count = StationClass::Get(STAT_CLASS_WAYP)->GetSpecCount();
if (HandlePlacePushButton(this, WID_RAT_BUILD_WAYPOINT, SPR_CURSOR_WAYPOINT, HT_RECT) && _waypoint_count > 1) {
ShowBuildWaypointPicker(this);
}
break;
case WID_RAT_BUILD_STATION:
if (HandlePlacePushButton(this, WID_RAT_BUILD_STATION, SPR_CURSOR_RAIL_STATION, HT_RECT)) {
ShowStationBuilder(this);
this->last_user_action = widget;
}
break;
case WID_RAT_BUILD_SIGNALS: {
this->last_user_action = widget;
bool started = HandlePlacePushButton(this, WID_RAT_BUILD_SIGNALS, ANIMCURSOR_BUILDSIGNALS, HT_RECT);
if (started && _settings_client.gui.enable_signal_gui != _ctrl_pressed) {
ShowSignalBuilder(this);
}
break;
}
case WID_RAT_BUILD_BRIDGE:
HandlePlacePushButton(this, WID_RAT_BUILD_BRIDGE, SPR_CURSOR_BRIDGE, HT_RECT);
this->last_user_action = widget;
break;
case WID_RAT_BUILD_TUNNEL:
HandlePlacePushButton(this, WID_RAT_BUILD_TUNNEL, GetRailTypeInfo(_cur_railtype)->cursor.tunnel, HT_SPECIAL);
this->last_user_action = widget;
break;
case WID_RAT_REMOVE:
BuildRailClick_Remove(this);
break;
case WID_RAT_CONVERT_RAIL:
HandlePlacePushButton(this, WID_RAT_CONVERT_RAIL, GetRailTypeInfo(_cur_railtype)->cursor.convert, HT_RECT | HT_DIAGONAL);
this->last_user_action = widget;
break;
default: NOT_REACHED();
}
this->UpdateRemoveWidgetStatus(widget);
if (_ctrl_pressed) RailToolbar_CtrlChanged(this);
}
EventState OnHotkey(int hotkey) override
{
MarkTileDirtyByTile(TileVirtXY(_thd.pos.x, _thd.pos.y)); // redraw tile selection
return Window::OnHotkey(hotkey);
}
void OnPlaceObject(Point pt, TileIndex tile) override
{
switch (this->last_user_action) {
case WID_RAT_BUILD_NS:
VpStartPlaceSizing(tile, VPM_FIX_VERTICAL | VPM_RAILDIRS, DDSP_PLACE_RAIL);
break;
case WID_RAT_BUILD_X:
VpStartPlaceSizing(tile, VPM_FIX_Y | VPM_RAILDIRS, DDSP_PLACE_RAIL);
break;
case WID_RAT_BUILD_EW:
VpStartPlaceSizing(tile, VPM_FIX_HORIZONTAL | VPM_RAILDIRS, DDSP_PLACE_RAIL);
break;
case WID_RAT_BUILD_Y:
VpStartPlaceSizing(tile, VPM_FIX_X | VPM_RAILDIRS, DDSP_PLACE_RAIL);
break;
case WID_RAT_AUTORAIL:
VpStartPlaceSizing(tile, VPM_RAILDIRS, DDSP_PLACE_RAIL);
break;
case WID_RAT_DEMOLISH:
PlaceProc_DemolishArea(tile);
break;
case WID_RAT_BUILD_DEPOT:
DoCommandP(tile, _cur_railtype, _build_depot_direction,
CMD_BUILD_TRAIN_DEPOT | CMD_MSG(STR_ERROR_CAN_T_BUILD_TRAIN_DEPOT),
CcRailDepot);
break;
case WID_RAT_BUILD_WAYPOINT:
PlaceRail_Waypoint(tile);
break;
case WID_RAT_BUILD_STATION:
PlaceRail_Station(tile);
break;
case WID_RAT_BUILD_SIGNALS:
VpStartPlaceSizing(tile, VPM_SIGNALDIRS, DDSP_BUILD_SIGNALS);
break;
case WID_RAT_BUILD_BRIDGE:
PlaceRail_Bridge(tile, this);
break;
case WID_RAT_BUILD_TUNNEL:
DoCommandP(tile, _cur_railtype | (TRANSPORT_RAIL << 8), 0, CMD_BUILD_TUNNEL | CMD_MSG(STR_ERROR_CAN_T_BUILD_TUNNEL_HERE), CcBuildRailTunnel);
break;
case WID_RAT_CONVERT_RAIL:
VpStartPlaceSizing(tile, VPM_X_AND_Y, DDSP_CONVERT_RAIL);
break;
default: NOT_REACHED();
}
}
void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt) override
{
/* no dragging if you have pressed the convert button */
if (FindWindowById(WC_BUILD_SIGNAL, 0) != nullptr && _convert_signal_button && this->IsWidgetLowered(WID_RAT_BUILD_SIGNALS)) return;
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile) override
{
if (pt.x != -1) {
switch (select_proc) {
default: NOT_REACHED();
case DDSP_BUILD_BRIDGE:
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
ShowBuildBridgeWindow(start_tile, end_tile, TRANSPORT_RAIL, _cur_railtype);
break;
case DDSP_PLACE_RAIL:
HandleAutodirPlacement();
break;
case DDSP_BUILD_SIGNALS:
HandleAutoSignalPlacement();
break;
case DDSP_DEMOLISH_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
case DDSP_CONVERT_RAIL:
DoCommandP(end_tile, start_tile, _cur_railtype | (_ctrl_pressed ? 1 << 6 : 0), CMD_CONVERT_RAIL | CMD_MSG(STR_ERROR_CAN_T_CONVERT_RAIL), CcPlaySound_SPLAT_RAIL);
break;
case DDSP_REMOVE_STATION:
case DDSP_BUILD_STATION:
if (this->IsWidgetLowered(WID_RAT_BUILD_STATION)) {
/* Station */
if (_remove_button_clicked) {
DoCommandP(end_tile, start_tile, _ctrl_pressed ? 0 : 1, CMD_REMOVE_FROM_RAIL_STATION | CMD_MSG(STR_ERROR_CAN_T_REMOVE_PART_OF_STATION), CcPlaySound_SPLAT_RAIL);
} else {
HandleStationPlacement(start_tile, end_tile);
}
} else {
/* Waypoint */
if (_remove_button_clicked) {
DoCommandP(end_tile, start_tile, _ctrl_pressed ? 0 : 1, CMD_REMOVE_FROM_RAIL_WAYPOINT | CMD_MSG(STR_ERROR_CAN_T_REMOVE_TRAIN_WAYPOINT), CcPlaySound_SPLAT_RAIL);
} else {
TileArea ta(start_tile, end_tile);
uint32 p1 = _cur_railtype | (select_method == VPM_X_LIMITED ? AXIS_X : AXIS_Y) << 6 | ta.w << 8 | ta.h << 16 | _ctrl_pressed << 24;
uint32 p2 = STAT_CLASS_WAYP | _cur_waypoint_type << 8 | INVALID_STATION << 16;
CommandContainer cmdcont = { ta.tile, p1, p2, CMD_BUILD_RAIL_WAYPOINT | CMD_MSG(STR_ERROR_CAN_T_BUILD_TRAIN_WAYPOINT), CcPlaySound_SPLAT_RAIL, "" };
ShowSelectWaypointIfNeeded(cmdcont, ta);
}
}
break;
}
}
}
void OnPlaceObjectAbort() override
{
if (this->IsWidgetLowered(WID_RAT_BUILD_STATION)) SetViewportCatchmentStation(nullptr, true);
this->RaiseButtons();
this->DisableWidget(WID_RAT_REMOVE);
this->SetWidgetDirty(WID_RAT_REMOVE);
DeleteWindowById(WC_BUILD_SIGNAL, TRANSPORT_RAIL);
DeleteWindowById(WC_BUILD_STATION, TRANSPORT_RAIL);
DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_RAIL);
DeleteWindowById(WC_BUILD_WAYPOINT, TRANSPORT_RAIL);
DeleteWindowById(WC_SELECT_STATION, 0);
DeleteWindowByClass(WC_BUILD_BRIDGE);
}
void OnPlacePresize(Point pt, TileIndex tile) override
{
DoCommand(tile, _cur_railtype | (TRANSPORT_RAIL << 8), 0, DC_AUTO, CMD_BUILD_TUNNEL);
VpSetPresizeRange(tile, _build_tunnel_endtile == 0 ? tile : _build_tunnel_endtile);
}
EventState OnCTRLStateChange() override
{
/* do not toggle Remove button by Ctrl when placing station */
if (!this->IsWidgetLowered(WID_RAT_BUILD_STATION) && !this->IsWidgetLowered(WID_RAT_BUILD_WAYPOINT) && RailToolbar_CtrlChanged(this)) return ES_HANDLED;
return ES_NOT_HANDLED;
}
static HotkeyList hotkeys;
};
/**
* Handler for global hotkeys of the BuildRailToolbarWindow.
* @param hotkey Hotkey
* @return ES_HANDLED if hotkey was accepted.
*/
static EventState RailToolbarGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_NORMAL || !CanBuildVehicleInfrastructure(VEH_TRAIN)) return ES_NOT_HANDLED;
extern RailType _last_built_railtype;
Window *w = ShowBuildRailToolbar(_last_built_railtype);
if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
const uint16 _railtoolbar_autorail_keys[] = {'5', 'A' | WKC_GLOBAL_HOTKEY, 0};
static Hotkey railtoolbar_hotkeys[] = {
Hotkey('1', "build_ns", WID_RAT_BUILD_NS),
Hotkey('2', "build_x", WID_RAT_BUILD_X),
Hotkey('3', "build_ew", WID_RAT_BUILD_EW),
Hotkey('4', "build_y", WID_RAT_BUILD_Y),
Hotkey(_railtoolbar_autorail_keys, "autorail", WID_RAT_AUTORAIL),
Hotkey('6', "demolish", WID_RAT_DEMOLISH),
Hotkey('7', "depot", WID_RAT_BUILD_DEPOT),
Hotkey('8', "waypoint", WID_RAT_BUILD_WAYPOINT),
Hotkey('9', "station", WID_RAT_BUILD_STATION),
Hotkey('S', "signal", WID_RAT_BUILD_SIGNALS),
Hotkey('B', "bridge", WID_RAT_BUILD_BRIDGE),
Hotkey('T', "tunnel", WID_RAT_BUILD_TUNNEL),
Hotkey('R', "remove", WID_RAT_REMOVE),
Hotkey('C', "convert", WID_RAT_CONVERT_RAIL),
HOTKEY_LIST_END
};
HotkeyList BuildRailToolbarWindow::hotkeys("railtoolbar", railtoolbar_hotkeys, RailToolbarGlobalHotkeys);
static const NWidgetPart _nested_build_rail_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_RAT_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
EndContainer(),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_NS),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_RAIL_NS, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_TRACK),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_X),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_RAIL_NE, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_TRACK),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_EW),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_RAIL_EW, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_TRACK),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_Y),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_RAIL_NW, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_TRACK),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_AUTORAIL),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_AUTORAIL, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_AUTORAIL),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN), SetMinimalSize(4, 22), SetDataTip(0x0, STR_NULL), EndContainer(),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_DEMOLISH),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_DYNAMITE, STR_TOOLTIP_DEMOLISH_BUILDINGS_ETC),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_DEPOT),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_DEPOT_RAIL, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_TRAIN_DEPOT_FOR_BUILDING),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_WAYPOINT),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_WAYPOINT, STR_RAIL_TOOLBAR_TOOLTIP_CONVERT_RAIL_TO_WAYPOINT),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_STATION),
SetFill(0, 1), SetMinimalSize(42, 22), SetDataTip(SPR_IMG_RAIL_STATION, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_STATION),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_SIGNALS),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_RAIL_SIGNALS, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_SIGNALS),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_BRIDGE),
SetFill(0, 1), SetMinimalSize(42, 22), SetDataTip(SPR_IMG_BRIDGE, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_BRIDGE),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_BUILD_TUNNEL),
SetFill(0, 1), SetMinimalSize(20, 22), SetDataTip(SPR_IMG_TUNNEL_RAIL, STR_RAIL_TOOLBAR_TOOLTIP_BUILD_RAILROAD_TUNNEL),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_REMOVE),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_REMOVE, STR_RAIL_TOOLBAR_TOOLTIP_TOGGLE_BUILD_REMOVE_FOR),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_RAT_CONVERT_RAIL),
SetFill(0, 1), SetMinimalSize(22, 22), SetDataTip(SPR_IMG_CONVERT_RAIL, STR_RAIL_TOOLBAR_TOOLTIP_CONVERT_RAIL),
EndContainer(),
};
static WindowDesc _build_rail_desc(
WDP_ALIGN_TOOLBAR, "toolbar_rail", 0, 0,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_CONSTRUCTION,
_nested_build_rail_widgets, lengthof(_nested_build_rail_widgets),
&BuildRailToolbarWindow::hotkeys
);
/**
* Open the build rail toolbar window for a specific rail type.
*
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
* @param railtype Rail type to open the window for
* @return newly opened rail toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildRailToolbar(RailType railtype)
{
if (!Company::IsValidID(_local_company)) return nullptr;
if (!ValParamRailtype(railtype)) return nullptr;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
_cur_railtype = railtype;
_remove_button_clicked = false;
return new BuildRailToolbarWindow(&_build_rail_desc, railtype);
}
/* TODO: For custom stations, respect their allowed platforms/lengths bitmasks!
* --pasky */
static void HandleStationPlacement(TileIndex start, TileIndex end)
{
TileArea ta(start, end);
uint numtracks = ta.w;
uint platlength = ta.h;
if (_railstation.orientation == AXIS_X) Swap(numtracks, platlength);
uint32 p1 = _cur_railtype | _railstation.orientation << 6 | numtracks << 8 | platlength << 16 | _ctrl_pressed << 24;
uint32 p2 = _railstation.station_class | _railstation.station_type << 8 | INVALID_STATION << 16;
CommandContainer cmdcont = { ta.tile, p1, p2, CMD_BUILD_RAIL_STATION | CMD_MSG(STR_ERROR_CAN_T_BUILD_RAILROAD_STATION), CcStation, "" };
ShowSelectStationIfNeeded(cmdcont, ta);
}
struct BuildRailStationWindow : public PickerWindowBase {
private:
uint line_height; ///< Height of a single line in the newstation selection matrix (#WID_BRAS_NEWST_LIST widget).
uint coverage_height; ///< Height of the coverage texts.
Scrollbar *vscroll; ///< Vertical scrollbar of the new station list.
Scrollbar *vscroll2; ///< Vertical scrollbar of the matrix with new stations.
/**
* Verify whether the currently selected station size is allowed after selecting a new station class/type.
* If not, change the station size variables ( _settings_client.gui.station_numtracks and _settings_client.gui.station_platlength ).
* @param statspec Specification of the new station class/type
*/
void CheckSelectedSize(const StationSpec *statspec)
{
if (statspec == nullptr || _settings_client.gui.station_dragdrop) return;
/* If current number of tracks is not allowed, make it as big as possible */
if (HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = 1;
if (statspec->disallowed_platforms != UINT8_MAX) {
while (HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
_settings_client.gui.station_numtracks++;
}
this->LowerWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
}
}
if (HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
this->RaiseWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = 1;
if (statspec->disallowed_lengths != UINT8_MAX) {
while (HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
_settings_client.gui.station_platlength++;
}
this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
}
}
}
public:
BuildRailStationWindow(WindowDesc *desc, Window *parent, bool newstation) : PickerWindowBase(desc, parent)
{
this->coverage_height = 2 * FONT_HEIGHT_NORMAL + 3 * WD_PAR_VSEP_NORMAL;
this->vscroll = nullptr;
_railstation.newstations = newstation;
this->CreateNestedTree();
NWidgetStacked *newst_additions = this->GetWidget<NWidgetStacked>(WID_BRAS_SHOW_NEWST_ADDITIONS);
newst_additions->SetDisplayedPlane(newstation ? 0 : SZSP_NONE);
newst_additions = this->GetWidget<NWidgetStacked>(WID_BRAS_SHOW_NEWST_MATRIX);
newst_additions->SetDisplayedPlane(newstation ? 0 : SZSP_NONE);
newst_additions = this->GetWidget<NWidgetStacked>(WID_BRAS_SHOW_NEWST_DEFSIZE);
newst_additions->SetDisplayedPlane(newstation ? 0 : SZSP_NONE);
newst_additions = this->GetWidget<NWidgetStacked>(WID_BRAS_SHOW_NEWST_RESIZE);
newst_additions->SetDisplayedPlane(newstation ? 0 : SZSP_NONE);
if (newstation) {
this->vscroll = this->GetScrollbar(WID_BRAS_NEWST_SCROLL);
this->vscroll2 = this->GetScrollbar(WID_BRAS_MATRIX_SCROLL);
}
this->FinishInitNested(TRANSPORT_RAIL);
this->LowerWidget(_railstation.orientation + WID_BRAS_PLATFORM_DIR_X);
if (_settings_client.gui.station_dragdrop) {
this->LowerWidget(WID_BRAS_PLATFORM_DRAG_N_DROP);
} else {
this->LowerWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
}
this->SetWidgetLoweredState(WID_BRAS_HIGHLIGHT_OFF, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(WID_BRAS_HIGHLIGHT_ON, _settings_client.gui.station_show_coverage);
if (!newstation || _railstation.station_class >= (int)StationClass::GetClassCount()) {
/* New stations are not available or changed, so ensure the default station
* type is 'selected'. */
_railstation.station_class = STAT_CLASS_DFLT;
_railstation.station_type = 0;
this->vscroll2 = nullptr;
}
if (newstation) {
_railstation.station_count = StationClass::Get(_railstation.station_class)->GetSpecCount();
_railstation.station_type = min(_railstation.station_type, _railstation.station_count - 1);
int count = 0;
for (uint i = 0; i < StationClass::GetClassCount(); i++) {
if (i == STAT_CLASS_WAYP) continue;
count++;
}
this->vscroll->SetCount(count);
this->vscroll->SetPosition(Clamp(_railstation.station_class - 2, 0, max(this->vscroll->GetCount() - this->vscroll->GetCapacity(), 0)));
NWidgetMatrix *matrix = this->GetWidget<NWidgetMatrix>(WID_BRAS_MATRIX);
matrix->SetScrollbar(this->vscroll2);
matrix->SetCount(_railstation.station_count);
matrix->SetClicked(_railstation.station_type);
}
}
virtual ~BuildRailStationWindow()
{
DeleteWindowById(WC_SELECT_STATION, 0);
}
void OnPaint() override
{
bool newstations = _railstation.newstations;
const StationSpec *statspec = newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
if (_settings_client.gui.station_dragdrop) {
SetTileSelectSize(1, 1);
} else {
int x = _settings_client.gui.station_numtracks;
int y = _settings_client.gui.station_platlength;
if (_railstation.orientation == AXIS_X) Swap(x, y);
if (!_remove_button_clicked) {
SetTileSelectSize(x, y);
}
}
int rad = (_settings_game.station.modified_catchment) ? CA_TRAIN : CA_UNMODIFIED;
if (_settings_client.gui.station_show_coverage) SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
for (uint bits = 0; bits < 7; bits++) {
bool disable = bits >= _settings_game.station.station_spread;
if (statspec == nullptr) {
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_NUM_1, disable);
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_LEN_1, disable);
} else {
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_NUM_1, HasBit(statspec->disallowed_platforms, bits) || disable);
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_LEN_1, HasBit(statspec->disallowed_lengths, bits) || disable);
}
}
this->DrawWidgets();
if (this->IsShaded()) return;
/* 'Accepts' and 'Supplies' texts. */
NWidgetBase *cov = this->GetWidget<NWidgetBase>(WID_BRAS_COVERAGE_TEXTS);
int top = cov->pos_y + WD_PAR_VSEP_NORMAL;
int left = cov->pos_x + WD_FRAMERECT_LEFT;
int right = cov->pos_x + cov->current_x - WD_FRAMERECT_RIGHT;
int bottom = cov->pos_y + cov->current_y;
top = DrawStationCoverageAreaText(left, right, top, SCT_ALL, rad, false) + WD_PAR_VSEP_NORMAL;
top = DrawStationCoverageAreaText(left, right, top, SCT_ALL, rad, true) + WD_PAR_VSEP_NORMAL;
/* Resize background if the window is too small.
* Never make the window smaller to avoid oscillating if the size change affects the acceptance.
* (This is the case, if making the window bigger moves the mouse into the window.) */
if (top > bottom) {
this->coverage_height += top - bottom;
this->ReInit();
}
}
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_BRAS_NEWST_LIST: {
Dimension d = {0, 0};
for (uint i = 0; i < StationClass::GetClassCount(); i++) {
if (i == STAT_CLASS_WAYP) continue;
d = maxdim(d, GetStringBoundingBox(StationClass::Get((StationClassID)i)->name));
}
size->width = max(size->width, d.width + padding.width);
this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
size->height = 5 * this->line_height;
resize->height = this->line_height;
break;
}
case WID_BRAS_SHOW_NEWST_TYPE: {
if (!_railstation.newstations) {
size->width = 0;
size->height = 0;
break;
}
/* If newstations exist, compute the non-zero minimal size. */
Dimension d = {0, 0};
StringID str = this->GetWidget<NWidgetCore>(widget)->widget_data;
for (StationClassID statclass = STAT_CLASS_BEGIN; statclass < (StationClassID)StationClass::GetClassCount(); statclass++) {
if (statclass == STAT_CLASS_WAYP) continue;
StationClass *stclass = StationClass::Get(statclass);
for (uint16 j = 0; j < stclass->GetSpecCount(); j++) {
const StationSpec *statspec = stclass->GetSpec(j);
SetDParam(0, (statspec != nullptr && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
d = maxdim(d, GetStringBoundingBox(str));
}
}
size->width = max(size->width, d.width + padding.width);
break;
}
case WID_BRAS_PLATFORM_DIR_X:
case WID_BRAS_PLATFORM_DIR_Y:
case WID_BRAS_IMAGE:
size->width = ScaleGUITrad(64) + 2;
size->height = ScaleGUITrad(58) + 2;
break;
case WID_BRAS_COVERAGE_TEXTS:
size->height = this->coverage_height;
break;
case WID_BRAS_MATRIX:
fill->height = 1;
resize->height = 1;
break;
}
}
void DrawWidget(const Rect &r, int widget) const override
{
DrawPixelInfo tmp_dpi;
switch (GB(widget, 0, 16)) {
case WID_BRAS_PLATFORM_DIR_X:
/* Set up a clipping area for the '/' station preview */
if (FillDrawPixelInfo(&tmp_dpi, r.left, r.top, r.right - r.left + 1, r.bottom - r.top + 1)) {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
int x = ScaleGUITrad(31) + 1;
int y = r.bottom - r.top - ScaleGUITrad(31);
if (!DrawStationTile(x, y, _cur_railtype, AXIS_X, _railstation.station_class, _railstation.station_type)) {
StationPickerDrawSprite(x, y, STATION_RAIL, _cur_railtype, INVALID_ROADTYPE, 2);
}
_cur_dpi = old_dpi;
}
break;
case WID_BRAS_PLATFORM_DIR_Y:
/* Set up a clipping area for the '\' station preview */
if (FillDrawPixelInfo(&tmp_dpi, r.left, r.top, r.right - r.left + 1, r.bottom - r.top + 1)) {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
int x = ScaleGUITrad(31) + 1;
int y = r.bottom - r.top - ScaleGUITrad(31);
if (!DrawStationTile(x, y, _cur_railtype, AXIS_Y, _railstation.station_class, _railstation.station_type)) {
StationPickerDrawSprite(x, y, STATION_RAIL, _cur_railtype, INVALID_ROADTYPE, 3);
}
_cur_dpi = old_dpi;
}
break;
case WID_BRAS_NEWST_LIST: {
uint statclass = 0;
uint row = 0;
for (uint i = 0; i < StationClass::GetClassCount(); i++) {
if (i == STAT_CLASS_WAYP) continue;
if (this->vscroll->IsVisible(statclass)) {
DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, row * this->line_height + r.top + WD_MATRIX_TOP,
StationClass::Get((StationClassID)i)->name,
(StationClassID)i == _railstation.station_class ? TC_WHITE : TC_BLACK);
row++;
}
statclass++;
}
break;
}
case WID_BRAS_IMAGE: {
byte type = GB(widget, 16, 16);
assert(type < _railstation.station_count);
/* Check station availability callback */
const StationSpec *statspec = StationClass::Get(_railstation.station_class)->GetSpec(type);
if (!IsStationAvailable(statspec)) {
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK, FILLRECT_CHECKER);
}
/* Set up a clipping area for the station preview. */
if (FillDrawPixelInfo(&tmp_dpi, r.left, r.top, r.right - r.left + 1, r.bottom - r.top + 1)) {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
int x = ScaleGUITrad(31) + 1;
int y = r.bottom - r.top - ScaleGUITrad(31);
if (!DrawStationTile(x, y, _cur_railtype, _railstation.orientation, _railstation.station_class, type)) {
StationPickerDrawSprite(x, y, STATION_RAIL, _cur_railtype, INVALID_ROADTYPE, 2 + _railstation.orientation);
}
_cur_dpi = old_dpi;
}
break;
}
}
}
void OnResize() override
{
if (this->vscroll != nullptr) { // New stations available.
this->vscroll->SetCapacityFromWidget(this, WID_BRAS_NEWST_LIST);
}
}
void SetStringParameters(int widget) const override
{
if (widget == WID_BRAS_SHOW_NEWST_TYPE) {
const StationSpec *statspec = StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type);
SetDParam(0, (statspec != nullptr && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
}
}
void OnClick(Point pt, int widget, int click_count) override
{
switch (GB(widget, 0, 16)) {
case WID_BRAS_PLATFORM_DIR_X:
case WID_BRAS_PLATFORM_DIR_Y:
this->RaiseWidget(_railstation.orientation + WID_BRAS_PLATFORM_DIR_X);
_railstation.orientation = (Axis)(widget - WID_BRAS_PLATFORM_DIR_X);
this->LowerWidget(_railstation.orientation + WID_BRAS_PLATFORM_DIR_X);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
case WID_BRAS_PLATFORM_NUM_1:
case WID_BRAS_PLATFORM_NUM_2:
case WID_BRAS_PLATFORM_NUM_3:
case WID_BRAS_PLATFORM_NUM_4:
case WID_BRAS_PLATFORM_NUM_5:
case WID_BRAS_PLATFORM_NUM_6:
case WID_BRAS_PLATFORM_NUM_7: {
this->RaiseWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
this->RaiseWidget(WID_BRAS_PLATFORM_DRAG_N_DROP);
_settings_client.gui.station_numtracks = widget - WID_BRAS_PLATFORM_NUM_BEGIN;
_settings_client.gui.station_dragdrop = false;
_settings_client.gui.station_dragdrop = false;
const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
if (statspec != nullptr && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
/* The previously selected number of platforms in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
this->RaiseWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = i + 1;
break;
}
}
}
this->LowerWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
case WID_BRAS_PLATFORM_LEN_1:
case WID_BRAS_PLATFORM_LEN_2:
case WID_BRAS_PLATFORM_LEN_3:
case WID_BRAS_PLATFORM_LEN_4:
case WID_BRAS_PLATFORM_LEN_5:
case WID_BRAS_PLATFORM_LEN_6:
case WID_BRAS_PLATFORM_LEN_7: {
this->RaiseWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
this->RaiseWidget(WID_BRAS_PLATFORM_DRAG_N_DROP);
_settings_client.gui.station_platlength = widget - WID_BRAS_PLATFORM_LEN_BEGIN;
_settings_client.gui.station_dragdrop = false;
_settings_client.gui.station_dragdrop = false;
const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
if (statspec != nullptr && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
/* The previously selected number of tracks in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = i + 1;
break;
}
}
}
this->LowerWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
case WID_BRAS_PLATFORM_DRAG_N_DROP: {
_settings_client.gui.station_dragdrop ^= true;
this->ToggleWidgetLoweredState(WID_BRAS_PLATFORM_DRAG_N_DROP);
/* get the first allowed length/number of platforms */
const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
if (statspec != nullptr && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
this->RaiseWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
_settings_client.gui.station_platlength = i + 1;
break;
}
}
}
if (statspec != nullptr && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
_settings_client.gui.station_numtracks = i + 1;
break;
}
}
}
this->SetWidgetLoweredState(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN, !_settings_client.gui.station_dragdrop);
this->SetWidgetLoweredState(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN, !_settings_client.gui.station_dragdrop);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
case WID_BRAS_HIGHLIGHT_OFF:
case WID_BRAS_HIGHLIGHT_ON:
_settings_client.gui.station_show_coverage = (widget != WID_BRAS_HIGHLIGHT_OFF);
this->SetWidgetLoweredState(WID_BRAS_HIGHLIGHT_OFF, !_settings_client.gui.station_show_coverage);
this->SetWidgetLoweredState(WID_BRAS_HIGHLIGHT_ON, _settings_client.gui.station_show_coverage);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
SetViewportCatchmentStation(nullptr, true);
break;
case WID_BRAS_NEWST_LIST: {
int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BRAS_NEWST_LIST, 0, this->line_height);
if (y >= (int)StationClass::GetClassCount()) return;
for (uint i = 0; i < StationClass::GetClassCount(); i++) {
if (i == STAT_CLASS_WAYP) continue;
if (y == 0) {
if (_railstation.station_class != (StationClassID)i) {
_railstation.station_class = (StationClassID)i;
StationClass *stclass = StationClass::Get(_railstation.station_class);
_railstation.station_count = stclass->GetSpecCount();
_railstation.station_type = min((int)_railstation.station_type, max(0, (int)_railstation.station_count - 1));
this->CheckSelectedSize(stclass->GetSpec(_railstation.station_type));
NWidgetMatrix *matrix = this->GetWidget<NWidgetMatrix>(WID_BRAS_MATRIX);
matrix->SetCount(_railstation.station_count);
matrix->SetClicked(_railstation.station_type);
}
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
y--;
}
break;
}
case WID_BRAS_IMAGE: {
int y = GB(widget, 16, 16);
if (y >= _railstation.station_count) return;
/* Check station availability callback */
const StationSpec *statspec = StationClass::Get(_railstation.station_class)->GetSpec(y);
if (!IsStationAvailable(statspec)) return;
_railstation.station_type = y;
this->CheckSelectedSize(statspec);
this->GetWidget<NWidgetMatrix>(WID_BRAS_MATRIX)->SetClicked(_railstation.station_type);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
}
}
}
void OnRealtimeTick(uint delta_ms) override
{
CheckRedrawStationCoverage(this);
}
};
static const NWidgetPart _nested_station_builder_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_STATION_BUILD_RAIL_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BRAS_SHOW_NEWST_DEFSIZE),
NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
EndContainer(),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_VERTICAL),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BRAS_SHOW_NEWST_ADDITIONS),
NWidget(NWID_HORIZONTAL), SetPIP(7, 0, 7), SetPadding(2, 0, 1, 0),
NWidget(WWT_MATRIX, COLOUR_GREY, WID_BRAS_NEWST_LIST), SetMinimalSize(122, 71), SetFill(1, 0),
SetMatrixDataTip(1, 0, STR_STATION_BUILD_STATION_CLASS_TOOLTIP), SetScrollbar(WID_BRAS_NEWST_SCROLL),
NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_BRAS_NEWST_SCROLL),
EndContainer(),
EndContainer(),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN), SetMinimalSize(144, 11), SetDataTip(STR_STATION_BUILD_ORIENTATION, STR_NULL), SetPadding(1, 2, 0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetMinimalSize(7, 0), SetFill(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAS_PLATFORM_DIR_X), SetMinimalSize(66, 60), SetFill(0, 0), SetDataTip(0x0, STR_STATION_BUILD_RAILROAD_ORIENTATION_TOOLTIP), EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(2, 0), SetFill(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAS_PLATFORM_DIR_Y), SetMinimalSize(66, 60), SetFill(0, 0), SetDataTip(0x0, STR_STATION_BUILD_RAILROAD_ORIENTATION_TOOLTIP), EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(7, 0), SetFill(1, 0),
EndContainer(),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN, WID_BRAS_SHOW_NEWST_TYPE), SetMinimalSize(144, 11), SetDataTip(STR_ORANGE_STRING, STR_NULL), SetPadding(1, 2, 4, 2),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN), SetMinimalSize(144, 11), SetDataTip(STR_STATION_BUILD_NUMBER_OF_TRACKS, STR_NULL), SetPadding(0, 2, 0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetFill(1, 0),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_1), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_1, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_2), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_2, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_3), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_3, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_4), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_4, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_5), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_5, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_6), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_6, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_NUM_7), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_7, STR_STATION_BUILD_NUMBER_OF_TRACKS_TOOLTIP),
NWidget(NWID_SPACER), SetFill(1, 0),
EndContainer(),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN), SetMinimalSize(144, 11), SetDataTip(STR_STATION_BUILD_PLATFORM_LENGTH, STR_NULL), SetPadding(2, 2, 0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetFill(1, 0),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_1), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_1, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_2), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_2, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_3), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_3, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_4), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_4, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_5), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_5, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_6), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_6, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_LEN_7), SetMinimalSize(15, 12), SetDataTip(STR_BLACK_7, STR_STATION_BUILD_PLATFORM_LENGTH_TOOLTIP),
NWidget(NWID_SPACER), SetFill(1, 0),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetMinimalSize(2, 0), SetFill(1, 0),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_PLATFORM_DRAG_N_DROP), SetMinimalSize(75, 12), SetDataTip(STR_STATION_BUILD_DRAG_DROP, STR_STATION_BUILD_DRAG_DROP_TOOLTIP),
NWidget(NWID_SPACER), SetMinimalSize(2, 0), SetFill(1, 0),
EndContainer(),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN), SetMinimalSize(144, 11), SetDataTip(STR_STATION_BUILD_COVERAGE_AREA_TITLE, STR_NULL), SetPadding(3, 2, 0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetMinimalSize(2, 0), SetFill(1, 0),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_HIGHLIGHT_OFF), SetMinimalSize(60, 12),
SetDataTip(STR_STATION_BUILD_COVERAGE_OFF, STR_STATION_BUILD_COVERAGE_AREA_OFF_TOOLTIP),
NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_BRAS_HIGHLIGHT_ON), SetMinimalSize(60, 12),
SetDataTip(STR_STATION_BUILD_COVERAGE_ON, STR_STATION_BUILD_COVERAGE_AREA_ON_TOOLTIP),
NWidget(NWID_SPACER), SetMinimalSize(2, 0), SetFill(1, 0),
EndContainer(),
EndContainer(),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BRAS_SHOW_NEWST_MATRIX),
/* We need an additional background for the matrix, as the matrix cannot handle the scrollbar due to not being an NWidgetCore. */
NWidget(WWT_PANEL, COLOUR_DARK_GREEN), SetScrollbar(WID_BRAS_MATRIX_SCROLL),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_MATRIX, COLOUR_DARK_GREEN, WID_BRAS_MATRIX), SetScrollbar(WID_BRAS_MATRIX_SCROLL), SetPIP(0, 2, 0), SetPadding(2, 0, 0, 0),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BRAS_IMAGE), SetMinimalSize(66, 60),
SetFill(0, 0), SetResize(0, 0), SetDataTip(0x0, STR_STATION_BUILD_STATION_TYPE_TOOLTIP), SetScrollbar(WID_BRAS_MATRIX_SCROLL),
EndContainer(),
EndContainer(),
NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BRAS_MATRIX_SCROLL),
EndContainer(),
EndContainer(),
EndContainer(),
EndContainer(),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_EMPTY, INVALID_COLOUR, WID_BRAS_COVERAGE_TEXTS), SetFill(1, 1), SetResize(1, 0),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_BRAS_SHOW_NEWST_RESIZE),
NWidget(NWID_VERTICAL),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN), SetFill(0, 1), EndContainer(),
NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
EndContainer(),
EndContainer(),
EndContainer(),
EndContainer(),
};
/** High level window description of the station-build window (default & newGRF) */
static WindowDesc _station_builder_desc(
WDP_AUTO, "build_station_rail", 350, 0,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_station_builder_widgets, lengthof(_nested_station_builder_widgets)
);
/** Open station build window */
static void ShowStationBuilder(Window *parent)
{
bool newstations = StationClass::GetClassCount() > 2 || StationClass::Get(STAT_CLASS_DFLT)->GetSpecCount() != 1;
new BuildRailStationWindow(&_station_builder_desc, parent, newstations);
}
struct BuildSignalWindow : public PickerWindowBase {
private:
Dimension sig_sprite_size; ///< Maximum size of signal GUI sprites.
int sig_sprite_bottom_offset; ///< Maximum extent of signal GUI sprite from reference point towards bottom.
/**
* Draw dynamic a signal-sprite in a button in the signal GUI
* Draw the sprite +1px to the right and down if the button is lowered
*
* @param widget_index index of this widget in the window
* @param image the sprite to draw
*/
void DrawSignalSprite(byte widget_index, SpriteID image) const
{
Point offset;
Dimension sprite_size = GetSpriteSize(image, &offset);
const NWidgetBase *widget = this->GetWidget<NWidgetBase>(widget_index);
int x = widget->pos_x - offset.x +
(widget->current_x - sprite_size.width + offset.x) / 2; // centered
int y = widget->pos_y - sig_sprite_bottom_offset + WD_IMGBTN_TOP +
(widget->current_y - WD_IMGBTN_TOP - WD_IMGBTN_BOTTOM + sig_sprite_size.height) / 2; // aligned to bottom
DrawSprite(image, PAL_NONE,
x + this->IsWidgetLowered(widget_index),
y + this->IsWidgetLowered(widget_index));
}
public:
BuildSignalWindow(WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->InitNested(TRANSPORT_RAIL);
this->OnInvalidateData();
}
~BuildSignalWindow()
{
_convert_signal_button = false;
}
void OnInit() override
{
/* Calculate maximum signal sprite size. */
this->sig_sprite_size.width = 0;
this->sig_sprite_size.height = 0;
this->sig_sprite_bottom_offset = 0;
const RailtypeInfo *rti = GetRailTypeInfo(_cur_railtype);
for (uint type = SIGTYPE_NORMAL; type < SIGTYPE_END; type++) {
for (uint variant = SIG_ELECTRIC; variant <= SIG_SEMAPHORE; variant++) {
for (uint lowered = 0; lowered < 2; lowered++) {
Point offset;
Dimension sprite_size = GetSpriteSize(rti->gui_sprites.signals[type][variant][lowered], &offset);
this->sig_sprite_bottom_offset = max<int>(this->sig_sprite_bottom_offset, sprite_size.height);
this->sig_sprite_size.width = max<int>(this->sig_sprite_size.width, sprite_size.width - offset.x);
this->sig_sprite_size.height = max<int>(this->sig_sprite_size.height, sprite_size.height - offset.y);
}
}
}
}
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (widget == WID_BS_DRAG_SIGNALS_DENSITY_LABEL) {
/* Two digits for signals density. */
size->width = max(size->width, 2 * GetDigitWidth() + padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT);
} else if (IsInsideMM(widget, WID_BS_SEMAPHORE_NORM, WID_BS_ELECTRIC_PBS_OWAY + 1)) {
size->width = max(size->width, this->sig_sprite_size.width + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT);
size->height = max(size->height, this->sig_sprite_size.height + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
}
}
void SetStringParameters(int widget) const override
{
switch (widget) {
case WID_BS_DRAG_SIGNALS_DENSITY_LABEL:
SetDParam(0, _settings_client.gui.drag_signals_density);
break;
}
}
void DrawWidget(const Rect &r, int widget) const override
{
if (IsInsideMM(widget, WID_BS_SEMAPHORE_NORM, WID_BS_ELECTRIC_PBS_OWAY + 1)) {
/* Extract signal from widget number. */
int type = (widget - WID_BS_SEMAPHORE_NORM) % SIGTYPE_END;
int var = SIG_SEMAPHORE - (widget - WID_BS_SEMAPHORE_NORM) / SIGTYPE_END; // SignalVariant order is reversed compared to the widgets.
SpriteID sprite = GetRailTypeInfo(_cur_railtype)->gui_sprites.signals[type][var][this->IsWidgetLowered(widget)];
this->DrawSignalSprite(widget, sprite);
}
}
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_BS_SEMAPHORE_NORM:
case WID_BS_SEMAPHORE_ENTRY:
case WID_BS_SEMAPHORE_EXIT:
case WID_BS_SEMAPHORE_COMBO:
case WID_BS_SEMAPHORE_PBS:
case WID_BS_SEMAPHORE_PBS_OWAY:
case WID_BS_ELECTRIC_NORM:
case WID_BS_ELECTRIC_ENTRY:
case WID_BS_ELECTRIC_EXIT:
case WID_BS_ELECTRIC_COMBO:
case WID_BS_ELECTRIC_PBS:
case WID_BS_ELECTRIC_PBS_OWAY:
this->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? WID_BS_ELECTRIC_NORM : WID_BS_SEMAPHORE_NORM) + _cur_signal_type);
_cur_signal_type = (SignalType)((uint)((widget - WID_BS_SEMAPHORE_NORM) % (SIGTYPE_LAST + 1)));
_cur_signal_variant = widget >= WID_BS_ELECTRIC_NORM ? SIG_ELECTRIC : SIG_SEMAPHORE;
/* If 'remove' button of rail build toolbar is active, disable it. */
if (_remove_button_clicked) {
Window *w = FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL);
if (w != nullptr) ToggleRailButton_Remove(w);
}
break;
case WID_BS_CONVERT:
_convert_signal_button = !_convert_signal_button;
break;
case WID_BS_DRAG_SIGNALS_DENSITY_DECREASE:
if (_settings_client.gui.drag_signals_density > 1) {
_settings_client.gui.drag_signals_density--;
SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_GAME_SETTINGS);
}
break;
case WID_BS_DRAG_SIGNALS_DENSITY_INCREASE:
if (_settings_client.gui.drag_signals_density < 20) {
_settings_client.gui.drag_signals_density++;
SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_GAME_SETTINGS);
}
break;
default: break;
}
this->InvalidateData();
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (!gui_scope) return;
this->LowerWidget((_cur_signal_variant == SIG_ELECTRIC ? WID_BS_ELECTRIC_NORM : WID_BS_SEMAPHORE_NORM) + _cur_signal_type);
this->SetWidgetLoweredState(WID_BS_CONVERT, _convert_signal_button);
this->SetWidgetDisabledState(WID_BS_DRAG_SIGNALS_DENSITY_DECREASE, _settings_client.gui.drag_signals_density == 1);
this->SetWidgetDisabledState(WID_BS_DRAG_SIGNALS_DENSITY_INCREASE, _settings_client.gui.drag_signals_density == 20);
}
};
/** Nested widget definition of the build signal window */
static const NWidgetPart _nested_signal_builder_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_BUILD_SIGNAL_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
EndContainer(),
NWidget(NWID_VERTICAL, NC_EQUALSIZE),
NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_NORM), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_NORM_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_ENTRY), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_ENTRY_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_EXIT), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_EXIT_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_COMBO), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_COMBO_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_PBS), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_PBS_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_SEMAPHORE_PBS_OWAY), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_SEMAPHORE_PBS_OWAY_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_IMGBTN, COLOUR_DARK_GREEN, WID_BS_CONVERT), SetDataTip(SPR_IMG_SIGNAL_CONVERT, STR_BUILD_SIGNAL_CONVERT_TOOLTIP), SetFill(1, 1),
EndContainer(),
NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_NORM), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_NORM_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_ENTRY), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_ENTRY_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_EXIT), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_EXIT_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_COMBO), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_COMBO_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_PBS), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_PBS_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BS_ELECTRIC_PBS_OWAY), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_ELECTRIC_PBS_OWAY_TOOLTIP), EndContainer(), SetFill(1, 1),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN), SetDataTip(STR_NULL, STR_BUILD_SIGNAL_DRAG_SIGNALS_DENSITY_TOOLTIP), SetFill(1, 1),
NWidget(WWT_LABEL, COLOUR_DARK_GREEN, WID_BS_DRAG_SIGNALS_DENSITY_LABEL), SetDataTip(STR_ORANGE_INT, STR_BUILD_SIGNAL_DRAG_SIGNALS_DENSITY_TOOLTIP), SetFill(1, 1),
NWidget(NWID_HORIZONTAL), SetPIP(2, 0, 2),
NWidget(NWID_SPACER), SetFill(1, 0),
NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_BS_DRAG_SIGNALS_DENSITY_DECREASE), SetMinimalSize(9, 12), SetDataTip(AWV_DECREASE, STR_BUILD_SIGNAL_DRAG_SIGNALS_DENSITY_DECREASE_TOOLTIP),
NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_BS_DRAG_SIGNALS_DENSITY_INCREASE), SetMinimalSize(9, 12), SetDataTip(AWV_INCREASE, STR_BUILD_SIGNAL_DRAG_SIGNALS_DENSITY_INCREASE_TOOLTIP),
NWidget(NWID_SPACER), SetFill(1, 0),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 2), SetFill(1, 0),
EndContainer(),
EndContainer(),
EndContainer(),
};
/** Signal selection window description */
static WindowDesc _signal_builder_desc(
WDP_AUTO, "build_signal", 0, 0,
WC_BUILD_SIGNAL, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_signal_builder_widgets, lengthof(_nested_signal_builder_widgets)
);
/**
* Open the signal selection window
*/
static void ShowSignalBuilder(Window *parent)
{
new BuildSignalWindow(&_signal_builder_desc, parent);
}
struct BuildRailDepotWindow : public PickerWindowBase {
BuildRailDepotWindow(WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->InitNested(TRANSPORT_RAIL);
this->LowerWidget(_build_depot_direction + WID_BRAD_DEPOT_NE);
}
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (!IsInsideMM(widget, WID_BRAD_DEPOT_NE, WID_BRAD_DEPOT_NW + 1)) return;
size->width = ScaleGUITrad(64) + 2;
size->height = ScaleGUITrad(48) + 2;
}
void DrawWidget(const Rect &r, int widget) const override
{
if (!IsInsideMM(widget, WID_BRAD_DEPOT_NE, WID_BRAD_DEPOT_NW + 1)) return;
DrawTrainDepotSprite(r.left + 1 + ScaleGUITrad(31), r.bottom - ScaleGUITrad(31), widget - WID_BRAD_DEPOT_NE + DIAGDIR_NE, _cur_railtype);
}
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_BRAD_DEPOT_NE:
case WID_BRAD_DEPOT_SE:
case WID_BRAD_DEPOT_SW:
case WID_BRAD_DEPOT_NW:
this->RaiseWidget(_build_depot_direction + WID_BRAD_DEPOT_NE);
_build_depot_direction = (DiagDirection)(widget - WID_BRAD_DEPOT_NE);
this->LowerWidget(_build_depot_direction + WID_BRAD_DEPOT_NE);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
};
/** Nested widget definition of the build rail depot window */
static const NWidgetPart _nested_build_depot_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_BUILD_DEPOT_TRAIN_ORIENTATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN),
NWidget(NWID_SPACER), SetMinimalSize(0, 3),
NWidget(NWID_HORIZONTAL_LTR),
NWidget(NWID_SPACER), SetMinimalSize(3, 0), SetFill(1, 0),
NWidget(NWID_VERTICAL),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAD_DEPOT_NW), SetMinimalSize(66, 50), SetDataTip(0x0, STR_BUILD_DEPOT_TRAIN_ORIENTATION_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 2),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAD_DEPOT_SW), SetMinimalSize(66, 50), SetDataTip(0x0, STR_BUILD_DEPOT_TRAIN_ORIENTATION_TOOLTIP),
EndContainer(),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(2, 0),
NWidget(NWID_VERTICAL),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAD_DEPOT_NE), SetMinimalSize(66, 50), SetDataTip(0x0, STR_BUILD_DEPOT_TRAIN_ORIENTATION_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 2),
NWidget(WWT_PANEL, COLOUR_GREY, WID_BRAD_DEPOT_SE), SetMinimalSize(66, 50), SetDataTip(0x0, STR_BUILD_DEPOT_TRAIN_ORIENTATION_TOOLTIP),
EndContainer(),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(3, 0), SetFill(1, 0),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 3),
EndContainer(),
};
static WindowDesc _build_depot_desc(
WDP_AUTO, nullptr, 0, 0,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_depot_widgets, lengthof(_nested_build_depot_widgets)
);
static void ShowBuildTrainDepotPicker(Window *parent)
{
new BuildRailDepotWindow(&_build_depot_desc, parent);
}
struct BuildRailWaypointWindow : PickerWindowBase {
BuildRailWaypointWindow(WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->CreateNestedTree();
NWidgetMatrix *matrix = this->GetWidget<NWidgetMatrix>(WID_BRW_WAYPOINT_MATRIX);
matrix->SetScrollbar(this->GetScrollbar(WID_BRW_SCROLL));
this->FinishInitNested(TRANSPORT_RAIL);
matrix->SetCount(_waypoint_count);
matrix->SetClicked(_cur_waypoint_type);
}
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_BRW_WAYPOINT_MATRIX:
/* Three blobs high and wide. */
size->width += resize->width * 2;
size->height += resize->height * 2;
/* Resizing in X direction only at blob size, but at pixel level in Y. */
resize->height = 1;
break;
case WID_BRW_WAYPOINT:
size->width = ScaleGUITrad(64) + 2;
size->height = ScaleGUITrad(58) + 2;
break;
}
}
void DrawWidget(const Rect &r, int widget) const override
{
switch (GB(widget, 0, 16)) {
case WID_BRW_WAYPOINT: {
byte type = GB(widget, 16, 16);
const StationSpec *statspec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(type);
DrawWaypointSprite(r.left + 1 + ScaleGUITrad(31), r.bottom - ScaleGUITrad(31), type, _cur_railtype);
if (!IsStationAvailable(statspec)) {
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK, FILLRECT_CHECKER);
}
}
}
}
void OnClick(Point pt, int widget, int click_count) override
{
switch (GB(widget, 0, 16)) {
case WID_BRW_WAYPOINT: {
byte type = GB(widget, 16, 16);
this->GetWidget<NWidgetMatrix>(WID_BRW_WAYPOINT_MATRIX)->SetClicked(_cur_waypoint_type);
/* Check station availability callback */
const StationSpec *statspec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(type);
if (!IsStationAvailable(statspec)) return;
_cur_waypoint_type = type;
this->GetWidget<NWidgetMatrix>(WID_BRW_WAYPOINT_MATRIX)->SetClicked(_cur_waypoint_type);
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
}
}
}
};
/** Nested widget definition for the build NewGRF rail waypoint window */
static const NWidgetPart _nested_build_waypoint_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_WAYPOINT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
EndContainer(),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_MATRIX, COLOUR_DARK_GREEN, WID_BRW_WAYPOINT_MATRIX), SetPIP(3, 2, 3), SetScrollbar(WID_BRW_SCROLL),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_BRW_WAYPOINT), SetMinimalSize(66, 60), SetDataTip(0x0, STR_WAYPOINT_GRAPHICS_TOOLTIP), SetScrollbar(WID_BRW_SCROLL), EndContainer(),
EndContainer(),
NWidget(NWID_VERTICAL),
NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_BRW_SCROLL),
NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
EndContainer(),
EndContainer(),
};
static WindowDesc _build_waypoint_desc(
WDP_AUTO, "build_waypoint", 0, 0,
WC_BUILD_WAYPOINT, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_waypoint_widgets, lengthof(_nested_build_waypoint_widgets)
);
static void ShowBuildWaypointPicker(Window *parent)
{
new BuildRailWaypointWindow(&_build_waypoint_desc, parent);
}
/**
* Initialize rail building GUI settings
*/
void InitializeRailGui()
{
_build_depot_direction = DIAGDIR_NW;
}
/**
* Re-initialize rail-build toolbar after toggling support for electric trains
* @param disable Boolean whether electric trains are disabled (removed from the game)
*/
void ReinitGuiAfterToggleElrail(bool disable)
{
extern RailType _last_built_railtype;
if (disable && _last_built_railtype == RAILTYPE_ELECTRIC) {
_last_built_railtype = _cur_railtype = RAILTYPE_RAIL;
BuildRailToolbarWindow *w = dynamic_cast<BuildRailToolbarWindow *>(FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL));
if (w != nullptr) w->ModifyRailType(_cur_railtype);
}
MarkWholeScreenDirty();
}
/** Set the initial (default) railtype to use */
static void SetDefaultRailGui()
{
if (_local_company == COMPANY_SPECTATOR || !Company::IsValidID(_local_company)) return;
extern RailType _last_built_railtype;
RailType rt;
switch (_settings_client.gui.default_rail_type) {
case 2: {
/* Find the most used rail type */
uint count[RAILTYPE_END];
memset(count, 0, sizeof(count));
for (TileIndex t = 0; t < MapSize(); t++) {
if (IsTileType(t, MP_RAILWAY) || IsLevelCrossingTile(t) || HasStationTileRail(t) ||
(IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL)) {
count[GetRailType(t)]++;
}
}
rt = static_cast<RailType>(std::max_element(count + RAILTYPE_BEGIN, count + RAILTYPE_END) - count);
if (count[rt] > 0) break;
/* No rail, just get the first available one */
FALLTHROUGH;
}
case 0: {
/* Use first available type */
std::vector<RailType>::const_iterator it = std::find_if(_sorted_railtypes.begin(), _sorted_railtypes.end(),
[](RailType r){ return HasRailtypeAvail(_local_company, r); });
rt = it != _sorted_railtypes.end() ? *it : RAILTYPE_BEGIN;
break;
}
case 1: {
/* Use last available type */
std::vector<RailType>::const_reverse_iterator it = std::find_if(_sorted_railtypes.rbegin(), _sorted_railtypes.rend(),
[](RailType r){ return HasRailtypeAvail(_local_company, r); });
rt = it != _sorted_railtypes.rend() ? *it : RAILTYPE_BEGIN;
break;
}
default:
NOT_REACHED();
}
_last_built_railtype = _cur_railtype = rt;
BuildRailToolbarWindow *w = dynamic_cast<BuildRailToolbarWindow *>(FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL));
if (w != nullptr) w->ModifyRailType(_cur_railtype);
}
/**
* Updates the current signal variant used in the signal GUI
* to the one adequate to current year.
* @param p needed to be called when a setting changes
* @return success, needed for settings
*/
bool ResetSignalVariant(int32 p)
{
SignalVariant new_variant = (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC);
if (new_variant != _cur_signal_variant) {
Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
if (w != nullptr) {
w->SetDirty();
w->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? WID_BS_ELECTRIC_NORM : WID_BS_SEMAPHORE_NORM) + _cur_signal_type);
}
_cur_signal_variant = new_variant;
}
return true;
}
/**
* Resets the rail GUI - sets default railtype to build
* and resets the signal GUI
*/
void InitializeRailGUI()
{
SetDefaultRailGui();
_convert_signal_button = false;
_cur_signal_type = _default_signal_type[_settings_client.gui.default_signal_type];
ResetSignalVariant();
}
/**
* Create a drop down list for all the rail types of the local company.
* @param for_replacement Whether this list is for the replacement window.
* @param all_option Whether to add an 'all types' item.
* @return The populated and sorted #DropDownList.
*/
DropDownList GetRailTypeDropDownList(bool for_replacement, bool all_option)
{
RailTypes used_railtypes;
RailTypes avail_railtypes;
const Company *c = Company::Get(_local_company);
/* Find the used railtypes. */
if (for_replacement) {
avail_railtypes = GetCompanyRailtypes(c->index, false);
used_railtypes = GetRailTypes(false);
} else {
avail_railtypes = c->avail_railtypes;
used_railtypes = GetRailTypes(true);
}
DropDownList list;
if (all_option) {
list.emplace_back(new DropDownListStringItem(STR_REPLACE_ALL_RAILTYPE, INVALID_RAILTYPE, false));
}
Dimension d = { 0, 0 };
RailType rt;
/* Get largest icon size, to ensure text is aligned on each menu item. */
if (!for_replacement) {
FOR_ALL_SORTED_RAILTYPES(rt) {
if (!HasBit(used_railtypes, rt)) continue;
const RailtypeInfo *rti = GetRailTypeInfo(rt);
d = maxdim(d, GetSpriteSize(rti->gui_sprites.build_x_rail));
}
}
FOR_ALL_SORTED_RAILTYPES(rt) {
/* If it's not used ever, don't show it to the user. */
if (!HasBit(used_railtypes, rt)) continue;
const RailtypeInfo *rti = GetRailTypeInfo(rt);
StringID str = for_replacement ? rti->strings.replace_text : (rti->max_speed > 0 ? STR_TOOLBAR_RAILTYPE_VELOCITY : STR_JUST_STRING);
DropDownListParamStringItem *item;
if (for_replacement) {
item = new DropDownListParamStringItem(str, rt, !HasBit(avail_railtypes, rt));
} else {
DropDownListIconItem *iconitem = new DropDownListIconItem(rti->gui_sprites.build_x_rail, PAL_NONE, str, rt, !HasBit(avail_railtypes, rt));
iconitem->SetDimension(d);
item = iconitem;
}
item->SetParam(0, rti->strings.menu_text);
item->SetParam(1, rti->max_speed);
list.emplace_back(item);
}
if (list.size() == 0) {
/* Empty dropdowns are not allowed */
list.emplace_back(new DropDownListStringItem(STR_NONE, INVALID_RAILTYPE, true));
}
return list;
}
| {
"pile_set_name": "Github"
} |
//.CommonJS
var CSSOM = {
CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet,
CSSStyleRule: require("./CSSStyleRule").CSSStyleRule,
CSSMediaRule: require("./CSSMediaRule").CSSMediaRule,
CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration,
CSSKeyframeRule: require('./CSSKeyframeRule').CSSKeyframeRule,
CSSKeyframesRule: require('./CSSKeyframesRule').CSSKeyframesRule
};
///CommonJS
/**
* Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively.
* @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet
* @nosideeffects
* @return {CSSOM.CSSStyleSheet}
*/
CSSOM.clone = function clone(stylesheet) {
var cloned = new CSSOM.CSSStyleSheet;
var rules = stylesheet.cssRules;
if (!rules) {
return cloned;
}
var RULE_TYPES = {
1: CSSOM.CSSStyleRule,
4: CSSOM.CSSMediaRule,
//3: CSSOM.CSSImportRule,
//5: CSSOM.CSSFontFaceRule,
//6: CSSOM.CSSPageRule,
8: CSSOM.CSSKeyframesRule,
9: CSSOM.CSSKeyframeRule
};
for (var i=0, rulesLength=rules.length; i < rulesLength; i++) {
var rule = rules[i];
var ruleClone = cloned.cssRules[i] = new RULE_TYPES[rule.type];
var style = rule.style;
if (style) {
var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration;
for (var j=0, styleLength=style.length; j < styleLength; j++) {
var name = styleClone[j] = style[j];
styleClone[name] = style[name];
styleClone._importants[name] = style.getPropertyPriority(name);
}
styleClone.length = style.length;
}
if (rule.hasOwnProperty('keyText')) {
ruleClone.keyText = rule.keyText;
}
if (rule.hasOwnProperty('selectorText')) {
ruleClone.selectorText = rule.selectorText;
}
if (rule.hasOwnProperty('mediaText')) {
ruleClone.mediaText = rule.mediaText;
}
if (rule.hasOwnProperty('cssRules')) {
ruleClone.cssRules = clone(rule).cssRules;
}
}
return cloned;
};
//.CommonJS
exports.clone = CSSOM.clone;
///CommonJS
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/bug.h>
#include <asm/hardware/cp14.h>
#include "coresight-etm.h"
int etm_readl_cp14(u32 reg, unsigned int *val)
{
switch (reg) {
case ETMCR:
*val = etm_read(ETMCR);
return 0;
case ETMCCR:
*val = etm_read(ETMCCR);
return 0;
case ETMTRIGGER:
*val = etm_read(ETMTRIGGER);
return 0;
case ETMSR:
*val = etm_read(ETMSR);
return 0;
case ETMSCR:
*val = etm_read(ETMSCR);
return 0;
case ETMTSSCR:
*val = etm_read(ETMTSSCR);
return 0;
case ETMTEEVR:
*val = etm_read(ETMTEEVR);
return 0;
case ETMTECR1:
*val = etm_read(ETMTECR1);
return 0;
case ETMFFLR:
*val = etm_read(ETMFFLR);
return 0;
case ETMACVRn(0):
*val = etm_read(ETMACVR0);
return 0;
case ETMACVRn(1):
*val = etm_read(ETMACVR1);
return 0;
case ETMACVRn(2):
*val = etm_read(ETMACVR2);
return 0;
case ETMACVRn(3):
*val = etm_read(ETMACVR3);
return 0;
case ETMACVRn(4):
*val = etm_read(ETMACVR4);
return 0;
case ETMACVRn(5):
*val = etm_read(ETMACVR5);
return 0;
case ETMACVRn(6):
*val = etm_read(ETMACVR6);
return 0;
case ETMACVRn(7):
*val = etm_read(ETMACVR7);
return 0;
case ETMACVRn(8):
*val = etm_read(ETMACVR8);
return 0;
case ETMACVRn(9):
*val = etm_read(ETMACVR9);
return 0;
case ETMACVRn(10):
*val = etm_read(ETMACVR10);
return 0;
case ETMACVRn(11):
*val = etm_read(ETMACVR11);
return 0;
case ETMACVRn(12):
*val = etm_read(ETMACVR12);
return 0;
case ETMACVRn(13):
*val = etm_read(ETMACVR13);
return 0;
case ETMACVRn(14):
*val = etm_read(ETMACVR14);
return 0;
case ETMACVRn(15):
*val = etm_read(ETMACVR15);
return 0;
case ETMACTRn(0):
*val = etm_read(ETMACTR0);
return 0;
case ETMACTRn(1):
*val = etm_read(ETMACTR1);
return 0;
case ETMACTRn(2):
*val = etm_read(ETMACTR2);
return 0;
case ETMACTRn(3):
*val = etm_read(ETMACTR3);
return 0;
case ETMACTRn(4):
*val = etm_read(ETMACTR4);
return 0;
case ETMACTRn(5):
*val = etm_read(ETMACTR5);
return 0;
case ETMACTRn(6):
*val = etm_read(ETMACTR6);
return 0;
case ETMACTRn(7):
*val = etm_read(ETMACTR7);
return 0;
case ETMACTRn(8):
*val = etm_read(ETMACTR8);
return 0;
case ETMACTRn(9):
*val = etm_read(ETMACTR9);
return 0;
case ETMACTRn(10):
*val = etm_read(ETMACTR10);
return 0;
case ETMACTRn(11):
*val = etm_read(ETMACTR11);
return 0;
case ETMACTRn(12):
*val = etm_read(ETMACTR12);
return 0;
case ETMACTRn(13):
*val = etm_read(ETMACTR13);
return 0;
case ETMACTRn(14):
*val = etm_read(ETMACTR14);
return 0;
case ETMACTRn(15):
*val = etm_read(ETMACTR15);
return 0;
case ETMCNTRLDVRn(0):
*val = etm_read(ETMCNTRLDVR0);
return 0;
case ETMCNTRLDVRn(1):
*val = etm_read(ETMCNTRLDVR1);
return 0;
case ETMCNTRLDVRn(2):
*val = etm_read(ETMCNTRLDVR2);
return 0;
case ETMCNTRLDVRn(3):
*val = etm_read(ETMCNTRLDVR3);
return 0;
case ETMCNTENRn(0):
*val = etm_read(ETMCNTENR0);
return 0;
case ETMCNTENRn(1):
*val = etm_read(ETMCNTENR1);
return 0;
case ETMCNTENRn(2):
*val = etm_read(ETMCNTENR2);
return 0;
case ETMCNTENRn(3):
*val = etm_read(ETMCNTENR3);
return 0;
case ETMCNTRLDEVRn(0):
*val = etm_read(ETMCNTRLDEVR0);
return 0;
case ETMCNTRLDEVRn(1):
*val = etm_read(ETMCNTRLDEVR1);
return 0;
case ETMCNTRLDEVRn(2):
*val = etm_read(ETMCNTRLDEVR2);
return 0;
case ETMCNTRLDEVRn(3):
*val = etm_read(ETMCNTRLDEVR3);
return 0;
case ETMCNTVRn(0):
*val = etm_read(ETMCNTVR0);
return 0;
case ETMCNTVRn(1):
*val = etm_read(ETMCNTVR1);
return 0;
case ETMCNTVRn(2):
*val = etm_read(ETMCNTVR2);
return 0;
case ETMCNTVRn(3):
*val = etm_read(ETMCNTVR3);
return 0;
case ETMSQ12EVR:
*val = etm_read(ETMSQ12EVR);
return 0;
case ETMSQ21EVR:
*val = etm_read(ETMSQ21EVR);
return 0;
case ETMSQ23EVR:
*val = etm_read(ETMSQ23EVR);
return 0;
case ETMSQ31EVR:
*val = etm_read(ETMSQ31EVR);
return 0;
case ETMSQ32EVR:
*val = etm_read(ETMSQ32EVR);
return 0;
case ETMSQ13EVR:
*val = etm_read(ETMSQ13EVR);
return 0;
case ETMSQR:
*val = etm_read(ETMSQR);
return 0;
case ETMEXTOUTEVRn(0):
*val = etm_read(ETMEXTOUTEVR0);
return 0;
case ETMEXTOUTEVRn(1):
*val = etm_read(ETMEXTOUTEVR1);
return 0;
case ETMEXTOUTEVRn(2):
*val = etm_read(ETMEXTOUTEVR2);
return 0;
case ETMEXTOUTEVRn(3):
*val = etm_read(ETMEXTOUTEVR3);
return 0;
case ETMCIDCVRn(0):
*val = etm_read(ETMCIDCVR0);
return 0;
case ETMCIDCVRn(1):
*val = etm_read(ETMCIDCVR1);
return 0;
case ETMCIDCVRn(2):
*val = etm_read(ETMCIDCVR2);
return 0;
case ETMCIDCMR:
*val = etm_read(ETMCIDCMR);
return 0;
case ETMIMPSPEC0:
*val = etm_read(ETMIMPSPEC0);
return 0;
case ETMIMPSPEC1:
*val = etm_read(ETMIMPSPEC1);
return 0;
case ETMIMPSPEC2:
*val = etm_read(ETMIMPSPEC2);
return 0;
case ETMIMPSPEC3:
*val = etm_read(ETMIMPSPEC3);
return 0;
case ETMIMPSPEC4:
*val = etm_read(ETMIMPSPEC4);
return 0;
case ETMIMPSPEC5:
*val = etm_read(ETMIMPSPEC5);
return 0;
case ETMIMPSPEC6:
*val = etm_read(ETMIMPSPEC6);
return 0;
case ETMIMPSPEC7:
*val = etm_read(ETMIMPSPEC7);
return 0;
case ETMSYNCFR:
*val = etm_read(ETMSYNCFR);
return 0;
case ETMIDR:
*val = etm_read(ETMIDR);
return 0;
case ETMCCER:
*val = etm_read(ETMCCER);
return 0;
case ETMEXTINSELR:
*val = etm_read(ETMEXTINSELR);
return 0;
case ETMTESSEICR:
*val = etm_read(ETMTESSEICR);
return 0;
case ETMEIBCR:
*val = etm_read(ETMEIBCR);
return 0;
case ETMTSEVR:
*val = etm_read(ETMTSEVR);
return 0;
case ETMAUXCR:
*val = etm_read(ETMAUXCR);
return 0;
case ETMTRACEIDR:
*val = etm_read(ETMTRACEIDR);
return 0;
case ETMVMIDCVR:
*val = etm_read(ETMVMIDCVR);
return 0;
case ETMOSLSR:
*val = etm_read(ETMOSLSR);
return 0;
case ETMOSSRR:
*val = etm_read(ETMOSSRR);
return 0;
case ETMPDCR:
*val = etm_read(ETMPDCR);
return 0;
case ETMPDSR:
*val = etm_read(ETMPDSR);
return 0;
default:
*val = 0;
return -EINVAL;
}
}
int etm_writel_cp14(u32 reg, u32 val)
{
switch (reg) {
case ETMCR:
etm_write(val, ETMCR);
break;
case ETMTRIGGER:
etm_write(val, ETMTRIGGER);
break;
case ETMSR:
etm_write(val, ETMSR);
break;
case ETMTSSCR:
etm_write(val, ETMTSSCR);
break;
case ETMTEEVR:
etm_write(val, ETMTEEVR);
break;
case ETMTECR1:
etm_write(val, ETMTECR1);
break;
case ETMFFLR:
etm_write(val, ETMFFLR);
break;
case ETMACVRn(0):
etm_write(val, ETMACVR0);
break;
case ETMACVRn(1):
etm_write(val, ETMACVR1);
break;
case ETMACVRn(2):
etm_write(val, ETMACVR2);
break;
case ETMACVRn(3):
etm_write(val, ETMACVR3);
break;
case ETMACVRn(4):
etm_write(val, ETMACVR4);
break;
case ETMACVRn(5):
etm_write(val, ETMACVR5);
break;
case ETMACVRn(6):
etm_write(val, ETMACVR6);
break;
case ETMACVRn(7):
etm_write(val, ETMACVR7);
break;
case ETMACVRn(8):
etm_write(val, ETMACVR8);
break;
case ETMACVRn(9):
etm_write(val, ETMACVR9);
break;
case ETMACVRn(10):
etm_write(val, ETMACVR10);
break;
case ETMACVRn(11):
etm_write(val, ETMACVR11);
break;
case ETMACVRn(12):
etm_write(val, ETMACVR12);
break;
case ETMACVRn(13):
etm_write(val, ETMACVR13);
break;
case ETMACVRn(14):
etm_write(val, ETMACVR14);
break;
case ETMACVRn(15):
etm_write(val, ETMACVR15);
break;
case ETMACTRn(0):
etm_write(val, ETMACTR0);
break;
case ETMACTRn(1):
etm_write(val, ETMACTR1);
break;
case ETMACTRn(2):
etm_write(val, ETMACTR2);
break;
case ETMACTRn(3):
etm_write(val, ETMACTR3);
break;
case ETMACTRn(4):
etm_write(val, ETMACTR4);
break;
case ETMACTRn(5):
etm_write(val, ETMACTR5);
break;
case ETMACTRn(6):
etm_write(val, ETMACTR6);
break;
case ETMACTRn(7):
etm_write(val, ETMACTR7);
break;
case ETMACTRn(8):
etm_write(val, ETMACTR8);
break;
case ETMACTRn(9):
etm_write(val, ETMACTR9);
break;
case ETMACTRn(10):
etm_write(val, ETMACTR10);
break;
case ETMACTRn(11):
etm_write(val, ETMACTR11);
break;
case ETMACTRn(12):
etm_write(val, ETMACTR12);
break;
case ETMACTRn(13):
etm_write(val, ETMACTR13);
break;
case ETMACTRn(14):
etm_write(val, ETMACTR14);
break;
case ETMACTRn(15):
etm_write(val, ETMACTR15);
break;
case ETMCNTRLDVRn(0):
etm_write(val, ETMCNTRLDVR0);
break;
case ETMCNTRLDVRn(1):
etm_write(val, ETMCNTRLDVR1);
break;
case ETMCNTRLDVRn(2):
etm_write(val, ETMCNTRLDVR2);
break;
case ETMCNTRLDVRn(3):
etm_write(val, ETMCNTRLDVR3);
break;
case ETMCNTENRn(0):
etm_write(val, ETMCNTENR0);
break;
case ETMCNTENRn(1):
etm_write(val, ETMCNTENR1);
break;
case ETMCNTENRn(2):
etm_write(val, ETMCNTENR2);
break;
case ETMCNTENRn(3):
etm_write(val, ETMCNTENR3);
break;
case ETMCNTRLDEVRn(0):
etm_write(val, ETMCNTRLDEVR0);
break;
case ETMCNTRLDEVRn(1):
etm_write(val, ETMCNTRLDEVR1);
break;
case ETMCNTRLDEVRn(2):
etm_write(val, ETMCNTRLDEVR2);
break;
case ETMCNTRLDEVRn(3):
etm_write(val, ETMCNTRLDEVR3);
break;
case ETMCNTVRn(0):
etm_write(val, ETMCNTVR0);
break;
case ETMCNTVRn(1):
etm_write(val, ETMCNTVR1);
break;
case ETMCNTVRn(2):
etm_write(val, ETMCNTVR2);
break;
case ETMCNTVRn(3):
etm_write(val, ETMCNTVR3);
break;
case ETMSQ12EVR:
etm_write(val, ETMSQ12EVR);
break;
case ETMSQ21EVR:
etm_write(val, ETMSQ21EVR);
break;
case ETMSQ23EVR:
etm_write(val, ETMSQ23EVR);
break;
case ETMSQ31EVR:
etm_write(val, ETMSQ31EVR);
break;
case ETMSQ32EVR:
etm_write(val, ETMSQ32EVR);
break;
case ETMSQ13EVR:
etm_write(val, ETMSQ13EVR);
break;
case ETMSQR:
etm_write(val, ETMSQR);
break;
case ETMEXTOUTEVRn(0):
etm_write(val, ETMEXTOUTEVR0);
break;
case ETMEXTOUTEVRn(1):
etm_write(val, ETMEXTOUTEVR1);
break;
case ETMEXTOUTEVRn(2):
etm_write(val, ETMEXTOUTEVR2);
break;
case ETMEXTOUTEVRn(3):
etm_write(val, ETMEXTOUTEVR3);
break;
case ETMCIDCVRn(0):
etm_write(val, ETMCIDCVR0);
break;
case ETMCIDCVRn(1):
etm_write(val, ETMCIDCVR1);
break;
case ETMCIDCVRn(2):
etm_write(val, ETMCIDCVR2);
break;
case ETMCIDCMR:
etm_write(val, ETMCIDCMR);
break;
case ETMIMPSPEC0:
etm_write(val, ETMIMPSPEC0);
break;
case ETMIMPSPEC1:
etm_write(val, ETMIMPSPEC1);
break;
case ETMIMPSPEC2:
etm_write(val, ETMIMPSPEC2);
break;
case ETMIMPSPEC3:
etm_write(val, ETMIMPSPEC3);
break;
case ETMIMPSPEC4:
etm_write(val, ETMIMPSPEC4);
break;
case ETMIMPSPEC5:
etm_write(val, ETMIMPSPEC5);
break;
case ETMIMPSPEC6:
etm_write(val, ETMIMPSPEC6);
break;
case ETMIMPSPEC7:
etm_write(val, ETMIMPSPEC7);
break;
case ETMSYNCFR:
etm_write(val, ETMSYNCFR);
break;
case ETMEXTINSELR:
etm_write(val, ETMEXTINSELR);
break;
case ETMTESSEICR:
etm_write(val, ETMTESSEICR);
break;
case ETMEIBCR:
etm_write(val, ETMEIBCR);
break;
case ETMTSEVR:
etm_write(val, ETMTSEVR);
break;
case ETMAUXCR:
etm_write(val, ETMAUXCR);
break;
case ETMTRACEIDR:
etm_write(val, ETMTRACEIDR);
break;
case ETMVMIDCVR:
etm_write(val, ETMVMIDCVR);
break;
case ETMOSLAR:
etm_write(val, ETMOSLAR);
break;
case ETMOSSRR:
etm_write(val, ETMOSSRR);
break;
case ETMPDCR:
etm_write(val, ETMPDCR);
break;
case ETMPDSR:
etm_write(val, ETMPDSR);
break;
default:
return -EINVAL;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
set hive.support.quoted.identifiers=none;
DESCRIBE FUNCTION `index`;
DESCRIBE FUNCTION EXTENDED `index`;
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.karaf.service.command;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.console.CommandLine;
import org.apache.karaf.shell.api.console.Completer;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.support.completers.StringsCompleter;
import org.osgi.framework.BundleContext;
@Service
public class ObjectClassCompleter implements Completer {
@Reference
private BundleContext context;
public void setContext(BundleContext context) {
this.context = context;
}
@Override
public int complete(final Session session, final CommandLine commandLine, final List<String> candidates) {
Map<String, Integer> serviceNamesMap = ListServices.getServiceNamesMap(context);
Set<String> serviceNames = serviceNamesMap.keySet();
List<String> strings = new ArrayList<>();
for (String name : serviceNames) {
strings.add(ObjectClassMatcher.getShortName(name));
}
strings.addAll(serviceNames);
return new StringsCompleter(strings).complete(session, commandLine, candidates);
}
}
| {
"pile_set_name": "Github"
} |
# `DissectedTriangleTessagon`

| {
"pile_set_name": "Github"
} |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +-------------------------------------------------------------------+
// | WiFiDog Authentication Server |
// | ============================= |
// | |
// | The WiFiDog Authentication Server is part of the WiFiDog captive |
// | portal suite. |
// +-------------------------------------------------------------------+
// | PHP version 5 required. |
// +-------------------------------------------------------------------+
// | Homepage: http://www.wifidog.org/ |
// | Source Forge: http://sourceforge.net/projects/wifidog/ |
// +-------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU General Public License as |
// | published by the Free Software Foundation; either version 2 of |
// | the License, or (at your option) any later version. |
// | |
// | 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. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, contact: |
// | |
// | Free Software Foundation Voice: +1-617-542-5942 |
// | 59 Temple Place - Suite 330 Fax: +1-617-542-2652 |
// | Boston, MA 02111-1307, USA gnu@gnu.org |
// | |
// +-------------------------------------------------------------------+
/**
* @package WiFiDogAuthServer
* @subpackage ContentClasses
* @author Benoit Grégoire <benoitg@coeus.ca>
* @copyright 2007 Benoit Grégoire, Technologies Coeus inc.
* @version Subversion $Id: $
* @link http://www.wifidog.org/
*/
/**
* Represents a list of banner ads
*
* @package WiFiDogAuthServer
* @subpackage ContentClasses
* @author Benoit Grégoire <benoitg@coeus.ca>
* @copyright 2006 Benoit Grégoire, Technologies Coeus inc.
*/
class ShoutBox extends Content {
const DEFAULT_SHOUT_FIELD_SIZE=40;
const DEFAULT_DISPLAY_NUM_ITEMS=5;
/**
* Constructor
*
* @param string $content_id Content id
*
* @return void */
protected function __construct($content_id) {
parent :: __construct($content_id);
}
/**
* Gets the content that is to be added as onclick value in the form
*
* @return Content or null
*/
private function getOnClickContent() {
$content_id = $this->getKVP('ShoutBox_onclick_content_id');
if($content_id)
{
return Content::getObject($content_id);
}
else
{
return null;
}
}
/**
* Set the content that is to be added as onclick value in the form
*
* @param Content object or null
*
* @return true
*/
private function setOnClickContent($content) {
if($content)
{
$this->setKVP('ShoutBox_onclick_content_id', $content->getId());
}
else
{
$this->setKVP('ShoutBox_onclick_content_id', null);
}
return true;
}
/**
* Set the size of the shout field (in characters)
* @param $$numChars integer >= 1 The number of characters.
* @return the value, AFTER it was set (so the previous value if the value was invalid)
*/
protected function setShoutFieldSize($numChars)
{
$numChars = (int)$numChars;
if($numChars >= 1) {
$retval = $this->setKVP(get_class($this) . '_shout_field_size', $numChars);
}
else {
//We gave an invalide value
$retval = $this->getMaxShoutChars();
}
return $retval;
}
/**
* Returns the maximum number of character one can shout. 0 means no limit.
*
* @return integer number of items to display
*/
protected function getShoutFieldSize()
{
$numChars = $this->getKVP(get_class($this) . '_shout_field_size');
if(empty($numChars)) {
$numChars = self::DEFAULT_SHOUT_FIELD_SIZE;
}
return $numChars;
}
/**
* Set the number of items to be displayed by the shoutbox
* @param $numChars integer >= 0 The maximum number of characters. 0 means no limit
* @return the value, AFTER it was set (so the previous value if the value was invalid)
*/
protected function setMaxShoutChars($numChars)
{
$numChars = (int)$numChars;
if($numChars >= 0) {
$retval = $this->setKVP(get_class($this) . '_max_shout_chars', $numChars);
}
else {
//We gave an invalide value
$retval = $this->getMaxShoutChars();
}
return $retval;
}
/**
* Returns the maximum number of character one can shout. 0 means no limit.
*
* @return integer number of items to display
*/
protected function getMaxShoutChars()
{
return $this->getKVP(get_class($this) . '_max_shout_chars');
}
/**
* Set the number of items to be displayed by the shoutbox
* @param $numItems integer >= 0 The number of items to display. 0 means no limit
*
* @return the value, AFTER it was set (so the previous value if the value was invalid)
*/
protected function setDisplayNumItems($numItems)
{
$numItems = (int)$numItems;
if($numItems >= 0) {
$retval = $this->setKVP(get_class($this) . '_display_num_items', $numItems);
}
else {
//We gave an invalid value
$retval = $this->getDisplayNumItems();
}
return $retval;
}
/**
* Returns the number of items to be displayed by the shoutbox
*
* @return integer number of items to display
*/
protected function getDisplayNumItems()
{
$displayNumItems = $this->getKVP(get_class($this) . '_display_num_items');
if(empty($displayNumItems)) {
$displayNumItems = self::DEFAULT_DISPLAY_NUM_ITEMS;
}
return $displayNumItems;
}
public function getAdminUI($subclass_admin_interface = null, $title = null) {
$html = null;
/*display_num_items*/
$displayNumItems = $this->getDisplayNumItems();
$html .= "<li class='admin_element_item_container'>\n";
$html .= "<div class='admin_element_label'>" . ("Number of shouts to display in the list (0 means no limit)") . ": </div>\n";
$html .= "<div class='admin_element_data'>\n";
$name = "shoutbox_{this->getId()}_display_num_items";
$html .= "<input type='text' size='6' value='$displayNumItems' name='$name'>\n";
$html .= "</div>\n";
$html .= "</li>\n";
/*max_shout_chars*/
$maxShoutChars = $this->getMaxShoutChars();
$html .= "<li class='admin_element_item_container'>\n";
$html .= "<div class='admin_element_label'>" . ("Maximum number of characters for each shouts (0 means no limit)") . ": </div>\n";
$html .= "<div class='admin_element_data'>\n";
$name = "shoutbox_{this->getId()}_max_num_chars";
$html .= "<input type='text' size='6' value='$maxShoutChars' name='$name'>\n";
$html .= "</div>\n";
$html .= "</li>\n";
/*shout_field_size*/
$shoutFieldSize = $this->getShoutFieldSize();
$html .= "<li class='admin_element_item_container'>\n";
$html .= "<div class='admin_element_label'>" . ("Size (num characters) of the shout field") . ": </div>\n";
$html .= "<div class='admin_element_data'>\n";
$name = "shoutbox_{this->getId()}_shout_field_size";
$html .= "<input type='text' size='6' value='$shoutFieldSize' name='$name'>\n";
$html .= "</div>\n";
$html .= "</li>\n";
/* OnclickContent */
$criteria_array = array (
array ('isTextualContent'),
array ('isSimpleContent')
);
$onclick_allowed_content_types = ContentTypeFilter :: getObject($criteria_array);
$content = $this->getOnClickContent();
$html .= "<li class='admin_element_item_container admin_section_edit_description'>\n";
$html .= "<div class='admin_element_data'>\n";
$onclick_title = _("Shout button 'onclick=' value (optionnal):");
if (!$content) {
$name = "shoutbox_" . $this->id . "_onclick_content_new";
$html .= self :: getNewContentUI($name, $onclick_allowed_content_types, $onclick_title);
$html .= $hint;
} else {
$html .= $content->getAdminUI(null, $onclick_title);
$html .= "<div class='admin_section_hint'>" . sprintf(_("Note that the onclick parameter will appear inside double quotes in html. They must be properly encoded fot that context. You can access the shout text in Javascript with: %s"), "document.getElementById('shout_text').value") . "</div>\n";
$html .= "</div>\n";
$html .= "<div class='admin_element_tools'>\n";
$name = "shoutbox_" . $this->id . "_onclick_content_erase";
$html .= "<input type='submit' class='submit' name='$name' value='" . sprintf(_("Delete %s (%s)"), _("onclick parameter"), get_class($content)) . "'>";
}
$html .= "</div>\n";
$html .= "</li>\n";
return parent :: getAdminUI($html, $title);
}
/**
* Processes the input of the administration interface for Picture
*
* @return void
*/
public function processAdminUI() {
$db=AbstractDb::getObject();
if ($this->DEPRECATEDisOwner(User :: getCurrentUser()) || User :: getCurrentUser()->DEPRECATEDisSuperAdmin()) {
parent :: processAdminUI();
/*display_num_items*/
$name = "shoutbox_{this->getId()}_display_num_items";
$this->setDisplayNumItems($_REQUEST[$name]);
/*max_shout_chars*/
$name = "shoutbox_{this->getId()}_max_num_chars";
$this->setMaxShoutChars($_REQUEST[$name]);
/*shout_field_size*/
$name = "shoutbox_{this->getId()}_shout_field_size";
$this->setShoutFieldSize($_REQUEST[$name]);
/* OnclickContent */
$content = $this->getOnClickContent();
if (!$content) {
$name = "shoutbox_" . $this->id . "_onclick_content_new";
$content = self :: processNewContentUI($name);
$this->setOnClickContent($content);
} else {
$name = "shoutbox_" . $this->id . "_onclick_content_erase";
if (!empty ($_REQUEST[$name]) && $_REQUEST[$name] == true) {
$this->setOnClickContent(null);
$content->delete($errmsg);
} else {
$content->processAdminUI();
}
}
}
}
/** Retreives the user interface of this object. Anything that overrides this method should call the parent method with it's output at the END of processing.
* @return The HTML fragment for this interface */
public function getUserUI() {
$real_node = Node::getCurrentRealNode();//For production
//$real_node = Node::getCurrentNode();//For testing
$node = Node::getCurrentNode();
$formHtml = null;
if($real_node) {
$formHtml .= "<form action='".BASE_URL_PATH."content/ShoutBox/add_message.php'>\n";
$formHtml .= "<input type='hidden' name='shoutbox_id' value='".$this->getId()."'/>\n";
//$html .= "destination_url: ";pretty_print_r($_SERVER);
$maxShoutChars = $this->getMaxShoutChars();
$shoutFieldSize = $this->getShoutFieldSize();
if($maxShoutChars>0) {
$max_size = "maxlength='$maxShoutChars'";
$maxShoutChars<=$shoutFieldSize?$size="size='$maxShoutChars'":$size="size='$shoutFieldSize'";
}
else {
$max_size = null;
$size = "size='$shoutFieldSize'";
}
$formHtml .= "<input type='hidden' name='node_id' value='".$node->getId()."'/>\n";
$formHtml .= "<input type='text' name='shout_text' id='shout_text' $size $max_size value=''/>\n";
$onclick_content = $this->getOnClickContent();
if($onclick_content){
$onclick="onclick=\"".$onclick_content->getString()."\"";
} else
{
$onclick = null;
}
$formHtml .= "<input type='submit' name='shout_submit' $onclick value='"._("Shout!")."'>\n";
$formHtml .= "</form>\n";
}
else
{
$formHtml .= "<p>"._("Sorry, you must be at a hotspot to use the shoutbox")."</p>\n";
}
$html_main = '';
$displayNumItems = $this->getDisplayNumItems();
$db = AbstractDb::getObject();
if($node) {
$node_id = $db->escapeString($node->getId());
if($displayNumItems>0) {
$limit = "LIMIT $displayNumItems";
$heading = "<em>".sprintf(_("Last %d messages:"), $displayNumItems)."</em>";
}
else {
$limit = null;
$heading = null;
}
$sql = "SELECT *, EXTRACT(EPOCH FROM creation_date) as creation_date_php FROM content_shoutbox_messages WHERE origin_node_id='$node_id' ORDER BY creation_date DESC $limit\n";
$db->execSql($sql, $rows, false);
$html_main .= "<ul>";
$html_main .= "<li>$formHtml</li>";
if($rows) {
//$html_main .= $heading;
foreach ($rows as $row) {
$user = User::getObject($row['author_user_id']);
$content = Content::getObject($row['message_content_id']);
$html_main .= "<li>";
$dateStr = "<span class='date'>".strftime('%x', $row['creation_date_php'])."</span>\n";
$html_main .= $dateStr.' '. $user->getListUI().": \n";
$html_main .= "<div class='message'>".$content->getListUI()."</div>\n";
$html_main .= "</li>";
}
}
$html_main .= "</ul>";
}
else
{
$html_main .= "<p>"._("Sorry, I am unable to determine your current node")."</p>\n";
}
$this->setUserUIMainDisplayContent($html_main);
//$this->setUserUIMainInteractionArea($formHtml);
return Content :: getUserUI();
}
/**
* Reloads the object from the database.
*
* Should normally be called after a set operation.
*
* This function is private because calling it from a subclass will call the
* constructor from the wrong scope
*
* @return void
*/
private function refresh() {
$this->__construct($this->id);
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.lang.model.util;
import javax.lang.model.element.*;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import static javax.lang.model.SourceVersion.*;
/**
* A scanning visitor of program elements with default behavior
* appropriate for source versions {@link SourceVersion#RELEASE_9
* RELEASE_9} through {@link SourceVersion#RELEASE_11 RELEASE_11}.
*
* The <code>visit<i>Xyz</i></code> methods in this
* class scan their component elements by calling {@code scan} on
* their {@linkplain Element#getEnclosedElements enclosed elements},
* {@linkplain ExecutableElement#getParameters parameters}, etc., as
* indicated in the individual method specifications. A subclass can
* control the order elements are visited by overriding the
* <code>visit<i>Xyz</i></code> methods. Note that clients of a scanner
* may get the desired behavior be invoking {@code v.scan(e, p)} rather
* than {@code v.visit(e, p)} on the root objects of interest.
*
* <p>When a subclass overrides a <code>visit<i>Xyz</i></code> method, the
* new method can cause the enclosed elements to be scanned in the
* default way by calling <code>super.visit<i>Xyz</i></code>. In this
* fashion, the concrete visitor can control the ordering of traversal
* over the component elements with respect to the additional
* processing; for example, consistently calling
* <code>super.visit<i>Xyz</i></code> at the start of the overridden
* methods will yield a preorder traversal, etc. If the component
* elements should be traversed in some other order, instead of
* calling <code>super.visit<i>Xyz</i></code>, an overriding visit method
* should call {@code scan} with the elements in the desired order.
*
* <p> Methods in this class may be overridden subject to their
* general contract. Note that annotating methods in concrete
* subclasses with {@link java.lang.Override @Override} will help
* ensure that methods are overridden as intended.
*
* <p> <b>WARNING:</b> The {@code ElementVisitor} interface
* implemented by this class may have methods added to it in the
* future to accommodate new, currently unknown, language structures
* added to future versions of the Java™ programming language.
* Therefore, methods whose names begin with {@code "visit"} may be
* added to this class in the future; to avoid incompatibilities,
* classes which extend this class should not declare any instance
* methods with names beginning with {@code "visit"}.
*
* <p>When such a new visit method is added, the default
* implementation in this class will be to call the {@link
* #visitUnknown visitUnknown} method. A new element scanner visitor
* class will also be introduced to correspond to the new language
* level; this visitor will have different default behavior for the
* visit method in question. When the new visitor is introduced, all
* or portions of this visitor may be deprecated.
*
* @param <R> the return type of this visitor's methods. Use {@link
* Void} for visitors that do not need to return results.
* @param <P> the type of the additional parameter to this visitor's
* methods. Use {@code Void} for visitors that do not need an
* additional parameter.
*
* @see ElementScanner6
* @see ElementScanner7
* @see ElementScanner8
* @since 9
* @spec JPMS
*/
@SupportedSourceVersion(RELEASE_11)
public class ElementScanner9<R, P> extends ElementScanner8<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
* default value.
*/
protected ElementScanner9(){
super(null);
}
/**
* Constructor for concrete subclasses; uses the argument for the
* default value.
*
* @param defaultValue the default value
*/
protected ElementScanner9(R defaultValue){
super(defaultValue);
}
/**
* {@inheritDoc}
*
* @implSpec This implementation scans the enclosed elements.
*
* @param e the element to visit
* @param p a visitor-specified parameter
* @return the result of the scan
*/
@Override
public R visitModule(ModuleElement e, P p) {
return scan(e.getEnclosedElements(), p); // TODO: Hmmm, this might not be right
}
}
| {
"pile_set_name": "Github"
} |
@objc class ClassInOtherFile {}
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace GoogleApi.Entities.Search.Common
{
/// <summary>
/// PageMap information.
/// </summary>
public class PageMap
{
/// <summary>
/// PageMap information, keyed by the name of this PageMap.
/// </summary>
[JsonProperty("list")]
public virtual IDictionary<string, IDictionary<string, string>> List { get; set; }
}
} | {
"pile_set_name": "Github"
} |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {browserProxy} from '../browser_proxy/browser_proxy.js';
import {assert, assertInstanceof} from '../chrome_util.js';
import {
PhotoConstraintsPreferrer, // eslint-disable-line no-unused-vars
VideoConstraintsPreferrer, // eslint-disable-line no-unused-vars
} from '../device/constraints_preferrer.js';
// eslint-disable-next-line no-unused-vars
import {DeviceInfoUpdater} from '../device/device_info_updater.js';
import * as metrics from '../metrics.js';
// eslint-disable-next-line no-unused-vars
import {ResultSaver} from '../models/result_saver.js';
import {ChromeHelper} from '../mojo/chrome_helper.js';
import {DeviceOperator} from '../mojo/device_operator.js';
import * as nav from '../nav.js';
// eslint-disable-next-line no-unused-vars
import {PerfLogger} from '../perf.js';
import * as sound from '../sound.js';
import * as state from '../state.js';
import * as toast from '../toast.js';
import {
Facing,
Mode,
ViewName,
} from '../type.js';
import * as util from '../util.js';
import {Layout} from './camera/layout.js';
import {
Modes,
PhotoResult, // eslint-disable-line no-unused-vars
Video,
VideoResult, // eslint-disable-line no-unused-vars
} from './camera/modes.js';
import {Options} from './camera/options.js';
import {Preview} from './camera/preview.js';
import * as timertick from './camera/timertick.js';
import {View} from './view.js';
/**
* Thrown when app window suspended during stream reconfiguration.
*/
class CameraSuspendedError extends Error {
/**
* @param {string=} message Error message.
*/
constructor(message = 'Camera suspended.') {
super(message);
this.name = this.constructor.name;
}
}
/**
* Camera-view controller.
*/
export class Camera extends View {
/**
* @param {!ResultSaver} resultSaver
* @param {!DeviceInfoUpdater} infoUpdater
* @param {!PhotoConstraintsPreferrer} photoPreferrer
* @param {!VideoConstraintsPreferrer} videoPreferrer
* @param {Mode} defaultMode
* @param {!PerfLogger} perfLogger
*/
constructor(
resultSaver, infoUpdater, photoPreferrer, videoPreferrer, defaultMode,
perfLogger) {
super(ViewName.CAMERA);
/**
* @type {!DeviceInfoUpdater}
* @private
*/
this.infoUpdater_ = infoUpdater;
/**
* @type {!Mode}
* @protected
*/
this.defaultMode_ = defaultMode;
/**
* @type {!PerfLogger}
* @private
*/
this.perfLogger_ = perfLogger;
/**
* Layout handler for the camera view.
* @type {!Layout}
* @private
*/
this.layout_ = new Layout();
/**
* Video preview for the camera.
* @type {!Preview}
* @private
*/
this.preview_ = new Preview(this.start.bind(this));
/**
* Options for the camera.
* @type {!Options}
* @private
*/
this.options_ = new Options(infoUpdater, this.start.bind(this));
/**
* @type {!ResultSaver}
* @protected
*/
this.resultSaver_ = resultSaver;
/**
* Device id of video device of active preview stream. Sets to null when
* preview become inactive.
* @type {?string}
* @private
*/
this.activeDeviceId_ = null;
const createVideoSaver = async () => resultSaver.startSaveVideo();
const playShutterEffect = () => {
sound.play('#sound-shutter');
util.animateOnce(this.preview_.video);
};
/**
* Modes for the camera.
* @type {Modes}
* @private
*/
this.modes_ = new Modes(
this.defaultMode_, photoPreferrer, videoPreferrer,
this.start.bind(this), this.doSavePhoto_.bind(this), createVideoSaver,
this.doSaveVideo_.bind(this), playShutterEffect,
() => this.preview_.toImage());
/**
* @type {!Facing}
* @protected
*/
this.facingMode_ = Facing.UNKNOWN;
/**
* @type {!metrics.ShutterType}
* @protected
*/
this.shutterType_ = metrics.ShutterType.UNKNOWN;
/**
* @type {boolean}
* @private
*/
this.locked_ = false;
/**
* @type {?number}
* @private
*/
this.retryStartTimeout_ = null;
/**
* Promise for the camera stream configuration process. It's resolved to
* boolean for whether the configuration is failed and kick out another
* round of reconfiguration. Sets to null once the configuration is
* completed.
* @type {?Promise<boolean>}
* @private
*/
this.configuring_ = null;
/**
* Promise for the current take of photo or recording.
* @type {?Promise}
* @protected
*/
this.take_ = null;
/**
* Gets type of ways to trigger shutter from click event.
* @param {!MouseEvent} e
* @return {!metrics.ShutterType}
*/
const getShutterType = (e) => {
if (e.clientX === 0 && e.clientY === 0) {
return metrics.ShutterType.KEYBOARD;
}
return e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents ?
metrics.ShutterType.TOUCH :
metrics.ShutterType.MOUSE;
};
document.querySelector('#start-takephoto')
.addEventListener('click', (e) => {
const mouseEvent = assertInstanceof(e, MouseEvent);
this.beginTake_(getShutterType(mouseEvent));
});
document.querySelector('#stop-takephoto')
.addEventListener('click', () => this.endTake_());
const videoShutter = document.querySelector('#recordvideo');
videoShutter.addEventListener('click', (e) => {
if (!state.get(state.State.TAKING)) {
this.beginTake_(getShutterType(assertInstanceof(e, MouseEvent)));
} else {
this.endTake_();
}
});
document.querySelector('#video-snapshot').addEventListener('click', () => {
const videoMode = assertInstanceof(this.modes_.current, Video);
videoMode.takeSnapshot();
});
const pauseShutter = document.querySelector('#pause-recordvideo');
pauseShutter.addEventListener('click', () => {
const videoMode = assertInstanceof(this.modes_.current, Video);
videoMode.togglePaused();
});
// TODO(shik): Tune the timing for playing video shutter button animation.
// Currently the |TAKING| state is ended when the file is saved.
util.bindElementAriaLabelWithState({
element: videoShutter,
state: state.State.TAKING,
onLabel: 'record_video_stop_button',
offLabel: 'record_video_start_button'
});
util.bindElementAriaLabelWithState({
element: pauseShutter,
state: state.State.RECORDING_PAUSED,
onLabel: 'record_video_resume_button',
offLabel: 'record_video_pause_button'
});
// Monitor the states to stop camera when locked/minimized.
ChromeHelper.getInstance().addOnLockListener((isLocked) => {
this.locked_ = isLocked;
if (this.locked_) {
this.start();
}
});
chrome.app.window.current().onMinimized.addListener(() => this.start());
document.addEventListener('visibilitychange', () => {
const recording = state.get(state.State.TAKING) && state.get(Mode.VIDEO);
if (this.isTabletBackground_() && !recording) {
this.start();
}
});
state.addObserver(state.State.SCREEN_OFF_AUTO, () => this.start());
this.configuring_ = null;
}
/**
* Initializes camera view.
* @return {!Promise}
*/
async initialize() {
const helper = await ChromeHelper.getInstance();
const setTablet = (isTablet) => state.set(state.State.TABLET, isTablet);
const isTablet = await helper.initTabletModeMonitor(setTablet);
setTablet(isTablet);
const setScreenOffAuto = (s) => {
const offAuto = s === chromeosCamera.mojom.ScreenState.OFF_AUTO;
state.set(state.State.SCREEN_OFF_AUTO, offAuto);
};
const screenState = await helper.initScreenStateMonitor(setScreenOffAuto);
setScreenOffAuto(screenState);
}
/**
* @return {boolean} Returns if window is fully overlapped by other window in
* both window mode or tablet mode.
* @private
*/
get isVisible_() {
return document.visibilityState !== 'hidden';
}
/**
* @return {boolean} Whether window is put to background in tablet mode.
* @private
*/
isTabletBackground_() {
return state.get(state.State.TABLET) && !this.isVisible_;
}
/**
* Whether app window is suspended.
* @return {boolean}
*/
isSuspended() {
return this.locked_ || chrome.app.window.current().isMinimized() ||
state.get(state.State.SUSPEND) ||
state.get(state.State.SCREEN_OFF_AUTO) || this.isTabletBackground_();
}
/**
* @override
*/
focus() {
// Avoid focusing invisible shutters.
document.querySelectorAll('.shutter')
.forEach((btn) => btn.offsetParent && btn.focus());
}
/**
* Begins to take photo or recording with the current options, e.g. timer.
* @param {metrics.ShutterType} shutterType The shutter is triggered by which
* shutter type.
* @return {?Promise} Promise resolved when take action completes. Returns
* null if CCA can't start take action.
* @protected
*/
beginTake_(shutterType) {
if (!state.get(state.State.STREAMING) || state.get(state.State.TAKING)) {
return null;
}
state.set(state.State.TAKING, true);
this.shutterType_ = shutterType;
this.focus(); // Refocus the visible shutter button for ChromeVox.
this.take_ = (async () => {
let hasError = false;
try {
await timertick.start();
await this.modes_.current.startCapture();
} catch (e) {
hasError = true;
if (e && e.message === 'cancel') {
return;
}
console.error(e);
} finally {
this.take_ = null;
state.set(
state.State.TAKING, false, {hasError, facing: this.facingMode_});
this.focus(); // Refocus the visible shutter button for ChromeVox.
}
})();
return this.take_;
}
/**
* Ends the current take (or clears scheduled further takes if any.)
* @return {!Promise} Promise for the operation.
* @private
*/
endTake_() {
timertick.cancel();
this.modes_.current.stopCapture();
return Promise.resolve(this.take_);
}
/**
* Handles captured photo result.
* @param {!PhotoResult} result Captured photo result.
* @param {string} name Name of the photo result to be saved as.
* @return {!Promise} Promise for the operation.
* @protected
*/
async doSavePhoto_({resolution, blob, isVideoSnapshot = false}, name) {
metrics.log(metrics.Type.CAPTURE, {
facing: this.facingMode_,
resolution,
shutterType: this.shutterType_,
isVideoSnapshot,
});
try {
await this.resultSaver_.savePhoto(blob, name);
} catch (e) {
toast.show('error_msg_save_file_failed');
throw e;
}
}
/**
* Handles captured video result.
* @param {!VideoResult} result Captured video result.
* @return {!Promise} Promise for the operation.
* @protected
*/
async doSaveVideo_({resolution, duration, videoSaver, everPaused}) {
metrics.log(metrics.Type.CAPTURE, {
facing: this.facingMode_,
duration,
resolution,
shutterType: this.shutterType_,
everPaused,
});
try {
await this.resultSaver_.finishSaveVideo(videoSaver);
} catch (e) {
toast.show('error_msg_save_file_failed');
throw e;
}
}
/**
* @override
*/
layout() {
this.layout_.update();
}
/**
* @override
*/
handlingKey(key) {
if (key === 'Ctrl-R') {
toast.show(this.preview_.toString());
return true;
}
if ((key === 'AudioVolumeUp' || key === 'AudioVolumeDown') &&
state.get(state.State.TABLET) && state.get(state.State.STREAMING)) {
if (state.get(state.State.TAKING)) {
this.endTake_();
} else {
this.beginTake_(metrics.ShutterType.VOLUME_KEY);
}
return true;
}
return false;
}
/**
* Stops camera and tries to start camera stream again if possible.
* @return {!Promise<boolean>} Promise resolved to whether start camera
* successfully.
*/
async start() {
// To prevent multiple callers enter this function at the same time, wait
// until previous caller resets configuring to null.
while (this.configuring_ !== null) {
if (!await this.configuring_) {
// Retry will be kicked out soon.
return false;
}
}
state.set(state.State.CAMERA_CONFIGURING, true);
this.configuring_ = (async () => {
try {
if (state.get(state.State.TAKING)) {
await this.endTake_();
}
} finally {
this.preview_.stop();
}
return this.start_();
})();
return this.configuring_;
}
/**
* Try start stream reconfiguration with specified mode and device id.
* @param {?string} deviceId
* @param {!Mode} mode
* @return {!Promise<boolean>} If found suitable stream and reconfigure
* successfully.
*/
async startWithMode_(deviceId, mode) {
const deviceOperator = await DeviceOperator.getInstance();
let resolCandidates = null;
if (deviceOperator !== null) {
if (deviceId !== null) {
const previewRs =
(await this.infoUpdater_.getDeviceResolutions(deviceId)).video;
resolCandidates =
this.modes_.getResolutionCandidates(mode, deviceId, previewRs);
} else {
console.error(
'Null device id present on HALv3 device. Fallback to v1.');
}
}
if (resolCandidates === null) {
resolCandidates = this.modes_.getResolutionCandidatesV1(mode, deviceId);
}
for (const {resolution: captureR, previewCandidates} of resolCandidates) {
for (const constraints of previewCandidates) {
if (this.isSuspended()) {
throw new CameraSuspendedError();
}
try {
if (deviceOperator !== null) {
assert(deviceId !== null);
const optConfigs =
mode === Mode.VIDEO ? {} : {stillCaptureResolution: captureR};
await deviceOperator.setStreamConfig(
deviceId, constraints, optConfigs);
await deviceOperator.setCaptureIntent(
deviceId, this.modes_.getCaptureIntent(mode));
}
const stream = await navigator.mediaDevices.getUserMedia(constraints);
await this.preview_.start(stream);
this.facingMode_ = await this.options_.updateValues(stream);
await this.modes_.updateModeSelectionUI(deviceId);
await this.modes_.updateMode(
mode, stream, this.facingMode_, deviceId, captureR);
nav.close(ViewName.WARNING, 'no-camera');
return true;
} catch (e) {
this.preview_.stop();
console.error(e);
}
}
}
return false;
}
/**
* Try start stream reconfiguration with specified device id.
* @param {?string} deviceId
* @return {!Promise<boolean>} If found suitable stream and reconfigure
* successfully.
*/
async startWithDevice_(deviceId) {
const supportedModes = await this.modes_.getSupportedModes(deviceId);
const modes = this.modes_.getModeCandidates().filter(
(m) => supportedModes.includes(m));
for (const mode of modes) {
if (await this.startWithMode_(deviceId, mode)) {
return true;
}
}
return false;
}
/**
* Starts camera configuration process.
* @return {!Promise<boolean>} Resolved to boolean for whether the
* configuration is succeeded or kicks out another round of
* reconfiguration.
* @private
*/
async start_() {
try {
await this.infoUpdater_.lockDeviceInfo(async () => {
if (!this.isSuspended()) {
for (const id of await this.options_.videoDeviceIds()) {
if (await this.startWithDevice_(id)) {
// Make the different active camera announced by screen reader.
const currentId = this.options_.currentDeviceId;
assert(currentId !== null);
if (currentId === this.activeDeviceId_) {
return;
}
this.activeDeviceId_ = currentId;
const info = await this.infoUpdater_.getDeviceInfo(currentId);
if (info !== null) {
toast.speak(browserProxy.getI18nMessage(
'status_msg_camera_switched', info.label));
}
return;
}
}
}
throw new CameraSuspendedError();
});
this.configuring_ = null;
state.set(state.State.CAMERA_CONFIGURING, false);
return true;
} catch (error) {
this.activeDeviceId_ = null;
if (!(error instanceof CameraSuspendedError)) {
console.error(error);
nav.open(ViewName.WARNING, 'no-camera');
}
// Schedule to retry.
if (this.retryStartTimeout_) {
clearTimeout(this.retryStartTimeout_);
this.retryStartTimeout_ = null;
}
this.retryStartTimeout_ = setTimeout(() => {
this.configuring_ = this.start_();
}, 100);
this.perfLogger_.interrupt();
return false;
}
}
}
| {
"pile_set_name": "Github"
} |
package com.alibaba.arthas.tunnel.server.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.arthas.tunnel.server.TunnelServer;
@Configuration
public class TunnelServerConfiguration {
@Autowired
ArthasProperties arthasProperties;
@Bean(initMethod = "start", destroyMethod = "stop")
public TunnelServer tunnelServer() {
TunnelServer tunnelServer = new TunnelServer();
tunnelServer.setHost(arthasProperties.getServer().getHost());
tunnelServer.setPort(arthasProperties.getServer().getPort());
tunnelServer.setSsl(arthasProperties.getServer().isSsl());
return tunnelServer;
}
}
| {
"pile_set_name": "Github"
} |
{
"created_at": "2015-02-27T22:27:27.559500",
"description": "Javascript Matrix and Vector library for High Performance WebGL apps",
"fork": false,
"full_name": "toji/gl-matrix",
"language": "JavaScript",
"updated_at": "2015-02-27T23:41:18.426683"
} | {
"pile_set_name": "Github"
} |
/**
* Module dependencies.
*/
var Polling = require('./polling');
var qs = require('querystring');
var rDoubleSlashes = /\\\\n/g;
var rSlashes = /(\\)?\\n/g;
var util = require('util');
/**
* Module exports.
*/
module.exports = JSONP;
/**
* JSON-P polling transport.
*
* @api public
*/
function JSONP (req) {
Polling.call(this, req);
this.head = '___eio[' + (req._query.j || '').replace(/[^0-9]/g, '') + '](';
this.foot = ');';
}
/**
* Inherits from Polling.
*/
util.inherits(JSONP, Polling);
/**
* Handles incoming data.
* Due to a bug in \n handling by browsers, we expect a escaped string.
*
* @api private
*/
JSONP.prototype.onData = function (data) {
// we leverage the qs module so that we get built-in DoS protection
// and the fast alternative to decodeURIComponent
data = qs.parse(data).d;
if ('string' === typeof data) {
// client will send already escaped newlines as \\\\n and newlines as \\n
// \\n must be replaced with \n and \\\\n with \\n
data = data.replace(rSlashes, function (match, slashes) {
return slashes ? match : '\n';
});
Polling.prototype.onData.call(this, data.replace(rDoubleSlashes, '\\n'));
}
};
/**
* Performs the write.
*
* @api private
*/
JSONP.prototype.doWrite = function (data, options, callback) {
// we must output valid javascript, not valid json
// see: http://timelessrepo.com/json-isnt-a-javascript-subset
var js = JSON.stringify(data)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
// prepare response
data = this.head + js + this.foot;
Polling.prototype.doWrite.call(this, data, options, callback);
};
| {
"pile_set_name": "Github"
} |
import { pipe } from "../src/Function"
import * as M from "../src/Map"
import * as R from "../src/Reader"
pipe(
new Map<string, number>([
["0", 0],
["1", 1],
["2", 2]
]),
M.foreachF(R.Applicative)((n: number) => R.access((s: string) => `s: ${s} (${n})`)),
R.runEnv("str"),
(out) => {
console.log(out)
}
)
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* @license
* Copyright (c) 2011, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
* License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
*
* Contributors:
* IBM Corporation - initial API and implementation
* Mihai Sucan (Mozilla Foundation) - fix for bug 350636
*******************************************************************************/
/*eslint-env browser, amd*/
/*global mocha*/
define([
'examples/editor/demoSetup',
'js-tests/editor/perf/performanceTests',
'orion/util',
], function(mSetup, mTestPerformance, util) {
/** Console */
var document = window.document;
var console = document.getElementById('console'); //$NON-NLS-0$
var consoleCol = document.getElementById('consoleParent'); //$NON-NLS-0$
/** Testing */
var bClearLog = document.getElementById("clearLog"); //$NON-NLS-0$
var bHideLog = document.getElementById("hideLog"); //$NON-NLS-0$
var bTest = document.getElementById("test"); //$NON-NLS-0$
var sTest = document.getElementById("testSelect"); //$NON-NLS-0$
/** Options */
var bSetOptions = document.getElementById("setOptions"); //$NON-NLS-0$
var sContents = document.getElementById("contentsSelect"); //$NON-NLS-0$
var sTheme = document.getElementById("themeSelect"); //$NON-NLS-0$
var sBindings = document.getElementById("bindingsSelect"); //$NON-NLS-0$
var sTabSize = document.getElementById('tabSize'); //$NON-NLS-0$
var sScrollAnimation = document.getElementById('scrollAnimation'); //$NON-NLS-0$
var bReadOnly = document.getElementById('readOnly'); //$NON-NLS-0$
var bFullSel = document.getElementById('fullSelection'); //$NON-NLS-0$
var bWrap = document.getElementById('wrap'); //$NON-NLS-0$
var bMarginRuler = document.getElementById('marginRuler'); //$NON-NLS-0$
var bZoomRuler = document.getElementById('zoomRuler'); //$NON-NLS-0$
var sMarginOffset = document.getElementById('marginOffset'); //$NON-NLS-0$
var sWrapOffset = document.getElementById('wrapOffset'); //$NON-NLS-0$
var bExpandTab = document.getElementById('expandTab'); //$NON-NLS-0$
var bAutoSet = document.getElementById('autoSetOptions'); //$NON-NLS-0$
var table = document.getElementById('table'); //$NON-NLS-0$
var keyBindings = "";
var showMarginRuler = false;
var showZoomRuler = true;
function resize() {
var height = document.documentElement.clientHeight;
table.style.height = (height - (util.isIE ? 8 : 0)) + "px"; //$NON-NLS-0$
if (mSetup.view) { mSetup.view.resize(); }
}
resize();
window.onresize = resize;
function clearConsole () {
if (!console) { return; }
while (console.hasChildNodes()) { console.removeChild(console.lastChild); }
}
function showConsole () {
if (!console) { return; }
consoleCol.style.display = "block"; //$NON-NLS-0$
if (mSetup.view) { mSetup.view.resize(); }
}
function hideConsole () {
if (!console) { return; }
consoleCol.style.display = "none"; //$NON-NLS-0$
if (mSetup.view) { mSetup.view.resize(); }
}
function log (text) {
if (!console) { return; }
showConsole();
for (var n = 1; n < arguments.length; n++) {
text += " "; //$NON-NLS-0$
text += arguments[n];
}
console.appendChild(document.createTextNode(text));
console.appendChild(util.createElement(document, "br")); //$NON-NLS-0$
console.scrollTop = console.scrollHeight;
}
window.log = log;
function getOptions() {
return {
readonly: bReadOnly.checked,
fullSelection: bFullSel.checked,
expandTab: bExpandTab.checked,
tabSize: parseInt(sTabSize.value, 10),
scrollAnimation: parseInt(sScrollAnimation.value, 10),
wrapMode: bWrap.checked,
keyBindings: (keyBindings = sBindings.value),
showMarginRuler: (showMarginRuler = bMarginRuler.checked),
showZoomRuler: (showZoomRuler = bZoomRuler.checked),
marginOffset: parseInt(sMarginOffset.value, 10),
wrapOffset: parseInt(sWrapOffset.value, 10),
themeClass: sTheme.value
};
}
function updateOptions() {
var view = mSetup.view;
var options = view.getOptions();
bReadOnly.checked = options.readonly;
bFullSel.checked = options.fullSelection;
bWrap.checked = options.wrapMode;
bMarginRuler.checked = showMarginRuler;
bZoomRuler.checked = showZoomRuler;
sWrapOffset.value = options.wrapOffset;
sMarginOffset.value = options.marginOffset;
bExpandTab.checked = options.expandTab;
sTabSize.value = options.tabSize;
sScrollAnimation.value = options.scrollAnimation;
sTheme.value = options.themeClass;
sBindings.value = keyBindings;
}
var contents, currentContents;
function setOptions() {
mSetup.checkView(getOptions());
updateOptions();
window.setTimeout(function() {
if (currentContents !== sContents.value) {
contents[sContents.value]();
currentContents = sContents.value;
}
}, 0);
}
function setupView(text, lang) {
var view = mSetup.setupView(text, lang, getOptions());
view.focus();
updateOptions();
return view;
}
function createJavaSample() {
return setupView(mSetup.getFile("text.txt"), "java"); //$NON-NLS-1$ //$NON-NLS-0$
}
function createJavaScriptSample() {
return setupView(mSetup.getFile("/orion/editor/textView.js"), "js"); //$NON-NLS-1$ //$NON-NLS-0$
}
function createHtmlSample() {
return setupView(mSetup.getFile("/examples/editor/demo.html"), "html"); //$NON-NLS-1$ //$NON-NLS-0$
}
function createPlainTextSample() {
var lineCount = 50000;
var lines = [];
for(var i = 0; i < lineCount; i++) {
lines.push("This is the line of text number "+i); //$NON-NLS-0$
}
return setupView(lines.join("\r\n"), null); //$NON-NLS-0$
}
function createBidiTextSample() {
var lines = [];
lines.push("Hello \u0644\u0645\u0646\u0647"); //$NON-NLS-0$
return setupView(lines.join(util.platformDelimiter), null);
}
contents = {
createJavaSample: createJavaSample,
createJavaScriptSample: createJavaScriptSample,
createHtmlSample: createHtmlSample,
createPlainTextSample: createPlainTextSample,
createBidiTextSample: createBidiTextSample
};
function updateSetOptionsButton() {
if (bAutoSet.checked) {
bSetOptions.style.display = "none"; //$NON-NLS-0$
setOptions();
} else {
bSetOptions.style.display = "block"; //$NON-NLS-0$
}
}
function checkSetOptions() {
if (bAutoSet.checked) {
setOptions();
}
}
updateSetOptionsButton();
/* Adding events */
bSetOptions.onclick = setOptions;
sContents.onchange = checkSetOptions;
sTheme.onchange = checkSetOptions;
sBindings.onchange = checkSetOptions;
bReadOnly.onchange = checkSetOptions;
sTabSize.onchange = checkSetOptions;
sScrollAnimation.onchange = checkSetOptions;
bFullSel.onchange = checkSetOptions;
bWrap.onchange = checkSetOptions;
bMarginRuler.onchange = checkSetOptions;
bZoomRuler.onchange = checkSetOptions;
sMarginOffset.onchange = checkSetOptions;
sWrapOffset.onchange = checkSetOptions;
bExpandTab.onchange = checkSetOptions;
bAutoSet.onchange = updateSetOptionsButton;
/* Adding console actions */
bClearLog.onclick = clearConsole;
bHideLog.onclick = hideConsole;
/* Adding testing actions */
var tests = {};
function runTest() {
tests[sTest.value]();
}
bTest.onclick = runTest;
function test() {
log("test"); //$NON-NLS-0$
}
tests.testTest = test;
function destroyTest() {
mSetup.destroyView();
}
tests.testDestroyTest = destroyTest;
// Grab perf tests out of the global `mocha` object
mocha.suite.eachTest(function(test) {
tests["test" + test.title] = test.fn; //$NON-NLS-0$
});
var prefix = "test"; //$NON-NLS-0$
var property, option;
for (property in tests) {
if (tests.hasOwnProperty(property)) {
option = util.createElement(document, "option"); //$NON-NLS-0$
option.setAttribute("value", property); //$NON-NLS-0$
option.appendChild(document.createTextNode(property.substring(prefix.length)));
sTest.appendChild(option);
tests[property] = tests[property];
}
}
document.body.style.display = "block"; //$NON-NLS-0$
setOptions();
});
| {
"pile_set_name": "Github"
} |
/*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2019 ArkNX authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"),
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_iterators.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "base/AFPlatform.hpp"
#include "base/AFMisc.hpp"
#include "base/AFDefine.hpp"
namespace ark {
class AFXml;
class AFXmlNode
{
public:
AFXmlNode(AFXml* xml)
{
xml_ = xml;
}
~AFXmlNode()
{
xml_node_ = nullptr;
}
bool IsValid()
{
return xml_node_ != nullptr;
}
void NextNode(const char* key = nullptr)
{
rapidxml::xml_node<>* node = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
xml_node_ = node->next_sibling(key);
}
AFXmlNode FindNode(const char* key)
{
ARK_ASSERT_NO_EFFECT(IsValid());
auto xmlnode = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
AFXmlNode node(xml_);
node.xml_node_ = xmlnode->first_node(key);
return node;
}
bool GetBool(const char* key, bool optional = false, bool default_value = false)
{
rapidxml::xml_node<>* xmlnode = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
auto attr = xmlnode->first_attribute(key);
if (attr == nullptr)
{
if (optional == false)
{
return default_value;
}
else
{
ARK_ASSERT_NO_EFFECT(0);
return default_value;
}
}
else
{
return AFMisc::FromString<bool>(attr->value());
}
}
uint32_t GetUint32(const char* key, bool optional = false, uint32_t default_value = NULL_INT)
{
rapidxml::xml_node<>* node = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
auto attr = node->first_attribute(key);
if (attr == nullptr)
{
if (optional == false)
{
return default_value;
}
else
{
ARK_ASSERT_NO_EFFECT(0);
return default_value;
}
}
else
{
return AFMisc::FromString<uint32_t>(attr->value());
}
}
float GetFloat(const char* key, bool optional = false, float default_value = NULL_FLOAT)
{
rapidxml::xml_node<>* node = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
auto attr = node->first_attribute(key);
if (attr == nullptr)
{
if (optional == false)
{
return default_value;
}
else
{
ARK_ASSERT_NO_EFFECT(0);
return default_value;
}
}
else
{
return AFMisc::FromString<float>(attr->value());
}
}
std::string GetString(const char* key, bool optional = false, std::string default_value = NULL_STR)
{
rapidxml::xml_node<>* node = reinterpret_cast<rapidxml::xml_node<>*>(xml_node_);
auto attr = node->first_attribute(key);
if (attr == nullptr)
{
if (optional == false)
{
return default_value;
}
else
{
ARK_ASSERT_NO_EFFECT(0);
return default_value;
}
}
else
{
return attr->value();
}
}
private:
friend class AFXml;
AFXml* xml_{nullptr};
void* xml_node_{nullptr};
};
class AFXml
{
public:
AFXml(const std::string& file_path)
: file_path_(file_path)
{
xml_file_ = ARK_NEW rapidxml::file<>();
xml_document_ = ARK_NEW rapidxml::xml_document<>();
ParseFile();
}
~AFXml()
{
ARK_DELETE(xml_file_);
ARK_DELETE(xml_document_);
}
AFXmlNode GetRootNode()
{
AFXmlNode node(this);
node.xml_node_ = xml_document_->first_node();
return node;
}
AFXmlNode FindNode(const char* key)
{
AFXmlNode node(this);
node.xml_node_ = xml_document_->first_node(key);
return node;
}
const char* GetFile() const
{
return file_path_.c_str();
}
const char* GetData()
{
return xml_file_->data();
}
uint32_t GetSize()
{
return xml_file_->size();
}
protected:
void ParseFile()
{
xml_file_->from(file_path_.c_str());
xml_document_->parse<0>(xml_file_->data());
}
private:
rapidxml::xml_document<>* xml_document_;
rapidxml::file<>* xml_file_;
std::string file_path_;
};
} // namespace ark
| {
"pile_set_name": "Github"
} |
define( [
"../core",
"../core/access",
"./support",
"../selector"
], function( jQuery, access, support ) {
"use strict";
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
} );
| {
"pile_set_name": "Github"
} |
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')
| {
"pile_set_name": "Github"
} |
package main
import (
"context"
"fmt"
"syscall"
"time"
)
func SigintAfterSigusr2Test(ctx context.Context) error {
if err := ensureOdysseyRunning(ctx); err != nil {
return err
}
go selectSleepNoWait(ctx, 10000)
time.Sleep(1 * time.Second)
if _, err := signalToProc(syscall.SIGUSR2, "odyssey"); err != nil {
return err
}
if _, err := pidNyName("odyssey"); err != nil {
return err
}
if _, err := signalToProc(syscall.SIGINT, "odyssey"); err != nil {
return err
}
if err := OdysseyIsAlive(ctx); err == nil {
return fmt.Errorf("odyssey ignores sigint")
}
return nil
}
func odySignalsTestSet(ctx context.Context) error {
if err := SigintAfterSigusr2Test(ctx); err != nil {
err = fmt.Errorf("signals test failed: %w", err)
fmt.Println(err)
return err
}
fmt.Println("odySignalsTestSet: Ok")
return nil
}
| {
"pile_set_name": "Github"
} |
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* FreeRDP Proxy Server
*
* Copyright 2019 Mati Shabtay <matishabtay@gmail.com>
* Copyright 2019 Kobi Mizrachi <kmizrachi18@gmail.com>
* Copyright 2019 Idan Freiberg <speidy@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FREERDP_SERVER_PROXY_PFGRAPHICS_H
#define FREERDP_SERVER_PROXY_PFGRAPHICS_H
#include <freerdp/freerdp.h>
#include "pf_client.h"
BOOL pf_register_pointer(rdpGraphics* graphics);
BOOL pf_register_graphics(rdpGraphics* graphics);
#endif /* FREERDP_SERVER_PROXY_PFGRAPHICS_H */
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NetworkPolicy describes what network traffic is allowed for a set of Pods
type NetworkPolicy struct {
metav1.TypeMeta `json:",inline"`
// Standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Specification of the desired behavior for this NetworkPolicy.
// +optional
Spec NetworkPolicySpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
}
// Policy Type string describes the NetworkPolicy type
// This type is beta-level in 1.8
type PolicyType string
const (
// PolicyTypeIngress is a NetworkPolicy that affects ingress traffic on selected pods
PolicyTypeIngress PolicyType = "Ingress"
// PolicyTypeEgress is a NetworkPolicy that affects egress traffic on selected pods
PolicyTypeEgress PolicyType = "Egress"
)
// NetworkPolicySpec provides the specification of a NetworkPolicy
type NetworkPolicySpec struct {
// Selects the pods to which this NetworkPolicy object applies. The array of
// ingress rules is applied to any pods selected by this field. Multiple network
// policies can select the same set of pods. In this case, the ingress rules for
// each are combined additively. This field is NOT optional and follows standard
// label selector semantics. An empty podSelector matches all pods in this
// namespace.
PodSelector metav1.LabelSelector `json:"podSelector" protobuf:"bytes,1,opt,name=podSelector"`
// List of ingress rules to be applied to the selected pods. Traffic is allowed to
// a pod if there are no NetworkPolicies selecting the pod
// (and cluster policy otherwise allows the traffic), OR if the traffic source is
// the pod's local node, OR if the traffic matches at least one ingress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy does not allow any traffic (and serves
// solely to ensure that the pods it selects are isolated by default)
// +optional
Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"`
// List of egress rules to be applied to the selected pods. Outgoing traffic is
// allowed if there are no NetworkPolicies selecting the pod (and cluster policy
// otherwise allows the traffic), OR if the traffic matches at least one egress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy limits all outgoing traffic (and serves
// solely to ensure that the pods it selects are isolated by default).
// This field is beta-level in 1.8
// +optional
Egress []NetworkPolicyEgressRule `json:"egress,omitempty" protobuf:"bytes,3,rep,name=egress"`
// List of rule types that the NetworkPolicy relates to.
// Valid options are "Ingress", "Egress", or "Ingress,Egress".
// If this field is not specified, it will default based on the existence of Ingress or Egress rules;
// policies that contain an Egress section are assumed to affect Egress, and all policies
// (whether or not they contain an Ingress section) are assumed to affect Ingress.
// If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ].
// Likewise, if you want to write a policy that specifies that no egress is allowed,
// you must specify a policyTypes value that include "Egress" (since such a policy would not include
// an Egress section and would otherwise default to just [ "Ingress" ]).
// This field is beta-level in 1.8
// +optional
PolicyTypes []PolicyType `json:"policyTypes,omitempty" protobuf:"bytes,4,rep,name=policyTypes,casttype=PolicyType"`
}
// NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods
// matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from.
type NetworkPolicyIngressRule struct {
// List of ports which should be made accessible on the pods selected for this
// rule. Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of sources which should be able to access the pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all sources (traffic not restricted by
// source). If this field is present and contains at least on item, this rule
// allows traffic only if the traffic matches at least one item in the from list.
// +optional
From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"`
}
// NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods
// matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to.
// This type is beta-level in 1.8
type NetworkPolicyEgressRule struct {
// List of destination ports for outgoing traffic.
// Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of destinations for outgoing traffic of pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all destinations (traffic not restricted by
// destination). If this field is present and contains at least one item, this rule
// allows traffic only if the traffic matches at least one item in the to list.
// +optional
To []NetworkPolicyPeer `json:"to,omitempty" protobuf:"bytes,2,rep,name=to"`
}
// NetworkPolicyPort describes a port to allow traffic on
type NetworkPolicyPort struct {
// The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this
// field defaults to TCP.
// +optional
Protocol *v1.Protocol `json:"protocol,omitempty" protobuf:"bytes,1,opt,name=protocol,casttype=k8s.io/api/core/v1.Protocol"`
// The port on the given protocol. This can either be a numerical or named port on
// a pod. If this field is not provided, this matches all port names and numbers.
// +optional
Port *intstr.IntOrString `json:"port,omitempty" protobuf:"bytes,2,opt,name=port"`
}
// IPBlock describes a particular CIDR (Ex. "192.168.1.1/24") that is allowed to the pods
// matched by a NetworkPolicySpec's podSelector. The except entry describes CIDRs that should
// not be included within this rule.
type IPBlock struct {
// CIDR is a string representing the IP Block
// Valid examples are "192.168.1.1/24"
CIDR string `json:"cidr" protobuf:"bytes,1,name=cidr"`
// Except is a slice of CIDRs that should not be included within an IP Block
// Valid examples are "192.168.1.1/24"
// Except values will be rejected if they are outside the CIDR range
// +optional
Except []string `json:"except,omitempty" protobuf:"bytes,2,rep,name=except"`
}
// NetworkPolicyPeer describes a peer to allow traffic from. Only certain combinations of
// fields are allowed
type NetworkPolicyPeer struct {
// This is a label selector which selects Pods. This field follows standard label
// selector semantics; if present but empty, it selects all pods.
//
// If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects
// the Pods matching PodSelector in the Namespaces selected by NamespaceSelector.
// Otherwise it selects the Pods matching PodSelector in the policy's own Namespace.
// +optional
PodSelector *metav1.LabelSelector `json:"podSelector,omitempty" protobuf:"bytes,1,opt,name=podSelector"`
// Selects Namespaces using cluster-scoped labels. This field follows standard label
// selector semantics; if present but empty, it selects all namespaces.
//
// If PodSelector is also set, then the NetworkPolicyPeer as a whole selects
// the Pods matching PodSelector in the Namespaces selected by NamespaceSelector.
// Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector.
// +optional
NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,2,opt,name=namespaceSelector"`
// IPBlock defines policy on a particular IPBlock. If this field is set then
// neither of the other fields can be.
// +optional
IPBlock *IPBlock `json:"ipBlock,omitempty" protobuf:"bytes,3,rep,name=ipBlock"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// NetworkPolicyList is a list of NetworkPolicy objects.
type NetworkPolicyList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Items is a list of schema objects.
Items []NetworkPolicy `json:"items" protobuf:"bytes,2,rep,name=items"`
}
| {
"pile_set_name": "Github"
} |
//
// Header for standard system include files.
//
#pragma once
#include <collection.h>
#include <ppltasks.h>
#include "App.xaml.h"
| {
"pile_set_name": "Github"
} |
[PATCH] fix build with uClibc
cdrkit unconditionally enables code using rcmd(3), which isn't available
on uClibc.
Signed-off-by: Peter Korsgaard <jacmet@sunsite.dk>
---
include/xconfig.h.in | 1 -
1 file changed, 1 deletion(-)
Index: cdrkit-1.1.10/include/xconfig.h.in
===================================================================
--- cdrkit-1.1.10.orig/include/xconfig.h.in
+++ cdrkit-1.1.10/include/xconfig.h.in
@@ -187,7 +187,6 @@
* they are placed before the large file tests.
*/
-#define HAVE_RCMD 1 /* rcmd() is present in libc/libsocket */
#define HAVE_SOCKET 1 /* socket() is present in libc/libsocket */
#define HAVE_SOCKETPAIR 1 /* socketpair() is present in libc/libsocket */
#define HAVE_GETSERVBYNAME 1 /* getservbyname() is present in libc/libsocket */
| {
"pile_set_name": "Github"
} |
/*jshint node: true */
var inserted,
Module = require('module'),
fs = require('fs'),
existingExtFn = Module._extensions['.js'],
amdefineRegExp = /amdefine\.js/;
inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}";
//From the node/lib/module.js source:
function stripBOM(content) {
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
//Also adapted from the node/lib/module.js source:
function intercept(module, filename) {
var content = stripBOM(fs.readFileSync(filename, 'utf8'));
if (!amdefineRegExp.test(module.id)) {
content = inserted + content;
}
module._compile(content, filename);
}
intercept._id = 'amdefine/intercept';
if (!existingExtFn._id || existingExtFn._id !== intercept._id) {
Module._extensions['.js'] = intercept;
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2020 Elisha Riedlinger
*
* This software is provided 'as-is', without any express or implied warranty. In no event will the
* authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "d3d9.h"
HRESULT m_IDirect3DVertexBuffer9::QueryInterface(THIS_ REFIID riid, void** ppvObj)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
if ((riid == IID_IDirect3DVertexBuffer9 || riid == IID_IUnknown || riid == IID_IDirect3DResource9) && ppvObj)
{
AddRef();
*ppvObj = this;
return D3D_OK;
}
HRESULT hr = ProxyInterface->QueryInterface(riid, ppvObj);
if (SUCCEEDED(hr))
{
D3d9Wrapper::genericQueryInterface(riid, ppvObj, m_pDeviceEx);
}
return hr;
}
ULONG m_IDirect3DVertexBuffer9::AddRef(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->AddRef();
}
ULONG m_IDirect3DVertexBuffer9::Release(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->Release();
}
HRESULT m_IDirect3DVertexBuffer9::GetDevice(THIS_ IDirect3DDevice9** ppDevice)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
if (!ppDevice)
{
return D3DERR_INVALIDCALL;
}
m_pDeviceEx->AddRef();
*ppDevice = m_pDeviceEx;
return D3D_OK;
}
HRESULT m_IDirect3DVertexBuffer9::SetPrivateData(THIS_ REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->SetPrivateData(refguid, pData, SizeOfData, Flags);
}
HRESULT m_IDirect3DVertexBuffer9::GetPrivateData(THIS_ REFGUID refguid, void* pData, DWORD* pSizeOfData)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->GetPrivateData(refguid, pData, pSizeOfData);
}
HRESULT m_IDirect3DVertexBuffer9::FreePrivateData(THIS_ REFGUID refguid)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->FreePrivateData(refguid);
}
DWORD m_IDirect3DVertexBuffer9::SetPriority(THIS_ DWORD PriorityNew)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->SetPriority(PriorityNew);
}
DWORD m_IDirect3DVertexBuffer9::GetPriority(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->GetPriority();
}
void m_IDirect3DVertexBuffer9::PreLoad(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->PreLoad();
}
D3DRESOURCETYPE m_IDirect3DVertexBuffer9::GetType(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->GetType();
}
HRESULT m_IDirect3DVertexBuffer9::Lock(THIS_ UINT OffsetToLock, UINT SizeToLock, void** ppbData, DWORD Flags)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->Lock(OffsetToLock, SizeToLock, ppbData, Flags);
}
HRESULT m_IDirect3DVertexBuffer9::Unlock(THIS)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->Unlock();
}
HRESULT m_IDirect3DVertexBuffer9::GetDesc(THIS_ D3DVERTEXBUFFER_DESC *pDesc)
{
Logging::LogDebug() << __FUNCTION__ << " (" << this << ")";
return ProxyInterface->GetDesc(pDesc);
}
| {
"pile_set_name": "Github"
} |
/**
******************************************************************************
* @file usbd_conf_template.h
* @author MCD Application Team
* @version V1.0.0
* @date 22-July-2011
* @brief usb device configuration template file
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CONF__H__
#define __USBD_CONF__H__
/* Includes ------------------------------------------------------------------*/
#include "stm32f2xx.h"
/** @defgroup USB_CONF_Exported_Defines
* @{
*/
#define USE_USB_OTG_HS
#define USBD_CFG_MAX_NUM 1
#define USB_MAX_STR_DESC_SIZ 64
#define USBD_EP0_MAX_PACKET_SIZE 64
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Types
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USB_CONF_Exported_FunctionsPrototype
* @{
*/
/**
* @}
*/
#endif //__USBD_CONF__H__
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.bootstrap.plugin.request.util;
/**
* @author Woonduk Kang(emeroad)
*/
public interface ParameterExtractor<T> {
String extractParameter(T request);
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2007-2011 iMatix Corporation
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ 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. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <new>
#include <string.h>
#include "ctx.hpp"
#include "socket_base.hpp"
#include "io_thread.hpp"
#include "platform.hpp"
#include "reaper.hpp"
#include "err.hpp"
#include "pipe.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.h"
#else
#include "unistd.h"
#endif
zmq::ctx_t::ctx_t (uint32_t io_threads_) :
terminating (false)
{
int rc;
// Initialise the array of mailboxes. Additional three slots are for
// internal log socket and the zmq_term thread the reaper thread.
slot_count = max_sockets + io_threads_ + 3;
slots = (mailbox_t**) malloc (sizeof (mailbox_t*) * slot_count);
alloc_assert (slots);
// Initialise the infrastructure for zmq_term thread.
slots [term_tid] = &term_mailbox;
// Create the reaper thread.
reaper = new (std::nothrow) reaper_t (this, reaper_tid);
alloc_assert (reaper);
slots [reaper_tid] = reaper->get_mailbox ();
reaper->start ();
// Create I/O thread objects and launch them.
for (uint32_t i = 2; i != io_threads_ + 2; i++) {
io_thread_t *io_thread = new (std::nothrow) io_thread_t (this, i);
alloc_assert (io_thread);
io_threads.push_back (io_thread);
slots [i] = io_thread->get_mailbox ();
io_thread->start ();
}
// In the unused part of the slot array, create a list of empty slots.
for (int32_t i = (int32_t) slot_count - 1;
i >= (int32_t) io_threads_ + 2; i--) {
empty_slots.push_back (i);
slots [i] = NULL;
}
// Create the logging infrastructure.
log_socket = create_socket (ZMQ_PUB);
zmq_assert (log_socket);
rc = log_socket->bind ("sys://log");
zmq_assert (rc == 0);
}
zmq::ctx_t::~ctx_t ()
{
// Check that there are no remaining sockets.
zmq_assert (sockets.empty ());
// Ask I/O threads to terminate. If stop signal wasn't sent to I/O
// thread subsequent invocation of destructor would hang-up.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
io_threads [i]->stop ();
// Wait till I/O threads actually terminate.
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++)
delete io_threads [i];
// Deallocate the reaper thread object.
delete reaper;
// Deallocate the array of mailboxes. No special work is
// needed as mailboxes themselves were deallocated with their
// corresponding io_thread/socket objects.
free (slots);
}
int zmq::ctx_t::terminate ()
{
// Check whether termination was already underway, but interrupted and now
// restarted.
slot_sync.lock ();
bool restarted = terminating;
slot_sync.unlock ();
// First attempt to terminate the context.
if (!restarted) {
// Close the logging infrastructure.
log_sync.lock ();
int rc = log_socket->close ();
zmq_assert (rc == 0);
log_socket = NULL;
log_sync.unlock ();
// First send stop command to sockets so that any blocking calls can be
// interrupted. If there are no sockets we can ask reaper thread to stop.
slot_sync.lock ();
terminating = true;
for (sockets_t::size_type i = 0; i != sockets.size (); i++)
sockets [i]->stop ();
if (sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
// Wait till reaper thread closes all the sockets.
command_t cmd;
int rc = term_mailbox.recv (&cmd, true);
if (rc == -1 && errno == EINTR)
return -1;
zmq_assert (rc == 0);
zmq_assert (cmd.type == command_t::done);
slot_sync.lock ();
zmq_assert (sockets.empty ());
slot_sync.unlock ();
// Deallocate the resources.
delete this;
return 0;
}
zmq::socket_base_t *zmq::ctx_t::create_socket (int type_)
{
slot_sync.lock ();
// Once zmq_term() was called, we can't create new sockets.
if (terminating) {
slot_sync.unlock ();
errno = ETERM;
return NULL;
}
// If max_sockets limit was reached, return error.
if (empty_slots.empty ()) {
slot_sync.unlock ();
errno = EMFILE;
return NULL;
}
// Choose a slot for the socket.
uint32_t slot = empty_slots.back ();
empty_slots.pop_back ();
// Create the socket and register its mailbox.
socket_base_t *s = socket_base_t::create (type_, this, slot);
if (!s) {
empty_slots.push_back (slot);
slot_sync.unlock ();
return NULL;
}
sockets.push_back (s);
slots [slot] = s->get_mailbox ();
slot_sync.unlock ();
return s;
}
void zmq::ctx_t::destroy_socket (class socket_base_t *socket_)
{
slot_sync.lock ();
// Free the associared thread slot.
uint32_t tid = socket_->get_tid ();
empty_slots.push_back (tid);
slots [tid] = NULL;
// Remove the socket from the list of sockets.
sockets.erase (socket_);
// If zmq_term() was already called and there are no more socket
// we can ask reaper thread to terminate.
if (terminating && sockets.empty ())
reaper->stop ();
slot_sync.unlock ();
}
zmq::object_t *zmq::ctx_t::get_reaper ()
{
return reaper;
}
void zmq::ctx_t::send_command (uint32_t tid_, const command_t &command_)
{
slots [tid_]->send (command_);
}
zmq::io_thread_t *zmq::ctx_t::choose_io_thread (uint64_t affinity_)
{
if (io_threads.empty ())
return NULL;
// Find the I/O thread with minimum load.
int min_load = -1;
io_threads_t::size_type result = 0;
for (io_threads_t::size_type i = 0; i != io_threads.size (); i++) {
if (!affinity_ || (affinity_ & (uint64_t (1) << i))) {
int load = io_threads [i]->get_load ();
if (min_load == -1 || load < min_load) {
min_load = load;
result = i;
}
}
}
zmq_assert (min_load != -1);
return io_threads [result];
}
int zmq::ctx_t::register_endpoint (const char *addr_, endpoint_t &endpoint_)
{
endpoints_sync.lock ();
bool inserted = endpoints.insert (endpoints_t::value_type (
std::string (addr_), endpoint_)).second;
if (!inserted) {
errno = EADDRINUSE;
endpoints_sync.unlock ();
return -1;
}
endpoints_sync.unlock ();
return 0;
}
void zmq::ctx_t::unregister_endpoints (socket_base_t *socket_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.begin ();
while (it != endpoints.end ()) {
if (it->second.socket == socket_) {
endpoints_t::iterator to_erase = it;
++it;
endpoints.erase (to_erase);
continue;
}
++it;
}
endpoints_sync.unlock ();
}
zmq::endpoint_t zmq::ctx_t::find_endpoint (const char *addr_)
{
endpoints_sync.lock ();
endpoints_t::iterator it = endpoints.find (addr_);
if (it == endpoints.end ()) {
endpoints_sync.unlock ();
errno = ECONNREFUSED;
endpoint_t empty = {NULL, options_t()};
return empty;
}
endpoint_t *endpoint = &it->second;
// Increment the command sequence number of the peer so that it won't
// get deallocated until "bind" command is issued by the caller.
// The subsequent 'bind' has to be called with inc_seqnum parameter
// set to false, so that the seqnum isn't incremented twice.
endpoint->socket->inc_seqnum ();
endpoints_sync.unlock ();
return *endpoint;
}
void zmq::ctx_t::log (const char *format_, va_list args_)
{
// Create the log message.
zmq_msg_t msg;
int rc = zmq_msg_init_size (&msg, strlen (format_) + 1);
zmq_assert (rc == 0);
memcpy (zmq_msg_data (&msg), format_, zmq_msg_size (&msg));
// At this point we migrate the log socket to the current thread.
// We rely on mutex for executing the memory barrier.
log_sync.lock ();
if (log_socket)
log_socket->send (&msg, 0);
log_sync.unlock ();
zmq_msg_close (&msg);
}
| {
"pile_set_name": "Github"
} |
<bib>
<book>
<author>Jim Melton</author>
<author>Alan Simon</author>
<title>SQL:1999</title>
</book>
<book>
<author>Jim Melton</author>
<title>Advanced SQL:1999</title>
</book>
<book>
<author>Alan Simon</author>
<title>Strategic Database Technology</title>
</book>
<book>
<author>Jim Melton</author>
<author>Andrew Eisenberg</author>
<title>Understanding SQL and Java Together</title>
</book>
<book>
<author>Jim Melton</author>
<author>Stephen Buxton</author>
<title>Querying XML</title>
</book>
</bib>
| {
"pile_set_name": "Github"
} |
\section{Delay Slot Filling}
\subsection{ Overview }
Superscalar architectures such as the Sparc
contain delayed branch and/or load instructions.
Delay slot filling is necessary
task of the back end to keep the instruction pipelines busy. To accomodate
the intricate semantics of branch delay slot in various architectures,
MLRISC uses the following very general framework for dealing with
delayed instructions.
\begin{description}
\item[Instruction representation]
To make it easy to deal with instruction with delay slot, MLRISC allow
the following extensions to instruction representations.
\begin{itemize}
\item Instructions with delay slot may have a
\begin{color}{#aa0000}nop\end{color} flag. When this flag is true
the delay slot is assumed to be filled with a NOP instruction.
\item Instructions with delay slots that can be nullified may have a
\begin{color}{#aa0000}nullified\end{color} flag.
When this flag is true the branch delay slot is assumed to be
nullified.
\end{itemize}
\item[Nullification semantics]
Unfortunately, nullification semantics
in architectures vary. In general, MLRISC allows the following
additional nullification characteristics to be specified.
\begin{itemize}
\item Nullification can be specified as illegal; this is needed
because some instructions can not be nullified
\item When nullification is enabled, the semantics of the delay slot
instruction may depend on the direction of the branch, and whether
a conditional test succeeds.
\item Certain ilk of instructions may be declared to be illegal
to fit into certain ilk of delay slots.
\end{itemize}
\end{description}
For example, conditional branch instructions on the Sparc are defined
as follows:
\begin{verbatim}
Bicc of {b:branch, a:Bool, label:Label.label, nop:Bool}
asm: ``b<b><a>\t<label><nop>''
padding: nop = true
nullified: a = true and (case b of I.BA => false | _ => true)
delayslot candidate: false
\end{verbatim}
\noindent where \sml{a} is \emph{annul} flag and \sml{nop} is the nop
flag (see \mlrischref{sparc/sparc.md}{the Sparc architecture description}).
A constructor term
\begin{SML}
Bicc\{b=BE, a=true, label=label, nop=true\}
\end{SML}
denotes the instruction sequence
\begin{verbatim}
be,a label
nop
\end{verbatim}
while
\begin{SML}
Bicc\{b=BE, a=false, label=label, nop=false\}
\end{SML}
denotes
\begin{verbatim}
be label
\end{verbatim}
\subsection{The Interface}
Architecture information about how delay slot filling is to be performed
is described in the api
\mlrischref{jmp/delaySlotProps.sig}{DELAY\_SLOT\_PROPERTIES}.
\begin{SML}
api Delay_Slot_Properties =
sig
package i : Machcode
enum delay_slot =
D_NONE | D_ERROR | D_ALWAYS
| D_TAKEN | D_FALLTHRU
my delaySlotSize : int
my delaySlot : \{ instruction : I.instruction, backward : Bool \} ->
\{ n : Bool,
nOn : delay_slot,
nOff : delay_slot,
nop : Bool
\}
my enableDelaySlot :
\{instruction : I.instruction, n:Bool, nop:Bool\} -> I.instruction
my conflict :
\{regmap:int->int,src:I.instruction,dst:I.instruction\} -> Bool
my delaySlotCandidate :
\{ jmp : I.instruction, delaySlot : I.instruction \} -> Bool
my setTarget : I.instruction * Label.label -> I.instruction
end
\end{SML}
The components of this api are:
\begin{description}
\item[delay\_slot] This enum describes properties related to a
delay slot.
\begin{description}
\item[D\_NONE] This indicates that no delay slot is possible.
\item[D\_ERROR] This indicates that it is an error
\item[D\_ALWAYS] This indicates that the delay slot is always active
\item[D\_TAKEN] This indicates that the
delay slot is only active when branch is taken
\item[D\_FALLTHRU] This indicates that the delay slot
is only active when branch is not taken
\end{description}
\item[delaySlotSize] This is size of delay slot in bytes.
\item[delaySlot] This method takes an instruction \sml{instruction}
and a flag indicating whether the branch is \sml{backward},
and returns the delay slot properties of an instruction. The
properties is described by four fields.
\begin{description}
\item[n : Bool] This bit is if the nullified bit in the
instruction is currently set.
\item[nOn : delay\_slot] This field indicates the delay slot
type when the instruction is nullified.
\item[nOff : delay\_slot] This field indiciates the delay slot
type when the instruction is not nullified.
\item[nop : Bool] This bit indicates whether there is an
implicit padded nop.
\end{description}
\item[enableDelaySlot]
This method set the nullification and nop flags of an instruction.
\item[conflict] This method checks whether there are any conflicts
between instruction \sml{src} and \sml{dst}.
\item[delaySlotCandidate]
This method checks whether instruction \sml{delaySlot} is within the
ilk of instructions that can fit within the delay slot of
instruction \sml{jmp}.
\item[setTarget]
This method changes the branch target of an instruction.
\end{description}
\subsubsection{Examples}
For example,
\begin{SML}
delaySlot\{instruction=instr, backward=true\} =
\{n=true, nOn=D_ERROR, nOff=D_ALWAYS, nop=true\}
\end{SML}
\noindent means that the instruction nullification bit is on, the
the nullification cannot be turned off, delay slot is always active
(when not nullified), and there is currently an implicit padded nop.
\begin{SML}
delaySlot\{instruction=instr, backward=false\} =
\{n=false, nOn=D_NONE, nOff=D_TAKEN, nop=false\}
\end{SML}
\noindent means that the nullification bit is off, the delay slot
is inactive when the nullification bit is off, the delay slot is only
active when the (forward) branch is taken when \sml{instruction} is
not-nullified, and there
is no implicitly padded nop.
\begin{SML}
delaySlot\{instruction=instr, backward=true\} =
\{n=true, nOn=D_TAKEN, nOff=D_ALWAYS, nop=true\}
\end{SML}
\noindent means that the nullification bit is on, the delay slot
is active on a taken (backward) branch when the nullification bit is off,
the delay slot is always active when \sml{instruction} is not-nullified,
and there is currently an implicitly padded nop.
| {
"pile_set_name": "Github"
} |
$Include "$SRCDIR\vpc_scripts\version.vpc"
$Include "$SRCDIR\vpc_scripts\source_linux_base_project.vpc"
$MacroRequired "OUTBINNAME" "$PROJECTNAME"
$MacroRequired "OUTBINDIR" "$SRCDIR\..\game\bin"
// General configuration info.
$Configuration
{
$General
{
$ConfigurationType "Dynamic Library (.dll)"
$OutputFile "$(OBJ_DIR)/$OUTBINNAME$_DLL_EXT"
$GameOutputFile "$OUTBINDIR/$OUTBINNAME$_DLL_EXT"
}
$Compiler
{
$PreprocessorDefinitions "$BASE;RAD_TELEMETRY_DISABLED" [$SOURCESDK ]
}
}
// Skeleton Project - All derived projects get this as a starting base
$Project
{
$Folder "Source Files"
{
$File "$SRCDIR\public\tier0\memoverride.cpp"
{
$Configuration
{
$Compiler
{
$Create/UsePrecompiledHeader "Not Using Precompiled Headers"
}
}
}
}
$Folder "Resources"
{
$File "$ROOTSCRIPT"
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html> <!-- Ejemplo basico de lanzador de la aplicacion -->
<head>
<title>Ejemplo de firma por lotes del MiniApplet @firma</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<script type="text/javascript" src="js/miniapplet.js"></script>
<script type="text/javascript" src="js/constantes.js"></script>
<script type="text/javascript">
var singleSigns = new Array();
function showResultCallback(signatureB64, certificateB64) {
showLog("Firma OK");
document.getElementById('result').value = signatureB64;
}
function showLogCallback(errorType, errorMessage) {
showLog("Type: " + errorType + "\nMessage: " + errorMessage);
}
function doSignBatch() {
try {
var batch = createBatchConfiguration();
showLog(batch);
MiniApplet.signBatch(
MiniApplet.getBase64FromText(batch),
Constants.URL_BASE_SERVICES + "/afirma-server-triphase-signer/BatchPresigner", //$NON-NLS-1$
Constants.URL_BASE_SERVICES + "/afirma-server-triphase-signer/BatchPostsigner", //$NON-NLS-1$
document.getElementById("filters").value,
showResultCallback,
showLogCallback);
} catch(e) {
try {
showLog("Type: " + MiniApplet.getErrorType() + "\nMessage: " + MiniApplet.getErrorMessage());
} catch(ex) {
showLog("Error: " + e);
}
}
}
function addSingleSign() {
singleSigns[singleSigns.length] = MiniApplet.getBase64FromText(buildSingleSign(generateUUID()));
document.getElementById("signButton").disabled = "";
}
function generateUUID(){
var d = new Date().getTime();
if(window.performance && typeof window.performance.now === "function"){
d += performance.now();; //use high-precision timer if available
}
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
function buildSingleSign(id) {
var datasource = document.getElementById("datasourceValue").value;
if (document.getElementById("datasource").value == "text") {
datasource = MiniApplet.getBase64FromText(datasource);
}
var format = document.getElementById("format").value;
var suboperation = document.getElementById("suboperation").value;
var extraParams = MiniApplet.getBase64FromText(document.getElementById("params").value);
var target = document.getElementById("target").value;
var config;
if (target == "es.gob.afirma.signers.batch.SignSaverFile") {
config = MiniApplet.getBase64FromText("FileName=" + document.getElementById("targetValue1").value);
}
else {
config = MiniApplet.getBase64FromText("PostUrl=" + document.getElementById("targetValue1").value +
"\nPostParamName=" + document.getElementById("targetValue2").value);
}
return "<singlesign Id=\"" + id + "\">"
+ "<datasource>" + datasource + "</datasource>"
+ "<format>" + format + "</format>"
+ "<suboperation>" + suboperation + "</suboperation>"
+ "<extraparams>" + extraParams + "</extraparams>"
+ "<signsaver>"
+ "<class>" + target + "</class>"
+ "<config>" + config + "</config>"
+ "</signsaver>"
+ "</singlesign>";
}
function createBatchConfiguration() {
var stopOnError = document.getElementById("stopOnError").checked;
var algorithm = document.getElementById("algorithm").value;
var concurrentTimeOut = document.getElementById("concurrentTimeOut").value;
var configuration = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"
+ "<signbatch stoponerror=\"" + stopOnError + "\" algorithm=\"" + algorithm + "\" ";
if (concurrentTimeOut) {
configuration += "concurrenttimeout=\"" + concurrentTimeOut + "\"";
}
configuration += ">";
for (var i=0; i < singleSigns.length; i++) {
configuration += MiniApplet.getTextFromBase64(singleSigns[i]);
}
configuration += "</signbatch>";
return configuration;
}
function showAppletLog() {
try {
showLog(MiniApplet.getCurrentLog());
} catch(e) {
showLog("Type: " + MiniApplet.getErrorType() + "\nMessage: " + MiniApplet.getErrorMessage());
}
}
function cleanDataField(dataField, textDiv) {
textDiv.innerHTML = "";
dataField.value = null;
}
function selectSignManager() {
var select = document.getElementById("target");
var newValue = select.options[select.selectedIndex].value;
if (newValue == "es.gob.afirma.signers.batch.SignSaverFile") {
document.getElementById('targetValue1').style.display = "block";
document.getElementById('targetValue1Label').style.display = "block";
document.getElementById('targetValue1Label').innerHTML = "FileName:";
document.getElementById('targetValue2').style.display = "none";
document.getElementById('targetValue2Label').style.display = "none";
}
else if (newValue == "es.gob.afirma.signers.batch.SignSaverHttpPost") {
document.getElementById('targetValue1').display = "block";
document.getElementById('targetValue1Label').style.display = "block";
document.getElementById('targetValue1Label').innerHTML = "PostUrl:";
document.getElementById('targetValue2').style.display = "block";
document.getElementById('targetValue2Label').style.display = "block";
document.getElementById('targetValue2Label').innerHTML = "PostParamName:";
}
}
function addExtraParam(newParamId, listParamsId) {
var paramsList = document.getElementById(listParamsId);
paramsList.value = paramsList.value + document.getElementById(newParamId).value + "\n";
document.getElementById(newParamId).value = "";
}
function cleanExtraParams(newParamId, listParamsId) {
document.getElementById(listParamsId).value = "";
document.getElementById(newParamId).value = "";
}
function showLog(newLog) {
document.getElementById('console').value = document.getElementById('console').value + "\n" + newLog;
}
</script>
</head>
<body>
<script type="text/javascript">
MiniApplet.cargarMiniApplet(Constants.URL_BASE_APPLET);
MiniApplet.setServlets(Constants.URL_BASE_SERVICES + "/afirma-signature-storage/StorageService", Constants.URL_BASE_SERVICES + "/afirma-signature-retriever/RetrieveService");
</script>
<fieldset><legend>Configuración general</legend>
<div>
<label for="algorithm">Algoritmo</label>
<select id="algorithm">
<option value="SHA1withRSA">SHA1 con RSA</option>
<option value="SHA512withRSA">SHA512 con RSA</option>
</select>
</div>
<div>
<input type="checkbox" id="stopOnError" />Parar en caso de error
</div>
<div>
<label for="concurrentTimeOut">Tiempo máximo por fase en los procesos concurrentes:</label> <input type="text" id="concurrentTimeOut" /> Segundos
</div>
<div>
<label for="filter">Filtros</label>
<input id="filter" type="text"><input type="button" value="Agregar" onclick="addExtraParam('filter', 'filters');">
<input type="button" value="Limpiar" onclick="cleanExtraParams('filter', 'filters');">
<span>(Insertar las propiedades de una en una)</span>
<br>
<textarea id="filters" cols="50" rows="5" readonly></textarea>
</div>
</fieldset>
<fieldset><legend>Configuración de firmas particulares</legend>
<fieldset><legend>Fuente de datos</legend>
<select id="datasource">
<option value="text" selected>Texto plano</option>
<option value="base64">Base64</option>
<option value="url">URL</option>
</select>
<br>
<input type="text" name="datasourceValue" id="datasourceValue" style="width: 600px;"/>
</fieldset>
<div>
<label for="format">Formato</label>
<select id="format">
<option value="CAdES" selected>CAdES</option>
<option value="PAdES">PAdES</option>
<option value="XAdES">XAdES</option>
<option value="FacturaE">FacturaE</option>
</select>
</div>
<div>
<label for="suboperation">Operación</label>
<select id="suboperation">
<option value="sign">Firma</option>
<option value="cosign">Cofirma</option>
<option value="countersign">Contrafirma</option>
</select>
</div>
<div>
<label for="newParam">ExtraParams</label>
<input id="newParam" type="text"><input type="button" value="Agregar" onclick="addExtraParam('newParam', 'params');">
<input type="button" value="Limpiar" onclick="cleanExtraParams('newParam', 'params');">
<span>(Insertar las propiedades de una en una)</span>
<br>
<textarea id="params" cols="50" rows="5" readonly></textarea>
</div>
<div>
<label for="target">Manejador para el guardado de la firma:</label><br>
<select id="target" name="target" onchange="selectSignManager();">
<option value="es.gob.afirma.signers.batch.SignSaverFile" selected>SignSaverFile</option>
<option value="es.gob.afirma.signers.batch.SignSaverHttpPost">SignSaverHttpPost</option>
</select>
<br>
<label id="targetValue1Label" for="targetValue1">Ruta completa de salida:</label><input type="text" name="targetValue1" id="targetValue1" style="width: 600px;"/>
<label id="targetValue2Label" for="targetValue2" style="display: none;"></label><input type="text" name="targetValue2" id="targetValue2" style="width: 600px; display: none;"/>
<div style="font-weight: bold;">NOTA: Los aquí presentados son manejadores de pruebas y no deben usarse tal cual en los entornos de producción</div>
</div>
<input type="button" value="Agregar firma" onclick="addSingleSign();">
</fieldset>
<br/>
<input type="button" id="signButton" value="Firmar" onclick="doSignBatch();" disabled="disabled">
<br/>
<br/>
<div>
<span>Consola</span>
<br>
<textarea id="console" cols="150" rows="10">
</textarea>
</div>
<div>
<span>Resultado</span>
<br>
<textarea id="result" cols="150" rows="10">
</textarea>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
/***********************************************************************
*
* Copyright (c) 2012-2020 Barbara Geller
* Copyright (c) 2012-2020 Ansel Sermersheim
*
* Copyright (c) 2015 The Qt Company Ltd.
* Copyright (c) 2012-2016 Digia Plc and/or its subsidiary(-ies).
* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
*
* This file is part of CopperSpice.
*
* CopperSpice is free software. You can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* CopperSpice 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.
*
* https://www.gnu.org/licenses/
*
***********************************************************************/
#include "translator.h"
#include <QDebug>
#include <QIODevice>
#include <QHash>
#include <QString>
#include <QTextCodec>
#include <QTextStream>
#include <ctype.h>
// Uncomment if you wish to hard wrap long lines in .po files. Note that this
// affects only msg strings, not comments.
//#define HARD_WRAP_LONG_WORDS
QT_BEGIN_NAMESPACE
static const int MAX_LEN = 79;
static QString poEscapedString(const QString &prefix, const QString &keyword,
bool noWrap, const QString &ba)
{
QStringList lines;
int off = 0;
QString res;
while (off < ba.length()) {
ushort c = ba[off++].unicode();
switch (c) {
case '\n':
res += QLatin1String("\\n");
lines.append(res);
res.clear();
break;
case '\r':
res += QLatin1String("\\r");
break;
case '\t':
res += QLatin1String("\\t");
break;
case '\v':
res += QLatin1String("\\v");
break;
case '\a':
res += QLatin1String("\\a");
break;
case '\b':
res += QLatin1String("\\b");
break;
case '\f':
res += QLatin1String("\\f");
break;
case '"':
res += QLatin1String("\\\"");
break;
case '\\':
res += QLatin1String("\\\\");
break;
default:
if (c < 32) {
res += QLatin1String("\\x");
res += QString::number(c, 16);
if (off < ba.length() && isxdigit(ba[off].unicode())) {
res += QLatin1String("\"\"");
}
} else {
res += QChar(c);
}
break;
}
}
if (!res.isEmpty()) {
lines.append(res);
}
if (!lines.isEmpty()) {
if (!noWrap) {
if (lines.count() != 1 ||
lines.first().length() > MAX_LEN - keyword.length() - prefix.length() - 3) {
QStringList olines = lines;
lines = QStringList(QString());
const int maxlen = MAX_LEN - prefix.length() - 2;
for (const QString & line : olines) {
int off = 0;
while (off + maxlen < line.length()) {
int idx = line.lastIndexOf(QLatin1Char(' '), off + maxlen - 1) + 1;
if (idx == off) {
#ifdef HARD_WRAP_LONG_WORDS
// This doesn't seem too nice, but who knows ...
idx = off + maxlen;
#else
idx = line.indexOf(QLatin1Char(' '), off + maxlen) + 1;
if (!idx) {
break;
}
#endif
}
lines.append(line.mid(off, idx - off));
off = idx;
}
lines.append(line.mid(off));
}
}
} else if (lines.count() > 1) {
lines.prepend(QString());
}
}
return prefix + keyword + QLatin1String(" \"") +
lines.join(QLatin1String("\"\n") + prefix + QLatin1Char('"')) +
QLatin1String("\"\n");
}
static QString poEscapedLines(const QString &prefix, bool addSpace, const QStringList &lines)
{
QString out;
for (const QString & line : lines) {
out += prefix;
if (addSpace && !line.isEmpty()) {
out += QLatin1Char(' ' );
}
out += line;
out += QLatin1Char('\n');
}
return out;
}
static QString poEscapedLines(const QString &prefix, bool addSpace, const QString &in0)
{
QString in = in0;
if (in.endsWith(QLatin1Char('\n'))) {
in.chop(1);
}
return poEscapedLines(prefix, addSpace, in.split(QLatin1Char('\n')));
}
static QString poWrappedEscapedLines(const QString &prefix, bool addSpace, const QString &line)
{
const int maxlen = MAX_LEN - prefix.length();
QStringList lines;
int off = 0;
while (off + maxlen < line.length()) {
int idx = line.lastIndexOf(QLatin1Char(' '), off + maxlen - 1);
if (idx < off) {
#if 0 //def HARD_WRAP_LONG_WORDS
// This cannot work without messing up semantics, so do not even try.
#else
idx = line.indexOf(QLatin1Char(' '), off + maxlen);
if (idx < 0) {
break;
}
#endif
}
lines.append(line.mid(off, idx - off));
off = idx + 1;
}
lines.append(line.mid(off));
return poEscapedLines(prefix, addSpace, lines);
}
struct PoItem {
public:
PoItem()
: isPlural(false), isFuzzy(false) {
}
public:
QByteArray id;
QByteArray context;
QByteArray tscomment;
QByteArray oldTscomment;
QByteArray lineNumber;
QByteArray fileName;
QByteArray references;
QByteArray translatorComments;
QByteArray automaticComments;
QByteArray msgId;
QByteArray oldMsgId;
QList<QByteArray> msgStr;
bool isPlural;
bool isFuzzy;
QHash<QString, QString> extra;
};
static bool isTranslationLine(const QByteArray &line)
{
return line.startsWith("#~ msgstr") || line.startsWith("msgstr");
}
static QByteArray slurpEscapedString(const QList<QByteArray> &lines, int &l,
int offset, const QByteArray &prefix, ConversionData &cd)
{
QByteArray msg;
int stoff;
for (; l < lines.size(); ++l) {
const QByteArray &line = lines.at(l);
if (line.isEmpty() || !line.startsWith(prefix)) {
break;
}
while (isspace(line[offset])) { // No length check, as string has no trailing spaces.
offset++;
}
if (line[offset] != '"') {
break;
}
offset++;
while (true) {
if (offset == line.length())
{
goto premature_eol;
}
uchar c = line[offset++];
if (c == '"')
{
if (offset == line.length()) {
break;
}
while (isspace(line[offset])) {
offset++;
}
if (line[offset++] != '"') {
cd.appendError(QString("PO parsing error: extra characters on line %1.").formatArg(l + 1));
break;
}
continue;
}
if (c == '\\')
{
if (offset == line.length()) {
goto premature_eol;
}
c = line[offset++];
switch (c) {
case 'r':
msg += '\r'; // Maybe just throw it away?
break;
case 'n':
msg += '\n';
break;
case 't':
msg += '\t';
break;
case 'v':
msg += '\v';
break;
case 'a':
msg += '\a';
break;
case 'b':
msg += '\b';
break;
case 'f':
msg += '\f';
break;
case '"':
msg += '"';
break;
case '\\':
msg += '\\';
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
stoff = offset - 1;
while ((c = line[offset]) >= '0' && c <= '7')
if (++offset == line.length()) {
goto premature_eol;
}
msg += line.mid(stoff, offset - stoff).toUInt(0, 8);
break;
case 'x':
stoff = offset;
while (isxdigit(line[offset]))
if (++offset == line.length()) {
goto premature_eol;
}
msg += line.mid(stoff, offset - stoff).toUInt(0, 16);
break;
default:
cd.appendError(QString("PO parsing error: invalid escape '\\%1' (line %2).").formatArg(c).formatArg(l + 1));
msg += '\\';
msg += c;
break;
}
} else {
msg += c;
}
}
offset = prefix.size();
}
--l;
return msg;
premature_eol:
cd.appendError(QString("PO parsing error: premature end of line %1.").formatArg(l + 1));
return QByteArray();
}
static void slurpComment(QByteArray &msg, const QList<QByteArray> &lines, int &l)
{
QByteArray prefix = lines.at(l);
for (int i = 1; ; i++) {
if (prefix.at(i) != ' ') {
prefix.truncate(i);
break;
}
}
for (; l < lines.size(); ++l) {
const QByteArray &line = lines.at(l);
if (line.startsWith(prefix)) {
msg += line.mid(prefix.size());
} else if (line != "#") {
break;
}
msg += '\n';
}
--l;
}
static void splitContext(QByteArray *comment, QByteArray *context)
{
char *data = comment->data();
int len = comment->size();
int sep = -1, j = 0;
for (int i = 0; i < len; i++, j++) {
if (data[i] == '~' && i + 1 < len) {
i++;
} else if (data[i] == '|') {
sep = j;
}
data[j] = data[i];
}
if (sep >= 0) {
QByteArray tmp = comment->mid(sep + 1, j - sep - 1);
comment->truncate(sep);
*context = *comment;
*comment = tmp;
} else {
comment->truncate(j);
}
}
static QString makePoHeader(const QString &str)
{
return QLatin1String("po-header-") + str.toLower().replace(QLatin1Char('-'), QLatin1Char('_'));
}
static QByteArray QByteArrayList_join(const QList<QByteArray> &that, char sep)
{
int totalLength = 0;
const int size = that.size();
for (int i = 0; i < size; ++i) {
totalLength += that.at(i).size();
}
if (size > 0) {
totalLength += size - 1;
}
QByteArray res;
if (totalLength == 0) {
return res;
}
res.reserve(totalLength);
for (int i = 0; i < that.size(); ++i) {
if (i) {
res += sep;
}
res += that.at(i);
}
return res;
}
bool loadPO(Translator &translator, QIODevice &dev, ConversionData &cd)
{
QTextCodec *codec = QTextCodec::codecForName(
cd.m_codecForSource.isEmpty() ? QByteArray("UTF-8") : cd.m_codecForSource);
bool error = false;
// format of a .po file entry:
// white-space
// # translator-comments
// #. automatic-comments
// #: reference...
// #, flag...
// #~ msgctxt, msgid*, msgstr - used for obsoleted messages
// #| msgctxt, msgid* previous untranslated-string - for fuzzy message
// msgctx string-context
// msgid untranslated-string
// -- For singular:
// msgstr translated-string
// -- For plural:
// msgid_plural untranslated-string-plural
// msgstr[0] translated-string
// ...
// we need line based lookahead below.
QList<QByteArray> lines;
while (!dev.atEnd()) {
lines.append(dev.readLine().trimmed());
}
lines.append(QByteArray());
int l = 0, lastCmtLine = -1;
bool qtContexts = false;
PoItem item;
for (; l != lines.size(); ++l) {
QByteArray line = lines.at(l);
if (line.isEmpty()) {
continue;
}
if (isTranslationLine(line)) {
bool isObsolete = line.startsWith("#~ msgstr");
const QByteArray prefix = isObsolete ? "#~ " : "";
while (true) {
int idx = line.indexOf(' ', prefix.length());
QByteArray str = slurpEscapedString(lines, l, idx, prefix, cd);
item.msgStr.append(str);
if (l + 1 >= lines.size() || !isTranslationLine(lines.at(l + 1))) {
break;
}
++l;
line = lines.at(l);
}
if (item.msgId.isEmpty()) {
QHash<QString, QByteArray> extras;
QList<QByteArray> hdrOrder;
QByteArray pluralForms;
for (const QByteArray & hdr : item.msgStr.first().split('\n')) {
if (hdr.isEmpty()) {
continue;
}
int idx = hdr.indexOf(':');
if (idx < 0) {
cd.appendError(QString("Unexpected PO header format '%1'").formatArg(QString::fromLatin1(hdr)));
error = true;
break;
}
QByteArray hdrName = hdr.left(idx).trimmed();
QByteArray hdrValue = hdr.mid(idx + 1).trimmed();
hdrOrder << hdrName;
if (hdrName == "X-Language") {
translator.setLanguageCode(QString::fromLatin1(hdrValue));
} else if (hdrName == "X-Source-Language") {
translator.setSourceLanguageCode(QString::fromLatin1(hdrValue));
} else if (hdrName == "X-Qt-Contexts") {
qtContexts = (hdrValue == "true");
} else if (hdrName == "Plural-Forms") {
pluralForms = hdrValue;
} else if (hdrName == "MIME-Version") {
// just assume it is 1.0
} else if (hdrName == "Content-Type") {
if (cd.m_codecForSource.isEmpty()) {
if (! hdrValue.startsWith("text/plain; charset=")) {
cd.appendError(QString("Unexpected Content-Type header '%1'").formatArg(QString::fromLatin1(hdrValue)));
error = true;
// This will avoid a flood of conversion errors.
codec = QTextCodec::codecForName("latin1");
} else {
QByteArray cod = hdrValue.mid(20);
QTextCodec *cdc = QTextCodec::codecForName(cod);
if (! cdc) {
cd.appendError(QString("Unsupported codec '%1'").formatArg(QString::fromLatin1(cod)));
error = true;
// This will avoid a flood of conversion errors.
codec = QTextCodec::codecForName("latin1");
} else {
codec = cdc;
}
}
}
} else if (hdrName == "Content-Transfer-Encoding") {
if (hdrValue != "8bit") {
cd.appendError(QString("Unexpected Content-Transfer-Encoding '%1'").formatArg(QString::fromLatin1(hdrValue)));
return false;
}
} else if (hdrName == "X-Virgin-Header") {
// legacy
} else {
extras[makePoHeader(QString::fromLatin1(hdrName))] = hdrValue;
}
}
if (! pluralForms.isEmpty()) {
if (translator.languageCode().isEmpty()) {
extras[makePoHeader("Plural-Forms")] = pluralForms;
} else {
// FIXME: make a consistency check
}
}
// Eliminate the field if only headers we added are present in standard order.
// Keep in sync with savePO
static const char *const dfltHdrs[] = {
"MIME-Version", "Content-Type", "Content-Transfer-Encoding",
"Plural-Forms", "X-Language", "X-Source-Language", "X-Qt-Contexts"
};
uint cdh = 0;
for (int cho = 0; cho < hdrOrder.length(); cho++) {
for (;; cdh++) {
if (cdh == sizeof(dfltHdrs) / sizeof(dfltHdrs[0])) {
extras["po-headers"] = QByteArrayList_join(hdrOrder, ',');
goto doneho;
}
if (hdrOrder.at(cho) == dfltHdrs[cdh]) {
cdh++;
break;
}
}
}
doneho:
if (lastCmtLine != -1) {
extras["po-header_comment"] = QByteArrayList_join(lines.mid(0, lastCmtLine + 1), '\n');
}
for (auto it = extras.constBegin(), end = extras.constEnd(); it != end; ++it) {
translator.setExtra(it.key(), codec->toUnicode(it.value()));
}
item = PoItem();
continue;
}
// build translator message
TranslatorMessage msg;
msg.setContext(codec->toUnicode(item.context));
if (! item.references.isEmpty()) {
QString xrefs;
QStringList list = codec->toUnicode(item.references).split(QRegularExpression("\\s"), QStringParser::SkipEmptyParts);
for (const QString &ref : list) {
int pos = ref.indexOf(':');
int lpos = ref.lastIndexOf(':');
if (pos != -1 && pos == lpos) {
bool ok;
int lno = ref.mid(pos + 1).toInteger<int>(&ok);
if (ok) {
msg.addReference(ref.left(pos), lno);
continue;
}
}
if (! xrefs.isEmpty()) {
xrefs += ' ';
}
xrefs += ref;
}
if (! xrefs.isEmpty()) {
item.extra["po-references"] = xrefs;
}
}
msg.setId(codec->toUnicode(item.id));
msg.setSourceText(codec->toUnicode(item.msgId));
msg.setOldSourceText(codec->toUnicode(item.oldMsgId));
msg.setComment(codec->toUnicode(item.tscomment));
msg.setOldComment(codec->toUnicode(item.oldTscomment));
msg.setExtraComment(codec->toUnicode(item.automaticComments));
msg.setTranslatorComment(codec->toUnicode(item.translatorComments));
msg.setPlural(item.isPlural || item.msgStr.size() > 1);
QStringList translations;
for (const QByteArray & bstr : item.msgStr) {
QString str = codec->toUnicode(bstr);
str.replace(QChar(Translator::TextVariantSeparator), QChar(Translator::BinaryVariantSeparator));
translations << str;
}
msg.setTranslations(translations);
if (isObsolete) {
msg.setType(TranslatorMessage::Obsolete);
} else if (item.isFuzzy || (!msg.sourceText().isEmpty() && !msg.isTranslated())) {
msg.setType(TranslatorMessage::Unfinished);
} else {
msg.setType(TranslatorMessage::Finished);
}
msg.setExtras(item.extra);
translator.append(msg);
item = PoItem();
} else if (line.startsWith('#')) {
switch (line.size() < 2 ? 0 : line.at(1)) {
case ':':
item.references += line.mid(3);
item.references += '\n';
break;
case ',': {
QStringList flags = QString::fromLatin1(line.mid(2)).split(QRegularExpression("[, ]"), QStringParser::SkipEmptyParts);
if (flags.removeOne(QLatin1String("fuzzy"))) {
item.isFuzzy = true;
}
flags.removeOne("qt-format");
TranslatorMessage::ExtraData::const_iterator it = item.extra.find(QLatin1String("po-flags"));
if (it != item.extra.end()) {
flags.prepend(*it);
}
if (!flags.isEmpty()) {
item.extra[QLatin1String("po-flags")] = flags.join(QLatin1String(", "));
}
break;
}
case 0:
item.translatorComments += '\n';
break;
case ' ':
slurpComment(item.translatorComments, lines, l);
break;
case '.':
if (line.startsWith("#. ts-context ")) { // legacy
item.context = line.mid(14);
} else if (line.startsWith("#. ts-id ")) {
item.id = line.mid(9);
} else {
item.automaticComments += line.mid(3);
item.automaticComments += '\n';
}
break;
case '|':
if (line.startsWith("#| msgid ")) {
item.oldMsgId = slurpEscapedString(lines, l, 9, "#| ", cd);
} else if (line.startsWith("#| msgid_plural ")) {
QByteArray extra = slurpEscapedString(lines, l, 16, "#| ", cd);
if (extra != item.oldMsgId)
item.extra[QLatin1String("po-old_msgid_plural")] = codec->toUnicode(extra);
} else if (line.startsWith("#| msgctxt ")) {
item.oldTscomment = slurpEscapedString(lines, l, 11, "#| ", cd);
if (qtContexts) {
splitContext(&item.oldTscomment, &item.context);
}
} else {
cd.appendError(QString("PO-format parse error in line %1: '%2'").formatArg(l + 1).formatArg(codec->toUnicode(lines[l])));
error = true;
}
break;
case '~':
if (line.startsWith("#~ msgid ")) {
item.msgId = slurpEscapedString(lines, l, 9, "#~ ", cd);
} else if (line.startsWith("#~ msgid_plural ")) {
QByteArray extra = slurpEscapedString(lines, l, 16, "#~ ", cd);
if (extra != item.msgId) {
item.extra[QLatin1String("po-msgid_plural")] = codec->toUnicode(extra);
}
item.isPlural = true;
} else if (line.startsWith("#~ msgctxt ")) {
item.tscomment = slurpEscapedString(lines, l, 11, "#~ ", cd);
if (qtContexts) {
splitContext(&item.tscomment, &item.context);
}
} else {
cd.appendError(QString("PO-format parse error in line %1: '%2'").formatArg(l + 1).formatArg(codec->toUnicode(lines[l])));
error = true;
}
break;
default:
cd.appendError(QString("PO-format parse error in line %1: '%2'").formatArg(l + 1).formatArg(codec->toUnicode(lines[l])));
error = true;
break;
}
lastCmtLine = l;
} else if (line.startsWith("msgctxt ")) {
item.tscomment = slurpEscapedString(lines, l, 8, QByteArray(), cd);
if (qtContexts) {
splitContext(&item.tscomment, &item.context);
}
} else if (line.startsWith("msgid ")) {
item.msgId = slurpEscapedString(lines, l, 6, QByteArray(), cd);
} else if (line.startsWith("msgid_plural ")) {
QByteArray extra = slurpEscapedString(lines, l, 13, QByteArray(), cd);
if (extra != item.msgId) {
item.extra[QLatin1String("po-msgid_plural")] = codec->toUnicode(extra);
}
item.isPlural = true;
} else {
cd.appendError(QString("PO-format error in line %1: '%2'").formatArg(l + 1).formatArg(codec->toUnicode(lines[l])));
error = true;
}
}
return !error && cd.errors().isEmpty();
}
static void addPoHeader(Translator::ExtraData &headers, QStringList &hdrOrder, const char *name, const QString &value)
{
QString qName = QString::fromLatin1(name);
if (! hdrOrder.contains(qName)) {
hdrOrder << qName;
}
headers[makePoHeader(qName)] = value;
}
static QString escapeComment(const QString &in, bool escape)
{
QString out = in;
if (escape) {
out.replace(QLatin1Char('~'), QLatin1String("~~"));
out.replace(QLatin1Char('|'), QLatin1String("~|"));
}
return out;
}
bool savePO(const Translator &translator, QIODevice &dev, ConversionData &cd)
{
QString str_format = QLatin1String("-format");
bool ok = true;
QTextStream out(&dev);
if (cd.m_outputCodec.isEmpty()) {
out.setCodec("UTF-8");
} else {
out.setCodec(cd.m_outputCodec.constData());
}
bool qtContexts = false;
for (const TranslatorMessage & msg : translator.messages())
if (!msg.context().isEmpty()) {
qtContexts = true;
break;
}
QString cmt = translator.extra(QLatin1String("po-header_comment"));
if (!cmt.isEmpty()) {
out << cmt << '\n';
}
out << "msgid \"\"\n";
Translator::ExtraData headers = translator.extras();
QStringList hdrOrder = translator.extra(QLatin1String("po-headers")) .split(QLatin1Char(','), QStringParser::SkipEmptyParts);
// Keep in sync with loadPO
addPoHeader(headers, hdrOrder, "MIME-Version", QLatin1String("1.0"));
addPoHeader(headers, hdrOrder, "Content-Type", QLatin1String("text/plain; charset=" + out.codec()->name()));
addPoHeader(headers, hdrOrder, "Content-Transfer-Encoding", QLatin1String("8bit"));
if (!translator.languageCode().isEmpty()) {
QLocale::Language l;
QLocale::Country c;
Translator::languageAndCountry(translator.languageCode(), &l, &c);
const char *gettextRules;
if (getNumerusInfo(l, c, 0, 0, &gettextRules)) {
addPoHeader(headers, hdrOrder, "Plural-Forms", QString::fromLatin1(gettextRules));
}
addPoHeader(headers, hdrOrder, "X-Language", translator.languageCode());
}
if (!translator.sourceLanguageCode().isEmpty()) {
addPoHeader(headers, hdrOrder, "X-Source-Language", translator.sourceLanguageCode());
}
if (qtContexts) {
addPoHeader(headers, hdrOrder, "X-Qt-Contexts", QLatin1String("true"));
}
QString hdrStr;
for (const QString & hdr : hdrOrder) {
hdrStr += hdr;
hdrStr += QLatin1String(": ");
hdrStr += headers.value(makePoHeader(hdr));
hdrStr += QLatin1Char('\n');
}
out << poEscapedString(QString(), QString::fromLatin1("msgstr"), true, hdrStr);
for (const TranslatorMessage & msg : translator.messages()) {
out << endl;
if (!msg.translatorComment().isEmpty()) {
out << poEscapedLines(QLatin1String("#"), true, msg.translatorComment());
}
if (!msg.extraComment().isEmpty()) {
out << poEscapedLines(QLatin1String("#."), true, msg.extraComment());
}
if (!msg.id().isEmpty()) {
out << QLatin1String("#. ts-id ") << msg.id() << '\n';
}
QString xrefs = msg.extra(QLatin1String("po-references"));
if (!msg.fileName().isEmpty() || !xrefs.isEmpty()) {
QStringList refs;
for (const TranslatorMessage::Reference &ref : msg.allReferences())
refs.append(QString("%2:%1").formatArg(ref.lineNumber()).formatArg(ref.fileName()));
if (! xrefs.isEmpty()) {
refs << xrefs;
}
out << poWrappedEscapedLines(QLatin1String("#:"), true, refs.join(" "));
}
bool noWrap = false;
bool skipFormat = false;
QStringList flags;
if (msg.type() == TranslatorMessage::Unfinished && msg.isTranslated()) {
flags.append(QLatin1String("fuzzy"));
}
TranslatorMessage::ExtraData::const_iterator itr =
msg.extras().find(QLatin1String("po-flags"));
if (itr != msg.extras().end()) {
QStringList atoms = itr->split(QLatin1String(", "));
for (const QString & atom : atoms)
if (atom.endsWith(str_format)) {
skipFormat = true;
break;
}
if (atoms.contains(QLatin1String("no-wrap"))) {
noWrap = true;
}
flags.append(*itr);
}
if (!skipFormat) {
QString source = msg.sourceText();
// This is fuzzy logic, as we don't know whether the string is
// actually used with QString::arg().
for (int off = 0; (off = source.indexOf(QLatin1Char('%'), off)) >= 0; ) {
if (++off >= source.length()) {
break;
}
if (source.at(off) == QLatin1Char('n') || source.at(off).isDigit()) {
flags.append(QLatin1String("qt-format"));
break;
}
}
}
if (!flags.isEmpty()) {
out << "#, " << flags.join(QLatin1String(", ")) << '\n';
}
QString prefix = QLatin1String("#| ");
if (!msg.oldComment().isEmpty())
out << poEscapedString(prefix, QLatin1String("msgctxt"), noWrap, escapeComment(msg.oldComment(), qtContexts));
if (!msg.oldSourceText().isEmpty()) {
out << poEscapedString(prefix, QLatin1String("msgid"), noWrap, msg.oldSourceText());
}
QString plural = msg.extra(QLatin1String("po-old_msgid_plural"));
if (!plural.isEmpty()) {
out << poEscapedString(prefix, QLatin1String("msgid_plural"), noWrap, plural);
}
prefix = (msg.type() == TranslatorMessage::Obsolete) ? QString("#~ ") : QString("");
if (!msg.context().isEmpty()) {
out << poEscapedString(prefix, "msgctxt", noWrap,
escapeComment(msg.context(), true) + '|' + escapeComment(msg.comment(), true));
} else if (! msg.comment().isEmpty()) {
out << poEscapedString(prefix, "msgctxt", noWrap, escapeComment(msg.comment(), qtContexts));
}
out << poEscapedString(prefix, "msgid", noWrap, msg.sourceText());
if (!msg.isPlural()) {
QString transl = msg.translation();
transl.replace(QChar(Translator::BinaryVariantSeparator), QChar(Translator::TextVariantSeparator));
out << poEscapedString(prefix, QLatin1String("msgstr"), noWrap, transl);
} else {
QString plural = msg.extra(QLatin1String("po-msgid_plural"));
if (plural.isEmpty()) {
plural = msg.sourceText();
}
out << poEscapedString(prefix, QLatin1String("msgid_plural"), noWrap, plural);
const QStringList &translations = msg.translations();
for (int i = 0; i != translations.size(); ++i) {
QString str = translations.at(i);
str.replace(QChar(Translator::BinaryVariantSeparator), QChar(Translator::TextVariantSeparator));
out << poEscapedString(prefix, QString::fromLatin1("msgstr[%1]").formatArg(i), noWrap, str);
}
}
}
return ok;
}
static bool savePOT(const Translator &translator, QIODevice &dev, ConversionData &cd)
{
Translator ttor = translator;
ttor.dropTranslations();
return savePO(ttor, dev, cd);
}
int initPO()
{
Translator::FileFormat format;
format.extension = QLatin1String("po");
format.description = QObject::tr("GNU Gettext localization files");
format.loader = &loadPO;
format.saver = &savePO;
format.fileType = Translator::FileFormat::TranslationSource;
format.priority = 1;
Translator::registerFileFormat(format);
format.extension = QLatin1String("pot");
format.description = QObject::tr("GNU Gettext localization template files");
format.loader = &loadPO;
format.saver = &savePOT;
format.fileType = Translator::FileFormat::TranslationSource;
format.priority = -1;
Translator::registerFileFormat(format);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(initPO)
QT_END_NAMESPACE
| {
"pile_set_name": "Github"
} |
<!doctype html>
<title>CodeMirror: Textile mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="textile.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/marijnh/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class="active" href="#">Textile</a>
</ul>
</div>
<article>
<h2>Textile mode</h2>
<form><textarea id="code" name="code">
h1. Textile Mode
A paragraph without formatting.
p. A simple Paragraph.
h2. Phrase Modifiers
Here are some simple phrase modifiers: *strong*, _emphasis_, **bold**, and __italic__.
A ??citation??, -deleted text-, +inserted text+, some ^superscript^, and some ~subscript~.
A %span element% and @code element@
A "link":http://example.com, a "link with (alt text)":urlAlias
[urlAlias]http://example.com/
An image: !http://example.com/image.png! and an image with a link: !http://example.com/image.png!:http://example.com
A sentence with a footnote.[123]
fn123. The footnote is defined here.
Registered(r), Trademark(tm), and Copyright(c)
h2. Headers
h1. Top level
h2. Second level
h3. Third level
h4. Fourth level
h5. Fifth level
h6. Lowest level
h2. Lists
* An unordered list
** foo bar
*** foo bar
**** foo bar
** foo bar
# An ordered list
## foo bar
### foo bar
#### foo bar
## foo bar
- definition list := description
- another item := foo bar
- spanning ines :=
foo bar
foo bar =:
h2. Attributes
Layouts and phrase modifiers can be modified with various kinds of attributes: alignment, CSS ID, CSS class names, language, padding, and CSS styles.
h3. Alignment
div<. left align
div>. right align
h3. CSS ID and class name
You are a %(my-id#my-classname) rad% person.
h3. Language
p[en_CA]. Strange weather, eh?
h3. Horizontal Padding
p(())). 2em left padding, 3em right padding
h3. CSS styling
p{background: red}. Fire!
h2. Table
|_. Header 1 |_. Header 2 |
|{background:#ddd}. Cell with background| Normal |
|\2. Cell spanning 2 columns |
|/2. Cell spanning 2 rows |(cell-class). one |
| two |
|>. Right aligned cell |<. Left aligned cell |
h3. A table with attributes:
table(#prices).
|Adults|$5|
|Children|$2|
h2. Code blocks
bc.
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
pre..
,,,,,,
o#'9MMHb':'-,o,
.oH":HH$' "' ' -*R&o,
dMMM*""'`' .oM"HM?.
,MMM' "HLbd< ?&H\
.:MH ."\ ` MM MM&b
. "*H - &MMMMMMMMMH:
. dboo MMMMMMMMMMMM.
. dMMMMMMb *MMMMMMMMMP.
. MMMMMMMP *MMMMMP .
`#MMMMM MM6P ,
' `MMMP" HM*`,
' :MM .- ,
'. `#?.. . ..'
-. . .-
''-.oo,oo.-''
\. _(9>
\==_)
-'=
h2. Temporarily disabling textile markup
notextile. Don't __touch this!__
Surround text with double-equals to disable textile inline. Example: Use ==*asterisks*== for *strong* text.
h2. HTML
Some block layouts are simply textile versions of HTML tags with the same name, like @div@, @pre@, and @p@. HTML tags can also exist on their own line:
<section>
<h1>Title</h1>
<p>Hello!</p>
</section>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-textile"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-textile</code>.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#textile_*">normal</a>, <a href="../../test/index.html#verbose,textile_*">verbose</a>.</p>
</article>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2008 biaoping.yin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.frameworkset.common.poolman;
import com.frameworkset.common.poolman.handle.FieldRowHandler;
import com.frameworkset.common.poolman.handle.NullRowHandler;
import com.frameworkset.common.poolman.handle.RowHandler;
import com.frameworkset.util.ListInfo;
import org.frameworkset.persitent.util.SQLInfo;
import org.frameworkset.persitent.util.SQLUtil;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Title: SQLExecutor.java</p>
* <p>Description: </p>
* <p>bboss workgroup</p>
* <p>Copyright (c) 2008</p>
* @Date 2010-3-11 下午01:46:25
* @author biaoping.yin
* @version 1.0
*/
public class SQLExecutor
{
/**
* 数据库查询语句属性
*/
protected String statement ;
// protected String pretoken;
// protected String endtoken;
protected String action;
public static final String ACTION_INSERT = "insert";
public static final String ACTION_UPDATE = "update";
public static final String ACTION_DELETE = "delete";
public static final String BATCH_COMMON = "common";
public static final String BATCH_PREPARED = "prepared";
// protected String dbname;
/**
* 批处理预编译操作参数集,
* List<Params>
*/
private List<SQLParams> batchsqlparams;
/**
* 批处理预编译操作参数集,
* List<String>
*/
private List<String> batchsqls;
private String batchtype=BATCH_COMMON;
/**
* 预编译参数列表,单独的预编语句参数
* Map<String,Param>
*/
protected SQLParams sqlparams ;
private String batchDBName;
private boolean batchOptimize = false;
public SQLParams getSQLParams() throws SetSQLParamException
{
if(sqlparams != null )
{
if((this.getPretoken() == null && this.getEndtoken()!= null) ||
(getPretoken() != null && getEndtoken() == null))
throw new SetSQLParamException("非法的绑定变量分割符设置:pretoken = " + getPretoken() + "endtoken =" + getEndtoken() );
}
return this.sqlparams;
}
/**
* 添加sql参数,由DefaultDataInfoImpl进行处理
* @param name
* @param value
* @param type
* @throws SetSQLParamException
*/
public void addSQLParam(String name, String value, String type) throws SetSQLParamException
{
addSQLParam( name, value, type, null);
}
private void init()
{
if(sqlparams == null)
{
sqlparams = new SQLParams();
}
}
/**
* 添加sql参数,由DefaultDataInfoImpl进行处理
* @param name
* @param value
* @param type
* @throws SetSQLParamException
*/
public void addSQLParam(String name, Object value, String type,String dataformat) throws SetSQLParamException
{
init();
addSQLParam( sqlparams, name, value, type, dataformat);
}
/**
* 添加sql参数,由DefaultDataInfoImpl进行处理
* @param name
* @param value
* @param type
* @throws SetSQLParamException
*/
public void addSQLParam(String name, Object value, String type,String dataformat,String charset) throws SetSQLParamException
{
init();
addSQLParam( sqlparams, name, value, type, dataformat,charset);
}
/**
* 添加sql参数,由DefaultDataInfoImpl进行处理
* @param name
* @param value
* @param type
* @throws SetSQLParamException
*/
public static void addSQLParam(SQLParams sqlparams,String name, Object value, String type,String dataformat) throws SetSQLParamException
{
// init();
sqlparams.addSQLParam( name, value, type, dataformat);
}
/**
* 添加sql参数,由DefaultDataInfoImpl进行处理
* @param name
* @param value
* @param type
* @throws SetSQLParamException
*/
public static void addSQLParam(SQLParams sqlparams,String name, Object value, String type,String dataformat,String charset) throws SetSQLParamException
{
// init();
sqlparams.addSQLParam( name, value, type, dataformat,charset);
}
public String getDbname()
{
init();
return this.sqlparams.getDbname();
}
public void setDbname(String dbname)
{
init();
this.sqlparams.setDbname(dbname);
}
public String getStatement()
{
return statement;
}
public void setStatement(String statement)
{
this.statement = statement;
}
public String getPretoken()
{
init();
return this.sqlparams.getPretoken();
}
public void setPretoken(String pretoken)
{
init();
sqlparams.setPretoken(pretoken);
}
public String getEndtoken()
{
init();
return this.sqlparams.getEndtoken();
}
public void setEndtoken(String endtoken)
{
init();
this.sqlparams.setEndtoken(endtoken);
}
public String getAction()
{
return action;
}
public void setAction(String action)
{
this.action = action;
}
public Object execute() throws SQLException
{
if(this.batchsqlparams == null && this.batchsqls == null)
{
action = action.toLowerCase();
PreparedDBUtil dbutil = new PreparedDBUtil();
if(action.equals(ACTION_INSERT))
{
if(this.getSQLParams().size() > 0)
{
dbutil.preparedInsert(this.getSQLParams(), this.getDbname(), SQLUtil.getGlobalSQLUtil().getSQLInfo(this.getStatement(),true,true));
}
else
{
dbutil.executeInsert(this.getDbname(),this.getStatement());
}
}
else if(action.equals(ACTION_UPDATE))
{
if(this.getSQLParams().size() > 0)
{
dbutil.preparedUpdate(this.getSQLParams(), this.getDbname(),SQLUtil.getGlobalSQLUtil().getSQLInfo(this.getStatement(),true,true));
}
else
{
dbutil.executeUpdate(this.getDbname(),this.getStatement());
}
}
else if(action.equals(ACTION_DELETE))
{
if(this.getSQLParams().size() > 0)
{
dbutil.preparedDelete(this.getSQLParams(), this.getDbname(),SQLUtil.getGlobalSQLUtil().getSQLInfo(this.getStatement(),true,true));
}
else
{
dbutil.executeDelete(this.getDbname(),this.getStatement());
}
}
else
throw new SQLException("不支持的数据库操作:" + action);
return dbutil.executePrepared();
}
else
{
if(this.batchtype.equals(BATCH_PREPARED))
{
PreparedDBUtil dbutil = new PreparedDBUtil();
dbutil.setBatchOptimize(isBatchOptimize());
dbutil.setPrepareDBName(batchDBName);
dbutil.addPreparedBatch(new ListSQLParams(batchsqlparams,null));
dbutil.executePreparedBatch();
}
else
{
DBUtil dbutil = new PreparedDBUtil();
dbutil.addBatch(this.batchsqls);
dbutil.executeBatch(this.getBatchDBName());
}
return null;
}
}
public void addPreparedBatch()
{
if(this.batchsqlparams == null)
{
batchsqlparams = new ArrayList<SQLParams>();
// batchparamsIDXBySQL = new HashMap();
}
batchsqlparams.add(this.sqlparams);
// batchparamsIDXBySQL.put(Params.prepareselect_sql, Params);
SQLInfo old = this.sqlparams.getOldsql();
String oldendtoken = this.sqlparams.getEndtoken();
String oldpretoken = this.sqlparams.getPretoken();
sqlparams = this.buildParams();
sqlparams.setOldsql(old);
sqlparams.setEndtoken(oldendtoken);
sqlparams.setPretoken(oldpretoken);
}
public void addBatch(String statement)
{
if(batchsqls == null)
batchsqls = new ArrayList<String>();
batchsqls.add(statement);
}
private SQLParams buildParams() {
// TODO Auto-generated method stub
return new SQLParams();
}
public String getBatchDBName() {
return batchDBName;
}
public void setBatchDBName(String batchDBName) {
this.batchDBName = batchDBName;
}
public boolean isBatchOptimize() {
return batchOptimize;
}
public void setBatchOptimize(boolean batchOptimize) {
this.batchOptimize = batchOptimize;
}
// public static void init(SQLParams sqlparams,String statement,String pretoken,String endtoken,String action)
// {
//// this.sqlparams = new SQLParams();
// sqlparams.setOldsql( statement);
// if(action != null)
// {
// if(action.equals(ACTION_INSERT))
// sqlparams.setAction(PreparedDBUtil.INSERT);
// else if(action.equals(ACTION_DELETE))
// sqlparams.setAction(PreparedDBUtil.DELETE);
// else if(action.equals(ACTION_UPDATE))
// sqlparams.setAction(PreparedDBUtil.UPDATE);
// }
// sqlparams.setPretoken(pretoken);
// sqlparams.setEndtoken(endtoken);
// //http://changsha.koubei.com/store/detail--storeId-b227fc4aee6e4862909ea7bf62556a7a
//
//
// }
public void init(String statement,String pretoken,String endtoken,String action)
{
this.sqlparams = new SQLParams();
// sqlparams.setOldsql( statement);
// if(action != null)
// {
// if(action.equals(ACTION_INSERT))
// sqlparams.setAction(PreparedDBUtil.INSERT);
// else if(action.equals(ACTION_DELETE))
// sqlparams.setAction(PreparedDBUtil.DELETE);
// else if(action.equals(ACTION_UPDATE))
// sqlparams.setAction(PreparedDBUtil.UPDATE);
// }
// sqlparams.setPretoken(pretoken);
// sqlparams.setEndtoken(endtoken);
// //http://changsha.koubei.com/store/detail--storeId-b227fc4aee6e4862909ea7bf62556a7a
SQLInfoExecutor.init(sqlparams, SQLUtil.getGlobalSQLUtil().getSQLInfo(statement,true,true), pretoken, endtoken, action);
}
public String getBatchtype() {
return batchtype;
}
public void setBatchtype(String batchtype) {
this.batchtype = batchtype;
}
public static void insertBeans(String dbname, String sql, List beans) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
// execute( dbname, sql, beans,PreparedDBUtil.INSERT,(GetCUDResult)null);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.insertBeans(dbname,sqlinfo, beans);
}
public static void insertBeans(String dbname, String sql, List beans,GetCUDResult getCUDResult) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
// execute( dbname, sql, beans,PreparedDBUtil.INSERT,getCUDResult);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.insertBeans(dbname,sqlinfo, beans,getCUDResult);
}
// public static void execute(String dbname, String sql, List beans,boolean isBatchOptimize,int action) throws SQLException
// {
// execute(dbname, sql, beans,isBatchOptimize,action,(GetCUDResult)null) ;
// }
// public static void execute(String dbname, String sql, List beans,boolean isBatchOptimize,int action,GetCUDResult getCUDResult) throws SQLException
// {
// Connection con = null;
// try
// {
// con = DBUtil.getConection(dbname);
// List<SQLParams> batchsqlparams = SQLParams.convertBeansToSqlParams(beans,new SQLInfo(sql,true,true),dbname,action,con);
// if(batchsqlparams == null)
// return ;
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.setBatchOptimize(isBatchOptimize);
// dbutil.setPrepareDBName(dbname);
// dbutil.addPreparedBatch(new ListSQLParams(batchsqlparams,null));
// dbutil.executePreparedBatch(con,getCUDResult);
// }
// finally
// {
// try {
// if (con != null)
// con.close();
// } catch (Exception e) {
// // TODO: handle exception
// }
// }
// }
// private static Object CUDexecute(String dbname, String sql, Object bean,int action) throws SQLException
// {
// return CUDexecute(dbname, sql, bean,action,false) ;
// }
// /**
// * 针对增删改三种类型DB操作的统一处理方法
// * @param dbname
// * @param sql
// * @param bean
// * @param isBatchOptimize
// * @param action
// * @return
// * @throws SQLException
// */
// private static Object CUDexecute(String dbname, String sql, Object bean,int action,boolean getCUDResult) throws SQLException
// {
// Connection con = null;
// try
// {
// SQLInfo sqlinfo = new SQLInfo(sql,true,false);
// con = DBUtil.getConection(dbname);
// SQLParams batchsqlparams = SQLParams.convertBeanToSqlParams(bean,sqlinfo,dbname,action,con);
// if(batchsqlparams == null)
// return null;
//// PreparedDBUtil dbutil = new PreparedDBUtil();
//// dbutil.setBatchOptimize(isBatchOptimize);
//// dbutil.setPrepareDBName(dbname);
//// dbutil.addPreparedBatch(batchsqlparams);
//// dbutil.executePreparedBatch(con);
//
//
//// action = action.toLowerCase();
// PreparedDBUtil dbutil = new PreparedDBUtil();
// if(action == PreparedDBUtil.INSERT)
// {
// if(batchsqlparams.size() > 0)
// {
// dbutil.preparedInsert(batchsqlparams, dbname,sqlinfo);
// return dbutil.executePrepared(con,getCUDResult);
// }
// else
// {
// return dbutil.executeInsert(dbname,sql,con);
// }
// }
// else if(action == PreparedDBUtil.UPDATE)
// {
// if(batchsqlparams.size() > 0)
// {
// dbutil.preparedUpdate(batchsqlparams, dbname,sqlinfo);
// return dbutil.executePrepared(con,getCUDResult);
// }
// else
// {
// return dbutil.executeUpdate(dbname,sql,con);
// }
//
// }
// else if(action == PreparedDBUtil.DELETE)
// {
// if(batchsqlparams.size() > 0)
// {
// dbutil.preparedDelete(batchsqlparams, dbname,sqlinfo);
// return dbutil.executePrepared(con,getCUDResult);
// }
// else
// {
// return dbutil.executeDelete(dbname,sql,con);
// }
// }
// else
// throw new SQLException("不支持的数据库操作:" + action);
//
// }
// finally
// {
// try {
// if (con != null)
// con.close();
// } catch (Exception e) {
// // TODO: handle exception
// }
// }
// }
// public static void execute(String dbname, String sql, List beans,int action) throws SQLException
// {
// execute(dbname, sql, beans,false,action,null);
// }
//
// public static void execute(String dbname, String sql, List beans,int action,GetCUDResult getCUDResult) throws SQLException
// {
// execute(dbname, sql, beans,false,action,getCUDResult);
// }
//
public static Object update( String sql, Object... fields) throws SQLException {
// return execute(null, sql,PreparedDBUtil.UPDATE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.update( sqlinfo,fields);
}
public static Object delete(String sql, Object... fields) throws SQLException {
// return execute(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.delete(sqlinfo, fields);
}
// public static void deleteByKeys(String sql, Object... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
//
// }
// public static void deleteByKeysWithDBName(String dbname,String sql, Object... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
//
// }
public static void deleteByKeys(String sql, int... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByKeys(sqlinfo, fields);
}
public static void deleteByKeysWithDBName(String dbname,String sql, int... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByKeysWithDBName(dbname,sqlinfo, fields);
}
public static void deleteByLongKeys(String sql, long... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByLongKeys(sqlinfo, fields);
}
public static void deleteByLongKeysWithDBName(String dbname,String sql, long... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByLongKeysWithDBName(dbname,sqlinfo, fields);
}
public static <T> void executeBatch(String sql,List<T> datas,int batchsize, BatchHandler<T> batchHandler) throws SQLException{
executeBatch(null,sql,datas,batchsize, batchHandler);
}
public static <T> void executeBatch(String dbname,String sql,List<T> datas,int batchsize, BatchHandler<T> batchHandler) throws SQLException{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.executeBatch( dbname, sqlinfo,datas,batchsize,batchHandler) ;
}
public static void updateByKeys(String sql, int... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByKeys(sqlinfo, fields);
}
public static void updateByKeysWithDBName(String dbname,String sql, int... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByKeysWithDBName(dbname,sqlinfo, fields);
}
public static void updateByLongKeys(String sql, long... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByLongKeys(sqlinfo, fields);
}
public static void updateByLongKeysWithDBName(String dbname,String sql, long... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByLongKeysWithDBName(dbname,sqlinfo, fields);
}
public static void updateByKeys(String sql, String... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByKeys(sqlinfo, fields);
}
public static void updateByKeysWithDBName(String dbname,String sql, String... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByKeysWithDBName(dbname,sqlinfo, fields);
}
public static void deleteByKeys(String sql, String... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByKeys(sqlinfo, fields);
}
public static void deleteByKeysWithDBName(String dbname,String sql, String... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByKeysWithDBName(dbname,sqlinfo, fields);
}
public static void deleteByShortKeys(String sql, short... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByShortKeys(sqlinfo, fields);
}
public static void deleteByShortKeysWithDBName(String dbname,String sql, short... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.deleteByShortKeysWithDBName(dbname,sqlinfo, fields);
}
public static void updateByShortKeys(String sql, short... fields) throws SQLException {
// executeBatch(null, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByShortKeys(sqlinfo, fields);
}
public static void updateByShortKeysWithDBName(String dbname,String sql, short... fields) throws SQLException {
// executeBatch(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.updateByShortKeysWithDBName(dbname,sqlinfo, fields);
}
public static Object insert(String sql, Object... fields) throws SQLException {
// return execute(null, sql,PreparedDBUtil.INSERT, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.insert(sqlinfo, fields);
}
public static Object updateWithDBName(String dbname, String sql, Object... fields) throws SQLException {
// return execute(dbname, sql,PreparedDBUtil.UPDATE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.updateWithDBName( dbname, sqlinfo, fields);
}
public static Object deleteWithDBName(String dbname, String sql, Object... fields) throws SQLException {
// return execute(dbname, sql,PreparedDBUtil.DELETE, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.deleteWithDBName(dbname,sqlinfo, fields);
}
public static Object insertWithDBName(String dbname, String sql, Object... fields) throws SQLException {
// return execute(dbname, sql,PreparedDBUtil.INSERT, fields);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.insertWithDBName(dbname,sqlinfo, fields);
}
public static void updateBeans(String dbname, String sql, List beans) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
// execute( dbname, sql, beans,PreparedDBUtil.UPDATE,(GetCUDResult)null);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.updateBeans( dbname, sqlinfo, beans);
}
public static void updateBeans(String dbname, String sql, List beans,GetCUDResult GetCUDResult) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
// execute( dbname, sql, beans,PreparedDBUtil.UPDATE,GetCUDResult);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.updateBeans( dbname, sqlinfo, beans,GetCUDResult);
}
public static void deleteBeans(String dbname, String sql, List beans) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.deleteBeans(dbname, sqlinfo, beans);
// execute( dbname, sql, beans,PreparedDBUtil.DELETE);
}
public static void deleteBeans(String dbname, String sql, List beans,GetCUDResult GetCUDResult) throws SQLException {
if(beans == null || beans.size() == 0)
return ;
// execute( dbname, sql, beans,PreparedDBUtil.DELETE, GetCUDResult);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,true);
SQLInfoExecutor.deleteBeans(dbname, sqlinfo, beans,GetCUDResult);
}
public static void insertBean(String dbname, String sql, Object bean) throws SQLException {
if(bean == null)
return ;
// List datas = new ArrayList();
// datas.add(bean);
// insertBeans( dbname, sql, datas);
// CUDexecute(dbname, sql, bean,PreparedDBUtil.INSERT,false);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.insertBean(dbname,sqlinfo, bean);
}
public static void insertBean(String dbname, String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
if(bean == null)
return ;
//// List datas = new ArrayList();
//// datas.add(bean);
//// insertBeans( dbname, sql, datas);
// if(getCUDResult == null)
// {
//
// CUDexecute(dbname, sql, bean,PreparedDBUtil.INSERT,false);
// }
// else
// {
// GetCUDResult getCUDResult_ = (GetCUDResult)CUDexecute(dbname, sql, bean,PreparedDBUtil.INSERT,true);
// getCUDResult.setGetCUDResult(getCUDResult_);
//
// }
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.insertBean(dbname,sqlinfo, bean,getCUDResult);
}
public static void updateBean(String dbname, String sql, Object bean) throws SQLException {
if(bean == null )
return ;
// List datas = new ArrayList();
// datas.add(bean);
// updateBeans( dbname, sql, datas);
// CUDexecute(dbname, sql, bean,PreparedDBUtil.UPDATE,false);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.updateBean( dbname, sqlinfo, bean);
}
public static void updateBean(String dbname, String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
if(bean == null )
return ;
// List datas = new ArrayList();
// datas.add(bean);
// updateBeans( dbname, sql, datas);
// if(getCUDResult != null)
// {
// GetCUDResult getCUDResult_ = (GetCUDResult)CUDexecute(dbname, sql, bean,PreparedDBUtil.UPDATE,true);
// getCUDResult.setGetCUDResult(getCUDResult_);
// }
// else
// CUDexecute(dbname, sql, bean,PreparedDBUtil.UPDATE,false);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.updateBean( dbname, sqlinfo, bean, getCUDResult);
}
public static void updateBean( String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
// if(bean == null )
// return ;
// List datas = new ArrayList();
// datas.add(bean);
// updateBeans( null, sql, datas);
updateBean((String)null, sql, bean, getCUDResult);
}
public static void deleteBean( String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
deleteBean((String )null,sql, bean,getCUDResult) ;
}
public static void deleteBean(String dbname, String sql, Object bean) throws SQLException {
if(bean == null)
return ;
// List datas = new ArrayList();
// datas.add(bean);
// deleteBeans( dbname, sql, datas);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.deleteBean(dbname, sqlinfo, bean);
// CUDexecute(dbname, sql, bean,PreparedDBUtil.DELETE,false);
}
public static void deleteBean(String dbname, String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
if(bean == null)
return ;
// List datas = new ArrayList();
// datas.add(bean);
// deleteBeans( dbname, sql, datas);
// if(getCUDResult != null)
// {
// GetCUDResult getCUDResult_ = (GetCUDResult)CUDexecute(dbname, sql, bean,PreparedDBUtil.DELETE,true);
// getCUDResult.setGetCUDResult(getCUDResult_);
// }
// else
// CUDexecute(dbname, sql, bean,PreparedDBUtil.DELETE,false);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.deleteBean(dbname, sqlinfo, bean,getCUDResult);
}
public static void insertBeans(String sql, List beans) throws SQLException {
insertBeans( null,sql, beans);
}
public static void insertBeans(String sql, List beans,GetCUDResult getCUDResult) throws SQLException {
insertBeans( (String)null,sql, beans,getCUDResult);
}
public static void updateBeans( String sql, List beans) throws SQLException {
updateBeans( null,sql, beans);
}
public static void deleteBeans( String sql, List beans) throws SQLException {
deleteBeans( null,sql, beans);
}
public static void insertBean( String sql, Object bean) throws SQLException {
// if(bean == null)
// return ;
// List datas = new ArrayList();
// datas.add(bean);
// insertBeans( null, sql, datas);
insertBean( (String)null,sql, bean);
}
public static void insertBean( String sql, Object bean,GetCUDResult getCUDResult) throws SQLException {
// if(bean == null)
// return ;
// List datas = new ArrayList();
// datas.add(bean);
// insertBeans( null, sql, datas);
insertBean( (String)null,sql, bean,getCUDResult);
}
public static void updateBean( String sql, Object bean) throws SQLException {
// if(bean == null )
// return ;
// List datas = new ArrayList();
// datas.add(bean);
// updateBeans( null, sql, datas);
updateBean( (String)null,sql, bean);
}
public static void deleteBean(String sql, Object bean) throws SQLException {
// if(bean == null)
// return ;
// List datas = new ArrayList();
// datas.add(bean);
// deleteBeans( null, sql, datas);
deleteBean((String)null,sql, bean);
}
public static <T> List<T> queryList(Class<T> beanType, String sql, Object... fields) throws SQLException
{
return queryListWithDBName(beanType,null, sql, fields);
}
/**
*
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName( beanType, dbname, sqlinfo, offset, pagesize, fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsize(Class<?> beanType,String dbname, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize,totalsize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsize( beanType, dbname, sqlinfo, offset, pagesize, totalsize, fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsizesql(Class<?> beanType,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelectWithTotalsizesql(dbname, sql,offset,pagesize,totalsizesql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfo totalsizesqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsizesql( beanType, dbname, sqlinfo, offset, pagesize, totalsizesqlinfo, fields);
}
/**
*
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfo(Class<?> beanType, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return queryListInfoWithDBName(beanType, null,sql, offset,pagesize,fields);
}
public static ListInfo queryListInfoWithTotalsize(Class<?> beanType, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsize(beanType, null,sql, offset,pagesize,totalsize,fields);
}
public static ListInfo queryListInfoWithTotalsizesql(Class<?> beanType, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsizesql(beanType, null,sql, offset,pagesize,totalsizesql,fields);
}
public static <T> T queryObject(Class<T> beanType, String sql, Object... fields) throws SQLException
{
return queryObjectWithDBName(beanType,null, sql, fields);
}
public static <T> List<T> queryListWithDBName(Class<T> beanType,String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
//
// return dbutil.executePreparedForList(beanType);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListWithDBName( beanType, dbname, sqlinfo, fields);
}
public static <T> T queryObjectWithDBName(Class<T> beanType,String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
// return (T)dbutil.executePreparedForObject(beanType);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryObjectWithDBName( beanType, dbname, sqlinfo, fields);
}
public static <T> List<T> queryListByRowHandler(RowHandler rowhandler,Class<T> beanType, String sql, Object... fields) throws SQLException
{
return queryListWithDBNameByRowHandler(rowhandler,beanType,null, sql, fields);
}
/**
*
* @param rowhandler
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType,rowhandler));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBNameByRowHandler( rowhandler, beanType, dbname, sqlinfo, offset,pagesize,fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsizeByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize,totalsize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType,rowhandler));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsizeByRowHandler( rowhandler, beanType, dbname, sqlinfo, offset, pagesize, totalsize,fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsizesqlByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelectWithTotalsizesql(dbname, sql,offset,pagesize,totalsizesql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType,rowhandler));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfo totalsizesqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsizesqlByRowHandler( rowhandler, beanType, dbname, sqlinfo, offset, pagesize, totalsizesqlinfo, fields);
}
/**
*
* @param rowhandler
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return queryListInfoWithDBNameByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,fields);
}
public static ListInfo queryListInfoWithTotalsizeByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsizeByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,totalsize,fields);
}
public static ListInfo queryListInfoWithTotalsizesqlByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsizesqlByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,totalsizesql,fields);
}
public static <T> T queryObjectByRowHandler(RowHandler rowhandler,Class<T> beanType, String sql, Object... fields) throws SQLException
{
return queryObjectWithDBNameByRowHandler(rowhandler,beanType,null, sql, fields);
}
public static <T> List<T> queryListWithDBNameByRowHandler(RowHandler rowhandler,Class<T> beanType,String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
//
// return dbutil.executePreparedForList(beanType,rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListWithDBNameByRowHandler( rowhandler,beanType, dbname, sqlinfo, fields);
}
public static <T> T queryObjectWithDBNameByRowHandler(RowHandler rowhandler,Class<T> beanType,String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
// return (T)dbutil.executePreparedForObject(beanType,rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryObjectWithDBNameByRowHandler( rowhandler, beanType, dbname, sqlinfo, fields);
}
/**
* 采用Null行处理器的通用查询,适用于单个Object查询,List查询等等
* @param rowhandler
* @param sql
* @param fields
* @throws SQLException
*/
public static void queryByNullRowHandler(NullRowHandler rowhandler, String sql, Object... fields) throws SQLException
{
queryWithDBNameByNullRowHandler( rowhandler,null, sql, fields);
}
/**
*
* @param rowhandler
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
// dbutil.executePreparedWithRowHandler(rowhandler);
// ListInfo datas = new ListInfo();
//
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsizeByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql,offset,pagesize,totalsize);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
// dbutil.executePreparedWithRowHandler(rowhandler);
// ListInfo datas = new ListInfo();
//
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsizeByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, totalsize,fields);
}
public static ListInfo queryListInfoWithDBName2ndTotalsizesqlByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelectWithTotalsizesql(dbname, sql,offset,pagesize,totalsizesql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
// dbutil.executePreparedWithRowHandler(rowhandler);
// ListInfo datas = new ListInfo();
//
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfo totalsizesqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,false,false);
return SQLInfoExecutor.queryListInfoWithDBName2ndTotalsizesqlByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, totalsizesqlinfo, fields);
}
/**
*
* @param rowhandler
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return queryListInfoWithDBNameByNullRowHandler( rowhandler, null,sql, offset,pagesize,fields);
}
public static ListInfo queryListInfoWithTotalsizeByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,long totalsize,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsizeByNullRowHandler( rowhandler, null,sql, offset,pagesize,totalsize,fields);
}
public static ListInfo queryListInfoWithTotalsizesqlByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,String totalsizesql,Object... fields) throws SQLException
{
return queryListInfoWithDBName2ndTotalsizesqlByNullRowHandler( rowhandler, null,sql, offset,pagesize,totalsizesql,fields);
}
/**
* 采用Null行处理器的通用查询,适用于单个Object查询,List查询等等
* @param rowhandler
* @param dbname
* @param sql
* @param fields
* @throws SQLException
*/
public static void queryWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
//
// dbutil.executePreparedWithRowHandler(rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
SQLInfoExecutor.queryWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo,fields);
}
public static <T> List<T> queryListBean(Class<T> beanType, String sql, Object bean) throws SQLException
{
return queryListBeanWithDBName(beanType,null, sql, bean);
}
/**
*
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql,offset,pagesize,totalsize);
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBName( beanType, dbname, sqlinfo, offset, pagesize, totalsize, bean);
}
public static ListInfo queryListInfoBeanWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelectWithTotalsizesql(params,dbname, sql,offset,pagesize,totalsizesql);
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfo totalsizesqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBName(beanType, dbname, sqlinfo, offset, pagesize, totalsizesqlinfo, bean);
}
/**
*
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql,offset,pagesize,-1L);
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBName( beanType, dbname, sqlinfo, offset, pagesize, bean);
}
/**
*
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBean(Class<?> beanType, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBName(beanType, null,sql, offset,pagesize,totalsize,bean);
}
public static ListInfo queryListInfoBean(Class<?> beanType, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
return queryListInfoBeanWithDBName(beanType, null,sql, offset,pagesize,totalsizesql,bean);
}
public static ListInfo queryListInfoBean(Class<?> beanType, String sql, long offset,int pagesize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBName(beanType, null,sql, offset,pagesize,-1L,bean);
}
public static String queryField( String sql, Object... fields) throws SQLException
{
return queryFieldWithDBName(null, sql, fields);
}
public static String queryFieldBean( String sql, Object bean) throws SQLException
{
return queryFieldBeanWithDBName(null, sql, bean);
}
public static String queryFieldBeanWithDBName(String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
//
//
//
//
// dbutil.executePrepared();
// if(dbutil.size() > 0)
// return dbutil.getString(0, 0);
// else
// {
// return null;
// }
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryFieldBeanWithDBName( dbname, sqlinfo, bean);
}
public static String queryFieldWithDBName(String dbname, String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
//
// dbutil.executePrepared();
// if(dbutil.size() > 0)
// return dbutil.getString(0, 0);
// else
// {
// return null;
// }
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryFieldWithDBName( dbname, sqlinfo, fields);
}
/**
*
* @param <T>
* @param type
* @param sql
* @param fields
* @return
* @throws SQLException
*/
public static <T> T queryTField( Class<T> type,String sql, Object... fields) throws SQLException
{
return queryTFieldWithDBName(null, type,sql, fields);
}
public static <T> T queryTFieldBean( Class<T> type,String sql, Object bean) throws SQLException
{
return queryTFieldBeanWithDBName(null, type,sql, bean);
}
public static <T> T queryTFieldBeanWithDBName(String dbname, Class<T> type,String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, sql, dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
//
//
//
//
// dbutil.executePrepared();
// if(dbutil.size() > 0)
// return (T)ValueObjectUtil.typeCast(dbutil.getObject(0, 0),type);
// else
// {
// return (T)ValueObjectUtil.getDefaultValue(type);
// }
return queryTFieldBeanWithDBName(dbname, type,(FieldRowHandler<T>)null,sql, bean) ;
}
public static <T> T queryTFieldWithDBName(String dbname, Class<T> type,String sql, Object... fields) throws SQLException
{
return queryTFieldWithDBName(dbname, type,(FieldRowHandler<T>)null,sql, fields);
}
public static <T> T queryTField( Class<T> type,FieldRowHandler<T> fieldRowHandler,String sql, Object... fields) throws SQLException
{
return queryTFieldWithDBName(null, type,fieldRowHandler,sql, fields);
}
public static <T> T queryTFieldBean( Class<T> type,FieldRowHandler<T> fieldRowHandler,String sql, Object bean) throws SQLException
{
return queryTFieldBeanWithDBName(null, type,fieldRowHandler,sql, bean);
}
public static <T> T queryTFieldBeanWithDBName(String dbname, Class<T> type,FieldRowHandler<T> fieldRowHandler,String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
//
//
//
// if(fieldRowHandler == null)
// {
// dbutil.executePrepared();
// if(dbutil.size() > 0)
// return (T)ValueObjectUtil.typeCast(dbutil.getObject(0, 0),type);
// else
// {
// return (T)ValueObjectUtil.getDefaultValue(type);
// }
//
// }
// else
// {
// return (T)dbutil.executePreparedForObject(type, fieldRowHandler);
// }
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryTFieldBeanWithDBName( dbname, type,fieldRowHandler,sqlinfo, bean);
}
public static <T> T queryTFieldWithDBName(String dbname, Class<T> type,FieldRowHandler<T> fieldRowHandler,String sql, Object... fields) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// dbutil.preparedSelect(dbname, sql);
// if(fields != null && fields.length > 0)
// {
// for(int i = 0; i < fields.length ; i ++)
// {
//
// Object field = fields[i];
// dbutil.setObject(i + 1, field);
// }
// }
//
//
//
// if(fieldRowHandler == null)
// {
// dbutil.executePrepared();
// if(dbutil.size() > 0)
// return (T)ValueObjectUtil.typeCast(dbutil.getObject(0, 0),type);
// else
// {
// return (T)ValueObjectUtil.getDefaultValue(type);
// }
// }
// else
// {
// return (T)dbutil.executePreparedForObject(type, fieldRowHandler);
// }
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
return SQLInfoExecutor.queryTFieldWithDBName( dbname, type,fieldRowHandler,sqlinfo, fields);
}
public static <T> T queryObjectBean(Class<T> beanType, String sql, Object bean) throws SQLException
{
return queryObjectBeanWithDBName(beanType,null, sql, bean);
}
public static <T> List<T> queryListBeanWithDBName(Class<T> beanType,String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
//
//
//
//
//
// return dbutil.executePreparedForList(beanType);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListBeanWithDBName(beanType, dbname, sqlinfo, bean);
}
public static <T> T queryObjectBeanWithDBName(Class<T> beanType,String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
// return (T)dbutil.executePreparedForObject(beanType);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryObjectBeanWithDBName( beanType, dbname, sqlinfo, bean);
}
public static <T> List<T> queryListBeanByRowHandler(RowHandler rowhandler,Class<T> beanType, String sql, Object bean) throws SQLException
{
return queryListBeanWithDBNameByRowHandler(rowhandler,beanType,null, sql, bean);
}
/**
*
* @param rowhandler
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, offset,pagesize,totalsize,bean);
}
public static ListInfo queryListInfoBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelectWithTotalsizesql(params,dbname, sql,offset,pagesize,totalsizesql);
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType,rowhandler));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfo totalsizesqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByRowHandler( rowhandler, beanType, dbname, sqlinfo, offset, pagesize, totalsizesqlinfo, bean);
}
/**
*
* @param rowhandler
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql,offset,pagesize,-1L);
// ListInfo datas = new ListInfo();
// datas.setDatas(dbutil.executePreparedForList(beanType,rowhandler));
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, offset,pagesize,bean);
}
/**
*
* @param rowhandler
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,totalsize,bean);
}
public static ListInfo queryListInfoBeanByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,totalsizesql,bean);
}
public static ListInfo queryListInfoBeanByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,-1L,bean);
}
public static <T> T queryObjectBeanByRowHandler(RowHandler rowhandler,Class<T> beanType, String sql, Object bean) throws SQLException
{
return queryObjectBeanWithDBNameByRowHandler(rowhandler,beanType,null, sql, bean);
}
public static <T> List<T> queryListBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<T> beanType,String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
//
// return dbutil.executePreparedForList(beanType,rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListBeanWithDBNameByRowHandler( rowhandler, beanType, dbname, sqlinfo, bean);
}
public static <T> T queryObjectBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<T> beanType,String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
// return (T)dbutil.executePreparedForObject(beanType,rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryObjectBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, bean);
}
public static void queryBeanByNullRowHandler(NullRowHandler rowhandler, String sql, Object bean) throws SQLException
{
queryBeanWithDBNameByNullRowHandler( rowhandler,null, sql, bean);
}
/**
*
* @param rowhandler
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql,offset,pagesize,totalsize);
// dbutil.executePreparedWithRowHandler(rowhandler);
// ListInfo datas = new ListInfo();
//
// datas.setTotalSize(dbutil.getLongTotalSize());
// return datas;
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, totalsize, bean);
}
public static ListInfo queryListInfoBeanWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfo totalsizesqlsqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(totalsizesql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, totalsizesqlsqlinfo, bean);
}
/**
*
* @param rowhandler
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
return SQLInfoExecutor.queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, bean);
}
/**
*
* @param rowhandler
* @param sql
* @param offset
* @param pagesize
* @param totalsize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo queryListInfoBeanByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,long totalsize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, null,sql, offset,pagesize,totalsize,bean);
}
public static ListInfo queryListInfoBeanByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,String totalsizesql,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, null,sql, offset,pagesize,totalsizesql,bean);
}
public static ListInfo queryListInfoBeanByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,Object bean) throws SQLException
{
return queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, null,sql, offset,pagesize,-1L,bean);
}
public static void queryBeanWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, Object bean) throws SQLException
{
// PreparedDBUtil dbutil = new PreparedDBUtil();
// SQLParams params = SQLParams.convertBeanToSqlParams(bean, new SQLInfo(sql,true,false), dbname, PreparedDBUtil.SELECT, null);
// dbutil.preparedSelect(params,dbname, sql);
// dbutil.executePreparedWithRowHandler(rowhandler);
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
SQLInfoExecutor.queryBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, bean);
}
/**
* more分页查询,不会计算总记录数,如果没有记录那么返回的ListInfo的datas的size为0,
* 提升性能,同时前台标签库也会做响应的调整
*/
/**
*
* @param rowhandler
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
// return SQLInfoExecutor.queryListInfoWithDBNameByRowHandler( rowhandler, beanType, dbname, sqlinfo, offset,pagesize,fields);
// SQLInfo sql = getSqlInfo(dbname, sqlname);
return SQLInfoExecutor.moreListInfoWithDBNameByRowHandler(rowhandler,beanType,dbname, sqlinfo, offset,pagesize,fields);
}
/**
*
* @param rowhandler
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
// return SQLInfoExecutor.queryListInfoWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, fields);
// SQLInfo sql = getSqlInfo(dbname, sqlname);
return SQLInfoExecutor.moreListInfoWithDBNameByNullRowHandler( rowhandler,dbname, sqlinfo, offset,pagesize,fields);
}
/**
*
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,false,false);
// return SQLInfoExecutor.queryListInfoWithDBName( beanType, dbname, sqlinfo, offset, pagesize, fields);
// SQLInfo sql = getSqlInfo(dbname, sqlname);
return SQLInfoExecutor.moreListInfoWithDBName(beanType,dbname, sqlinfo, offset,pagesize,fields);
}
/**
*
* @param rowhandler
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return moreListInfoWithDBNameByRowHandler( rowhandler,beanType, null,sql, offset,pagesize,fields);
}
/**
*
* @param rowhandler
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return moreListInfoWithDBNameByNullRowHandler( rowhandler, null,sql, offset,pagesize,fields);
}
/**
*
* @param rowhandler
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoBeanWithDBNameByRowHandler(RowHandler rowhandler,Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, offset,pagesize,bean);
// SQLInfo sql = getSqlInfo(dbname, sql);
return SQLInfoExecutor.moreListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, offset,pagesize,bean);
}
/**
*
* @param rowhandler
* @param dbname
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoBeanWithDBNameByNullRowHandler(NullRowHandler rowhandler,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, bean);
// SQLInfo sql = getSqlInfo(dbname, sql);
return SQLInfoExecutor.moreListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset,pagesize,bean);
}
/**
*
* @param beanType
* @param dbname
* @param sql
* @param offset
* @param pagesize
* @param bean
* @return
* @throws SQLException
*/
public static ListInfo moreListInfoBeanWithDBName(Class<?> beanType,String dbname, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBName( beanType, dbname, sqlinfo, offset, pagesize, bean);
// SQLInfo sql = getSqlInfo(dbname, sql);
return SQLInfoExecutor.moreListInfoBeanWithDBName( beanType, dbname, sqlinfo, offset, pagesize, bean);
}
public static ListInfo moreListInfoBeanByRowHandler(RowHandler rowhandler,Class<?> beanType, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,dbname, sqlinfo, offset,pagesize,totalsize,bean);
return SQLInfoExecutor.moreListInfoBeanWithDBNameByRowHandler( rowhandler,beanType,(String)null, sqlinfo, offset,pagesize,bean);
}
public static ListInfo moreListInfoBeanByNullRowHandler(NullRowHandler rowhandler, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBNameByNullRowHandler( rowhandler, dbname, sqlinfo, offset, pagesize, totalsize, bean);
// SQLInfo sql = getSqlInfo(null, sql);
return SQLInfoExecutor.moreListInfoBeanWithDBNameByNullRowHandler( rowhandler, (String)null, sqlinfo, offset,pagesize,bean);
}
public static ListInfo moreListInfoBean(Class<?> beanType, String sql, long offset,int pagesize,Object bean) throws SQLException
{
SQLInfo sqlinfo = SQLUtil.getGlobalSQLUtil().getSQLInfo(sql,true,false);
// return SQLInfoExecutor.queryListInfoBeanWithDBName( beanType, dbname, sqlinfo, offset, pagesize, totalsize, bean);
// SQLInfo sql = getSqlInfo(null, sql);
return SQLInfoExecutor.moreListInfoBeanWithDBName( beanType, (String)null, sqlinfo, offset, pagesize, bean);
}
/**
*
* @param beanType
* @param sql
* @param offset
* @param pagesize
* @param fields
* @return
* @throws SQLException
*/
public static ListInfo moreListInfo(Class<?> beanType, String sql, long offset,int pagesize,Object... fields) throws SQLException
{
return moreListInfoWithDBName(beanType, null,sql, offset,pagesize,fields);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2009 by Martin Fuzzey
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* 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. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* this file is part of imx21-hcd.c */
#ifdef CONFIG_DYNAMIC_DEBUG
#define DEBUG
#endif
#ifndef DEBUG
static inline void create_debug_files(struct imx21 *imx21) { }
static inline void remove_debug_files(struct imx21 *imx21) { }
static inline void debug_urb_submitted(struct imx21 *imx21, struct urb *urb) {}
static inline void debug_urb_completed(struct imx21 *imx21, struct urb *urb,
int status) {}
static inline void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb) {}
static inline void debug_urb_queued_for_etd(struct imx21 *imx21,
struct urb *urb) {}
static inline void debug_urb_queued_for_dmem(struct imx21 *imx21,
struct urb *urb) {}
static inline void debug_etd_allocated(struct imx21 *imx21) {}
static inline void debug_etd_freed(struct imx21 *imx21) {}
static inline void debug_dmem_allocated(struct imx21 *imx21, int size) {}
static inline void debug_dmem_freed(struct imx21 *imx21, int size) {}
static inline void debug_isoc_submitted(struct imx21 *imx21,
int frame, struct td *td) {}
static inline void debug_isoc_completed(struct imx21 *imx21,
int frame, struct td *td, int cc, int len) {}
#else
#include <linux/debugfs.h>
#include <linux/seq_file.h>
static const char *dir_labels[] = {
"TD 0",
"OUT",
"IN",
"TD 1"
};
static const char *speed_labels[] = {
"Full",
"Low"
};
static const char *format_labels[] = {
"Control",
"ISO",
"Bulk",
"Interrupt"
};
static inline struct debug_stats *stats_for_urb(struct imx21 *imx21,
struct urb *urb)
{
return usb_pipeisoc(urb->pipe) ?
&imx21->isoc_stats : &imx21->nonisoc_stats;
}
static void debug_urb_submitted(struct imx21 *imx21, struct urb *urb)
{
stats_for_urb(imx21, urb)->submitted++;
}
static void debug_urb_completed(struct imx21 *imx21, struct urb *urb, int st)
{
if (st)
stats_for_urb(imx21, urb)->completed_failed++;
else
stats_for_urb(imx21, urb)->completed_ok++;
}
static void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb)
{
stats_for_urb(imx21, urb)->unlinked++;
}
static void debug_urb_queued_for_etd(struct imx21 *imx21, struct urb *urb)
{
stats_for_urb(imx21, urb)->queue_etd++;
}
static void debug_urb_queued_for_dmem(struct imx21 *imx21, struct urb *urb)
{
stats_for_urb(imx21, urb)->queue_dmem++;
}
static inline void debug_etd_allocated(struct imx21 *imx21)
{
imx21->etd_usage.maximum = max(
++(imx21->etd_usage.value),
imx21->etd_usage.maximum);
}
static inline void debug_etd_freed(struct imx21 *imx21)
{
imx21->etd_usage.value--;
}
static inline void debug_dmem_allocated(struct imx21 *imx21, int size)
{
imx21->dmem_usage.value += size;
imx21->dmem_usage.maximum = max(
imx21->dmem_usage.value,
imx21->dmem_usage.maximum);
}
static inline void debug_dmem_freed(struct imx21 *imx21, int size)
{
imx21->dmem_usage.value -= size;
}
static void debug_isoc_submitted(struct imx21 *imx21,
int frame, struct td *td)
{
struct debug_isoc_trace *trace = &imx21->isoc_trace[
imx21->isoc_trace_index++];
imx21->isoc_trace_index %= ARRAY_SIZE(imx21->isoc_trace);
trace->schedule_frame = td->frame;
trace->submit_frame = frame;
trace->request_len = td->len;
trace->td = td;
}
static inline void debug_isoc_completed(struct imx21 *imx21,
int frame, struct td *td, int cc, int len)
{
struct debug_isoc_trace *trace, *trace_failed;
int i;
int found = 0;
trace = imx21->isoc_trace;
for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++) {
if (trace->td == td) {
trace->done_frame = frame;
trace->done_len = len;
trace->cc = cc;
trace->td = NULL;
found = 1;
break;
}
}
if (found && cc) {
trace_failed = &imx21->isoc_trace_failed[
imx21->isoc_trace_index_failed++];
imx21->isoc_trace_index_failed %= ARRAY_SIZE(
imx21->isoc_trace_failed);
*trace_failed = *trace;
}
}
static char *format_ep(struct usb_host_endpoint *ep, char *buf, int bufsize)
{
if (ep)
snprintf(buf, bufsize, "ep_%02x (type:%02X kaddr:%p)",
ep->desc.bEndpointAddress,
usb_endpoint_type(&ep->desc),
ep);
else
snprintf(buf, bufsize, "none");
return buf;
}
static char *format_etd_dword0(u32 value, char *buf, int bufsize)
{
snprintf(buf, bufsize,
"addr=%d ep=%d dir=%s speed=%s format=%s halted=%d",
value & 0x7F,
(value >> DW0_ENDPNT) & 0x0F,
dir_labels[(value >> DW0_DIRECT) & 0x03],
speed_labels[(value >> DW0_SPEED) & 0x01],
format_labels[(value >> DW0_FORMAT) & 0x03],
(value >> DW0_HALTED) & 0x01);
return buf;
}
static int debug_status_show(struct seq_file *s, void *v)
{
struct imx21 *imx21 = s->private;
int etds_allocated = 0;
int etds_sw_busy = 0;
int etds_hw_busy = 0;
int dmem_blocks = 0;
int queued_for_etd = 0;
int queued_for_dmem = 0;
unsigned int dmem_bytes = 0;
int i;
struct etd_priv *etd;
u32 etd_enable_mask;
unsigned long flags;
struct imx21_dmem_area *dmem;
struct ep_priv *ep_priv;
spin_lock_irqsave(&imx21->lock, flags);
etd_enable_mask = readl(imx21->regs + USBH_ETDENSET);
for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) {
if (etd->alloc)
etds_allocated++;
if (etd->urb)
etds_sw_busy++;
if (etd_enable_mask & (1<<i))
etds_hw_busy++;
}
list_for_each_entry(dmem, &imx21->dmem_list, list) {
dmem_bytes += dmem->size;
dmem_blocks++;
}
list_for_each_entry(ep_priv, &imx21->queue_for_etd, queue)
queued_for_etd++;
list_for_each_entry(etd, &imx21->queue_for_dmem, queue)
queued_for_dmem++;
spin_unlock_irqrestore(&imx21->lock, flags);
seq_printf(s,
"Frame: %d\n"
"ETDs allocated: %d/%d (max=%d)\n"
"ETDs in use sw: %d\n"
"ETDs in use hw: %d\n"
"DMEM allocated: %d/%d (max=%d)\n"
"DMEM blocks: %d\n"
"Queued waiting for ETD: %d\n"
"Queued waiting for DMEM: %d\n",
readl(imx21->regs + USBH_FRMNUB) & 0xFFFF,
etds_allocated, USB_NUM_ETD, imx21->etd_usage.maximum,
etds_sw_busy,
etds_hw_busy,
dmem_bytes, DMEM_SIZE, imx21->dmem_usage.maximum,
dmem_blocks,
queued_for_etd,
queued_for_dmem);
return 0;
}
static int debug_dmem_show(struct seq_file *s, void *v)
{
struct imx21 *imx21 = s->private;
struct imx21_dmem_area *dmem;
unsigned long flags;
char ep_text[40];
spin_lock_irqsave(&imx21->lock, flags);
list_for_each_entry(dmem, &imx21->dmem_list, list)
seq_printf(s,
"%04X: size=0x%X "
"ep=%s\n",
dmem->offset, dmem->size,
format_ep(dmem->ep, ep_text, sizeof(ep_text)));
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static int debug_etd_show(struct seq_file *s, void *v)
{
struct imx21 *imx21 = s->private;
struct etd_priv *etd;
char buf[60];
u32 dword;
int i, j;
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) {
int state = -1;
struct urb_priv *urb_priv;
if (etd->urb) {
urb_priv = etd->urb->hcpriv;
if (urb_priv)
state = urb_priv->state;
}
seq_printf(s,
"etd_num: %d\n"
"ep: %s\n"
"alloc: %d\n"
"len: %d\n"
"busy sw: %d\n"
"busy hw: %d\n"
"urb state: %d\n"
"current urb: %p\n",
i,
format_ep(etd->ep, buf, sizeof(buf)),
etd->alloc,
etd->len,
etd->urb != NULL,
(readl(imx21->regs + USBH_ETDENSET) & (1 << i)) > 0,
state,
etd->urb);
for (j = 0; j < 4; j++) {
dword = etd_readl(imx21, i, j);
switch (j) {
case 0:
format_etd_dword0(dword, buf, sizeof(buf));
break;
case 2:
snprintf(buf, sizeof(buf),
"cc=0X%02X", dword >> DW2_COMPCODE);
break;
default:
*buf = 0;
break;
}
seq_printf(s,
"dword %d: submitted=%08X cur=%08X [%s]\n",
j,
etd->submitted_dwords[j],
dword,
buf);
}
seq_printf(s, "\n");
}
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static void debug_statistics_show_one(struct seq_file *s,
const char *name, struct debug_stats *stats)
{
seq_printf(s, "%s:\n"
"submitted URBs: %lu\n"
"completed OK: %lu\n"
"completed failed: %lu\n"
"unlinked: %lu\n"
"queued for ETD: %lu\n"
"queued for DMEM: %lu\n\n",
name,
stats->submitted,
stats->completed_ok,
stats->completed_failed,
stats->unlinked,
stats->queue_etd,
stats->queue_dmem);
}
static int debug_statistics_show(struct seq_file *s, void *v)
{
struct imx21 *imx21 = s->private;
unsigned long flags;
spin_lock_irqsave(&imx21->lock, flags);
debug_statistics_show_one(s, "nonisoc", &imx21->nonisoc_stats);
debug_statistics_show_one(s, "isoc", &imx21->isoc_stats);
seq_printf(s, "unblock kludge triggers: %lu\n", imx21->debug_unblocks);
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static void debug_isoc_show_one(struct seq_file *s,
const char *name, int index, struct debug_isoc_trace *trace)
{
seq_printf(s, "%s %d:\n"
"cc=0X%02X\n"
"scheduled frame %d (%d)\n"
"submitted frame %d (%d)\n"
"completed frame %d (%d)\n"
"requested length=%d\n"
"completed length=%d\n\n",
name, index,
trace->cc,
trace->schedule_frame, trace->schedule_frame & 0xFFFF,
trace->submit_frame, trace->submit_frame & 0xFFFF,
trace->done_frame, trace->done_frame & 0xFFFF,
trace->request_len,
trace->done_len);
}
static int debug_isoc_show(struct seq_file *s, void *v)
{
struct imx21 *imx21 = s->private;
struct debug_isoc_trace *trace;
unsigned long flags;
int i;
spin_lock_irqsave(&imx21->lock, flags);
trace = imx21->isoc_trace_failed;
for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace_failed); i++, trace++)
debug_isoc_show_one(s, "isoc failed", i, trace);
trace = imx21->isoc_trace;
for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++)
debug_isoc_show_one(s, "isoc", i, trace);
spin_unlock_irqrestore(&imx21->lock, flags);
return 0;
}
static int debug_status_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_status_show, inode->i_private);
}
static int debug_dmem_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_dmem_show, inode->i_private);
}
static int debug_etd_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_etd_show, inode->i_private);
}
static int debug_statistics_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_statistics_show, inode->i_private);
}
static int debug_isoc_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_isoc_show, inode->i_private);
}
static const struct file_operations debug_status_fops = {
.open = debug_status_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations debug_dmem_fops = {
.open = debug_dmem_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations debug_etd_fops = {
.open = debug_etd_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations debug_statistics_fops = {
.open = debug_statistics_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations debug_isoc_fops = {
.open = debug_isoc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void create_debug_files(struct imx21 *imx21)
{
imx21->debug_root = debugfs_create_dir(dev_name(imx21->dev), NULL);
if (!imx21->debug_root)
goto failed_create_rootdir;
if (!debugfs_create_file("status", S_IRUGO,
imx21->debug_root, imx21, &debug_status_fops))
goto failed_create;
if (!debugfs_create_file("dmem", S_IRUGO,
imx21->debug_root, imx21, &debug_dmem_fops))
goto failed_create;
if (!debugfs_create_file("etd", S_IRUGO,
imx21->debug_root, imx21, &debug_etd_fops))
goto failed_create;
if (!debugfs_create_file("statistics", S_IRUGO,
imx21->debug_root, imx21, &debug_statistics_fops))
goto failed_create;
if (!debugfs_create_file("isoc", S_IRUGO,
imx21->debug_root, imx21, &debug_isoc_fops))
goto failed_create;
return;
failed_create:
debugfs_remove_recursive(imx21->debug_root);
failed_create_rootdir:
imx21->debug_root = NULL;
}
static void remove_debug_files(struct imx21 *imx21)
{
if (imx21->debug_root) {
debugfs_remove_recursive(imx21->debug_root);
imx21->debug_root = NULL;
}
}
#endif
| {
"pile_set_name": "Github"
} |
<!doctype html>
<title>CodeMirror: Tiki wiki mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="tiki.css">
<script src="../../lib/codemirror.js"></script>
<script src="tiki.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Tiki wiki</a>
</ul>
</div>
<article>
<h2>Tiki wiki mode</h2>
<div><textarea id="code" name="code">
Headings
!Header 1
!!Header 2
!!!Header 3
!!!!Header 4
!!!!!Header 5
!!!!!!Header 6
Styling
-=titlebar=-
^^ Box on multi
lines
of content^^
__bold__
''italic''
===underline===
::center::
--Line Through--
Operators
~np~No parse~/np~
Link
[link|desc|nocache]
Wiki
((Wiki))
((Wiki|desc))
((Wiki|desc|timeout))
Table
||row1 col1|row1 col2|row1 col3
row2 col1|row2 col2|row2 col3
row3 col1|row3 col2|row3 col3||
Lists:
*bla
**bla-1
++continue-bla-1
***bla-2
++continue-bla-1
*bla
+continue-bla
#bla
** tra-la-la
+continue-bla
#bla
Plugin (standard):
{PLUGIN(attr="my attr")}
Plugin Body
{PLUGIN}
Plugin (inline):
{plugin attr="my attr"}
</textarea></div>
<script type="text/javascript">
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'tiki',
lineNumbers: true
});
</script>
</article>
| {
"pile_set_name": "Github"
} |
/***************************************************************************
* This file is part of the propertyEditor project *
* Copyright (C) 2008 by BogDan Vatra *
* bog_dan_ro@yahoo.com *
** GNU General Public License Usage **
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
** GNU Lesser General Public License **
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
* This library 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. See the *
* GNU General Public License for more details. *
****************************************************************************/
#ifndef INAGE_H
#define IMAGE_H
#include <propertyinterface.h>
using namespace PropertyEditor;
class Image : public PropertyInterface
{
Q_OBJECT
#if QT_VERSION >= 0x050000
Q_PLUGIN_METADATA(IID "eu.licentia.PropertyEditor.PropetyInterface/1.0")
#endif
Q_INTERFACES(PropertyEditor::PropertyInterface)
public:
Image(QObject* parent = 0, QObject* object = 0, int property = -1, const PropertyModel * propertyModel = 0);
QWidget* createEditor(QWidget * parent, const QModelIndex & index);
QVariant data(const QModelIndex & index);
bool setData(QVariant data, const QModelIndex & index);
void setEditorData(QWidget * /*editor*/, const QModelIndex & /*index*/){}
bool canHandle(QObject * object, int property)const;
PropertyInterface* createInstance(QObject * object, int property, const PropertyModel * propertyModel) const;
public slots:
void chooseClicked();
};
#endif
| {
"pile_set_name": "Github"
} |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Implementations of DataNode for wrapping XML data.
*
*/
goog.provide('goog.ds.XmlDataSource');
goog.provide('goog.ds.XmlHttpDataSource');
goog.require('goog.Uri');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.xml');
goog.require('goog.ds.BasicNodeList');
goog.require('goog.ds.DataManager');
goog.require('goog.ds.LoadState');
goog.require('goog.ds.logger');
goog.require('goog.net.XhrIo');
goog.require('goog.string');
/**
* Data source whose backing is an xml node
*
* @param {Node} node The XML node. Can be null.
* @param {goog.ds.XmlDataSource} parent Parent of XML element. Can be null.
* @param {string=} opt_name The name of this node relative to the parent node.
*
* @extends {goog.ds.DataNode}
* @constructor
*/
// TODO(arv): Use interfaces when available.
goog.ds.XmlDataSource = function(node, parent, opt_name) {
this.parent_ = parent;
this.dataName_ = opt_name || (node ? node.nodeName : '');
this.setNode_(node);
};
/**
* Constant to select XML attributes for getChildNodes
* @type {string}
* @private
*/
goog.ds.XmlDataSource.ATTRIBUTE_SELECTOR_ = '@*';
/**
* Set the current root nodeof the data source.
* Can be an attribute node, text node, or element node
* @param {Node} node The node. Can be null.
*
* @private
*/
goog.ds.XmlDataSource.prototype.setNode_ = function(node) {
this.node_ = node;
if (node != null) {
switch (node.nodeType) {
case goog.dom.NodeType.ATTRIBUTE:
case goog.dom.NodeType.TEXT:
this.value_ = node.nodeValue;
break;
case goog.dom.NodeType.ELEMENT:
if (node.childNodes.length == 1 &&
node.firstChild.nodeType == goog.dom.NodeType.TEXT) {
this.value_ = node.firstChild.nodeValue;
}
}
}
};
/**
* Creates the DataNodeList with the child nodes for this element.
* Allows for only building list as needed.
*
* @private
*/
goog.ds.XmlDataSource.prototype.createChildNodes_ = function() {
if (this.childNodeList_) {
return;
}
var childNodeList = new goog.ds.BasicNodeList();
if (this.node_ != null) {
var childNodes = this.node_.childNodes;
for (var i = 0, childNode; childNode = childNodes[i]; i++) {
if (childNode.nodeType != goog.dom.NodeType.TEXT ||
!goog.ds.XmlDataSource.isEmptyTextNodeValue_(childNode.nodeValue)) {
var newNode = new goog.ds.XmlDataSource(childNode,
this, childNode.nodeName);
childNodeList.add(newNode);
}
}
}
this.childNodeList_ = childNodeList;
};
/**
* Creates the DataNodeList with the attributes for the element
* Allows for only building list as needed.
*
* @private
*/
goog.ds.XmlDataSource.prototype.createAttributes_ = function() {
if (this.attributes_) {
return;
}
var attributes = new goog.ds.BasicNodeList();
if (this.node_ != null && this.node_.attributes != null) {
var atts = this.node_.attributes;
for (var i = 0, att; att = atts[i]; i++) {
var newNode = new goog.ds.XmlDataSource(att, this, att.nodeName);
attributes.add(newNode);
}
}
this.attributes_ = attributes;
};
/**
* Get the value of the node
* @return {Object} The value of the node, or null if no value.
* @override
*/
goog.ds.XmlDataSource.prototype.get = function() {
this.createChildNodes_();
return this.value_;
};
/**
* Set the value of the node
* @param {*} value The new value of the node.
* @override
*/
goog.ds.XmlDataSource.prototype.set = function(value) {
throw Error('Can\'t set on XmlDataSource yet');
};
/** @override */
goog.ds.XmlDataSource.prototype.getChildNodes = function(opt_selector) {
if (opt_selector && opt_selector ==
goog.ds.XmlDataSource.ATTRIBUTE_SELECTOR_) {
this.createAttributes_();
return this.attributes_;
} else if (opt_selector == null ||
opt_selector == goog.ds.STR_ALL_CHILDREN_SELECTOR) {
this.createChildNodes_();
return this.childNodeList_;
} else {
throw Error('Unsupported selector');
}
};
/**
* Gets a named child node of the current node
* @param {string} name The node name.
* @return {goog.ds.DataNode} The child node, or null if
* no node of this name exists.
* @override
*/
goog.ds.XmlDataSource.prototype.getChildNode = function(name) {
if (goog.string.startsWith(name, goog.ds.STR_ATTRIBUTE_START)) {
var att = this.node_.getAttributeNode(name.substring(1));
return att ? new goog.ds.XmlDataSource(att, this) : null;
} else {
return /** @type {goog.ds.DataNode} */ (this.getChildNodes().get(name));
}
};
/**
* Gets the value of a child node
* @param {string} name The node name.
* @return {*} The value of the node, or null if no value or the child node
* doesn't exist.
* @override
*/
goog.ds.XmlDataSource.prototype.getChildNodeValue = function(name) {
if (goog.string.startsWith(name, goog.ds.STR_ATTRIBUTE_START)) {
var node = this.node_.getAttributeNode(name.substring(1));
return node ? node.nodeValue : null;
} else {
var node = this.getChildNode(name);
return node ? node.get() : null;
}
};
/**
* Get the name of the node relative to the parent node
* @return {string} The name of the node.
* @override
*/
goog.ds.XmlDataSource.prototype.getDataName = function() {
return this.dataName_;
};
/**
* Setthe name of the node relative to the parent node
* @param {string} name The name of the node.
* @override
*/
goog.ds.XmlDataSource.prototype.setDataName = function(name) {
this.dataName_ = name;
};
/**
* Gets the a qualified data path to this node
* @return {string} The data path.
* @override
*/
goog.ds.XmlDataSource.prototype.getDataPath = function() {
var parentPath = '';
if (this.parent_) {
parentPath = this.parent_.getDataPath() +
(this.dataName_.indexOf(goog.ds.STR_ARRAY_START) != -1 ? '' :
goog.ds.STR_PATH_SEPARATOR);
}
return parentPath + this.dataName_;
};
/**
* Load or reload the backing data for this node
* @override
*/
goog.ds.XmlDataSource.prototype.load = function() {
// Nothing to do
};
/**
* Gets the state of the backing data for this node
* @return {goog.ds.LoadState} The state.
* @override
*/
goog.ds.XmlDataSource.prototype.getLoadState = function() {
return this.node_ ? goog.ds.LoadState.LOADED : goog.ds.LoadState.NOT_LOADED;
};
/**
* Check whether a node is an empty text node. Nodes consisting of only white
* space (#x20, #xD, #xA, #x9) can generally be collapsed to a zero length
* text string.
* @param {string} str String to match.
* @return {boolean} True if string equates to empty text node.
* @private
*/
goog.ds.XmlDataSource.isEmptyTextNodeValue_ = function(str) {
return /^[\r\n\t ]*$/.test(str);
};
/**
* Creates an XML document with one empty node.
* Useful for places where you need a node that
* can be queried against.
*
* @return {Document} Document with one empty node.
* @private
*/
goog.ds.XmlDataSource.createChildlessDocument_ = function() {
return goog.dom.xml.createDocument('nothing');
};
/**
* Data source whose backing is an XMLHttpRequest,
*
* A URI of an empty string will mean that no request is made
* and the data source will be a single, empty node.
*
* @param {(string,goog.Uri)} uri URL of the XMLHttpRequest.
* @param {string} name Name of the datasource.
*
* implements goog.ds.XmlHttpDataSource.
* @constructor
* @extends {goog.ds.XmlDataSource}
*/
goog.ds.XmlHttpDataSource = function(uri, name) {
goog.ds.XmlDataSource.call(this, null, null, name);
if (uri) {
this.uri_ = new goog.Uri(uri);
} else {
this.uri_ = null;
}
};
goog.inherits(goog.ds.XmlHttpDataSource, goog.ds.XmlDataSource);
/**
* Default load state is NOT_LOADED
* @private
*/
goog.ds.XmlHttpDataSource.prototype.loadState_ = goog.ds.LoadState.NOT_LOADED;
/**
* Load or reload the backing data for this node.
* Fires the XMLHttpRequest
* @override
*/
goog.ds.XmlHttpDataSource.prototype.load = function() {
if (this.uri_) {
goog.log.info(goog.ds.logger, 'Sending XML request for DataSource ' +
this.getDataName() + ' to ' + this.uri_);
this.loadState_ = goog.ds.LoadState.LOADING;
goog.net.XhrIo.send(this.uri_, goog.bind(this.complete_, this));
} else {
this.node_ = goog.ds.XmlDataSource.createChildlessDocument_();
this.loadState_ = goog.ds.LoadState.NOT_LOADED;
}
};
/**
* Gets the state of the backing data for this node
* @return {goog.ds.LoadState} The state.
* @override
*/
goog.ds.XmlHttpDataSource.prototype.getLoadState = function() {
return this.loadState_;
};
/**
* Handles the completion of an XhrIo request. Dispatches to success or load
* based on the result.
* @param {!goog.events.Event} e The XhrIo event object.
* @private
*/
goog.ds.XmlHttpDataSource.prototype.complete_ = function(e) {
var xhr = /** @type {goog.net.XhrIo} */ (e.target);
if (xhr && xhr.isSuccess()) {
this.success_(xhr);
} else {
this.failure_();
}
};
/**
* Success result. Checks whether valid XML was returned
* and sets the XML and loadstate.
*
* @param {!goog.net.XhrIo} xhr The successful XhrIo object.
* @private
*/
goog.ds.XmlHttpDataSource.prototype.success_ = function(xhr) {
goog.log.info(goog.ds.logger,
'Got data for DataSource ' + this.getDataName());
var xml = xhr.getResponseXml();
// Fix for case where IE returns valid XML as text but
// doesn't parse by default
if (xml && !xml.hasChildNodes() &&
goog.isObject(xhr.getResponseText())) {
xml = goog.dom.xml.loadXml(xhr.getResponseText());
}
// Failure result
if (!xml || !xml.hasChildNodes()) {
this.loadState_ = goog.ds.LoadState.FAILED;
this.node_ = goog.ds.XmlDataSource.createChildlessDocument_();
} else {
this.loadState_ = goog.ds.LoadState.LOADED;
this.node_ = xml.documentElement;
}
if (this.getDataName()) {
goog.ds.DataManager.getInstance().fireDataChange(this.getDataName());
}
};
/**
* Failure result
*
* @private
*/
goog.ds.XmlHttpDataSource.prototype.failure_ = function() {
goog.log.info(goog.ds.logger, 'Data retrieve failed for DataSource ' +
this.getDataName());
this.loadState_ = goog.ds.LoadState.FAILED;
this.node_ = goog.ds.XmlDataSource.createChildlessDocument_();
if (this.getDataName()) {
goog.ds.DataManager.getInstance().fireDataChange(this.getDataName());
}
};
| {
"pile_set_name": "Github"
} |
CREATE TABLE lancamento (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
descricao VARCHAR(50) NOT NULL,
data_vencimento DATE NOT NULL,
data_pagamento DATE,
valor DECIMAL(10,2) NOT NULL,
observacao VARCHAR(100),
tipo VARCHAR(20) NOT NULL,
codigo_categoria BIGINT(20) NOT NULL,
codigo_pessoa BIGINT(20) NOT NULL,
FOREIGN KEY (codigo_categoria) REFERENCES categoria(codigo),
FOREIGN KEY (codigo_pessoa) REFERENCES pessoa(codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Salário mensal', '2017-06-10', null, 6500.00, 'Distribuição de lucros', 'RECEITA', 1, 1);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Bahamas', '2017-02-10', '2017-02-10', 100.32, null, 'DESPESA', 2, 2);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Top Club', '2017-06-10', null, 120, null, 'RECEITA', 3, 3);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('CEMIG', '2017-02-10', '2017-02-10', 110.44, 'Geração', 'RECEITA', 3, 4);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('DMAE', '2017-06-10', null, 200.30, null, 'DESPESA', 3, 5);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Extra', '2017-03-10', '2017-03-10', 1010.32, null, 'RECEITA', 4, 6);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Bahamas', '2017-06-10', null, 500, null, 'RECEITA', 1, 7);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Top Club', '2017-03-10', '2017-03-10', 400.32, null, 'DESPESA', 4, 8);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Despachante', '2017-06-10', null, 123.64, 'Multas', 'DESPESA', 3, 9);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Pneus', '2017-04-10', '2017-04-10', 665.33, null, 'RECEITA', 5, 10);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Café', '2017-06-10', null, 8.32, null, 'DESPESA', 1, 5);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Eletrônicos', '2017-04-10', '2017-04-10', 2100.32, null, 'DESPESA', 5, 4);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Instrumentos', '2017-06-10', null, 1040.32, null, 'DESPESA', 4, 3);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Café', '2017-04-10', '2017-04-10', 4.32, null, 'DESPESA', 4, 2);
INSERT INTO lancamento (descricao, data_vencimento, data_pagamento, valor, observacao, tipo, codigo_categoria, codigo_pessoa) values ('Lanche', '2017-06-10', null, 10.20, null, 'DESPESA', 4, 1);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* 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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
* HOLDER OR 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.
*/
package com.rtg.vcf.header;
import junit.framework.TestCase;
/**
* Test class
*/
public class SampleFieldTest extends TestCase {
public void testSomeMethod() {
final String io = "##SAMPLE=<ID=yo, Genomes=cancer;normal, Mixture=roobar, Description=\"fun for the whole family\">";
final SampleField f = new SampleField(io);
assertEquals(io.replaceAll(",\\s+", ","), f.toString());
assertEquals("yo", f.getId());
assertEquals("cancer;normal", f.getGenomes());
assertEquals("roobar", f.getMixture());
assertEquals("fun for the whole family", f.getDescription());
final String io2 = "##SAMPLE=<ID=%$&*,Genomes=A;B,Mixture=robbyy,Description=\"oh rearry\">";
final SampleField f2 = new SampleField(io2);
assertEquals(io2, f2.toString());
assertEquals("%$&*", f2.getId());
assertEquals("A;B", f2.getGenomes());
assertEquals("robbyy", f2.getMixture());
assertEquals("oh rearry", f2.getDescription());
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 7192bcddc4cdd43b89a2372a4ded8b83
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
// useful global vars for javascripts needing info from template toolkit on page loads.
var webroot = "[% webroot %]";
[% IF refresh %]var refreshtime = "[% refresh %]";[% END %]
var player = "[% playerURI %]";
var playerid = "[% player %]";
var url = "[% statusroot %]";
var statusroot = "[% statusroot %]";
var browserTarget;
[% IF browserTarget %]browserTarget = "[% browserTarget %]";[% END %]
var orderByUrl = '';
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2016-2017 Intel Corporation
* Copyright(c) 2019 Arm Limited
*/
/**
* @file
* RTE Event Ring
*
* This provides a ring implementation for passing rte_event structures
* from one core to another.
*/
#ifndef _RTE_EVENT_RING_
#define _RTE_EVENT_RING_
#include <stdint.h>
#include <rte_common.h>
#include <rte_memory.h>
#include <rte_malloc.h>
#include <rte_ring.h>
#include <rte_ring_elem.h>
#include "rte_eventdev.h"
#define RTE_TAILQ_EVENT_RING_NAME "RTE_EVENT_RING"
/**
* Generic ring structure for passing rte_event objects from core to core.
*
* Based on the primitives given in the rte_ring library. Designed to be
* used inside software eventdev implementations and by applications
* directly as needed.
*/
struct rte_event_ring {
struct rte_ring r;
};
/**
* Returns the number of events in the ring
*
* @param r
* pointer to the event ring
* @return
* the number of events in the ring
*/
static __rte_always_inline unsigned int
rte_event_ring_count(const struct rte_event_ring *r)
{
return rte_ring_count(&r->r);
}
/**
* Returns the amount of free space in the ring
*
* @param r
* pointer to the event ring
* @return
* the number of free slots in the ring, i.e. the number of events that
* can be successfully enqueued before dequeue must be called
*/
static __rte_always_inline unsigned int
rte_event_ring_free_count(const struct rte_event_ring *r)
{
return rte_ring_free_count(&r->r);
}
/**
* Enqueue a set of events onto a ring
*
* Note: this API enqueues by copying the events themselves onto the ring,
* rather than just placing a pointer to each event onto the ring. This
* means that statically-allocated events can safely be enqueued by this
* API.
*
* @param r
* pointer to the event ring
* @param events
* pointer to an array of struct rte_event objects
* @param n
* number of events in the array to enqueue
* @param free_space
* if non-null, is updated to indicate the amount of free space in the
* ring once the enqueue has completed.
* @return
* the number of elements, n', enqueued to the ring, 0 <= n' <= n
*/
static __rte_always_inline unsigned int
rte_event_ring_enqueue_burst(struct rte_event_ring *r,
const struct rte_event *events,
unsigned int n, uint16_t *free_space)
{
unsigned int num;
uint32_t space;
num = rte_ring_enqueue_burst_elem(&r->r, events,
sizeof(struct rte_event), n,
&space);
if (free_space != NULL)
*free_space = space;
return num;
}
/**
* Dequeue a set of events from a ring
*
* Note: this API does not work with pointers to events, rather it copies
* the events themselves to the destination ``events`` buffer.
*
* @param r
* pointer to the event ring
* @param events
* pointer to an array to hold the struct rte_event objects
* @param n
* number of events that can be held in the ``events`` array
* @param available
* if non-null, is updated to indicate the number of events remaining in
* the ring once the dequeue has completed
* @return
* the number of elements, n', dequeued from the ring, 0 <= n' <= n
*/
static __rte_always_inline unsigned int
rte_event_ring_dequeue_burst(struct rte_event_ring *r,
struct rte_event *events,
unsigned int n, uint16_t *available)
{
unsigned int num;
uint32_t remaining;
num = rte_ring_dequeue_burst_elem(&r->r, events,
sizeof(struct rte_event), n,
&remaining);
if (available != NULL)
*available = remaining;
return num;
}
/*
* Initializes an already-allocated ring structure
*
* @param r
* pointer to the ring memory to be initialized
* @param name
* name to be given to the ring
* @param count
* the number of elements to be stored in the ring. If the flag
* ``RING_F_EXACT_SZ`` is not set, this must be a power of 2, and the actual
* usable space in the ring will be ``count - 1`` entries. If the flag
* ``RING_F_EXACT_SZ`` is set, the this can be any value up to the ring size
* limit - 1, and the usable space will be exactly that requested.
* @param flags
* An OR of the following:
* - RING_F_SP_ENQ: If this flag is set, the default behavior when
* using ``rte_ring_enqueue()`` or ``rte_ring_enqueue_bulk()``
* is "single-producer". Otherwise, it is "multi-producers".
* - RING_F_SC_DEQ: If this flag is set, the default behavior when
* using ``rte_ring_dequeue()`` or ``rte_ring_dequeue_bulk()``
* is "single-consumer". Otherwise, it is "multi-consumers".
* - RING_F_EXACT_SZ: If this flag is set, the ``count`` parameter is to
* be taken as the exact usable size of the ring, and as such does not
* need to be a power of 2. The underlying ring memory should be a
* power-of-2 size greater than the count value.
* @return
* 0 on success, or a negative value on error.
*/
int
rte_event_ring_init(struct rte_event_ring *r, const char *name,
unsigned int count, unsigned int flags);
/*
* Create an event ring structure
*
* This function allocates memory and initializes an event ring inside that
* memory.
*
* @param name
* name to be given to the ring
* @param count
* the number of elements to be stored in the ring. If the flag
* ``RING_F_EXACT_SZ`` is not set, this must be a power of 2, and the actual
* usable space in the ring will be ``count - 1`` entries. If the flag
* ``RING_F_EXACT_SZ`` is set, the this can be any value up to the ring size
* limit - 1, and the usable space will be exactly that requested.
* @param socket_id
* The *socket_id* argument is the socket identifier in case of
* NUMA. The value can be *SOCKET_ID_ANY* if there is no NUMA
* constraint for the reserved zone.
* @param flags
* An OR of the following:
* - RING_F_SP_ENQ: If this flag is set, the default behavior when
* using ``rte_ring_enqueue()`` or ``rte_ring_enqueue_bulk()``
* is "single-producer". Otherwise, it is "multi-producers".
* - RING_F_SC_DEQ: If this flag is set, the default behavior when
* using ``rte_ring_dequeue()`` or ``rte_ring_dequeue_bulk()``
* is "single-consumer". Otherwise, it is "multi-consumers".
* - RING_F_EXACT_SZ: If this flag is set, the ``count`` parameter is to
* be taken as the exact usable size of the ring, and as such does not
* need to be a power of 2. The underlying ring memory should be a
* power-of-2 size greater than the count value.
* @return
* On success, the pointer to the new allocated ring. NULL on error with
* rte_errno set appropriately. Possible errno values include:
* - E_RTE_NO_CONFIG - function could not get pointer to rte_config structure
* - E_RTE_SECONDARY - function was called from a secondary process instance
* - EINVAL - count provided is not a power of 2
* - ENOSPC - the maximum number of memzones has already been allocated
* - EEXIST - a memzone with the same name already exists
* - ENOMEM - no appropriate memory area found in which to create memzone
*/
struct rte_event_ring *
rte_event_ring_create(const char *name, unsigned int count, int socket_id,
unsigned int flags);
/**
* Search for an event ring based on its name
*
* @param name
* The name of the ring.
* @return
* The pointer to the ring matching the name, or NULL if not found,
* with rte_errno set appropriately. Possible rte_errno values include:
* - ENOENT - required entry not available to return.
*/
struct rte_event_ring *
rte_event_ring_lookup(const char *name);
/**
* De-allocate all memory used by the ring.
*
* @param r
* Ring to free
*/
void
rte_event_ring_free(struct rte_event_ring *r);
/**
* Return the size of the event ring.
*
* @param r
* A pointer to the ring structure.
* @return
* The size of the data store used by the ring.
* NOTE: this is not the same as the usable space in the ring. To query that
* use ``rte_ring_get_capacity()``.
*/
static inline unsigned int
rte_event_ring_get_size(const struct rte_event_ring *r)
{
return rte_ring_get_size(&r->r);
}
/**
* Return the number of elements which can be stored in the event ring.
*
* @param r
* A pointer to the ring structure.
* @return
* The usable size of the ring.
*/
static inline unsigned int
rte_event_ring_get_capacity(const struct rte_event_ring *r)
{
return rte_ring_get_capacity(&r->r);
}
#endif
| {
"pile_set_name": "Github"
} |
/*
***************************************************************************************
* Copyright (C) 2006 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
***************************************************************************************
*/
package com.espertech.esper.common.internal.event.map;
import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.common.client.type.EPTypeClass;
import com.espertech.esper.common.internal.event.core.EventBeanCopyMethod;
import com.espertech.esper.common.internal.event.core.EventBeanTypedEventFactory;
import com.espertech.esper.common.internal.event.core.MappedEventBean;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
/**
* Copy method for Map-underlying events.
*/
public class MapEventBeanCopyMethodWithArrayMap implements EventBeanCopyMethod {
public final static EPTypeClass EPTYPE = new EPTypeClass(MapEventBeanCopyMethodWithArrayMap.class);
private final MapEventType mapEventType;
private final EventBeanTypedEventFactory eventBeanTypedEventFactory;
private final String[] mapPropertiesToCopy;
private final String[] arrayPropertiesToCopy;
/**
* Ctor.
*
* @param mapEventType map event type
* @param eventBeanTypedEventFactory for copying events
* @param mapPropertiesToCopy map props
* @param arrayPropertiesToCopy array props
*/
public MapEventBeanCopyMethodWithArrayMap(MapEventType mapEventType, EventBeanTypedEventFactory eventBeanTypedEventFactory, String[] mapPropertiesToCopy, String[] arrayPropertiesToCopy) {
this.mapEventType = mapEventType;
this.eventBeanTypedEventFactory = eventBeanTypedEventFactory;
this.mapPropertiesToCopy = mapPropertiesToCopy;
this.arrayPropertiesToCopy = arrayPropertiesToCopy;
}
public EventBean copy(EventBean theEvent) {
MappedEventBean mapped = (MappedEventBean) theEvent;
Map<String, Object> props = mapped.getProperties();
HashMap<String, Object> shallowCopy = new HashMap<String, Object>(props);
for (String name : mapPropertiesToCopy) {
Map<String, Object> innerMap = (Map<String, Object>) props.get(name);
if (innerMap != null) {
Map copy = new HashMap<String, Object>(innerMap);
shallowCopy.put(name, copy);
}
}
for (String name : arrayPropertiesToCopy) {
Object array = props.get(name);
if (array != null && array.getClass().isArray() && Array.getLength(array) != 0) {
Object copied = Array.newInstance(array.getClass().getComponentType(), Array.getLength(array));
System.arraycopy(array, 0, copied, 0, Array.getLength(array));
shallowCopy.put(name, copied);
}
}
return eventBeanTypedEventFactory.adapterForTypedMap(shallowCopy, mapEventType);
}
}
| {
"pile_set_name": "Github"
} |
python-coveralls
coverage
nose
| {
"pile_set_name": "Github"
} |
vamp.persistence.key-value-store {
# type = "zookeeper"
zookeeper {
servers = ""
session-timeout = 5000
connect-timeout = 5000
}
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:47 ICT 2012 -->
<TITLE>
org.apache.fop.render.extensions.prepress (Apache FOP 1.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-16">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.fop.render.extensions.prepress (Apache FOP 1.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/fop/render/bitmap/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../org/apache/fop/render/intermediate/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/extensions/prepress/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package org.apache.fop.render.extensions.prepress
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/fop/render/extensions/prepress/PageBoundaries.html" title="class in org.apache.fop.render.extensions.prepress">PageBoundaries</A></B></TD>
<TD>This class is used to calculate the effective boundaries of a page including special-purpose
boxes used in prepress.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/fop/render/extensions/prepress/PageScale.html" title="class in org.apache.fop.render.extensions.prepress">PageScale</A></B></TD>
<TD>This class provides utility methods to parse the 'fox:scale' extension attribute.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/fop/render/bitmap/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../org/apache/fop/render/intermediate/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/extensions/prepress/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
# instant – transparent live-reloading
[](https://travis-ci.org/fgnass/instant)
Instant is ultra lightweight live-reload implementation with a unique feature set:
* Works in all browsers including mobile devices and IE6
* No browser plugin required
* Can be used as drop-in replacement for the express.static() middleware
* Production mode with zero overhead
* Automatic client code injection
## How it works
All static files that are served by the middleware are added to a watch list. Whenever one of these files is modified the client gets notified an reloads the resource. CSS files are updated without reloading the whole page.
Instant automatically injects a script-tag right before the closing `body` tag
of any HTML page (including dynamic ones) in order to load the client code.
The client uses
[server-sent events](http://en.wikipedia.org/wiki/Server-sent_events) to
listen for updates. Browsers that don't support EventSource will fall back to a
[hidden iframe](http://en.wikipedia.org/wiki/Comet_%28programming%29#Hidden_iframe).
## Usage
```js
var express = require('express');
var instant = require('instant');
var app = express();
app.use(instant(__dirname + '/static'));
```
If `$NODE_ENV` is set to `production` or `{ bypass: true }` is passed as option, instant will behave just like `express.static()` with no additional overhead.
### Reloading dynamic files
The instant middlware also exposes a `.reload()` function that can be called to
reload arbitrary URLs. This can be useful if you want to reload scripts or
stylesheets that have been processed/compiled on the fly.
Note: If you don't want to server any static files at all you can safely omit
the `root` argument.
```js
var express = require('express');
var instant = require('instant');
var app = express();
var ins = instant();
app.use(ins);
app.get('/tick', function(req, res) {
res.send('Current date: ' + new Date());
});
// Trigger a reload of the page every 10 seconds:
setInterval(function() {
ins.reload('/tick');
}, 10000);
```
### Options
The following options are supported:
* __bypass__ If set to `true` instant will behave just like express.static(). Defaults to `process.env.NODE_ENV == 'production'`
* __watch__ List of file extensions to watch. Defaults to `['html', 'js', 'css']`
* __prefix__ A prefix to add to the URLs under which the client script and the EventSource are exposed. Defaults to `'/instant'`
* __delay__ Amount of time in milliseconds to wait before triggering a reload. Defaults to `10`
All other options like `etag`, `dotfiles`, `index`, etc. are passed on to [send](https://www.npmjs.com/package/send).
## instant(1)
There is also an `instant` binary that can be used to spawn a development
server in the current directory.
The [instant-server](https://github.com/fgnass/instant-server) is packaged as
speparate module and can be installed via npm:
```
npm install -g instant-server
```

### The MIT License (MIT)
Copyright (c) 2013-2015 Felix Gnass
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.
| {
"pile_set_name": "Github"
} |
/*
* Warewolf - Once bitten, there's no going back
* Copyright 2019 by Warewolf Ltd <alpha@warewolf.io>
* Licensed under GNU Affero General Public License 3.0 or later.
* Some rights reserved.
* Visit our website for more information <http://warewolf.io/>
* AUTHORS <http://warewolf.io/authors.php> , CONTRIBUTORS <http://warewolf.io/contributors.php>
* @license GNU Affero General Public License <http://www.gnu.org/licenses/agpl-3.0.html>
*/
using System;
using Warewolf.Options;
namespace Warewolf.Data.Decisions.Operations
{
/// <summary>
/// Is Not Hex Decision
/// </summary>
public class IsNotHex : IDecisionOperation
{
public bool Invoke(string[] cols)
{
if (!string.IsNullOrEmpty(cols[0]))
{
return !cols[0].IsHex();
}
return false;
}
public Enum HandlesType() => enDecisionType.IsNotHex;
}
}
| {
"pile_set_name": "Github"
} |
import {CLOUD_FLAGS, OSS_FLAGS} from 'src/shared/selectors/flags'
describe("getting the user's feature flags", () => {
beforeEach(() => {
jest.resetModules()
})
it('gets the OSS flags by default if CLOUD is not enabled', () => {
jest.mock('src/shared/constants/index', () => ({
CLOUD: false,
CLOUD_BILLING_VISIBLE: true,
}))
const {getUserFlags} = require('src/shared/utils/featureFlag')
const flags = getUserFlags()
expect(flags).toEqual(OSS_FLAGS)
})
it('gets the cloud flags if CLOUD is enabled', () => {
jest.mock('src/shared/constants/index', () => ({
CLOUD: true,
CLOUD_BILLING_VISIBLE: false,
}))
const {getUserFlags} = require('src/shared/utils/featureFlag')
const flags = getUserFlags()
expect(flags).toEqual(CLOUD_FLAGS)
})
})
// todo: test the dadgum isFlagEnabled function
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2013,2015 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// <boost/thread/concurrent_queues/sync_deque.hpp>
// class sync_deque<T>
// sync_deque();
#define BOOST_THREAD_VERSION 4
#include <boost/thread/concurrent_queues/sync_deque.hpp>
#include <boost/detail/lightweight_test.hpp>
class non_copyable
{
BOOST_THREAD_MOVABLE_ONLY(non_copyable)
int val;
public:
non_copyable(int v) : val(v){}
non_copyable(BOOST_RV_REF(non_copyable) x): val(x.val) {}
non_copyable& operator=(BOOST_RV_REF(non_copyable) x) { val=x.val; return *this; }
bool operator==(non_copyable const& x) const {return val==x.val;}
template <typename OSTREAM>
friend OSTREAM& operator <<(OSTREAM& os, non_copyable const&x )
{
os << x.val;
return os;
}
};
int main()
{
{
// default queue invariants
boost::sync_deque<int> q;
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// empty queue try_pull fails
boost::sync_deque<int> q;
int i;
BOOST_TEST( boost::queue_op_status::empty == q.try_pull_front(i));
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// empty queue push rvalue/copyable succeeds
boost::sync_deque<int> q;
q.push_back(1);
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue push lvalue/copyable succeeds
boost::sync_deque<int> q;
int i;
q.push_back(i);
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
{
// empty queue push rvalue/non_copyable succeeds
boost::sync_deque<non_copyable> q;
q.push_back(non_copyable(1));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#endif
{
// empty queue push rvalue/non_copyable succeeds
boost::sync_deque<non_copyable> q;
non_copyable nc(1);
q.push_back(boost::move(nc));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue push rvalue succeeds
boost::sync_deque<int> q;
q.push_back(1);
q.push_back(2);
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 2u);
BOOST_TEST(! q.closed());
}
{
// empty queue push lvalue succeeds
boost::sync_deque<int> q;
int i;
q.push_back(i);
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue try_push rvalue/copyable succeeds
boost::sync_deque<int> q;
BOOST_TEST(boost::queue_op_status::success == q.try_push_back(1));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue try_push rvalue/copyable succeeds
boost::sync_deque<int> q;
BOOST_TEST(boost::queue_op_status::success == q.try_push_back(1));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
{
// empty queue try_push rvalue/non-copyable succeeds
boost::sync_deque<non_copyable> q;
BOOST_TEST(boost::queue_op_status::success ==q.try_push_back(non_copyable(1)));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#endif
{
// empty queue try_push rvalue/non-copyable succeeds
boost::sync_deque<non_copyable> q;
non_copyable nc(1);
BOOST_TEST(boost::queue_op_status::success == q.try_push_back(boost::move(nc)));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue try_push lvalue succeeds
boost::sync_deque<int> q;
int i=1;
BOOST_TEST(boost::queue_op_status::success == q.try_push_back(i));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// empty queue try_push rvalue succeeds
boost::sync_deque<int> q;
BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push_back(1));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
{
// empty queue nonblocking_push_back rvalue/non-copyable succeeds
boost::sync_deque<non_copyable> q;
BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push_back(non_copyable(1)));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
#endif
{
// empty queue nonblocking_push_back rvalue/non-copyable succeeds
boost::sync_deque<non_copyable> q;
non_copyable nc(1);
BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push_back(boost::move(nc)));
BOOST_TEST(! q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 1u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
int i;
q.pull_front(i);
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc2(2);
q.pull_front(nc2);
BOOST_TEST_EQ(nc1, nc2);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
int i = q.pull_front();
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc = q.pull_front();
BOOST_TEST_EQ(nc, nc1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue try_pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
int i;
BOOST_TEST(boost::queue_op_status::success == q.try_pull_front(i));
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue try_pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc(2);
BOOST_TEST(boost::queue_op_status::success == q.try_pull_front(nc));
BOOST_TEST_EQ(nc, nc1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue nonblocking_pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
int i;
BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull_front(i));
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue nonblocking_pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc(2);
BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull_front(nc));
BOOST_TEST_EQ(nc, nc1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue wait_pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc(2);
BOOST_TEST(boost::queue_op_status::success == q.wait_pull_front(nc));
BOOST_TEST_EQ(nc, nc1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue wait_pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
int i;
BOOST_TEST(boost::queue_op_status::success == q.wait_pull_front(i));
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// 1-element queue wait_pull_front succeed
boost::sync_deque<non_copyable> q;
non_copyable nc1(1);
q.push_back(boost::move(nc1));
non_copyable nc(2);
BOOST_TEST(boost::queue_op_status::success == q.wait_pull_front(nc));
BOOST_TEST_EQ(nc, nc1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(! q.closed());
}
{
// closed invariants
boost::sync_deque<int> q;
q.close();
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(q.closed());
}
{
// closed queue push fails
boost::sync_deque<int> q;
q.close();
try {
q.push_back(1);
BOOST_TEST(false);
} catch (...) {
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(q.closed());
}
}
{
// 1-element closed queue pull succeed
boost::sync_deque<int> q;
q.push_back(1);
q.close();
int i;
q.pull_front(i);
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(q.closed());
}
{
// 1-element closed queue wait_pull_front succeed
boost::sync_deque<int> q;
q.push_back(1);
q.close();
int i;
BOOST_TEST(boost::queue_op_status::success == q.wait_pull_front(i));
BOOST_TEST_EQ(i, 1);
BOOST_TEST(q.empty());
BOOST_TEST(! q.full());
BOOST_TEST_EQ(q.size(), 0u);
BOOST_TEST(q.closed());
}
{
// closed empty queue wait_pull_front fails
boost::sync_deque<int> q;
q.close();
BOOST_TEST(q.empty());
BOOST_TEST(q.closed());
int i;
BOOST_TEST(boost::queue_op_status::closed == q.wait_pull_front(i));
BOOST_TEST(q.empty());
BOOST_TEST(q.closed());
}
return boost::report_errors();
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.core.application.service;
import com.abixen.platform.common.domain.model.enumtype.PermissionName;
import com.abixen.platform.core.domain.model.Module;
import com.abixen.platform.core.domain.model.User;
import com.abixen.platform.core.domain.repository.ModuleRepository;
import com.abixen.platform.core.domain.repository.PageRepository;
import com.abixen.platform.core.domain.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@Slf4j
public class SecurityServiceTest {
@Resource
private UserRepository userRepository;
@Resource
private PageRepository pageRepository;
@Resource
private ModuleRepository moduleRepository;
@Autowired
private SecurityService securityService;
//@Test
/* public void userHasPermissionToViewPageOld() {
log.debug("userHasPermissionToViewPage()");
//User user = userRepository.findOne(1L);
//Page page = pageRepository.findOne(1L);
Boolean hasPermission = true;//securityService.hasUserPermissionToPage(user, PermissionName.PAGE_VIEW, page);
assertTrue(hasPermission);
}*/
//@Test
/*public void userHasPermissionToViewModule() {
log.debug("userHasPermissionToViewModule()");
//User user = userRepository.findOne(1L);
//Module module = moduleRepository.findOne(1L);
log.debug("modules: " + moduleRepository.findAll());
Boolean hasPermission = false; //securityService.hasUserPermissionToModule(user, PermissionName.MODULE_VIEW, module);
assertFalse(hasPermission);
}*/
/**
* The user admin has permission to view the module with id equal 1, because he got this permission by ACL configuration.
*/
@Ignore
@Test
public void userAdminHasPermissionToViewModule() {
log.debug("userAdminHasPermissionToViewModule()");
User admin = userRepository.findOne(1L);
Module module = moduleRepository.findOne(2L);
Boolean hasPermission = securityService.hasUserPermissionToObject(admin, PermissionName.MODULE_VIEW, module);
assertFalse(hasPermission);
}
/**
* The user admin has permission to add the module with id equal 1, because he got this permission by ACL configuration.
*/
@Ignore
@Test
public void userAdminHasPermissionToAddModule() {
log.debug("userAdminHasPermissionToAddModule()");
User admin = userRepository.findOne(1L);
Module module = moduleRepository.findOne(2L);
Boolean hasPermission = securityService.hasUserPermissionToObject(admin, PermissionName.MODULE_ADD, module);
assertTrue(hasPermission);
}
/**
* The user admin has permission to edit the module with id equal 1, because he is the owner.
*/
@Ignore
@Test
public void userAdminHasPermissionToEditModule() {
log.debug("userAdminHasPermissionToEditModule()");
User admin = userRepository.findOne(1L);
Module module = moduleRepository.findOne(2L);
Boolean hasPermission = securityService.hasUserPermissionToObject(admin, PermissionName.MODULE_EDIT, module);
assertTrue(hasPermission);
}
/**
* The user admin has not permission to delete the module with id equal 1,
* because he got neither ACL nor appropriate role.
*/
@Ignore
@Test
public void userAdminHasNotPermissionToDeleteModule() {
log.debug("userAdminHasNotPermissionToDeleteModule()");
User admin = userRepository.findOne(1L);
Module module = moduleRepository.findOne(2L);
Boolean hasPermission = securityService.hasUserPermissionToObject(admin, PermissionName.MODULE_DELETE, module);
assertTrue(hasPermission);
}
/**
* The user editor has permission to view the module with id equal 1,
* because he got this permission by assigning to appropriate role contains it.
*/
@Ignore
@Test
public void userEditorHasPermissionToViewModule() {
log.debug("userEditorHasPermissionToViewModule()");
User editor = userRepository.findOne(3L);
Module module = moduleRepository.findOne(2L);
Boolean hasPermission = securityService.hasUserPermissionToObject(editor, PermissionName.MODULE_VIEW, module);
assertTrue(hasPermission);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012 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 "webrtc/modules/audio_coding/neteq/decoder_database.h"
#include <utility> // pair
#include "webrtc/api/audio_codecs/audio_decoder.h"
#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/logging.h"
namespace webrtc {
DecoderDatabase::DecoderDatabase(
const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
: active_decoder_type_(-1),
active_cng_decoder_type_(-1),
decoder_factory_(decoder_factory) {}
DecoderDatabase::~DecoderDatabase() = default;
DecoderDatabase::DecoderInfo::DecoderInfo(const SdpAudioFormat& audio_format,
AudioDecoderFactory* factory,
const std::string& codec_name)
: name_(codec_name),
audio_format_(audio_format),
factory_(factory),
external_decoder_(nullptr),
cng_decoder_(CngDecoder::Create(audio_format)),
subtype_(SubtypeFromFormat(audio_format)) {}
DecoderDatabase::DecoderInfo::DecoderInfo(const SdpAudioFormat& audio_format,
AudioDecoderFactory* factory)
: DecoderInfo(audio_format, factory, audio_format.name) {}
DecoderDatabase::DecoderInfo::DecoderInfo(NetEqDecoder ct,
AudioDecoderFactory* factory)
: DecoderInfo(*NetEqDecoderToSdpAudioFormat(ct), factory) {}
DecoderDatabase::DecoderInfo::DecoderInfo(const SdpAudioFormat& audio_format,
AudioDecoder* ext_dec,
const std::string& codec_name)
: name_(codec_name),
audio_format_(audio_format),
factory_(nullptr),
external_decoder_(ext_dec),
subtype_(Subtype::kNormal) {
RTC_CHECK(ext_dec);
}
DecoderDatabase::DecoderInfo::DecoderInfo(DecoderInfo&&) = default;
DecoderDatabase::DecoderInfo::~DecoderInfo() = default;
AudioDecoder* DecoderDatabase::DecoderInfo::GetDecoder() const {
if (subtype_ != Subtype::kNormal) {
// These are handled internally, so they have no AudioDecoder objects.
return nullptr;
}
if (external_decoder_) {
RTC_DCHECK(!decoder_);
RTC_DCHECK(!cng_decoder_);
return external_decoder_;
}
if (!decoder_) {
// TODO(ossu): Keep a check here for now, since a number of tests create
// DecoderInfos without factories.
RTC_DCHECK(factory_);
decoder_ = factory_->MakeAudioDecoder(audio_format_);
}
RTC_DCHECK(decoder_) << "Failed to create: " << audio_format_;
return decoder_.get();
}
bool DecoderDatabase::DecoderInfo::IsType(const char* name) const {
return STR_CASE_CMP(audio_format_.name.c_str(), name) == 0;
}
bool DecoderDatabase::DecoderInfo::IsType(const std::string& name) const {
return IsType(name.c_str());
}
rtc::Optional<DecoderDatabase::DecoderInfo::CngDecoder>
DecoderDatabase::DecoderInfo::CngDecoder::Create(const SdpAudioFormat& format) {
if (STR_CASE_CMP(format.name.c_str(), "CN") == 0) {
// CN has a 1:1 RTP clock rate to sample rate ratio.
const int sample_rate_hz = format.clockrate_hz;
RTC_DCHECK(sample_rate_hz == 8000 || sample_rate_hz == 16000 ||
sample_rate_hz == 32000 || sample_rate_hz == 48000);
return rtc::Optional<DecoderDatabase::DecoderInfo::CngDecoder>(
{sample_rate_hz});
} else {
return rtc::Optional<CngDecoder>();
}
}
DecoderDatabase::DecoderInfo::Subtype
DecoderDatabase::DecoderInfo::SubtypeFromFormat(const SdpAudioFormat& format) {
if (STR_CASE_CMP(format.name.c_str(), "CN") == 0) {
return Subtype::kComfortNoise;
} else if (STR_CASE_CMP(format.name.c_str(), "telephone-event") == 0) {
return Subtype::kDtmf;
} else if (STR_CASE_CMP(format.name.c_str(), "red") == 0) {
return Subtype::kRed;
}
return Subtype::kNormal;
}
bool DecoderDatabase::Empty() const { return decoders_.empty(); }
int DecoderDatabase::Size() const { return static_cast<int>(decoders_.size()); }
void DecoderDatabase::Reset() {
decoders_.clear();
active_decoder_type_ = -1;
active_cng_decoder_type_ = -1;
}
std::vector<int> DecoderDatabase::SetCodecs(
const std::map<int, SdpAudioFormat>& codecs) {
// First collect all payload types that we'll remove or reassign, then remove
// them from the database.
std::vector<int> changed_payload_types;
for (const std::pair<uint8_t, const DecoderInfo&> kv : decoders_) {
auto i = codecs.find(kv.first);
if (i == codecs.end() || i->second != kv.second.GetFormat()) {
changed_payload_types.push_back(kv.first);
}
}
for (int pl_type : changed_payload_types) {
Remove(pl_type);
}
// Enter the new and changed payload type mappings into the database.
for (const auto& kv : codecs) {
const int& rtp_payload_type = kv.first;
const SdpAudioFormat& audio_format = kv.second;
RTC_DCHECK_GE(rtp_payload_type, 0);
RTC_DCHECK_LE(rtp_payload_type, 0x7f);
if (decoders_.count(rtp_payload_type) == 0) {
decoders_.insert(std::make_pair(
rtp_payload_type, DecoderInfo(audio_format, decoder_factory_.get())));
} else {
// The mapping for this payload type hasn't changed.
}
}
return changed_payload_types;
}
int DecoderDatabase::RegisterPayload(uint8_t rtp_payload_type,
NetEqDecoder codec_type,
const std::string& name) {
if (rtp_payload_type > 0x7F) {
return kInvalidRtpPayloadType;
}
// kCodecArbitrary is only supported through InsertExternal.
if (codec_type == NetEqDecoder::kDecoderArbitrary ||
!CodecSupported(codec_type)) {
return kCodecNotSupported;
}
const auto opt_format = NetEqDecoderToSdpAudioFormat(codec_type);
if (!opt_format) {
return kCodecNotSupported;
}
DecoderInfo info(*opt_format, decoder_factory_, name);
auto ret =
decoders_.insert(std::make_pair(rtp_payload_type, std::move(info)));
if (ret.second == false) {
// Database already contains a decoder with type |rtp_payload_type|.
return kDecoderExists;
}
return kOK;
}
int DecoderDatabase::RegisterPayload(int rtp_payload_type,
const SdpAudioFormat& audio_format) {
if (rtp_payload_type < 0 || rtp_payload_type > 0x7f) {
return kInvalidRtpPayloadType;
}
const auto ret = decoders_.insert(std::make_pair(
rtp_payload_type, DecoderInfo(audio_format, decoder_factory_.get())));
if (ret.second == false) {
// Database already contains a decoder with type |rtp_payload_type|.
return kDecoderExists;
}
return kOK;
}
int DecoderDatabase::InsertExternal(uint8_t rtp_payload_type,
NetEqDecoder codec_type,
const std::string& codec_name,
AudioDecoder* decoder) {
if (rtp_payload_type > 0x7F) {
return kInvalidRtpPayloadType;
}
if (!decoder) {
return kInvalidPointer;
}
const auto opt_db_format = NetEqDecoderToSdpAudioFormat(codec_type);
const SdpAudioFormat format = opt_db_format.value_or({"arbitrary", 0, 0});
std::pair<DecoderMap::iterator, bool> ret;
DecoderInfo info(format, decoder, codec_name);
ret = decoders_.insert(std::make_pair(rtp_payload_type, std::move(info)));
if (ret.second == false) {
// Database already contains a decoder with type |rtp_payload_type|.
return kDecoderExists;
}
return kOK;
}
int DecoderDatabase::Remove(uint8_t rtp_payload_type) {
if (decoders_.erase(rtp_payload_type) == 0) {
// No decoder with that |rtp_payload_type|.
return kDecoderNotFound;
}
if (active_decoder_type_ == rtp_payload_type) {
active_decoder_type_ = -1; // No active decoder.
}
if (active_cng_decoder_type_ == rtp_payload_type) {
active_cng_decoder_type_ = -1; // No active CNG decoder.
}
return kOK;
}
void DecoderDatabase::RemoveAll() {
decoders_.clear();
active_decoder_type_ = -1; // No active decoder.
active_cng_decoder_type_ = -1; // No active CNG decoder.
}
const DecoderDatabase::DecoderInfo* DecoderDatabase::GetDecoderInfo(
uint8_t rtp_payload_type) const {
DecoderMap::const_iterator it = decoders_.find(rtp_payload_type);
if (it == decoders_.end()) {
// Decoder not found.
return NULL;
}
return &it->second;
}
int DecoderDatabase::SetActiveDecoder(uint8_t rtp_payload_type,
bool* new_decoder) {
// Check that |rtp_payload_type| exists in the database.
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
if (!info) {
// Decoder not found.
return kDecoderNotFound;
}
RTC_CHECK(!info->IsComfortNoise());
RTC_DCHECK(new_decoder);
*new_decoder = false;
if (active_decoder_type_ < 0) {
// This is the first active decoder.
*new_decoder = true;
} else if (active_decoder_type_ != rtp_payload_type) {
// Moving from one active decoder to another. Delete the first one.
const DecoderInfo *old_info = GetDecoderInfo(active_decoder_type_);
RTC_DCHECK(old_info);
old_info->DropDecoder();
*new_decoder = true;
}
active_decoder_type_ = rtp_payload_type;
return kOK;
}
AudioDecoder* DecoderDatabase::GetActiveDecoder() const {
if (active_decoder_type_ < 0) {
// No active decoder.
return NULL;
}
return GetDecoder(active_decoder_type_);
}
int DecoderDatabase::SetActiveCngDecoder(uint8_t rtp_payload_type) {
// Check that |rtp_payload_type| exists in the database.
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
if (!info) {
// Decoder not found.
return kDecoderNotFound;
}
if (active_cng_decoder_type_ >= 0 &&
active_cng_decoder_type_ != rtp_payload_type) {
// Moving from one active CNG decoder to another. Delete the first one.
RTC_DCHECK(active_cng_decoder_);
active_cng_decoder_.reset();
}
active_cng_decoder_type_ = rtp_payload_type;
return kOK;
}
ComfortNoiseDecoder* DecoderDatabase::GetActiveCngDecoder() const {
if (active_cng_decoder_type_ < 0) {
// No active CNG decoder.
return NULL;
}
if (!active_cng_decoder_) {
active_cng_decoder_.reset(new ComfortNoiseDecoder);
}
return active_cng_decoder_.get();
}
AudioDecoder* DecoderDatabase::GetDecoder(uint8_t rtp_payload_type) const {
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
return info ? info->GetDecoder() : nullptr;
}
bool DecoderDatabase::IsType(uint8_t rtp_payload_type, const char* name) const {
const DecoderInfo* info = GetDecoderInfo(rtp_payload_type);
return info && info->IsType(name);
}
bool DecoderDatabase::IsType(uint8_t rtp_payload_type,
const std::string& name) const {
return IsType(rtp_payload_type, name.c_str());
}
bool DecoderDatabase::IsComfortNoise(uint8_t rtp_payload_type) const {
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
return info && info->IsComfortNoise();
}
bool DecoderDatabase::IsDtmf(uint8_t rtp_payload_type) const {
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
return info && info->IsDtmf();
}
bool DecoderDatabase::IsRed(uint8_t rtp_payload_type) const {
const DecoderInfo *info = GetDecoderInfo(rtp_payload_type);
return info && info->IsRed();
}
int DecoderDatabase::CheckPayloadTypes(const PacketList& packet_list) const {
PacketList::const_iterator it;
for (it = packet_list.begin(); it != packet_list.end(); ++it) {
if (!GetDecoderInfo(it->payload_type)) {
// Payload type is not found.
LOG(LS_WARNING) << "CheckPayloadTypes: unknown RTP payload type "
<< static_cast<int>(it->payload_type);
return kDecoderNotFound;
}
}
return kOK;
}
} // namespace webrtc
| {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"# Ch `04`: Concept `01`"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Linear regression for classification (just for demonstrative purposes)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Import the usual libraries:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import tensorflow as tf\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Let's say we have numbers that we want to classify. They'll just be 1-dimensional values. Numbers close to 5 will be given the label `[0]`, and numbers close to 2 will be given the label `[1]`, as designed here:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.collections.PathCollection at 0x7f5be2699fd0>"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEACAYAAACwB81wAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAElFJREFUeJzt3H+M5Hd93/Hn63w+e417hgMDiY3vaAyBEhzOrmyrpHSQ\nSX2kyI4UiZyTUIJSJ1JruUqVym7UyGs1f8Sp1ISIJMSt45iEy6YQQZw0hoPCJCKp4yv+gXO+yxnQ\nOjYkvsWlRQ4kcsy7f+z4WNazuzM3s/ODz/Mhjfz98Z7P5z0z59d857M7m6pCkvStb8e0G5AkTYaB\nL0mNMPAlqREGviQ1wsCXpEYY+JLUiLEEfpI7kjyZ5DMbnP+hJA/1bp9K8vpxzCtJGty4rvDvBK7e\n5PzngTdV1XcDPwv81zHNK0ka0M5xDFJVn0qyd5Pz967ZvRe4YBzzSpIGN401/H8F3DOFeSWpaWO5\nwh9UkjcD7wK+Z5LzSpImGPhJLgFuBw5U1Zc3qPEP+0jSaaiqbFUzziWd9G7PP5FcBPwu8I6q+txm\ng1TV3N5uueWWqfdg/9Pvw/7n7zbPvVcNfp08liv8JIeADvDiJH8J3ALsWs3vuh34GWAP8CtJAjxT\nVZePY25J0mDG9Vs6P7TF+euB68cxlyTp9PhN2zHqdDrTbmEk9j9d9j8989z7MDLM+s92S1Kz1I8k\nzYMk1IR/aCtJmmEGviQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWqEgS9JjTDwJakRBr4kNcLAl6RG\nGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQIA1+SGjGWwE9yR5Ink3xm\nk5pfSvJokgeTvGEc80qSBjeuK/w7gas3OpnkrcB3VNWrgJ8A3jumeTe1srLCkSNHWFlZGercdvZz\n+PBhDh8+/E3zTqOXUfXreRKPY9Ze01maX9pSVY3lBuwFPrPBufcCP7hm/xjwsj51NS6HDi3VwsKe\nOu+8S2thYU8dOrQ00LntcujQUu3adV7BxQXn1JlnnluHDi1NpZdR9et5Eo9j1l7TQXuTtlsvO7fO\n6UGKBhpo88D/feCfrNn/OHBpn7qxPPiTJ0/WwsKegocKquChWljYUydPntz03HbpNye8qM46a/fE\nexnVRs/f2We/cFsfx6y9poP2Jk3CoIG/c3KfJQazuLh4arvT6dDpdIYeY3l5mV279vG1r13SO3IJ\nZ565l+XlZYANz51//vmjtL5pPzt2vAL4xpywj+Qpdux40Tcd3+5eRtXvud2x40Lg79jOxzFrr+mg\nvc3q66j51u126Xa7w99xkHeFQW4Mt6RznG1c0pm1q0Gv8LdvXq/wpeks6ewDHt7g3PcB/6O3fSVw\n7wZ1Y3sCnltT3b17/4brvf3ObZdvrOF/R981/En2Mqp+PU/icczaazpob9J2GzTws1o7miSHgA7w\nYuBJ4BZgV6+J23s17wEOAH8DvKuq7u8zTo2jn+esrKywvLzMvn37nvfRerNz22VlZYUHHngAgP37\n95+adxq9jKpfz5N4HLP2ms7S/GpXEqoqW9aNM2BHNe7Al6QWDBr4ftNWkhph4EtSIwx8SWqEgS9J\njTDwJakRBr4kNcLAl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQI\nA1+SGmHgS1IjDHxJaoSBL0mNMPAlqREGviQ1wsCXpEaMJfCTHEhyPMmJJDf1Of+KJJ9Icn+SB5O8\ndRzzSpIGl6oabYBkB3ACuAr4InAEOFhVx9fU/Bpwf1X9WpLXAn9YVa/sM1aN2o8ktSYJVZWt6sZx\nhX858GhVPVZVzwBLwLXrar4O7O5tvxD4whjmlSQNYecYxrgAeHzN/hOsvgmsdStwOMmNwDnAW8Yw\nryRpCOMI/EFcB9xZVb+Q5Ergt4DX9StcXFw8td3pdOh0OpPoT5LmRrfbpdvtDn2/cazhXwksVtWB\n3v7NQFXVbWtq/hy4uqq+0Nv/HHBFVX1p3Viu4UvSkCa5hn8EuDjJ3iS7gIPA3etqHqO3jNP7oe1Z\n68NekrS9Rg78qnoWuAE4DBwFlqrqWJJbk7ytV/ZTwPVJHgTeD7xz1HklScMZeUlnnFzSkaThTXJJ\nR5I0Bwx8SWqEgS9JjTDwJakRBr4kNcLAl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+\nJDXCwJekRhj4ktQIA1+SGmHgS1IjDHxJaoSBL0mNMPAlqREGviQ1wsCXpEYY+JLUiLEEfpIDSY4n\nOZHkpg1q3p7kaJKHk/zWOOaVJA0uVTXaAMkO4ARwFfBF4AhwsKqOr6m5GPgd4M1V9ZUkL6mqL/UZ\nq0btR5Jak4SqylZ147jCvxx4tKoeq6pngCXg2nU11wO/XFVfAegX9pKk7TWOwL8AeHzN/hO9Y2u9\nGvjOJJ9K8qdJrh7DvJKkIeyc4DwXA28CLgL+OMl3PXfFv9bi4uKp7U6nQ6fTmVCLkjQfut0u3W53\n6PuNYw3/SmCxqg709m8GqqpuW1Pzq8C9VXVXb//jwE1V9el1Y7mGL0lDmuQa/hHg4iR7k+wCDgJ3\nr6v5MPDmXmMvAV4FfH4Mc0uSBjRy4FfVs8ANwGHgKLBUVceS3Jrkbb2ajwJPJTkK/E/gp6rqy6PO\nLUka3MhLOuPkko4kDW+SSzqSpDlg4EtSIwx8SWqEgS9JjTDwJakRBr4kNcLAl6RGGPiS1AgDX5Ia\nYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQIA1+SGmHgS1IjDHxJaoSBL0mNMPAlqREG\nviQ1wsCXpEaMJfCTHEhyPMmJJDdtUvcDSb6e5NJxzCtJGtzIgZ9kB/Ae4GrgdcB1SV7Tp+5c4Ebg\n3lHnlCQNbxxX+JcDj1bVY1X1DLAEXNun7j8BPwf83RjmlCQNaRyBfwHw+Jr9J3rHTkmyH7iwqu4Z\nw3ySpNOwc7snSBLgvwDvXHt4o/rFxcVT251Oh06ns12tSdJc6na7dLvdoe+Xqhpp4iRXAotVdaC3\nfzNQVXVbb3838FngaVaD/uXAU8A1VXX/urFq1H4kqTVJqKoNL6RP1Y0h8M8A/gK4Cvgr4D7guqo6\ntkH9J4F/V1UP9Dln4EvSkAYN/JHX8KvqWeAG4DBwFFiqqmNJbk3ytn53YZMlHUnS9hj5Cn+cvMKX\npOFN7ApfkjQfDHxJaoSBL0mNMPAlqREGviQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWqEgS9JjTDw\nJakRBr4kNcLAl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktSIsQR+\nkgNJjic5keSmPud/MsnRJA8m+ViSV4xjXknS4EYO/CQ7gPcAVwOvA65L8pp1ZfcDl1XVG4DfBf7z\nqPNKkoYzjiv8y4FHq+qxqnoGWAKuXVtQVX9UVX/b270XuGAM80qShjCOwL8AeHzN/hNsHug/Btwz\nhnklSUPYOcnJkvwIcBnwzzaqWVxcPLXd6XTodDrb3pckzZNut0u32x36fqmqkSZOciWwWFUHevs3\nA1VVt62rewvwbuBNVfXUBmPVqP1IUmuSUFXZqm4cSzpHgIuT7E2yCzgI3L2umf3Ae4FrNgp7SdL2\nGjnwq+pZ4AbgMHAUWKqqY0luTfK2XtnPAy8APpDkgSQfHnVeSdJwRl7SGSeXdCRpeJNc0pEkzQED\nX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQIA1+SGmHgS1IjDHxJaoSBL0mNMPAl\nqREGviQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWqEgS9JjTDwJakRBr4kNWIsgZ/kQJLjSU4kuanP\n+V1JlpI8muR/JbloHPNKkgY3cuAn2QG8B7gaeB1wXZLXrCv7MeD/VNWrgF8Efn7UeaXTsbKywpEj\nR1hZWdn02HbON2ztoGNM4nEcO3ZsJp6rSZi1fsaiqka6AVcC96zZvxm4aV3NR4ArettnACsbjFXS\ndjl0aKkWFvbUeeddWgsLe+rQoaW+x7ZzvmFrBx1jEo9jYeH1BQu1sPDKqT5XkzBr/Wyll51b5/Ug\nRZsOAD8A3L5m/0eAX1pX8zDw7Wv2HwX29BlrW58UtevkyZO1sLCn4KGCKniozj77hc87trCwp06e\nPLkt82009ka1jzzyyEBjDDPXOB4H7Cn45FSeq0mYtX4GMWjg75zEp4g+stGJxcXFU9udTodOpzOB\ndvStbnl5mV279vG1r13SO3IJZ5zxUmAB+MaxM8/cy/LyMueff/7Y59to7I1q77vvvoHGGGaucTwO\n2Au8YCrP1STMWj/9dLtdut3u8Hcc5F1hsxurSzofWbPfb0nnHr55SefkBmNt67ug2uUV/vgeh1f4\ns4cJLumcAXyW1bf9XcCDwGvX1fxr4Fd62weBpQ3G2uanRS17bl129+79z1vDX3tsO+cbtnbQMSbx\nOBYWvqtgoc4+e99Un6tJmLV+tjJo4Ge1djRJDgDvZvW3fu6oqp9LcitwpKr+IMlZwG8C+4GngINV\ntdxnnBpHP9JGVlZWWF5eZt++fac+nvc7tp3zDVs76BiTeBznnnsuTz/99NSfq0mYtX42k4Sq2nCp\n/FTdLAWsgS9Jwxs08P2mrSQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWqEgS9JjTDwJakRBr4kNcLA\nl6RGGPiS1AgDX5IaYeBLUiMMfElqhIEvSY0w8CWpEQa+JDXCwJekRhj4ktQIA1+SGmHgS1IjDHxJ\nasRIgZ/kRUkOJ/mLJB9Ncl6fmu9O8qdJHk7yYJK3jzKnJOn0jHqFfzPw8ar6TuATwH/oU/M3wDuq\n6vXAW4FfTLJ7xHlnUrfbnXYLI7H/6bL/6Znn3ocxauBfC9zV274L+P71BVX12ar6XG/7r4CTwPkj\nzjuT5v0fjf1Pl/1Pzzz3PoxRA/+lVfUkQFX9NfDSzYqTXA6c+dwbgCRpcnZuVZDkY8DL1h4CCviP\nfcprk3G+DXgf8I4he5QkjUGqNszore+cHAM6VfVkkpcDn6yq1/ap+wdAF/jZqvrQJuOdfjOS1LCq\nylY1W17hb+Fu4EeB24B3Ar+3viDJmcCHgbs2C3sYrGFJ0ukZ9Qp/D/DfgVcAjwFvr6r/m+Qy4Ceq\n6seT/DDw68BRvrEc9KNV9ZmRu5ckDWykwJckzY+Z+aZtkgNJjic5keSmafczjCR3JHkyyVx+akly\nYZJPJDna+4LcjdPuaRhJzkryZ0ke6PV/y7R7GlaSHUnuT3L3tHsZVpLlJA/1nv/7pt3PsJKcl+QD\nSY71/h+4Yto9DSrJq3vP+/29//6/zf7/nYkr/CQ7gBPAVcAXgSPAwao6PtXGBpTke4CngfdV1SXT\n7mdYvR+4v7yqHkxyLvBp4Np5ef4BkpxTVV9NcgbwJ8CNVTU34ZPkJ4HLgN1Vdc20+xlGks8Dl1XV\nl6fdy+lI8hvAH1XVnUl2AudU1Vem3NbQejn6BHBFVT3er2ZWrvAvBx6tqseq6hlgidUvdc2FqvoU\nMJf/2GH1OxRV9WBv+2ngGHDBdLsaTlV9tbd5Fqu/jDD9K5kBJbkQ+D7gv027l9MUZidLhtL71v8/\nrao7Aarq7+cx7HveAnxuo7CH2XmRLgDWNvkEcxY43yqS7APeAPzZdDsZTm9J5AHgr4GPVdWRafc0\nhF8A/j1z9Ca1TgEfTXIkyfXTbmZIrwS+lOTO3rLI7UkWpt3UafpB4Lc3K5iVwNcM6C3nfBD4t70r\n/blRVV+vqv3AhcAVSf7RtHsaRJJ/ATzZ+4SV3m3evLGq/jGrn1L+TW+Jc17sBC4FfrmqLgW+yurf\nCJsrvV9/vwb4wGZ1sxL4XwAuWrN/Ye+YJqS3dvlB4Der6nnfp5gXvY/jnwQOTLuXAb0RuKa3Dv7b\nwJuTvG/KPQ2l9zeyqKoV4EOsLtHOiyeAx6vqf/f2P8jqG8C8eSvw6d5rsKFZCfwjwMVJ9ibZBRxk\n9Utd82Rer86e8+vAI1X17mk3MqwkL3nuT3P3Po5/LzAXP3Cuqp+uqouq6h+y+u/+E1X1L6fd16CS\nnNP7ZEiSFwD/HPjz6XY1uN7fAns8yat7h64CHpliS6frOrZYzoHRv2k7FlX1bJIbgMOsvgndUVXH\nptzWwJIcAjrAi5P8JXDLcz8EmgdJ3gj8MPBwbx28gJ+uqo9Mt7OBfRtwV++3FHYAv1NVfzjlnlrx\nMuBDvT+LshN4f1UdnnJPw7oReH9vWeTzwLum3M9QkpzD6g9sf3zL2ln4tUxJ0vablSUdSdI2M/Al\nqREGviQ1wsCXpEYY+JLUCANfkhph4EtSIwx8SWrE/wf7PkEAQHmpsgAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x7f5be23c6c50>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"x_label0 = np.random.normal(5, 1, 10)\n",
"x_label1 = np.random.normal(2, 1, 10)\n",
"xs = np.append(x_label0, x_label1)\n",
"labels = [0.] * len(x_label0) + [1.] * len(x_label1)\n",
"\n",
"plt.scatter(xs, labels)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Define the hyper-parameters, placeholders, and variables:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"learning_rate = 0.001\n",
"training_epochs = 1000\n",
"\n",
"X = tf.placeholder(\"float\")\n",
"Y = tf.placeholder(\"float\")\n",
"\n",
"w = tf.Variable([0., 0.], name=\"parameters\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Define the model:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def model(X, w):\n",
" return tf.add(tf.multiply(w[1], tf.pow(X, 1)),\n",
" tf.multiply(w[0], tf.pow(X, 0)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Given a model, define the cost function:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"y_model = model(X, w)\n",
"cost = tf.reduce_sum(tf.square(Y-y_model))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Set up the training op, and also introduce a couple ops to calculate some metrics, such as accuracy:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n",
"correct_prediction = tf.equal(Y, tf.to_float(tf.greater(y_model, 0.5)))\n",
"accuracy = tf.reduce_mean(tf.to_float(correct_prediction))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Prepare the session:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"sess = tf.Session()\n",
"init = tf.global_variables_initializer()\n",
"sess.run(init)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Run the training op multiple times on the input data:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 8.63226\n",
"100 3.23953\n",
"200 2.14632\n",
"300 1.90881\n",
"400 1.8572\n",
"500 1.84599\n",
"600 1.84356\n",
"700 1.84303\n",
"800 1.84291\n",
"900 1.84289\n"
]
}
],
"source": [
"for epoch in range(training_epochs):\n",
" sess.run(train_op, feed_dict={X: xs, Y: labels})\n",
" current_cost = sess.run(cost, feed_dict={X: xs, Y: labels})\n",
" if epoch % 100 == 0:\n",
" print(epoch, current_cost)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Show some final metrics/results:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"learned parameters [ 1.28786051 -0.25033307]\n",
"accuracy 0.95\n"
]
}
],
"source": [
"w_val = sess.run(w)\n",
"print('learned parameters', w_val)\n",
"\n",
"print('accuracy', sess.run(accuracy, feed_dict={X: xs, Y: labels}))\n",
"\n",
"sess.close()"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"Plot the learned function"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX8AAAEACAYAAABbMHZzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHZRJREFUeJzt3XmcVXX9x/HXB2ZGhmWGRUATBHLPXFhEwG1MTSSXREVQ\nfmFa9uuXaVkmagY9/KXmUqloahhujWhqGqiIiONWyCLiAgguw6LAjGm/tHwU6uf3x/dKI81y79w7\n8733nvfz8ZiHdzn3nPfMQz733M/9nHPM3RERkWTpEDuAiIi0PxV/EZEEUvEXEUkgFX8RkQRS8RcR\nSSAVfxGRBMpJ8TezW8xsk5m92MTzh5jZX83s+dTPj3OxXRERaZ2SHK1nBnAdcHszyzzl7sfmaHsi\nIpKFnOz5u/szwHstLGa52JaIiGSvPXv+I8xsqZk9ZGZfaMftiojIVnLV9mnJEmCAu//DzI4CHgB2\nbadti4jIVtql+Lv7Bw1uP2JmN5hZT3d/d+tlzUwnGxIRyZC7Z9Raz2Xbx2iir29mfRvcHg5YY4X/\nU+5ekD9TpkyJnkH54+dQ/sL8KeT8rZGTPX8zqwaqgF5mthaYApSFOu43Ayea2beBzcCHwMm52K6I\niLROToq/u5/SwvPXA9fnYlsiIpI9HeGbQ1VVVbEjZEX541L+uAo9f6astf2itmJmnm+ZRETymZnh\nEb/wFRGRAqHiLyKSQCr+IiIJpOIvIpJAKv4iIgmk4i8ikkAq/iIiCaTiLyKSQCr+ObR+fewEIiLp\nUfHPkY0bYcgQuPlm0AHKIpLvdHqHHFq1CsaOheHD4frrobw8diIRSQKd3iGyXXeFBQvgww/hgAPg\njTdiJxIRaZyKf4517QrV1XDaaTByJDz8cOxEIiL/SW2fNvTss3DyyXDGGfCTn0DHjrETiUgxak3b\nR8W/jW3cCOPHh/7/nXdCr16xE4lIsVHPPw9ttx3Mmwdf/CIMGwZLlsROJCKi4t8uSkrgyivDz+jR\nMH167EQiknRq+7SzlSvDOOioUTBtGnTqFDuRiBQ6tX0KwO67w8KF8P77YRy0tjZ2IhFJIhX/CLp2\nhZkzYeJE2H9/mDMndiIRSRq1fSJ7+ukwDXTmmXDxxdBBb8cikiGNehaoDRvC8QBdu4Zx0J49YycS\nkUKinn+B2n57ePzx8H3A0KHw/POxE4lIsVPxzxOlpfCLX8DPfw5HHgkzZsROJCLFTG2fPLR8OZxw\nAhx0EFx7rcZBRaR5avsUiS98IYyDvvdeeANYsyZ2IhEpNjkp/mZ2i5ltMrMXm1nmWjNbbWYvmNm+\nudhuMevWDe65J0wC7b8/zJ0bO5GIFJNc7fnPAI5s6kkzOwrYyd13Ab4F3Jij7RY1M/jBD+Duu8Mp\noi+5BD75JHYqESkGOev5m9kAYJa7793IczcCT7j73an7K4Aqd9/UyLJF3/Ovr6+ntraWgQMHAmy5\n3bt37yZf8/bbMG4cdO8Od9wBH31Uz9KlSwHo378/H3zwQYvraK+suXhtS+vL9e8pUsha0/PH3XPy\nAwwAXmziuVnAqAb35wFDmljWi1l19UwvL+/plZVDvLS0m5eVVXpl5RAvL+/p1dUzm33tv/7lfs45\n7n36vO8lJQc67OzQ2aHMy8v3Smsdrc1aVlbppaVd086aze/Z0vpy/XuKFLpU3cysZmf6giZXpOLf\norq6Oi8v7+mwzKHOoUfqtjss8/Lynl5XV9fiOkpLz3DYvOV1YT11aa8j86yZbScXv2dLWXL1e4oU\ng9YU/5IsP22k6y2gf4P7/VKPNWrq1KlbbldVVVFVVdVWudpVbW0tZWUD+fDDvYFFwCDg0y7Z3pSW\nDqC2trbZlkZYx2I2by7Z8jrYBagF9ktrHZln/XQ7A9PaTi5+z5ay5Or3FClENTU11NTUZLeSTN8t\nmvohVIaXmnhuDPBQ6vYIYEEz62mj98b4crXn/9m94L86LHZ4R3v+IglFrLYPUA28DfwTWAt8nTDV\nc2aDZaYBrwHLaKLl40Ve/N3/3buuqBjspaVdvays0isqBmfUx66unullZZUOO6V6/pMd6r2s7Pg2\n6flXVAze0vNPN2sufs+m1qeev8hntab46wjfCHIxBVNf/9lpnyefNKZO3YWzz+7I5Mm5Ozuopn1E\n8p/O6plwb70FJ50EvXvDbbeFsVARKX46vUPC7bAD1NTAjjvCfvvBi00eby0iSafiX2TKyuC662Dq\nVDjssHBAmIjI1tT2KWIvvRTODnrEEfDLX4Y3BhEpPmr7yGfstRcsWhRODXHwwbB+fexEIpIvVPyL\nXGUl3H8/HH98+B5g/vzYiUQkH6jtkyCPPw4TJ8L3vgc/+lE4a6iIFD6NekqL1q+HE08M1w2+9dbw\nyUBECpt6/tKifv3gqafgc58LbaCXX46dSERiUPFPoLIyuP56uPhiOPRQqK6OnUhE2pvaPgm3bFkY\nBx0zBq66SuOgIoVIbR/J2D77wOLFUFsLVVXhFBEiUvxU/IXu3eGBB+Doo8P3AE88ETuRiLQ1tX3k\nM+bNC+OgP/gB/PCHGgcVKQQa9ZScWLs2jIP27w8zZkBFRexEItIc9fwlJ3bcEZ5+Opwaer/94JVX\nYicSkVxT8ZdGbbMN3HgjXHhh+CJ45szYiUQkl9T2kRa98EIYBz3mGLjySigtjZ1IRBpS20faxL77\nhnHQ118PB4Vt2BA7kYhkS8Vf0tKjBzz4IIweDcOGwZNPxk4kItlQ20cy9uijMGkSnHcenHuuxkFF\nYtOop7SbNWvCOOiAAWEctFu32IlEkks9f2k3AwaEcdCePWH4cFi+PHYiEcmEir+0WqdOcPPNof1z\nyCFwzz2xE4lIutT2kZx4/vnQBjr+eLj8co2DirQntX0kmiFDwjjoihVw2GEaBxXJdyr+kjM9e8Ls\n2aH4DxsWvhMQkfykto+0iTlzwjjoBRfAOedoHFSkLWnUU/LKm2+G7wF22QWmT4euXWMnEilO0Xr+\nZjbazFaa2SozO7+R5yeZWZ2ZPZ/6OT0X25X8NmgQPPssdOkSxkFXroydSEQ+lXXxN7MOwDTgSGBP\nYIKZ7d7IojPdfUjq57fZblcKQ6dOcMst4Ujggw6Ce++NnUhEIDd7/sOB1e6+xt03AzOB4xpZTl3f\nBPvGN8L3AOedF64Q9tFHsROJJFsuiv8OwLoG99enHtvaWDN7wczuMbN+OdiuFJihQ8M46Msvw+GH\nw6ZNsROJJFdJO23nj0C1u282szOB24DDmlp46tSpW25XVVVRVVXV1vmknfTqBQ89BJdcEsZB774b\nRo2KnUqksNTU1FBTU5PVOrKe9jGzEcBUdx+duj8ZcHf/eRPLdwDedffuTTyvaZ+EeOghOP10uOgi\n+O53NQ4q0lqxpn0WATub2QAzKwPGE/b0GwbbrsHd4wCdBkz4ylfgz38OZwU99VT44IPYiUSSI+vi\n7+4fA2cBc4FXCFM9K8zsp2Z2dGqxs83sZTNbmlr2tGy3K8Xh85+HP/0pTAXtvz+8+mrsRCLJoIO8\nJC+4hwPBLroIbropnCBORNKjI3yl4C1aBCedBCefDD/7GZS010iCSAFT8Zei8M47cMopsHkzzJwJ\nffvGTiSS33RKZykK224LjzwCBx4YxkH//OfYiUSKj/b8Ja/NmgVnnAE/+Ql85zsaBxVpjNo+UpRe\nfx3GjoW99gpfBnfpEjuRSH5R20eK0k47hdZPx44wciSsXh07kUjhU/GXgtC5M9x6K3z723DAAfDg\ng7ETiRQ2tX2k4Dz3XBgHPfXUcI4gjYNK0qnnL4lRXw8TJoSDw+66C/r0iZ1IJB71/CUxeveGRx8N\np4QYNix8GhCR9Kn4S8Hq2BEuvRSuuw6OOQZ+/evwSUBEWqa2jxSF114L46D77gs33hi+IBZJCrV9\nJLF23hkWLAh7/iNHhjcDEWmair8Ujc6d4fbb4VvfClcHmzUrdiKR/KW2jxSlBQvCOOikSfDTn4bv\nB0SKlUY9RRqoq4Px48NxANXV4YRxIsVIPX+RBvr0gblzYcgQGDoUFi6MnUgkf6j4S1ErKYHLL4df\n/SpcM/immzQOKgJq+0iCrFoVxkH32w9uuAHKy2MnEskNtX1EmrHrruFI4H/+M0wDvfFG7EQi8aj4\nS6J06QK/+x2cfno4HuDhh2MnEolDbR9JrGefDReKP/10mDJF46BSuDTqKZKhTZvCG0CnTuETQa9e\nsROJZE49f5EM9e0L8+aFS0QOHQqLF8dOJNI+VPwl8UpK4Mor4eqr4aijYPr02IlE2p7aPiINrFwZ\nxkFHjoRp0zQOKoVBbR+RLO2+ezgS+O9/D9cKfvPN2IlE2oaKv8hWunYNl4acNAlGjIBHHomdSCT3\nclL8zWy0ma00s1Vmdn4jz5eZ2UwzW21mfzazHXOxXZG2YgbnnAP33Qff/GY4M+gnn8ROJZI7WRd/\nM+sATAOOBPYEJpjZ7lstdgbwrrvvAvwKuCLb7Urhq6+vZ9GiRdTX13/mdiavy2R9mW5j7ty5/OMf\nc5kz5y88/jgcfTS8+27muTKVq/WINMvds/oBRgCPNLg/GTh/q2XmAPunbncE6ptZn0vxq66e6eXl\nPb2ycoiXlnbzsrJKr6wc4uXlPb26emZar2u4bEvra+p1TW2jrKzSYWeHzl5a2tVvv/1uP/dc90GD\n3JcsST9XNn+XbNYjyZKqm5nV7kxf8B8rgBOAmxvcnwhcu9UyLwGfa3B/NdCzifW12R9I8kNdXZ2X\nl/d0WOZQ59Ajddsdlnl5eU+vq6tr4XX/Xnb58uUtrq9Tp+6t3gb08E6duntdXZ3ffbf7ttu6T5/e\ncq7G1p/+36X165HkaU3xL2mPTxeNaHYkaerUqVtuV1VVUVVV1cZxpD3V1tZSVjaQDz/cG1gEDAL2\nTj27N6WlA6itraV3797NvO7fyy5cuLDZ9XXo0A/4Z9rb6NCh/2eWhYF07Ph3amtrGTeuN3vtBSec\nEK4Wdt11TedqbP3p/11avx4pfjU1NdTU1GS3kkzfLbb+IbR95jS431jb5xE+2/apa2Z9bfbuKPmh\nkPf8P/W3v7mfdJL70KHuS5a8oz1/iYpIbZ+OwGvAAKAMeAHYY6tl/ge4IXV7PDCzmfW14Z9I8sWn\nve2KisFeWtrVy8oqvaJicNo9/62XbWl9Tb2uqW2Env9OW3r+jS3/ySfuV1/t3rev+/nn16S9/nT/\nLur5S7paU/xzcoSvmY0GriFMD93i7peb2U+BRe4+28y2Ae4ABgN/Aca7e20T6/JcZJL8V19fT21t\nLQMHDgTYcrulFkfD1zVctqX1NfW6praxdOlSAAYPHtzs8k89BRMmwMSJf2fs2OV8/vMtr781v59I\nU3RWT5FINmyAceOgogLuvBN69IidSJJEp3cQiWT77WH+/HC1sKFD4YUXYicSaZ6Kv0iOlJbCL38J\nl10GRxwBt90WO5FI09T2EWkDr7wSzg566KFwzTWwzTaxE0kxU9tHJE/suScsWgT19XDQQbB2bexE\nIp+l4i/SRioq4N574aSTYPhweOyx2IlE/k1tH5F2UFMDp5wCZ50FkydDB+12SQ5p1FMkj731VhgH\n7dULbr8dunePnUiKhXr+Inlshx3giSdg0CAYNgyWLYudSJJMxV+kHZWVhemfSy6Bww8PnwBEYlDb\nRySSl18O46CHHx6OD9A4qLSW2j4iBeSLXwzjoBs3wsEHw7p1sRNJkqj4i0RUWRmuE3zCCWEc9PHH\nYyeSpFDbRyRPzJ8Pp54aLhz/ox9pHFTSp1FPkQK3fj2ceCL07RvODaRxUEmHev4iBa5fv3B9gP79\nYb/94KWXYieSYqXiL5Jnyspg2jSYMgW+9CX43e9iJ5JipLaPSB578cXwZfDo0XD11eGNQWRravuI\nFJm99w7joGvXQlVV+E5AJBdU/EXyXPfu8Ic/wDHHhO8BnngidiIpBmr7iBSQefNg4kQ491w47zyw\njD7oS7HSqKdIAqxbF8ZBd9gBbr01XDdAkk09f5EE6N8/jINut11oA73ySuxEUohU/EUK0DbbwA03\nwEUXhS+C77ordiIpNGr7iBS4ZcvCOOiYMXDVVRoHTSK1fUQSaJ99wjjom2/CoYfC22/HTiSFQMVf\npAj06AEPPhj2/ocNgyefjJ1I8p3aPiJFZu5c+NrXwijouedqHDQJNOopIgCsWRPGQQcOhN/+Frp1\ni51I2lK79/zNrIeZzTWzV83sUTOrbGK5j83seTNbamYPZLNNEWnZgAHw9NPQs2cYB12+PHYiyTfZ\n9vwnA/PcfTdgPnBBE8v93d2HuPtgd/9qltsUkTR06gQ33QSTJ8Mhh8A998ROJPkkq7aPma0EDnH3\nTWa2HVDj7rs3stz77p7WB0+1fURyb+nSMA563HFwxRVQWho7keRSjFHPPu6+CcDdNwJ9mlhuGzNb\naGZ/MrPjstymiGRo8GBYsgRWrQrXCNiwIXYiia2kpQXM7DGgb8OHAAd+3MjiTe2yD3D3DWY2CJhv\nZi+6+5tNbXPq1KlbbldVVVFVVdVSTBFpQY8eMGsW/O//hnHQu+6Cgw+OnUpao6amhpqamqzWkW3b\nZwVQ1aDt84S779HCa2YAs9z9/iaeV9tHpI3NmQOTJsH558P3v69x0EIXo+3zR+C01O1JwIONhOpu\nZmWp29sCowDNHohENHo0PPccVFfDySfD++/HTiTtLdvi/3PgCDN7FTgMuBzAzIaa2c2pZfYAFpvZ\nUuBx4DJ3X5nldkUkSwMHwjPPhFNC778/rNS/ykTRQV4iwvTpcMEF8Otfh4PDpLDoCF8RabUlS0Lh\nP+EEuOwyjYMWEp3VU0RabehQWLw4XBzm8MNh48bYiaQtqfiLyBa9esHs2eHU0MOGwbPPxk4kbUVt\nHxFp1MMPw9e/DhdeCGefrXHQfKaev4jk1Jtvhu8AdtsNfvMb6No1diJpjHr+IpJTgwaF1k95eRgH\nffXV2IkkV1T8RaRZ5eVwyy3wve/BgQfCfffFTiS5oLaPiKRt8eIwDjpuHFx6KZS0eHYwaQ/q+YtI\nm3vnHTj1VPjXv2DmTOjbt+XXSNtSz19E2ty224ZJoAMPDOOgf/pT7ETSGtrzF5FWmz0bTj8dLr4Y\nzjpL46CxqO0jIu3u9dfDOOiee8LNN0OXLrETJY/aPiLS7nbaKbR+SkthxAhYvTp2IkmHir+IZK1z\nZ5gxA77zHTjgAHjggdiJpCVq+4hITj33HJx0EpxySrhkpMZB2556/iKSF+rrQ/H/5JNwreA+fWIn\nKm7q+YtIXujdO1wneMSIMA66YEHsRLI1FX8RaRMdO8LPfgbXXw/HHgs33AD6UJ8/1PYRkTb32msw\ndizssw/cdFP4glhyR20fEclLO+/879bPiBHhzUDiUvEXkXbRuTPcfjv893/DqFHw4IOxEyWb2j4i\n0u4WLAjjoP/1X3DJJeH7AWk9jXqKSMGoq4MJE6BDhzAOuu22sRMVLvX8RaRg9OkDjz4aRkGHDoWF\nC2MnShYVfxGJpqQELrsMfvUrOPpouPFGjYO2F7V9RCQvrFoVzg46dGg4JkDjoOlT20dECtauu4Yv\ngjdvDtNAr78eO1FxU/EXkbzRpQvceSd84xvhDWD27NiJildWxd/MTjSzl83sYzMb0sxyo81spZmt\nMrPzs9mmiBQ3s3BVsD/8Ab797XCVsI8/jp2q+GS75/8ScDzwZFMLmFkHYBpwJLAnMMHMds9yuyJS\n5EaNgsWL4Zln4KijwoXjJXeyKv7u/qq7rwaa+6JhOLDa3de4+2ZgJnBcNtsVkWTo2xceewz23TeM\nhC5eHDtR8WiPnv8OwLoG99enHhMRaVFJCVxxBfziFzBmDPzmNxoHzYUWr7FjZo8BfRs+BDhwkbvP\naqtgIiINjR0bLhI/dmyYCpo2DcrLY6cqXC0Wf3c/IsttvAXs2OB+v9RjTZo6deqW21VVVVRVVWUZ\nQUSKwW67hctEfvOb4VrB990HgwbFTtX+ampqqKmpyWodOTnIy8yeAH7o7ksaea4j8CpwGLABWAhM\ncPcVTaxLB3mJSLPc4dpr4dJLw4Xjx4yJnSiudj/Iy8y+ambrgBHAbDN7JPX49mY2G8DdPwbOAuYC\nrwAzmyr8IiLpMINzzoH774czz4QpUzQOmimd3kFECtrGjXDyyeF0EHfeCb16xU7U/nR6BxFJnO22\ng3nzwpfBw4bBkv9oPktjVPxFpOCVlsJVV8GVV8Lo0TB9euxE+U9tHxEpKitWhLODjhoVxkE7dYqd\nqO2p7SMiibfHHmEc9G9/C+OgtbWxE+UnFX8RKTrdusHdd8PEiTBiBMyZEztR/lHbR0SK2tNPw/jx\n8K1vwY9/HK4ZXGx0AXcRkUZs2ADjxkFFBdxxB/TsGTtRbqnnLyLSiO23h/nzw+khhg2DpUtjJ4pP\nxV9EEqG0NJwZ9LLL4MtfDqeFSDK1fUQkcZYvD2cHPeQQuOaawh8HVdtHRCQNX/gCLFwIf/kLHHQQ\nrFkTO1H7U/EXkUSqqIDf/z5MAo0cCe+9FztR+1LbR0QSb+1a2HHHlpfLVxr1FBFJIPX8RUQkLSr+\nIiIJpOIvIpJAKv4iIgmk4i8ikkAq/iIiCaTiLyKSQCr+IiIJpOIvIpJAKv4iIgmk4i8ikkAq/iIi\nCaTiLyKSQCr+IiIJlFXxN7MTzexlM/vYzIY0s1ytmS0zs6VmtjCbbYqISPay3fN/CTgeeLKF5T4B\nqtx9sLsPz3KbeaumpiZ2hKwof1zKH1eh589UVsXf3V9199VASxcRsGy3VQgK/X8e5Y9L+eMq9PyZ\naq+C7MCjZrbIzL7ZTtsUEZEmlLS0gJk9BvRt+BChmF/k7rPS3M4B7r7BzHoDj5nZCnd/JvO4IiKS\nCzm5hq+ZPQH8wN2fT2PZKcD77v6LJp7XBXxFRDKU6TV8W9zzz0CjGzazzkAHd//AzLoAXwZ+2tRK\nMv0FREQkc9mOen7VzNYBI4DZZvZI6vHtzWx2arG+wDNmthRYAMxy97nZbFdERLKTk7aPiIgUlrwb\nvzSzK8xshZm9YGb3mVlF7EzpMLPRZrbSzFaZ2fmx82TCzPqZ2Xwze8XMXjKzs2NnypSZdTCz583s\nj7GzZMrMKs3s96n/718xs/1jZ8qEmX0/dbDni2b2OzMri52pOWZ2i5ltMrMXGzzWw8zmmtmrZvao\nmVXGzNicJvJnXDfzrvgDc4E93X1fYDVwQeQ8LTKzDsA04EhgT2CCme0eN1VGPgLOdfc9gZHAdwos\nP8A5wPLYIVrpGuBhd98D2AdYETlP2szsc8B3gSHuvjfhe8TxcVO1aAbh32pDk4F57r4bMJ/8rjuN\n5c+4buZd8Xf3ee7+SeruAqBfzDxpGg6sdvc17r4ZmAkcFzlT2tx9o7u/kLr9AaH47BA3VfrMrB8w\nBpgeO0umUntoB7n7DAB3/8jd/xY5VqY6Al3MrAToDLwdOU+zUmPm72318HHAbanbtwFfbddQGWgs\nf2vqZt4V/62cDjwSO0QadgDWNbi/ngIqng2Z2UBgX+C5uEky8kvgPMLxJ4VmEPCOmc1Ita1uNrPy\n2KHS5e5vA1cDa4G3gL+6+7y4qVqlj7tvgrAzBPSJnCcbadXNKMXfzB5L9Qc//Xkp9d9jGixzEbDZ\n3atjZEwiM+sK3Auck/oEkPfM7CvAptQnF6PlU43kmxJgCHC9uw8B/kFoQRQEM+tO2GseAHwO6Gpm\np8RNlROFuCORUd3M5Zx/2tz9iOaeN7PTCB/jv9QugbL3FrBjg/v9Uo8VjNRH9nuBO9z9wdh5MnAA\ncKyZjQHKgW5mdru7fy1yrnStB9a5++LU/XuBQhoYOBx4w93fBTCz+4FRQKHttG0ys77uvsnMtgPq\nYgfKVKZ1M+/aPmY2mvAR/lh3/2fsPGlaBOxsZgNSkw7jgUKbOvktsNzdr4kdJBPufqG77+junyf8\n3ecXUOEn1WpYZ2a7ph46jML64notMMLMOpmZEfIXwhfWW39K/CNwWur2JCDfd4A+k781dTPv5vzN\nbDVQBvwl9dACd/+fiJHSkvrjX0N4Q73F3S+PHCltZnYA8BThFN2e+rnQ3edEDZYhMzuEcJqRY2Nn\nyYSZ7UP4sroUeAP4urv/X9xU6UudsmU8sBlYCnwjNfiQl8ysGqgCegGbgCnAA8Dvgf7AGmCcu/81\nVsbmNJH/QjKsm3lX/EVEpO3lXdtHRETanoq/iEgCqfiLiCSQir+ISAKp+IuIJJCKv4hIAqn4i4gk\nkIq/iEgC/T8q+K/9gov3jwAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x7f5be252a9b0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"all_xs = np.linspace(0, 10, 100)\n",
"plt.plot(all_xs, all_xs*w_val[1] + w_val[0])\n",
"plt.scatter(xs, labels)\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 1998 Aladdin Enterprises. All rights reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
For more information about licensing, please refer to
http://www.ghostscript.com/licensing/. For information on
commercial licensing, go to http://www.artifex.com/licensing/ or
contact Artifex Software, Inc., 101 Lucas Valley Road #110,
San Rafael, CA 94903, U.S.A., +1(415)492-9861.
*/
/* $Id: gendev.c,v 1.7 2004/12/08 21:35:13 stefan Exp $ */
/* Generate .dev configuration files */
#include "stdpre.h"
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h> /* for calloc */
#include <string.h>
/*
* This program generates .dev configuration files.
*
* Usage:
* gendev [-Z] [-n [<name_prefix> | -]] [-C [<dir> | -]]
* (-d <devfile> | -m <modfile> | -a <modfile>)
* (-<category> | <item>)*
*
* The name_prefix is for device[2], font, init, and iodev resources.
* ****** DOESN'T HANDLE -replace YET ******
* ****** DOESN'T MERGE device AND device2 ******
*/
#define DEFAULT_NAME_PREFIX "gs_"
#define INITIAL_CATEGORY "obj"
typedef struct config_s {
/* Set once */
FILE *out;
bool debug;
const char *name_prefix;
const char *file_prefix;
ulong file_id; /* for uniq_last detection */
/* Updated dynamically */
#define ITEM_ID_BITS 5
uint item_id;
bool any_scan_items;
bool in_res_scan;
bool in_category; /* in_category implies in_res_scan */
const char *current_category;
} config;
static const config init_config =
{
0, /* out */
0, /* debug */
DEFAULT_NAME_PREFIX, /* name_prefix */
"", /* file_prefix */
0, /* file_id */
0, /* item_id */
0, /* any_scan_items */
0, /* in_res_scan */
0, /* in_category */
"" /* current_category */
};
static const char *indent_INCLUDED = "\t\t\t\t";
static const char *indent_RES_SCAN = " ";
static const char *indent_category = "\t";
static const char *indent_SEEN = "\t ";
static const char *indent_include = " ";
static const char *indent_scan_item = "\t";
static const char *indent_item = "";
/* Forward definitions */
void add_entry(config *, const char *, const char *, bool);
main(int argc, char *argv[])
{
config conf;
int i, j;
bool dev, append;
const char *category = INITIAL_CATEGORY;
const char *fnarg;
FILE *out;
long pos;
conf = init_config;
/* Process command line arguments. */
for (i = 1; i < argc; i++) {
const char *arg = argv[i];
if (*arg != '-') {
fprintf(stderr, "-d|m|a must precede non-switches.\n", arg);
exit(1);
}
switch (arg[1]) {
case 'C': /* change directory, by analogy with make */
conf.file_prefix =
(argv[i + 1][0] == '-' ? "" : argv[i + 1]);
++i;
continue;
case 'n':
conf.name_prefix =
(argv[i + 1][0] == '-' ? "" : argv[i + 1]);
++i;
continue;
case 'a':
dev = false, append = true;
break;
case 'd':
dev = true, append = false;
break;
case 'm':
dev = false, append = false;
break;
case 'Z':
conf.debug = true;
continue;
default:
fprintf(stderr, "Unknown switch %s.\n", argv[i]);
exit(1);
}
break;
}
if (i == argc - 1) {
fprintf(stderr, "No output file name given, last argument is %s.\n",
argv[i]);
exit(1);
}
/* Must be the output file. */
fnarg = argv[++i];
{
char fname[100];
strcpy(fname, fnarg);
strcat(fname, ".dev");
out = fopen(fname, (append ? "a" : "w"));
if (out == 0) {
fprintf(stderr, "Can't open %s for output.\n", fname);
exit(1);
}
if (!append)
fprintf(out,
"/*\n * File %s created automatically by gendev.\n */\n",
fname);
}
conf.out = out;
pos = ftell(out);
/* We need a separate _INCLUDED flag for each batch of definitions. */
fprintf(out, "\n#%sifndef %s_%ld_INCLUDED\n",
indent_INCLUDED, fnarg, pos);
fprintf(out, "#%s define %s_%ld_INCLUDED\n",
indent_INCLUDED, fnarg, pos);
/* Create a "unique" hash for the output file. */
for (j = 0; fnarg[j] != 0; ++j)
conf.file_id = conf.file_id * 41 + fnarg[j];
conf.item_id <<= ITEM_ID_BITS;
/* Add the real entries. */
if (dev)
add_entry(&conf, "dev", fnarg, false);
for (j = i + 1; j < argc; ++j) {
const char *arg = argv[j];
if (arg[0] == '-')
category = arg + 1;
else
add_entry(&conf, category, arg, false);
}
if (conf.in_category)
fprintf(out, "#%sendif /* -%s */\n",
indent_category, conf.current_category);
/* Add the scanning entries, if any. */
if (conf.any_scan_items) {
if (conf.in_res_scan)
fprintf(out, "#%selse /* RES_SCAN */\n", indent_RES_SCAN);
else
fprintf(out, "#%sifdef RES_SCAN\n", indent_RES_SCAN);
conf.in_res_scan = true;
category = INITIAL_CATEGORY;
conf.item_id = 0;
for (j = i + 1; j < argc; ++j) {
const char *arg = argv[j];
if (arg[0] == '-')
category = arg + 1;
else
add_entry(&conf, category, arg, true);
}
}
if (conf.in_res_scan)
fprintf(out, "#%sendif /* RES_SCAN */\n", indent_RES_SCAN);
fprintf(out, "#%sendif /* !%s_%ld_INCLUDED */\n",
indent_INCLUDED, fnarg, pos);
fclose(out);
exit(0);
}
/* Add an entry to the output. */
typedef enum {
uniq_none = 0,
uniq_first,
uniq_last
} uniq_mode;
void
write_item(config * pconf, const char *str, const char *category,
const char *item, uniq_mode mode)
{
FILE *out = pconf->out;
char cati[80];
if (!pconf->in_res_scan) {
fprintf(out, "#%sifndef RES_SCAN\n", indent_RES_SCAN);
pconf->in_res_scan = true;
}
if (strcmp(pconf->current_category, category)) {
const char *paren = strchr(str, '(');
if (pconf->in_category)
fprintf(out, "#%sendif /* -%s */\n",
indent_category, pconf->current_category);
fprintf(out, "#%sifdef ", indent_category);
fwrite(str, sizeof(char), paren - str, out);
fprintf(out, "\n");
pconf->current_category = category;
pconf->in_category = true;
}
sprintf(cati, "%s_%s_", category, item);
switch (mode) {
case uniq_none:
fprintf(out, "%s%s\n", indent_item, str);
break;
case uniq_first:
fprintf(out, "#%sifndef %sSEEN\n", indent_SEEN, cati);
fprintf(out, "#%s define %sSEEN\n", indent_SEEN, cati);
write_item(pconf, str, category, item, uniq_none);
fprintf(out, "#%sendif\n", indent_SEEN, cati);
break;
case uniq_last:
fprintf(out, "#%sif %sSEEN == %lu\n", indent_SEEN, cati,
pconf->file_id + pconf->item_id++);
write_item(pconf, str, category, item, uniq_none);
fprintf(out, "#%sendif\n", indent_SEEN, cati);
pconf->any_scan_items = true;
break;
}
}
void
write_scan_item(config * pconf, const char *str, const char *category,
const char *item, uniq_mode mode)
{
FILE *out = pconf->out;
char cati[80];
sprintf(cati, "%s_%s_", category, item);
switch (mode) {
case uniq_none:
break;
case uniq_first:
break;
case uniq_last:
fprintf(out, "#%sundef %sSEEN\n", indent_scan_item, cati);
fprintf(out, "#%s define %sSEEN %lu\n", indent_scan_item, cati,
pconf->file_id + pconf->item_id++);
}
}
void
add_entry(config * pconf, const char *category, const char *item, bool scan)
{
char str[80];
uniq_mode mode = uniq_first;
if (pconf->debug && !scan)
printf("Adding %s %s;\n", category, item);
str[0] = 0;
switch (category[0]) { /* just an accelerator */
#define is_cat(str) !strcmp(category, str)
case 'd':
if (is_cat("dev"))
sprintf(str, "device_(%s%s_device)\n",
pconf->name_prefix, item);
else if (is_cat("dev2"))
sprintf(str, "device2_(%s%s_device)\n",
pconf->name_prefix, item);
break;
case 'e':
if (is_cat("emulator"))
sprintf(str, "emulator_(\"%s\",%d)",
item, strlen(item));
break;
case 'f':
if (is_cat("font"))
sprintf(str, "font_(\"0.font_%s\",%sf_%s,zf_%s)",
item, pconf->name_prefix, item, item);
break;
case 'i':
if (is_cat("include")) {
int len = strlen(item);
if (scan)
return;
if (strcmp(pconf->current_category, category)) {
if (pconf->in_category) {
fprintf(pconf->out, "#%sendif /* -%s */\n",
indent_category, pconf->current_category);
pconf->in_category = false;
}
pconf->current_category = category;
}
if (pconf->in_res_scan) {
fprintf(pconf->out, "#%sendif /* RES_SCAN */\n",
indent_RES_SCAN);
pconf->in_res_scan = false;
}
if (len < 5 || strcmp(item + len - 4, ".dev"))
fprintf(pconf->out, "#%sinclude \"%s.dev\"\n",
indent_include, item);
else
fprintf(pconf->out, "#%sinclude \"%s\"\n",
indent_include, item);
return;
} else if (is_cat("init"))
sprintf(str, "init_(%s%s_init)", pconf->name_prefix, item);
else if (is_cat("iodev"))
sprintf(str, "io_device_(%siodev_%s)", pconf->name_prefix, item);
break;
case 'l':
if (is_cat("lib")) {
sprintf(str, "lib_(%s)", item);
mode = uniq_last;
}
break;
case 'o':
if (is_cat("obj"))
sprintf(str, "obj_(%s%s)", pconf->file_prefix, item);
else if (is_cat("oper"))
sprintf(str, "oper_(%s_op_defs)", item);
break;
case 'p':
if (is_cat("ps"))
sprintf(str, "psfile_(\"%s.ps\",%d)",
item, strlen(item) + 3);
break;
#undef is_cat
default:
;
}
if (str[0] == 0) {
fprintf(stderr, "Unknown category %s.\n", category);
exit(1);
}
if (scan)
write_scan_item(pconf, str, category, item, mode);
else
write_item(pconf, str, category, item, mode);
}
| {
"pile_set_name": "Github"
} |
/*
* URB OHCI HCD (Host Controller Driver) for USB on the AT91RM9200 and PCI bus.
*
* Interrupt support is added. Now, it has been tested
* on ULI1575 chip and works well with USB keyboard.
*
* (C) Copyright 2007
* Zhang Wei, Freescale Semiconductor, Inc. <wei.zhang@freescale.com>
*
* (C) Copyright 2003
* Gary Jennejohn, DENX Software Engineering <garyj@denx.de>
*
* Note: Much of this code has been derived from Linux 2.4
* (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
* (C) Copyright 2000-2002 David Brownell
*
* Modified for the MP2USB by (C) Copyright 2005 Eric Benard
* ebenard@eukrea.com - based on s3c24x0's driver
*
* SPDX-License-Identifier: GPL-2.0+
*/
/*
* IMPORTANT NOTES
* 1 - Read doc/README.generic_usb_ohci
* 2 - this driver is intended for use with USB Mass Storage Devices
* (BBB) and USB keyboard. There is NO support for Isochronous pipes!
* 2 - when running on a PQFP208 AT91RM9200, define CONFIG_AT91C_PQFP_UHPBUG
* to activate workaround for bug #41 or this driver will NOT work!
*/
#include <common.h>
#include <asm/byteorder.h>
#include <dm.h>
#include <errno.h>
#if defined(CONFIG_PCI_OHCI)
# include <pci.h>
#if !defined(CONFIG_PCI_OHCI_DEVNO)
#define CONFIG_PCI_OHCI_DEVNO 0
#endif
#endif
#include <malloc.h>
#include <memalign.h>
#include <usb.h>
#include "ohci.h"
#ifdef CONFIG_AT91RM9200
#include <asm/arch/hardware.h> /* needed for AT91_USB_HOST_BASE */
#endif
#if defined(CONFIG_CPU_ARM920T) || \
defined(CONFIG_PCI_OHCI) || \
defined(CONFIG_SYS_OHCI_USE_NPS)
# define OHCI_USE_NPS /* force NoPowerSwitching mode */
#endif
#undef OHCI_VERBOSE_DEBUG /* not always helpful */
#undef DEBUG
#undef SHOW_INFO
#undef OHCI_FILL_TRACE
/* For initializing controller (mask in an HCFS mode too) */
#define OHCI_CONTROL_INIT \
(OHCI_CTRL_CBSR & 0x3) | OHCI_CTRL_IE | OHCI_CTRL_PLE
#ifdef CONFIG_PCI_OHCI
static struct pci_device_id ohci_pci_ids[] = {
{0x10b9, 0x5237}, /* ULI1575 PCI OHCI module ids */
{0x1033, 0x0035}, /* NEC PCI OHCI module ids */
{0x1131, 0x1561}, /* Philips 1561 PCI OHCI module ids */
/* Please add supported PCI OHCI controller ids here */
{0, 0}
};
#endif
#ifdef CONFIG_PCI_EHCI_DEVNO
static struct pci_device_id ehci_pci_ids[] = {
{0x1131, 0x1562}, /* Philips 1562 PCI EHCI module ids */
/* Please add supported PCI EHCI controller ids here */
{0, 0}
};
#endif
#ifdef DEBUG
#define dbg(format, arg...) printf("DEBUG: " format "\n", ## arg)
#else
#define dbg(format, arg...) do {} while (0)
#endif /* DEBUG */
#define err(format, arg...) printf("ERROR: " format "\n", ## arg)
#ifdef SHOW_INFO
#define info(format, arg...) printf("INFO: " format "\n", ## arg)
#else
#define info(format, arg...) do {} while (0)
#endif
#ifdef CONFIG_SYS_OHCI_BE_CONTROLLER
# define m16_swap(x) cpu_to_be16(x)
# define m32_swap(x) cpu_to_be32(x)
#else
# define m16_swap(x) cpu_to_le16(x)
# define m32_swap(x) cpu_to_le32(x)
#endif /* CONFIG_SYS_OHCI_BE_CONTROLLER */
/* We really should do proper cache flushing everywhere */
#define flush_dcache_buffer(addr, size) \
flush_dcache_range((unsigned long)(addr), \
ALIGN((unsigned long)(addr) + size, ARCH_DMA_MINALIGN))
#define invalidate_dcache_buffer(addr, size) \
invalidate_dcache_range((unsigned long)(addr), \
ALIGN((unsigned long)(addr) + size, ARCH_DMA_MINALIGN))
/* Do not use sizeof(ed / td) as our ed / td structs contain extra members */
#define flush_dcache_ed(addr) flush_dcache_buffer(addr, 16)
#define flush_dcache_td(addr) flush_dcache_buffer(addr, 16)
#define flush_dcache_iso_td(addr) flush_dcache_buffer(addr, 32)
#define flush_dcache_hcca(addr) flush_dcache_buffer(addr, 256)
#define invalidate_dcache_ed(addr) invalidate_dcache_buffer(addr, 16)
#define invalidate_dcache_td(addr) invalidate_dcache_buffer(addr, 16)
#define invalidate_dcache_iso_td(addr) invalidate_dcache_buffer(addr, 32)
#define invalidate_dcache_hcca(addr) invalidate_dcache_buffer(addr, 256)
#ifdef CONFIG_DM_USB
/*
* The various ohci_mdelay(1) calls in the code seem unnecessary. We keep
* them around when building for older boards not yet converted to the dm
* just in case (to avoid regressions), for dm this turns them into nops.
*/
#define ohci_mdelay(x)
#else
#define ohci_mdelay(x) mdelay(x)
#endif
#ifndef CONFIG_DM_USB
/* global ohci_t */
static ohci_t gohci;
/* this must be aligned to a 256 byte boundary */
struct ohci_hcca ghcca[1];
#endif
/* mapping of the OHCI CC status to error codes */
static int cc_to_error[16] = {
/* No Error */ 0,
/* CRC Error */ USB_ST_CRC_ERR,
/* Bit Stuff */ USB_ST_BIT_ERR,
/* Data Togg */ USB_ST_CRC_ERR,
/* Stall */ USB_ST_STALLED,
/* DevNotResp */ -1,
/* PIDCheck */ USB_ST_BIT_ERR,
/* UnExpPID */ USB_ST_BIT_ERR,
/* DataOver */ USB_ST_BUF_ERR,
/* DataUnder */ USB_ST_BUF_ERR,
/* reservd */ -1,
/* reservd */ -1,
/* BufferOver */ USB_ST_BUF_ERR,
/* BuffUnder */ USB_ST_BUF_ERR,
/* Not Access */ -1,
/* Not Access */ -1
};
static const char *cc_to_string[16] = {
"No Error",
"CRC: Last data packet from endpoint contained a CRC error.",
"BITSTUFFING: Last data packet from endpoint contained a bit " \
"stuffing violation",
"DATATOGGLEMISMATCH: Last packet from endpoint had data toggle PID\n" \
"that did not match the expected value.",
"STALL: TD was moved to the Done Queue because the endpoint returned" \
" a STALL PID",
"DEVICENOTRESPONDING: Device did not respond to token (IN) or did\n" \
"not provide a handshake (OUT)",
"PIDCHECKFAILURE: Check bits on PID from endpoint failed on data PID\n"\
"(IN) or handshake (OUT)",
"UNEXPECTEDPID: Receive PID was not valid when encountered or PID\n" \
"value is not defined.",
"DATAOVERRUN: The amount of data returned by the endpoint exceeded\n" \
"either the size of the maximum data packet allowed\n" \
"from the endpoint (found in MaximumPacketSize field\n" \
"of ED) or the remaining buffer size.",
"DATAUNDERRUN: The endpoint returned less than MaximumPacketSize\n" \
"and that amount was not sufficient to fill the\n" \
"specified buffer",
"reserved1",
"reserved2",
"BUFFEROVERRUN: During an IN, HC received data from endpoint faster\n" \
"than it could be written to system memory",
"BUFFERUNDERRUN: During an OUT, HC could not retrieve data from\n" \
"system memory fast enough to keep up with data USB " \
"data rate.",
"NOT ACCESSED: This code is set by software before the TD is placed" \
"on a list to be processed by the HC.(1)",
"NOT ACCESSED: This code is set by software before the TD is placed" \
"on a list to be processed by the HC.(2)",
};
static inline u32 roothub_a(struct ohci *hc)
{ return ohci_readl(&hc->regs->roothub.a); }
static inline u32 roothub_b(struct ohci *hc)
{ return ohci_readl(&hc->regs->roothub.b); }
static inline u32 roothub_status(struct ohci *hc)
{ return ohci_readl(&hc->regs->roothub.status); }
static inline u32 roothub_portstatus(struct ohci *hc, int i)
{ return ohci_readl(&hc->regs->roothub.portstatus[i]); }
/* forward declaration */
static int hc_interrupt(ohci_t *ohci);
static void td_submit_job(ohci_t *ohci, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *setup, urb_priv_t *urb,
int interval);
static int ep_link(ohci_t * ohci, ed_t * ed);
static int ep_unlink(ohci_t * ohci, ed_t * ed);
static ed_t *ep_add_ed(ohci_dev_t *ohci_dev, struct usb_device *usb_dev,
unsigned long pipe, int interval, int load);
/*-------------------------------------------------------------------------*/
/* TDs ... */
static struct td *td_alloc(ohci_dev_t *ohci_dev, struct usb_device *usb_dev)
{
int i;
struct td *td;
td = NULL;
for (i = 0; i < NUM_TD; i++)
{
if (ohci_dev->tds[i].usb_dev == NULL)
{
td = &ohci_dev->tds[i];
td->usb_dev = usb_dev;
break;
}
}
return td;
}
static inline void ed_free(struct ed *ed)
{
ed->usb_dev = NULL;
}
/*-------------------------------------------------------------------------*
* URB support functions
*-------------------------------------------------------------------------*/
/* free HCD-private data associated with this URB */
static void urb_free_priv(urb_priv_t *urb)
{
int i;
int last;
struct td *td;
last = urb->length - 1;
if (last >= 0) {
for (i = 0; i <= last; i++) {
td = urb->td[i];
if (td) {
td->usb_dev = NULL;
urb->td[i] = NULL;
}
}
}
free(urb);
}
/*-------------------------------------------------------------------------*/
#ifdef DEBUG
static int sohci_get_current_frame_number(ohci_t *ohci);
/* debug| print the main components of an URB
* small: 0) header + data packets 1) just header */
static void pkt_print(ohci_t *ohci, urb_priv_t *purb, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *setup, char *str, int small)
{
dbg("%s URB:[%4x] dev:%2lu,ep:%2lu-%c,type:%s,len:%d/%d stat:%#lx",
str,
sohci_get_current_frame_number(ohci),
usb_pipedevice(pipe),
usb_pipeendpoint(pipe),
usb_pipeout(pipe)? 'O': 'I',
usb_pipetype(pipe) < 2 ? \
(usb_pipeint(pipe)? "INTR": "ISOC"): \
(usb_pipecontrol(pipe)? "CTRL": "BULK"),
(purb ? purb->actual_length : 0),
transfer_len, dev->status);
#ifdef OHCI_VERBOSE_DEBUG
if (!small) {
int i, len;
if (usb_pipecontrol(pipe)) {
printf(__FILE__ ": cmd(8):");
for (i = 0; i < 8 ; i++)
printf(" %02x", ((__u8 *) setup) [i]);
printf("\n");
}
if (transfer_len > 0 && buffer) {
printf(__FILE__ ": data(%d/%d):",
(purb ? purb->actual_length : 0),
transfer_len);
len = usb_pipeout(pipe)? transfer_len:
(purb ? purb->actual_length : 0);
for (i = 0; i < 16 && i < len; i++)
printf(" %02x", ((__u8 *) buffer) [i]);
printf("%s\n", i < len? "...": "");
}
}
#endif
}
/* just for debugging; prints non-empty branches of the int ed tree
* inclusive iso eds */
void ep_print_int_eds(ohci_t *ohci, char *str)
{
int i, j;
__u32 *ed_p;
for (i = 0; i < 32; i++) {
j = 5;
ed_p = &(ohci->hcca->int_table [i]);
if (*ed_p == 0)
continue;
invalidate_dcache_ed(ed_p);
printf(__FILE__ ": %s branch int %2d(%2x):", str, i, i);
while (*ed_p != 0 && j--) {
ed_t *ed = (ed_t *)m32_swap(ed_p);
invalidate_dcache_ed(ed);
printf(" ed: %4x;", ed->hwINFO);
ed_p = &ed->hwNextED;
}
printf("\n");
}
}
static void ohci_dump_intr_mask(char *label, __u32 mask)
{
dbg("%s: 0x%08x%s%s%s%s%s%s%s%s%s",
label,
mask,
(mask & OHCI_INTR_MIE) ? " MIE" : "",
(mask & OHCI_INTR_OC) ? " OC" : "",
(mask & OHCI_INTR_RHSC) ? " RHSC" : "",
(mask & OHCI_INTR_FNO) ? " FNO" : "",
(mask & OHCI_INTR_UE) ? " UE" : "",
(mask & OHCI_INTR_RD) ? " RD" : "",
(mask & OHCI_INTR_SF) ? " SF" : "",
(mask & OHCI_INTR_WDH) ? " WDH" : "",
(mask & OHCI_INTR_SO) ? " SO" : ""
);
}
static void maybe_print_eds(char *label, __u32 value)
{
ed_t *edp = (ed_t *)value;
if (value) {
dbg("%s %08x", label, value);
invalidate_dcache_ed(edp);
dbg("%08x", edp->hwINFO);
dbg("%08x", edp->hwTailP);
dbg("%08x", edp->hwHeadP);
dbg("%08x", edp->hwNextED);
}
}
static char *hcfs2string(int state)
{
switch (state) {
case OHCI_USB_RESET: return "reset";
case OHCI_USB_RESUME: return "resume";
case OHCI_USB_OPER: return "operational";
case OHCI_USB_SUSPEND: return "suspend";
}
return "?";
}
/* dump control and status registers */
static void ohci_dump_status(ohci_t *controller)
{
struct ohci_regs *regs = controller->regs;
__u32 temp;
temp = ohci_readl(®s->revision) & 0xff;
if (temp != 0x10)
dbg("spec %d.%d", (temp >> 4), (temp & 0x0f));
temp = ohci_readl(®s->control);
dbg("control: 0x%08x%s%s%s HCFS=%s%s%s%s%s CBSR=%d", temp,
(temp & OHCI_CTRL_RWE) ? " RWE" : "",
(temp & OHCI_CTRL_RWC) ? " RWC" : "",
(temp & OHCI_CTRL_IR) ? " IR" : "",
hcfs2string(temp & OHCI_CTRL_HCFS),
(temp & OHCI_CTRL_BLE) ? " BLE" : "",
(temp & OHCI_CTRL_CLE) ? " CLE" : "",
(temp & OHCI_CTRL_IE) ? " IE" : "",
(temp & OHCI_CTRL_PLE) ? " PLE" : "",
temp & OHCI_CTRL_CBSR
);
temp = ohci_readl(®s->cmdstatus);
dbg("cmdstatus: 0x%08x SOC=%d%s%s%s%s", temp,
(temp & OHCI_SOC) >> 16,
(temp & OHCI_OCR) ? " OCR" : "",
(temp & OHCI_BLF) ? " BLF" : "",
(temp & OHCI_CLF) ? " CLF" : "",
(temp & OHCI_HCR) ? " HCR" : ""
);
ohci_dump_intr_mask("intrstatus", ohci_readl(®s->intrstatus));
ohci_dump_intr_mask("intrenable", ohci_readl(®s->intrenable));
maybe_print_eds("ed_periodcurrent",
ohci_readl(®s->ed_periodcurrent));
maybe_print_eds("ed_controlhead", ohci_readl(®s->ed_controlhead));
maybe_print_eds("ed_controlcurrent",
ohci_readl(®s->ed_controlcurrent));
maybe_print_eds("ed_bulkhead", ohci_readl(®s->ed_bulkhead));
maybe_print_eds("ed_bulkcurrent", ohci_readl(®s->ed_bulkcurrent));
maybe_print_eds("donehead", ohci_readl(®s->donehead));
}
static void ohci_dump_roothub(ohci_t *controller, int verbose)
{
__u32 temp, ndp, i;
temp = roothub_a(controller);
ndp = (temp & RH_A_NDP);
#ifdef CONFIG_AT91C_PQFP_UHPBUG
ndp = (ndp == 2) ? 1:0;
#endif
if (verbose) {
dbg("roothub.a: %08x POTPGT=%d%s%s%s%s%s NDP=%d", temp,
((temp & RH_A_POTPGT) >> 24) & 0xff,
(temp & RH_A_NOCP) ? " NOCP" : "",
(temp & RH_A_OCPM) ? " OCPM" : "",
(temp & RH_A_DT) ? " DT" : "",
(temp & RH_A_NPS) ? " NPS" : "",
(temp & RH_A_PSM) ? " PSM" : "",
ndp
);
temp = roothub_b(controller);
dbg("roothub.b: %08x PPCM=%04x DR=%04x",
temp,
(temp & RH_B_PPCM) >> 16,
(temp & RH_B_DR)
);
temp = roothub_status(controller);
dbg("roothub.status: %08x%s%s%s%s%s%s",
temp,
(temp & RH_HS_CRWE) ? " CRWE" : "",
(temp & RH_HS_OCIC) ? " OCIC" : "",
(temp & RH_HS_LPSC) ? " LPSC" : "",
(temp & RH_HS_DRWE) ? " DRWE" : "",
(temp & RH_HS_OCI) ? " OCI" : "",
(temp & RH_HS_LPS) ? " LPS" : ""
);
}
for (i = 0; i < ndp; i++) {
temp = roothub_portstatus(controller, i);
dbg("roothub.portstatus [%d] = 0x%08x%s%s%s%s%s%s%s%s%s%s%s%s",
i,
temp,
(temp & RH_PS_PRSC) ? " PRSC" : "",
(temp & RH_PS_OCIC) ? " OCIC" : "",
(temp & RH_PS_PSSC) ? " PSSC" : "",
(temp & RH_PS_PESC) ? " PESC" : "",
(temp & RH_PS_CSC) ? " CSC" : "",
(temp & RH_PS_LSDA) ? " LSDA" : "",
(temp & RH_PS_PPS) ? " PPS" : "",
(temp & RH_PS_PRS) ? " PRS" : "",
(temp & RH_PS_POCI) ? " POCI" : "",
(temp & RH_PS_PSS) ? " PSS" : "",
(temp & RH_PS_PES) ? " PES" : "",
(temp & RH_PS_CCS) ? " CCS" : ""
);
}
}
static void ohci_dump(ohci_t *controller, int verbose)
{
dbg("OHCI controller usb-%s state", controller->slot_name);
/* dumps some of the state we know about */
ohci_dump_status(controller);
if (verbose)
ep_print_int_eds(controller, "hcca");
invalidate_dcache_hcca(controller->hcca);
dbg("hcca frame #%04x", controller->hcca->frame_no);
ohci_dump_roothub(controller, 1);
}
#endif /* DEBUG */
/*-------------------------------------------------------------------------*
* Interface functions (URB)
*-------------------------------------------------------------------------*/
/* get a transfer request */
int sohci_submit_job(ohci_t *ohci, ohci_dev_t *ohci_dev, urb_priv_t *urb,
struct devrequest *setup)
{
ed_t *ed;
urb_priv_t *purb_priv = urb;
int i, size = 0;
struct usb_device *dev = urb->dev;
unsigned long pipe = urb->pipe;
void *buffer = urb->transfer_buffer;
int transfer_len = urb->transfer_buffer_length;
int interval = urb->interval;
/* when controller's hung, permit only roothub cleanup attempts
* such as powering down ports */
if (ohci->disabled) {
err("sohci_submit_job: EPIPE");
return -1;
}
/* we're about to begin a new transaction here so mark the
* URB unfinished */
urb->finished = 0;
/* every endpoint has a ed, locate and fill it */
ed = ep_add_ed(ohci_dev, dev, pipe, interval, 1);
if (!ed) {
err("sohci_submit_job: ENOMEM");
return -1;
}
/* for the private part of the URB we need the number of TDs (size) */
switch (usb_pipetype(pipe)) {
case PIPE_BULK: /* one TD for every 4096 Byte */
size = (transfer_len - 1) / 4096 + 1;
break;
case PIPE_CONTROL:/* 1 TD for setup, 1 for ACK and 1 for every 4096 B */
size = (transfer_len == 0)? 2:
(transfer_len - 1) / 4096 + 3;
break;
case PIPE_INTERRUPT: /* 1 TD */
size = 1;
break;
}
ed->purb = urb;
if (size >= (N_URB_TD - 1)) {
err("need %d TDs, only have %d", size, N_URB_TD);
return -1;
}
purb_priv->pipe = pipe;
/* fill the private part of the URB */
purb_priv->length = size;
purb_priv->ed = ed;
purb_priv->actual_length = 0;
/* allocate the TDs */
/* note that td[0] was allocated in ep_add_ed */
for (i = 0; i < size; i++) {
purb_priv->td[i] = td_alloc(ohci_dev, dev);
if (!purb_priv->td[i]) {
purb_priv->length = i;
urb_free_priv(purb_priv);
err("sohci_submit_job: ENOMEM");
return -1;
}
}
if (ed->state == ED_NEW || (ed->state & ED_DEL)) {
urb_free_priv(purb_priv);
err("sohci_submit_job: EINVAL");
return -1;
}
/* link the ed into a chain if is not already */
if (ed->state != ED_OPER)
ep_link(ohci, ed);
/* fill the TDs and link it to the ed */
td_submit_job(ohci, dev, pipe, buffer, transfer_len,
setup, purb_priv, interval);
return 0;
}
/*-------------------------------------------------------------------------*/
#ifdef DEBUG
/* tell us the current USB frame number */
static int sohci_get_current_frame_number(ohci_t *ohci)
{
invalidate_dcache_hcca(ohci->hcca);
return m16_swap(ohci->hcca->frame_no);
}
#endif
/*-------------------------------------------------------------------------*
* ED handling functions
*-------------------------------------------------------------------------*/
/* search for the right branch to insert an interrupt ed into the int tree
* do some load ballancing;
* returns the branch and
* sets the interval to interval = 2^integer (ld (interval)) */
static int ep_int_ballance(ohci_t *ohci, int interval, int load)
{
int i, branch = 0;
/* search for the least loaded interrupt endpoint
* branch of all 32 branches
*/
for (i = 0; i < 32; i++)
if (ohci->ohci_int_load [branch] > ohci->ohci_int_load [i])
branch = i;
branch = branch % interval;
for (i = branch; i < 32; i += interval)
ohci->ohci_int_load [i] += load;
return branch;
}
/*-------------------------------------------------------------------------*/
/* 2^int( ld (inter)) */
static int ep_2_n_interval(int inter)
{
int i;
for (i = 0; ((inter >> i) > 1) && (i < 5); i++);
return 1 << i;
}
/*-------------------------------------------------------------------------*/
/* the int tree is a binary tree
* in order to process it sequentially the indexes of the branches have to
* be mapped the mapping reverses the bits of a word of num_bits length */
static int ep_rev(int num_bits, int word)
{
int i, wout = 0;
for (i = 0; i < num_bits; i++)
wout |= (((word >> i) & 1) << (num_bits - i - 1));
return wout;
}
/*-------------------------------------------------------------------------*
* ED handling functions
*-------------------------------------------------------------------------*/
/* link an ed into one of the HC chains */
static int ep_link(ohci_t *ohci, ed_t *edi)
{
volatile ed_t *ed = edi;
int int_branch;
int i;
int inter;
int interval;
int load;
__u32 *ed_p;
ed->state = ED_OPER;
ed->int_interval = 0;
switch (ed->type) {
case PIPE_CONTROL:
ed->hwNextED = 0;
flush_dcache_ed(ed);
if (ohci->ed_controltail == NULL)
ohci_writel((uintptr_t)ed, &ohci->regs->ed_controlhead);
else
ohci->ed_controltail->hwNextED =
m32_swap((unsigned long)ed);
ed->ed_prev = ohci->ed_controltail;
if (!ohci->ed_controltail && !ohci->ed_rm_list[0] &&
!ohci->ed_rm_list[1] && !ohci->sleeping) {
ohci->hc_control |= OHCI_CTRL_CLE;
ohci_writel(ohci->hc_control, &ohci->regs->control);
}
ohci->ed_controltail = edi;
break;
case PIPE_BULK:
ed->hwNextED = 0;
flush_dcache_ed(ed);
if (ohci->ed_bulktail == NULL)
ohci_writel((uintptr_t)ed, &ohci->regs->ed_bulkhead);
else
ohci->ed_bulktail->hwNextED =
m32_swap((unsigned long)ed);
ed->ed_prev = ohci->ed_bulktail;
if (!ohci->ed_bulktail && !ohci->ed_rm_list[0] &&
!ohci->ed_rm_list[1] && !ohci->sleeping) {
ohci->hc_control |= OHCI_CTRL_BLE;
ohci_writel(ohci->hc_control, &ohci->regs->control);
}
ohci->ed_bulktail = edi;
break;
case PIPE_INTERRUPT:
load = ed->int_load;
interval = ep_2_n_interval(ed->int_period);
ed->int_interval = interval;
int_branch = ep_int_ballance(ohci, interval, load);
ed->int_branch = int_branch;
for (i = 0; i < ep_rev(6, interval); i += inter) {
inter = 1;
for (ed_p = &(ohci->hcca->int_table[\
ep_rev(5, i) + int_branch]);
(*ed_p != 0) &&
(((ed_t *)ed_p)->int_interval >= interval);
ed_p = &(((ed_t *)ed_p)->hwNextED))
inter = ep_rev(6,
((ed_t *)ed_p)->int_interval);
ed->hwNextED = *ed_p;
flush_dcache_ed(ed);
*ed_p = m32_swap((unsigned long)ed);
flush_dcache_hcca(ohci->hcca);
}
break;
}
return 0;
}
/*-------------------------------------------------------------------------*/
/* scan the periodic table to find and unlink this ED */
static void periodic_unlink(struct ohci *ohci, volatile struct ed *ed,
unsigned index, unsigned period)
{
__maybe_unused unsigned long aligned_ed_p;
for (; index < NUM_INTS; index += period) {
__u32 *ed_p = &ohci->hcca->int_table [index];
/* ED might have been unlinked through another path */
while (*ed_p != 0) {
if (((struct ed *)(uintptr_t)
m32_swap((unsigned long)ed_p)) == ed) {
*ed_p = ed->hwNextED;
aligned_ed_p = (unsigned long)ed_p;
aligned_ed_p &= ~(ARCH_DMA_MINALIGN - 1);
flush_dcache_range(aligned_ed_p,
aligned_ed_p + ARCH_DMA_MINALIGN);
break;
}
ed_p = &(((struct ed *)(uintptr_t)
m32_swap((unsigned long)ed_p))->hwNextED);
}
}
}
/* unlink an ed from one of the HC chains.
* just the link to the ed is unlinked.
* the link from the ed still points to another operational ed or 0
* so the HC can eventually finish the processing of the unlinked ed */
static int ep_unlink(ohci_t *ohci, ed_t *edi)
{
volatile ed_t *ed = edi;
int i;
ed->hwINFO |= m32_swap(OHCI_ED_SKIP);
flush_dcache_ed(ed);
switch (ed->type) {
case PIPE_CONTROL:
if (ed->ed_prev == NULL) {
if (!ed->hwNextED) {
ohci->hc_control &= ~OHCI_CTRL_CLE;
ohci_writel(ohci->hc_control,
&ohci->regs->control);
}
ohci_writel(m32_swap(*((__u32 *)&ed->hwNextED)),
&ohci->regs->ed_controlhead);
} else {
ed->ed_prev->hwNextED = ed->hwNextED;
flush_dcache_ed(ed->ed_prev);
}
if (ohci->ed_controltail == ed) {
ohci->ed_controltail = ed->ed_prev;
} else {
((ed_t *)(uintptr_t)m32_swap(
*((__u32 *)&ed->hwNextED)))->ed_prev = ed->ed_prev;
}
break;
case PIPE_BULK:
if (ed->ed_prev == NULL) {
if (!ed->hwNextED) {
ohci->hc_control &= ~OHCI_CTRL_BLE;
ohci_writel(ohci->hc_control,
&ohci->regs->control);
}
ohci_writel(m32_swap(*((__u32 *)&ed->hwNextED)),
&ohci->regs->ed_bulkhead);
} else {
ed->ed_prev->hwNextED = ed->hwNextED;
flush_dcache_ed(ed->ed_prev);
}
if (ohci->ed_bulktail == ed) {
ohci->ed_bulktail = ed->ed_prev;
} else {
((ed_t *)(uintptr_t)m32_swap(
*((__u32 *)&ed->hwNextED)))->ed_prev = ed->ed_prev;
}
break;
case PIPE_INTERRUPT:
periodic_unlink(ohci, ed, 0, 1);
for (i = ed->int_branch; i < 32; i += ed->int_interval)
ohci->ohci_int_load[i] -= ed->int_load;
break;
}
ed->state = ED_UNLINK;
return 0;
}
/*-------------------------------------------------------------------------*/
/* add/reinit an endpoint; this should be done once at the
* usb_set_configuration command, but the USB stack is a little bit
* stateless so we do it at every transaction if the state of the ed
* is ED_NEW then a dummy td is added and the state is changed to
* ED_UNLINK in all other cases the state is left unchanged the ed
* info fields are setted anyway even though most of them should not
* change
*/
static ed_t *ep_add_ed(ohci_dev_t *ohci_dev, struct usb_device *usb_dev,
unsigned long pipe, int interval, int load)
{
td_t *td;
ed_t *ed_ret;
volatile ed_t *ed;
ed = ed_ret = &ohci_dev->ed[(usb_pipeendpoint(pipe) << 1) |
(usb_pipecontrol(pipe)? 0: usb_pipeout(pipe))];
if ((ed->state & ED_DEL) || (ed->state & ED_URB_DEL)) {
err("ep_add_ed: pending delete");
/* pending delete request */
return NULL;
}
if (ed->state == ED_NEW) {
/* dummy td; end of td list for ed */
td = td_alloc(ohci_dev, usb_dev);
ed->hwTailP = m32_swap((unsigned long)td);
ed->hwHeadP = ed->hwTailP;
ed->state = ED_UNLINK;
ed->type = usb_pipetype(pipe);
ohci_dev->ed_cnt++;
}
ed->hwINFO = m32_swap(usb_pipedevice(pipe)
| usb_pipeendpoint(pipe) << 7
| (usb_pipeisoc(pipe)? 0x8000: 0)
| (usb_pipecontrol(pipe)? 0: \
(usb_pipeout(pipe)? 0x800: 0x1000))
| (usb_dev->speed == USB_SPEED_LOW) << 13
| usb_maxpacket(usb_dev, pipe) << 16);
if (ed->type == PIPE_INTERRUPT && ed->state == ED_UNLINK) {
ed->int_period = interval;
ed->int_load = load;
}
flush_dcache_ed(ed);
return ed_ret;
}
/*-------------------------------------------------------------------------*
* TD handling functions
*-------------------------------------------------------------------------*/
/* enqueue next TD for this URB (OHCI spec 5.2.8.2) */
static void td_fill(ohci_t *ohci, unsigned int info,
void *data, int len,
struct usb_device *dev, int index, urb_priv_t *urb_priv)
{
volatile td_t *td, *td_pt;
#ifdef OHCI_FILL_TRACE
int i;
#endif
if (index > urb_priv->length) {
err("index > length");
return;
}
/* use this td as the next dummy */
td_pt = urb_priv->td [index];
td_pt->hwNextTD = 0;
flush_dcache_td(td_pt);
/* fill the old dummy TD */
td = urb_priv->td [index] =
(td_t *)(uintptr_t)
(m32_swap(urb_priv->ed->hwTailP) & ~0xf);
td->ed = urb_priv->ed;
td->next_dl_td = NULL;
td->index = index;
td->data = (uintptr_t)data;
#ifdef OHCI_FILL_TRACE
if (usb_pipebulk(urb_priv->pipe) && usb_pipeout(urb_priv->pipe)) {
for (i = 0; i < len; i++)
printf("td->data[%d] %#2x ", i, ((unsigned char *)td->data)[i]);
printf("\n");
}
#endif
if (!len)
data = 0;
td->hwINFO = m32_swap(info);
td->hwCBP = m32_swap((unsigned long)data);
if (data)
td->hwBE = m32_swap((unsigned long)(data + len - 1));
else
td->hwBE = 0;
td->hwNextTD = m32_swap((unsigned long)td_pt);
flush_dcache_td(td);
/* append to queue */
td->ed->hwTailP = td->hwNextTD;
flush_dcache_ed(td->ed);
}
/*-------------------------------------------------------------------------*/
/* prepare all TDs of a transfer */
static void td_submit_job(ohci_t *ohci, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *setup, urb_priv_t *urb,
int interval)
{
int data_len = transfer_len;
void *data;
int cnt = 0;
__u32 info = 0;
unsigned int toggle = 0;
flush_dcache_buffer(buffer, data_len);
/* OHCI handles the DATA-toggles itself, we just use the USB-toggle
* bits for resetting */
if (usb_gettoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe))) {
toggle = TD_T_TOGGLE;
} else {
toggle = TD_T_DATA0;
usb_settoggle(dev, usb_pipeendpoint(pipe),
usb_pipeout(pipe), 1);
}
urb->td_cnt = 0;
if (data_len)
data = buffer;
else
data = 0;
switch (usb_pipetype(pipe)) {
case PIPE_BULK:
info = usb_pipeout(pipe)?
TD_CC | TD_DP_OUT : TD_CC | TD_DP_IN ;
while (data_len > 4096) {
td_fill(ohci, info | (cnt? TD_T_TOGGLE:toggle),
data, 4096, dev, cnt, urb);
data += 4096; data_len -= 4096; cnt++;
}
info = usb_pipeout(pipe)?
TD_CC | TD_DP_OUT : TD_CC | TD_R | TD_DP_IN ;
td_fill(ohci, info | (cnt? TD_T_TOGGLE:toggle), data,
data_len, dev, cnt, urb);
cnt++;
if (!ohci->sleeping) {
/* start bulk list */
ohci_writel(OHCI_BLF, &ohci->regs->cmdstatus);
}
break;
case PIPE_CONTROL:
/* Setup phase */
info = TD_CC | TD_DP_SETUP | TD_T_DATA0;
flush_dcache_buffer(setup, 8);
td_fill(ohci, info, setup, 8, dev, cnt++, urb);
/* Optional Data phase */
if (data_len > 0) {
info = usb_pipeout(pipe)?
TD_CC | TD_R | TD_DP_OUT | TD_T_DATA1 :
TD_CC | TD_R | TD_DP_IN | TD_T_DATA1;
/* NOTE: mishandles transfers >8K, some >4K */
td_fill(ohci, info, data, data_len, dev, cnt++, urb);
}
/* Status phase */
info = (usb_pipeout(pipe) || data_len == 0) ?
TD_CC | TD_DP_IN | TD_T_DATA1:
TD_CC | TD_DP_OUT | TD_T_DATA1;
td_fill(ohci, info, data, 0, dev, cnt++, urb);
if (!ohci->sleeping) {
/* start Control list */
ohci_writel(OHCI_CLF, &ohci->regs->cmdstatus);
}
break;
case PIPE_INTERRUPT:
info = usb_pipeout(urb->pipe)?
TD_CC | TD_DP_OUT | toggle:
TD_CC | TD_R | TD_DP_IN | toggle;
td_fill(ohci, info, data, data_len, dev, cnt++, urb);
break;
}
if (urb->length != cnt)
dbg("TD LENGTH %d != CNT %d", urb->length, cnt);
}
/*-------------------------------------------------------------------------*
* Done List handling functions
*-------------------------------------------------------------------------*/
/* calculate the transfer length and update the urb */
static void dl_transfer_length(td_t *td)
{
__u32 tdBE, tdCBP;
urb_priv_t *lurb_priv = td->ed->purb;
tdBE = m32_swap(td->hwBE);
tdCBP = m32_swap(td->hwCBP);
if (!(usb_pipecontrol(lurb_priv->pipe) &&
((td->index == 0) || (td->index == lurb_priv->length - 1)))) {
if (tdBE != 0) {
if (td->hwCBP == 0)
lurb_priv->actual_length += tdBE - td->data + 1;
else
lurb_priv->actual_length += tdCBP - td->data;
}
}
}
/*-------------------------------------------------------------------------*/
static void check_status(td_t *td_list)
{
urb_priv_t *lurb_priv = td_list->ed->purb;
int urb_len = lurb_priv->length;
__u32 *phwHeadP = &td_list->ed->hwHeadP;
int cc;
cc = TD_CC_GET(m32_swap(td_list->hwINFO));
if (cc) {
err(" USB-error: %s (%x)", cc_to_string[cc], cc);
invalidate_dcache_ed(td_list->ed);
if (*phwHeadP & m32_swap(0x1)) {
if (lurb_priv &&
((td_list->index + 1) < urb_len)) {
*phwHeadP =
(lurb_priv->td[urb_len - 1]->hwNextTD &\
m32_swap(0xfffffff0)) |
(*phwHeadP & m32_swap(0x2));
lurb_priv->td_cnt += urb_len -
td_list->index - 1;
} else
*phwHeadP &= m32_swap(0xfffffff2);
flush_dcache_ed(td_list->ed);
}
}
}
/* replies to the request have to be on a FIFO basis so
* we reverse the reversed done-list */
static td_t *dl_reverse_done_list(ohci_t *ohci)
{
uintptr_t td_list_hc;
td_t *td_rev = NULL;
td_t *td_list = NULL;
invalidate_dcache_hcca(ohci->hcca);
td_list_hc = m32_swap(ohci->hcca->done_head) & 0xfffffff0;
ohci->hcca->done_head = 0;
flush_dcache_hcca(ohci->hcca);
while (td_list_hc) {
td_list = (td_t *)td_list_hc;
invalidate_dcache_td(td_list);
check_status(td_list);
td_list->next_dl_td = td_rev;
td_rev = td_list;
td_list_hc = m32_swap(td_list->hwNextTD) & 0xfffffff0;
}
return td_list;
}
/*-------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
static void finish_urb(ohci_t *ohci, urb_priv_t *urb, int status)
{
if ((status & (ED_OPER | ED_UNLINK)) && (urb->state != URB_DEL))
urb->finished = 1;
else
dbg("finish_urb: strange.., ED state %x, \n", status);
}
/*
* Used to take back a TD from the host controller. This would normally be
* called from within dl_done_list, however it may be called directly if the
* HC no longer sees the TD and it has not appeared on the donelist (after
* two frames). This bug has been observed on ZF Micro systems.
*/
static int takeback_td(ohci_t *ohci, td_t *td_list)
{
ed_t *ed;
int cc;
int stat = 0;
/* urb_t *urb; */
urb_priv_t *lurb_priv;
__u32 tdINFO, edHeadP, edTailP;
invalidate_dcache_td(td_list);
tdINFO = m32_swap(td_list->hwINFO);
ed = td_list->ed;
lurb_priv = ed->purb;
dl_transfer_length(td_list);
lurb_priv->td_cnt++;
/* error code of transfer */
cc = TD_CC_GET(tdINFO);
if (cc) {
err("USB-error: %s (%x)", cc_to_string[cc], cc);
stat = cc_to_error[cc];
}
/* see if this done list makes for all TD's of current URB,
* and mark the URB finished if so */
if (lurb_priv->td_cnt == lurb_priv->length)
finish_urb(ohci, lurb_priv, ed->state);
dbg("dl_done_list: processing TD %x, len %x\n",
lurb_priv->td_cnt, lurb_priv->length);
if (ed->state != ED_NEW && (!usb_pipeint(lurb_priv->pipe))) {
invalidate_dcache_ed(ed);
edHeadP = m32_swap(ed->hwHeadP) & 0xfffffff0;
edTailP = m32_swap(ed->hwTailP);
/* unlink eds if they are not busy */
if ((edHeadP == edTailP) && (ed->state == ED_OPER))
ep_unlink(ohci, ed);
}
return stat;
}
static int dl_done_list(ohci_t *ohci)
{
int stat = 0;
td_t *td_list = dl_reverse_done_list(ohci);
while (td_list) {
td_t *td_next = td_list->next_dl_td;
stat = takeback_td(ohci, td_list);
td_list = td_next;
}
return stat;
}
/*-------------------------------------------------------------------------*
* Virtual Root Hub
*-------------------------------------------------------------------------*/
#include <usbroothubdes.h>
/* Hub class-specific descriptor is constructed dynamically */
/*-------------------------------------------------------------------------*/
#define OK(x) len = (x); break
#ifdef DEBUG
#define WR_RH_STAT(x) {info("WR:status %#8x", (x)); ohci_writel((x), \
&ohci->regs->roothub.status); }
#define WR_RH_PORTSTAT(x) {info("WR:portstatus[%d] %#8x", wIndex-1, \
(x)); ohci_writel((x), &ohci->regs->roothub.portstatus[wIndex-1]); }
#else
#define WR_RH_STAT(x) ohci_writel((x), &ohci->regs->roothub.status)
#define WR_RH_PORTSTAT(x) ohci_writel((x), \
&ohci->regs->roothub.portstatus[wIndex-1])
#endif
#define RD_RH_STAT roothub_status(ohci)
#define RD_RH_PORTSTAT roothub_portstatus(ohci, wIndex-1)
/* request to virtual root hub */
int rh_check_port_status(ohci_t *controller)
{
__u32 temp, ndp, i;
int res;
res = -1;
temp = roothub_a(controller);
ndp = (temp & RH_A_NDP);
#ifdef CONFIG_AT91C_PQFP_UHPBUG
ndp = (ndp == 2) ? 1:0;
#endif
for (i = 0; i < ndp; i++) {
temp = roothub_portstatus(controller, i);
/* check for a device disconnect */
if (((temp & (RH_PS_PESC | RH_PS_CSC)) ==
(RH_PS_PESC | RH_PS_CSC)) &&
((temp & RH_PS_CCS) == 0)) {
res = i;
break;
}
}
return res;
}
static int ohci_submit_rh_msg(ohci_t *ohci, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *cmd)
{
void *data = buffer;
int leni = transfer_len;
int len = 0;
int stat = 0;
__u16 bmRType_bReq;
__u16 wValue;
__u16 wIndex;
__u16 wLength;
ALLOC_ALIGN_BUFFER(__u8, databuf, 16, sizeof(u32));
#ifdef DEBUG
pkt_print(ohci, NULL, dev, pipe, buffer, transfer_len,
cmd, "SUB(rh)", usb_pipein(pipe));
#else
ohci_mdelay(1);
#endif
if (usb_pipeint(pipe)) {
info("Root-Hub submit IRQ: NOT implemented");
return 0;
}
bmRType_bReq = cmd->requesttype | (cmd->request << 8);
wValue = le16_to_cpu(cmd->value);
wIndex = le16_to_cpu(cmd->index);
wLength = le16_to_cpu(cmd->length);
info("Root-Hub: adr: %2x cmd(%1x): %08x %04x %04x %04x",
dev->devnum, 8, bmRType_bReq, wValue, wIndex, wLength);
switch (bmRType_bReq) {
/* Request Destination:
without flags: Device,
RH_INTERFACE: interface,
RH_ENDPOINT: endpoint,
RH_CLASS means HUB here,
RH_OTHER | RH_CLASS almost ever means HUB_PORT here
*/
case RH_GET_STATUS:
*(u16 *)databuf = cpu_to_le16(1);
OK(2);
case RH_GET_STATUS | RH_INTERFACE:
*(u16 *)databuf = cpu_to_le16(0);
OK(2);
case RH_GET_STATUS | RH_ENDPOINT:
*(u16 *)databuf = cpu_to_le16(0);
OK(2);
case RH_GET_STATUS | RH_CLASS:
*(u32 *)databuf = cpu_to_le32(
RD_RH_STAT & ~(RH_HS_CRWE | RH_HS_DRWE));
OK(4);
case RH_GET_STATUS | RH_OTHER | RH_CLASS:
*(u32 *)databuf = cpu_to_le32(RD_RH_PORTSTAT);
OK(4);
case RH_CLEAR_FEATURE | RH_ENDPOINT:
switch (wValue) {
case (RH_ENDPOINT_STALL):
OK(0);
}
break;
case RH_CLEAR_FEATURE | RH_CLASS:
switch (wValue) {
case RH_C_HUB_LOCAL_POWER:
OK(0);
case (RH_C_HUB_OVER_CURRENT):
WR_RH_STAT(RH_HS_OCIC);
OK(0);
}
break;
case RH_CLEAR_FEATURE | RH_OTHER | RH_CLASS:
switch (wValue) {
case (RH_PORT_ENABLE): WR_RH_PORTSTAT(RH_PS_CCS); OK(0);
case (RH_PORT_SUSPEND): WR_RH_PORTSTAT(RH_PS_POCI); OK(0);
case (RH_PORT_POWER): WR_RH_PORTSTAT(RH_PS_LSDA); OK(0);
case (RH_C_PORT_CONNECTION): WR_RH_PORTSTAT(RH_PS_CSC); OK(0);
case (RH_C_PORT_ENABLE): WR_RH_PORTSTAT(RH_PS_PESC); OK(0);
case (RH_C_PORT_SUSPEND): WR_RH_PORTSTAT(RH_PS_PSSC); OK(0);
case (RH_C_PORT_OVER_CURRENT):WR_RH_PORTSTAT(RH_PS_OCIC); OK(0);
case (RH_C_PORT_RESET): WR_RH_PORTSTAT(RH_PS_PRSC); OK(0);
}
break;
case RH_SET_FEATURE | RH_OTHER | RH_CLASS:
switch (wValue) {
case (RH_PORT_SUSPEND):
WR_RH_PORTSTAT(RH_PS_PSS); OK(0);
case (RH_PORT_RESET): /* BUG IN HUP CODE *********/
if (RD_RH_PORTSTAT & RH_PS_CCS)
WR_RH_PORTSTAT(RH_PS_PRS);
OK(0);
case (RH_PORT_POWER):
WR_RH_PORTSTAT(RH_PS_PPS);
OK(0);
case (RH_PORT_ENABLE): /* BUG IN HUP CODE *********/
if (RD_RH_PORTSTAT & RH_PS_CCS)
WR_RH_PORTSTAT(RH_PS_PES);
OK(0);
}
break;
case RH_SET_ADDRESS:
ohci->rh.devnum = wValue;
OK(0);
case RH_GET_DESCRIPTOR:
switch ((wValue & 0xff00) >> 8) {
case (0x01): /* device descriptor */
len = min_t(unsigned int,
leni,
min_t(unsigned int,
sizeof(root_hub_dev_des),
wLength));
databuf = root_hub_dev_des; OK(len);
case (0x02): /* configuration descriptor */
len = min_t(unsigned int,
leni,
min_t(unsigned int,
sizeof(root_hub_config_des),
wLength));
databuf = root_hub_config_des; OK(len);
case (0x03): /* string descriptors */
if (wValue == 0x0300) {
len = min_t(unsigned int,
leni,
min_t(unsigned int,
sizeof(root_hub_str_index0),
wLength));
databuf = root_hub_str_index0;
OK(len);
}
if (wValue == 0x0301) {
len = min_t(unsigned int,
leni,
min_t(unsigned int,
sizeof(root_hub_str_index1),
wLength));
databuf = root_hub_str_index1;
OK(len);
}
default:
stat = USB_ST_STALLED;
}
break;
case RH_GET_DESCRIPTOR | RH_CLASS:
{
__u32 temp = roothub_a(ohci);
databuf[0] = 9; /* min length; */
databuf[1] = 0x29;
databuf[2] = temp & RH_A_NDP;
#ifdef CONFIG_AT91C_PQFP_UHPBUG
databuf[2] = (databuf[2] == 2) ? 1 : 0;
#endif
databuf[3] = 0;
if (temp & RH_A_PSM) /* per-port power switching? */
databuf[3] |= 0x1;
if (temp & RH_A_NOCP) /* no overcurrent reporting? */
databuf[3] |= 0x10;
else if (temp & RH_A_OCPM)/* per-port overcurrent reporting? */
databuf[3] |= 0x8;
databuf[4] = 0;
databuf[5] = (temp & RH_A_POTPGT) >> 24;
databuf[6] = 0;
temp = roothub_b(ohci);
databuf[7] = temp & RH_B_DR;
if (databuf[2] < 7) {
databuf[8] = 0xff;
} else {
databuf[0] += 2;
databuf[8] = (temp & RH_B_DR) >> 8;
databuf[10] = databuf[9] = 0xff;
}
len = min_t(unsigned int, leni,
min_t(unsigned int, databuf[0], wLength));
OK(len);
}
case RH_GET_CONFIGURATION:
databuf[0] = 0x01;
OK(1);
case RH_SET_CONFIGURATION:
WR_RH_STAT(0x10000);
OK(0);
default:
dbg("unsupported root hub command");
stat = USB_ST_STALLED;
}
#ifdef DEBUG
ohci_dump_roothub(ohci, 1);
#else
ohci_mdelay(1);
#endif
len = min_t(int, len, leni);
if (data != databuf)
memcpy(data, databuf, len);
dev->act_len = len;
dev->status = stat;
#ifdef DEBUG
pkt_print(ohci, NULL, dev, pipe, buffer,
transfer_len, cmd, "RET(rh)", 0/*usb_pipein(pipe)*/);
#else
ohci_mdelay(1);
#endif
return stat;
}
/*-------------------------------------------------------------------------*/
static ohci_dev_t *ohci_get_ohci_dev(ohci_t *ohci, int devnum, int intr)
{
int i;
if (!intr)
return &ohci->ohci_dev;
/* First see if we already have an ohci_dev for this dev. */
for (i = 0; i < NUM_INT_DEVS; i++) {
if (ohci->int_dev[i].devnum == devnum)
return &ohci->int_dev[i];
}
/* If not then find a free one. */
for (i = 0; i < NUM_INT_DEVS; i++) {
if (ohci->int_dev[i].devnum == -1) {
ohci->int_dev[i].devnum = devnum;
return &ohci->int_dev[i];
}
}
printf("ohci: Error out of ohci_devs for interrupt endpoints\n");
return NULL;
}
/* common code for handling submit messages - used for all but root hub */
/* accesses. */
static urb_priv_t *ohci_alloc_urb(struct usb_device *dev, unsigned long pipe,
void *buffer, int transfer_len, int interval)
{
urb_priv_t *urb;
urb = calloc(1, sizeof(urb_priv_t));
if (!urb) {
printf("ohci: Error out of memory allocating urb\n");
return NULL;
}
urb->dev = dev;
urb->pipe = pipe;
urb->transfer_buffer = buffer;
urb->transfer_buffer_length = transfer_len;
urb->interval = interval;
return urb;
}
static int submit_common_msg(ohci_t *ohci, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *setup, int interval)
{
int stat = 0;
int maxsize = usb_maxpacket(dev, pipe);
int timeout;
urb_priv_t *urb;
ohci_dev_t *ohci_dev;
urb = ohci_alloc_urb(dev, pipe, buffer, transfer_len, interval);
if (!urb)
return -ENOMEM;
#ifdef DEBUG
urb->actual_length = 0;
pkt_print(ohci, urb, dev, pipe, buffer, transfer_len,
setup, "SUB", usb_pipein(pipe));
#else
ohci_mdelay(1);
#endif
if (!maxsize) {
err("submit_common_message: pipesize for pipe %lx is zero",
pipe);
return -1;
}
ohci_dev = ohci_get_ohci_dev(ohci, dev->devnum, usb_pipeint(pipe));
if (!ohci_dev)
return -ENOMEM;
if (sohci_submit_job(ohci, ohci_dev, urb, setup) < 0) {
err("sohci_submit_job failed");
return -1;
}
#if 0
mdelay(10);
/* ohci_dump_status(ohci); */
#endif
timeout = USB_TIMEOUT_MS(pipe);
/* wait for it to complete */
for (;;) {
/* check whether the controller is done */
stat = hc_interrupt(ohci);
if (stat < 0) {
stat = USB_ST_CRC_ERR;
break;
}
/* NOTE: since we are not interrupt driven in U-Boot and always
* handle only one URB at a time, we cannot assume the
* transaction finished on the first successful return from
* hc_interrupt().. unless the flag for current URB is set,
* meaning that all TD's to/from device got actually
* transferred and processed. If the current URB is not
* finished we need to re-iterate this loop so as
* hc_interrupt() gets called again as there needs to be some
* more TD's to process still */
if ((stat >= 0) && (stat != 0xff) && (urb->finished)) {
/* 0xff is returned for an SF-interrupt */
break;
}
if (--timeout) {
mdelay(1);
if (!urb->finished)
dbg("*");
} else {
if (!usb_pipeint(pipe))
err("CTL:TIMEOUT ");
dbg("submit_common_msg: TO status %x\n", stat);
urb->finished = 1;
stat = USB_ST_CRC_ERR;
break;
}
}
dev->status = stat;
dev->act_len = urb->actual_length;
if (usb_pipein(pipe) && dev->status == 0 && dev->act_len)
invalidate_dcache_buffer(buffer, dev->act_len);
#ifdef DEBUG
pkt_print(ohci, urb, dev, pipe, buffer, transfer_len,
setup, "RET(ctlr)", usb_pipein(pipe));
#else
ohci_mdelay(1);
#endif
urb_free_priv(urb);
return 0;
}
#define MAX_INT_QUEUESIZE 8
struct int_queue {
int queuesize;
int curr_urb;
urb_priv_t *urb[MAX_INT_QUEUESIZE];
};
static struct int_queue *_ohci_create_int_queue(ohci_t *ohci,
struct usb_device *udev, unsigned long pipe, int queuesize,
int elementsize, void *buffer, int interval)
{
struct int_queue *queue;
ohci_dev_t *ohci_dev;
int i;
if (queuesize > MAX_INT_QUEUESIZE)
return NULL;
ohci_dev = ohci_get_ohci_dev(ohci, udev->devnum, 1);
if (!ohci_dev)
return NULL;
queue = malloc(sizeof(*queue));
if (!queue) {
printf("ohci: Error out of memory allocating int queue\n");
return NULL;
}
for (i = 0; i < queuesize; i++) {
queue->urb[i] = ohci_alloc_urb(udev, pipe,
buffer + i * elementsize,
elementsize, interval);
if (!queue->urb[i])
break;
if (sohci_submit_job(ohci, ohci_dev, queue->urb[i], NULL)) {
printf("ohci: Error submitting int queue job\n");
urb_free_priv(queue->urb[i]);
break;
}
}
if (i == 0) {
/* We did not succeed in submitting even 1 urb */
free(queue);
return NULL;
}
queue->queuesize = i;
queue->curr_urb = 0;
return queue;
}
static void *_ohci_poll_int_queue(ohci_t *ohci, struct usb_device *udev,
struct int_queue *queue)
{
if (queue->curr_urb == queue->queuesize)
return NULL; /* Queue depleted */
if (hc_interrupt(ohci) < 0)
return NULL;
if (queue->urb[queue->curr_urb]->finished) {
void *ret = queue->urb[queue->curr_urb]->transfer_buffer;
queue->curr_urb++;
return ret;
}
return NULL;
}
static int _ohci_destroy_int_queue(ohci_t *ohci, struct usb_device *dev,
struct int_queue *queue)
{
int i;
for (i = 0; i < queue->queuesize; i++)
urb_free_priv(queue->urb[i]);
free(queue);
return 0;
}
#ifndef CONFIG_DM_USB
/* submit routines called from usb.c */
int submit_bulk_msg(struct usb_device *dev, unsigned long pipe, void *buffer,
int transfer_len)
{
info("submit_bulk_msg");
return submit_common_msg(&gohci, dev, pipe, buffer, transfer_len,
NULL, 0);
}
int submit_int_msg(struct usb_device *dev, unsigned long pipe, void *buffer,
int transfer_len, int interval)
{
info("submit_int_msg");
return submit_common_msg(&gohci, dev, pipe, buffer, transfer_len, NULL,
interval);
}
struct int_queue *create_int_queue(struct usb_device *dev,
unsigned long pipe, int queuesize, int elementsize,
void *buffer, int interval)
{
return _ohci_create_int_queue(&gohci, dev, pipe, queuesize,
elementsize, buffer, interval);
}
void *poll_int_queue(struct usb_device *dev, struct int_queue *queue)
{
return _ohci_poll_int_queue(&gohci, dev, queue);
}
int destroy_int_queue(struct usb_device *dev, struct int_queue *queue)
{
return _ohci_destroy_int_queue(&gohci, dev, queue);
}
#endif
static int _ohci_submit_control_msg(ohci_t *ohci, struct usb_device *dev,
unsigned long pipe, void *buffer, int transfer_len,
struct devrequest *setup)
{
int maxsize = usb_maxpacket(dev, pipe);
info("submit_control_msg");
#ifdef DEBUG
pkt_print(ohci, NULL, dev, pipe, buffer, transfer_len,
setup, "SUB", usb_pipein(pipe));
#else
ohci_mdelay(1);
#endif
if (!maxsize) {
err("submit_control_message: pipesize for pipe %lx is zero",
pipe);
return -1;
}
if (((pipe >> 8) & 0x7f) == ohci->rh.devnum) {
ohci->rh.dev = dev;
/* root hub - redirect */
return ohci_submit_rh_msg(ohci, dev, pipe, buffer,
transfer_len, setup);
}
return submit_common_msg(ohci, dev, pipe, buffer, transfer_len,
setup, 0);
}
/*-------------------------------------------------------------------------*
* HC functions
*-------------------------------------------------------------------------*/
/* reset the HC and BUS */
static int hc_reset(ohci_t *ohci)
{
#ifdef CONFIG_PCI_EHCI_DEVNO
pci_dev_t pdev;
#endif
int timeout = 30;
int smm_timeout = 50; /* 0,5 sec */
dbg("%s\n", __FUNCTION__);
#ifdef CONFIG_PCI_EHCI_DEVNO
/*
* Some multi-function controllers (e.g. ISP1562) allow root hub
* resetting via EHCI registers only.
*/
pdev = pci_find_devices(ehci_pci_ids, CONFIG_PCI_EHCI_DEVNO);
if (pdev != -1) {
u32 base;
int timeout = 1000;
pci_read_config_dword(pdev, PCI_BASE_ADDRESS_0, &base);
base += EHCI_USBCMD_OFF;
ohci_writel(ohci_readl(base) | EHCI_USBCMD_HCRESET, base);
while (ohci_readl(base) & EHCI_USBCMD_HCRESET) {
if (timeout-- <= 0) {
printf("USB RootHub reset timed out!");
break;
}
udelay(1);
}
} else
printf("No EHCI func at %d index!\n", CONFIG_PCI_EHCI_DEVNO);
#endif
if (ohci_readl(&ohci->regs->control) & OHCI_CTRL_IR) {
/* SMM owns the HC, request ownership */
ohci_writel(OHCI_OCR, &ohci->regs->cmdstatus);
info("USB HC TakeOver from SMM");
while (ohci_readl(&ohci->regs->control) & OHCI_CTRL_IR) {
mdelay(10);
if (--smm_timeout == 0) {
err("USB HC TakeOver failed!");
return -1;
}
}
}
/* Disable HC interrupts */
ohci_writel(OHCI_INTR_MIE, &ohci->regs->intrdisable);
dbg("USB HC reset_hc usb-%s: ctrl = 0x%X ;\n",
ohci->slot_name,
ohci_readl(&ohci->regs->control));
/* Reset USB (needed by some controllers) */
ohci->hc_control = 0;
ohci_writel(ohci->hc_control, &ohci->regs->control);
/* HC Reset requires max 10 us delay */
ohci_writel(OHCI_HCR, &ohci->regs->cmdstatus);
while ((ohci_readl(&ohci->regs->cmdstatus) & OHCI_HCR) != 0) {
if (--timeout == 0) {
err("USB HC reset timed out!");
return -1;
}
udelay(1);
}
return 0;
}
/*-------------------------------------------------------------------------*/
/* Start an OHCI controller, set the BUS operational
* enable interrupts
* connect the virtual root hub */
static int hc_start(ohci_t *ohci)
{
__u32 mask;
unsigned int fminterval;
int i;
ohci->disabled = 1;
for (i = 0; i < NUM_INT_DEVS; i++)
ohci->int_dev[i].devnum = -1;
/* Tell the controller where the control and bulk lists are
* The lists are empty now. */
ohci_writel(0, &ohci->regs->ed_controlhead);
ohci_writel(0, &ohci->regs->ed_bulkhead);
ohci_writel((uintptr_t)ohci->hcca,
&ohci->regs->hcca); /* reset clears this */
fminterval = 0x2edf;
ohci_writel((fminterval * 9) / 10, &ohci->regs->periodicstart);
fminterval |= ((((fminterval - 210) * 6) / 7) << 16);
ohci_writel(fminterval, &ohci->regs->fminterval);
ohci_writel(0x628, &ohci->regs->lsthresh);
/* start controller operations */
ohci->hc_control = OHCI_CONTROL_INIT | OHCI_USB_OPER;
ohci->disabled = 0;
ohci_writel(ohci->hc_control, &ohci->regs->control);
/* disable all interrupts */
mask = (OHCI_INTR_SO | OHCI_INTR_WDH | OHCI_INTR_SF | OHCI_INTR_RD |
OHCI_INTR_UE | OHCI_INTR_FNO | OHCI_INTR_RHSC |
OHCI_INTR_OC | OHCI_INTR_MIE);
ohci_writel(mask, &ohci->regs->intrdisable);
/* clear all interrupts */
mask &= ~OHCI_INTR_MIE;
ohci_writel(mask, &ohci->regs->intrstatus);
/* Choose the interrupts we care about now - but w/o MIE */
mask = OHCI_INTR_RHSC | OHCI_INTR_UE | OHCI_INTR_WDH | OHCI_INTR_SO;
ohci_writel(mask, &ohci->regs->intrenable);
#ifdef OHCI_USE_NPS
/* required for AMD-756 and some Mac platforms */
ohci_writel((roothub_a(ohci) | RH_A_NPS) & ~RH_A_PSM,
&ohci->regs->roothub.a);
ohci_writel(RH_HS_LPSC, &ohci->regs->roothub.status);
#endif /* OHCI_USE_NPS */
/* connect the virtual root hub */
ohci->rh.devnum = 0;
return 0;
}
/*-------------------------------------------------------------------------*/
/* an interrupt happens */
static int hc_interrupt(ohci_t *ohci)
{
struct ohci_regs *regs = ohci->regs;
int ints;
int stat = -1;
invalidate_dcache_hcca(ohci->hcca);
if ((ohci->hcca->done_head != 0) &&
!(m32_swap(ohci->hcca->done_head) & 0x01)) {
ints = OHCI_INTR_WDH;
} else {
ints = ohci_readl(®s->intrstatus);
if (ints == ~(u32)0) {
ohci->disabled++;
err("%s device removed!", ohci->slot_name);
return -1;
} else {
ints &= ohci_readl(®s->intrenable);
if (ints == 0) {
dbg("hc_interrupt: returning..\n");
return 0xff;
}
}
}
/* dbg("Interrupt: %x frame: %x", ints,
le16_to_cpu(ohci->hcca->frame_no)); */
if (ints & OHCI_INTR_RHSC)
stat = 0xff;
if (ints & OHCI_INTR_UE) {
ohci->disabled++;
err("OHCI Unrecoverable Error, controller usb-%s disabled",
ohci->slot_name);
/* e.g. due to PCI Master/Target Abort */
#ifdef DEBUG
ohci_dump(ohci, 1);
#else
ohci_mdelay(1);
#endif
/* FIXME: be optimistic, hope that bug won't repeat often. */
/* Make some non-interrupt context restart the controller. */
/* Count and limit the retries though; either hardware or */
/* software errors can go forever... */
hc_reset(ohci);
return -1;
}
if (ints & OHCI_INTR_WDH) {
ohci_mdelay(1);
ohci_writel(OHCI_INTR_WDH, ®s->intrdisable);
(void)ohci_readl(®s->intrdisable); /* flush */
stat = dl_done_list(ohci);
ohci_writel(OHCI_INTR_WDH, ®s->intrenable);
(void)ohci_readl(®s->intrdisable); /* flush */
}
if (ints & OHCI_INTR_SO) {
dbg("USB Schedule overrun\n");
ohci_writel(OHCI_INTR_SO, ®s->intrenable);
stat = -1;
}
/* FIXME: this assumes SOF (1/ms) interrupts don't get lost... */
if (ints & OHCI_INTR_SF) {
unsigned int frame = m16_swap(ohci->hcca->frame_no) & 1;
mdelay(1);
ohci_writel(OHCI_INTR_SF, ®s->intrdisable);
if (ohci->ed_rm_list[frame] != NULL)
ohci_writel(OHCI_INTR_SF, ®s->intrenable);
stat = 0xff;
}
ohci_writel(ints, ®s->intrstatus);
return stat;
}
/*-------------------------------------------------------------------------*/
#ifndef CONFIG_DM_USB
/*-------------------------------------------------------------------------*/
/* De-allocate all resources.. */
static void hc_release_ohci(ohci_t *ohci)
{
dbg("USB HC release ohci usb-%s", ohci->slot_name);
if (!ohci->disabled)
hc_reset(ohci);
}
/*-------------------------------------------------------------------------*/
/*
* low level initalisation routine, called from usb.c
*/
static char ohci_inited = 0;
int usb_lowlevel_init(int index, enum usb_init_type init, void **controller)
{
#ifdef CONFIG_PCI_OHCI
pci_dev_t pdev;
#endif
#ifdef CONFIG_SYS_USB_OHCI_CPU_INIT
/* cpu dependant init */
if (usb_cpu_init())
return -1;
#endif
#ifdef CONFIG_SYS_USB_OHCI_BOARD_INIT
/* board dependant init */
if (board_usb_init(index, USB_INIT_HOST))
return -1;
#endif
memset(&gohci, 0, sizeof(ohci_t));
/* align the storage */
if ((__u32)&ghcca[0] & 0xff) {
err("HCCA not aligned!!");
return -1;
}
gohci.hcca = &ghcca[0];
info("aligned ghcca %p", gohci.hcca);
memset(gohci.hcca, 0, sizeof(struct ohci_hcca));
gohci.disabled = 1;
gohci.sleeping = 0;
gohci.irq = -1;
#ifdef CONFIG_PCI_OHCI
pdev = pci_find_devices(ohci_pci_ids, CONFIG_PCI_OHCI_DEVNO);
if (pdev != -1) {
u16 vid, did;
u32 base;
pci_read_config_word(pdev, PCI_VENDOR_ID, &vid);
pci_read_config_word(pdev, PCI_DEVICE_ID, &did);
printf("OHCI pci controller (%04x, %04x) found @(%d:%d:%d)\n",
vid, did, (pdev >> 16) & 0xff,
(pdev >> 11) & 0x1f, (pdev >> 8) & 0x7);
pci_read_config_dword(pdev, PCI_BASE_ADDRESS_0, &base);
printf("OHCI regs address 0x%08x\n", base);
gohci.regs = (struct ohci_regs *)base;
} else
return -1;
#else
gohci.regs = (struct ohci_regs *)CONFIG_SYS_USB_OHCI_REGS_BASE;
#endif
gohci.flags = 0;
gohci.slot_name = CONFIG_SYS_USB_OHCI_SLOT_NAME;
if (hc_reset (&gohci) < 0) {
hc_release_ohci (&gohci);
err ("can't reset usb-%s", gohci.slot_name);
#ifdef CONFIG_SYS_USB_OHCI_BOARD_INIT
/* board dependant cleanup */
board_usb_cleanup(index, USB_INIT_HOST);
#endif
#ifdef CONFIG_SYS_USB_OHCI_CPU_INIT
/* cpu dependant cleanup */
usb_cpu_init_fail();
#endif
return -1;
}
if (hc_start(&gohci) < 0) {
err("can't start usb-%s", gohci.slot_name);
hc_release_ohci(&gohci);
/* Initialization failed */
#ifdef CONFIG_SYS_USB_OHCI_BOARD_INIT
/* board dependant cleanup */
usb_board_stop();
#endif
#ifdef CONFIG_SYS_USB_OHCI_CPU_INIT
/* cpu dependant cleanup */
usb_cpu_stop();
#endif
return -1;
}
#ifdef DEBUG
ohci_dump(&gohci, 1);
#else
ohci_mdelay(1);
#endif
ohci_inited = 1;
return 0;
}
int usb_lowlevel_stop(int index)
{
/* this gets called really early - before the controller has */
/* even been initialized! */
if (!ohci_inited)
return 0;
/* TODO release any interrupts, etc. */
/* call hc_release_ohci() here ? */
hc_reset(&gohci);
#ifdef CONFIG_SYS_USB_OHCI_BOARD_INIT
/* board dependant cleanup */
if (usb_board_stop())
return -1;
#endif
#ifdef CONFIG_SYS_USB_OHCI_CPU_INIT
/* cpu dependant cleanup */
if (usb_cpu_stop())
return -1;
#endif
/* This driver is no longer initialised. It needs a new low-level
* init (board/cpu) before it can be used again. */
ohci_inited = 0;
return 0;
}
int submit_control_msg(struct usb_device *dev, unsigned long pipe,
void *buffer, int transfer_len, struct devrequest *setup)
{
return _ohci_submit_control_msg(&gohci, dev, pipe, buffer,
transfer_len, setup);
}
#endif
#ifdef CONFIG_DM_USB
static int ohci_submit_control_msg(struct udevice *dev, struct usb_device *udev,
unsigned long pipe, void *buffer, int length,
struct devrequest *setup)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return _ohci_submit_control_msg(ohci, udev, pipe, buffer,
length, setup);
}
static int ohci_submit_bulk_msg(struct udevice *dev, struct usb_device *udev,
unsigned long pipe, void *buffer, int length)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return submit_common_msg(ohci, udev, pipe, buffer, length, NULL, 0);
}
static int ohci_submit_int_msg(struct udevice *dev, struct usb_device *udev,
unsigned long pipe, void *buffer, int length,
int interval)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return submit_common_msg(ohci, udev, pipe, buffer, length,
NULL, interval);
}
static struct int_queue *ohci_create_int_queue(struct udevice *dev,
struct usb_device *udev, unsigned long pipe, int queuesize,
int elementsize, void *buffer, int interval)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return _ohci_create_int_queue(ohci, udev, pipe, queuesize, elementsize,
buffer, interval);
}
static void *ohci_poll_int_queue(struct udevice *dev, struct usb_device *udev,
struct int_queue *queue)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return _ohci_poll_int_queue(ohci, udev, queue);
}
static int ohci_destroy_int_queue(struct udevice *dev, struct usb_device *udev,
struct int_queue *queue)
{
ohci_t *ohci = dev_get_priv(usb_get_bus(dev));
return _ohci_destroy_int_queue(ohci, udev, queue);
}
int ohci_register(struct udevice *dev, struct ohci_regs *regs)
{
struct usb_bus_priv *priv = dev_get_uclass_priv(dev);
ohci_t *ohci = dev_get_priv(dev);
u32 reg;
priv->desc_before_addr = true;
ohci->regs = regs;
ohci->hcca = memalign(256, sizeof(struct ohci_hcca));
if (!ohci->hcca)
return -ENOMEM;
memset(ohci->hcca, 0, sizeof(struct ohci_hcca));
flush_dcache_hcca(ohci->hcca);
if (hc_reset(ohci) < 0)
return -EIO;
if (hc_start(ohci) < 0)
return -EIO;
reg = ohci_readl(®s->revision);
printf("USB OHCI %x.%x\n", (reg >> 4) & 0xf, reg & 0xf);
return 0;
}
int ohci_deregister(struct udevice *dev)
{
ohci_t *ohci = dev_get_priv(dev);
if (hc_reset(ohci) < 0)
return -EIO;
free(ohci->hcca);
return 0;
}
struct dm_usb_ops ohci_usb_ops = {
.control = ohci_submit_control_msg,
.bulk = ohci_submit_bulk_msg,
.interrupt = ohci_submit_int_msg,
.create_int_queue = ohci_create_int_queue,
.poll_int_queue = ohci_poll_int_queue,
.destroy_int_queue = ohci_destroy_int_queue,
};
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Name:
Base16 Atelier Lakeside Light
Credits:
Original Base16 color schemes by Chris Kempson
gedit template by Jan T. Sott
Installation:
Copy style to the respective directories, replace GTK version if necessary!
Linux:
/usr/share/gtksourceview-2.0/language-specs
Mac OS X (MacPorts):
/opt/local/share/gtksourceview-2.0/language-specs
Windows:
%PROGRAMFILES%\gedit\share\gtksourceview-2.0\styles
Base16 Project:
https://github.com/chriskempson/base16
-->
<style-scheme id="base16-atelierlakeside-light" _name="Base16 Atelier Lakeside Light" version="1.0">
<!-- Meta -->
<author>Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/)</author>
<_description>Base16 Atelier Lakeside Light</_description>
<!-- Palette -->
<color name="base00" value="#161b1d"/>
<color name="base01" value="#1f292e"/>
<color name="base02" value="#516d7b"/>
<color name="base03" value="#5a7b8c"/>
<color name="base04" value="#7195a8"/>
<color name="base05" value="#7ea2b4"/>
<color name="base06" value="#c1e4f6"/>
<color name="base07" value="#ebf8ff"/>
<color name="base08" value="#d22d72"/>
<color name="base09" value="#935c25"/>
<color name="base0A" value="#8a8a0f"/>
<color name="base0B" value="#568c3b"/>
<color name="base0C" value="#2d8f6f"/>
<color name="base0D" value="#257fad"/>
<color name="base0E" value="#6b6bb8"/>
<color name="base0F" value="#b72dd2"/>
<!-- Styles -->
<style name="bracket-match" background="base06" bold="true"/>
<style name="bracket-mismatch" background="base06" underline="true"/>
<style name="css:at-rules" foreground="base0E"/>
<style name="css:color" foreground="base02"/>
<style name="css:keyword" foreground="base0A"/>
<style name="current-line" background="base06"/>
<style name="cursor" foreground="base04"/>
<style name="def:base-n-integer" foreground="base09"/>
<style name="def:boolean" foreground="base09"/>
<style name="def:builtin" foreground="base09"/>
<style name="def:character" foreground="base09"/>
<style name="def:comment" foreground="base03"/>
<style name="def:complex" foreground="base09"/>
<style name="def:decimal" foreground="base09"/>
<style name="def:doc-comment" foreground="base03"/>
<style name="def:doc-comment-element" foreground="base03"/>
<style name="def:error" foreground="base07" background="base08"/>
<style name="def:floating-point" foreground="base09"/>
<style name="def:function" foreground="base0D"/>
<style name="def:identifier" foreground="base08"/>
<style name="def:keyword" foreground="base0E"/>
<style name="def:note" foreground="base03"/>
<style name="def:number" foreground="base09"/>
<style name="def:operator" foreground="base0C"/>
<style name="def:preprocessor" foreground="base09"/>
<style name="def:reserved" foreground="base0E"/>
<style name="def:shebang" foreground="base03"/>
<style name="def:special-char" foreground="base09"/>
<style name="def:special-constant" foreground="base09"/>
<style name="def:statement" foreground="base0E"/>
<style name="def:string" foreground="base0B"/>
<style name="def:type" foreground="base0A"/>
<style name="draw-spaces" foreground="base05"/>
<style name="html:dtd" foreground="base0B"/>
<style name="html:tag" foreground="base08"/>
<style name="js:function" foreground="base0D"/>
<style name="line-numbers" foreground="base01" background="base06"/>
<style name="perl:builtin" foreground="base0D"/>
<style name="perl:include-statement" foreground="base0E"/>
<style name="perl:special-variable" foreground="base09"/>
<style name="perl:variable" foreground="base08"/>
<style name="php:string" foreground="base0B"/>
<style name="python:builtin-constant" foreground="base0E"/>
<style name="python:builtin-function" foreground="base0D"/>
<style name="python:module-handler" foreground="base0E"/>
<style name="python:special-variable" foreground="base0E"/>
<style name="ruby:attribute-definition" foreground="base0E"/>
<style name="ruby:builtin" foreground="base08"/>
<style name="ruby:class-variable" foreground="base08"/>
<style name="ruby:constant" foreground="base08"/>
<style name="ruby:global-variable" foreground="base0D"/>
<style name="ruby:instance-variable" foreground="base08"/>
<style name="ruby:module-handler" foreground="base0E"/>
<style name="ruby:predefined-variable" foreground="base09"/>
<style name="ruby:regex" foreground="base08"/>
<style name="ruby:special-variable" foreground="base0E"/>
<style name="ruby:symbol" foreground="base0B"/>
<style name="rubyonrails:attribute-definition" foreground="base0E"/>
<style name="rubyonrails:block-parameter" foreground="base09"/>
<style name="rubyonrails:builtin" foreground="base08"/>
<style name="rubyonrails:class-inherit" foreground="base0B"/>
<style name="rubyonrails:class-name" foreground="base0A"/>
<style name="rubyonrails:class-variable" foreground="base08"/>
<style name="rubyonrails:complex-interpolation" foreground="base09"/>
<style name="rubyonrails:constant" foreground="base08"/>
<style name="rubyonrails:global-variable" foreground="base0D"/>
<style name="rubyonrails:instance-variable" foreground="base08"/>
<style name="rubyonrails:module-handler" foreground="base0E"/>
<style name="rubyonrails:module-name" foreground="base0A"/>
<style name="rubyonrails:predefined-variable" foreground="base09"/>
<style name="rubyonrails:rails" foreground="base08"/>
<style name="rubyonrails:regex" foreground="base08"/>
<style name="rubyonrails:simple-interpolation" foreground="base09"/>
<style name="rubyonrails:special-variable" foreground="base0E"/>
<style name="rubyonrails:symbol" foreground="base0B"/>
<style name="search-match" background="base06" bold="true" underline="true"/>
<style name="selection" foreground="base01" background="base02"/>
<style name="text" foreground="base01" background="base07"/>
<style name="xml:attribute-name" foreground="base08"/>
<style name="xml:doctype" foreground="base08"/>
<style name="xml:element-name" foreground="base08"/>
<style name="xml:namespace" foreground="base08"/>
<style name="xml:tag" foreground="base08"/>
</style-scheme>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>8.0</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<html><head>
<meta charset="utf-8">
<title>Reference: Clamp 'automatic minimum size' to definite max-sizing of block item with margin:auto</title>
<link rel="author" title="Mats Palmgren" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1300369">
<style type="text/css">
body,html { color:black; background:white; font:16px/1 monospace; padding:0; margin:0; }
.grid {
display: grid;
grid-template-columns: repeat(2,minmax(auto, 15px));
grid-template-rows: repeat(2,minmax(auto, 10px));
grid-gap: 1px;
align-items: start;
justify-items: start;
float: left;
border: 1px dashed;
margin-right: 16px;
margin-bottom: 14px;
}
.sz {
width: 40px;
height: 40px;
}
.definite {
grid-template-columns: repeat(2,15px);
grid-template-rows: repeat(2,10px);
}
.min {
grid-template-columns: repeat(2,minmax(min-content, 15px));
grid-template-rows: repeat(2,minmax(min-content, 10px));
}
.max {
grid-template-columns: repeat(2,minmax(max-content, 15px));
grid-template-rows: repeat(2,minmax(max-content, 10px));
}
.larger .grid {
grid-template-columns: repeat(2,minmax(auto, 25px));
grid-template-rows: repeat(2,minmax(auto, 28px));
}
.larger .definite {
grid-template-columns: repeat(2,25px);
grid-template-rows: repeat(2,28px);
}
.larger .min {
grid-template-columns: repeat(2,minmax(min-content, 25px));
grid-template-rows: repeat(2,minmax(min-content, 28px));
}
.larger .max {
grid-template-columns: repeat(2,minmax(max-content, 25px));
grid-template-rows: repeat(2,minmax(max-content, 28px));
}
.stretch .grid {
align-items: stretch;
justify-items: stretch;
}
span {
grid-area: 1 / 1;
font-size: 48px;
background: grey;
background-clip: content-box;
border: 1px solid;
padding: 1px 3px 5px 7px;
margin: 0;
}
.span2 {
grid-area: 1 / 1 / span 2 / span 2;
}
.larger .grid .span2 {
font-size: 32px;
}
.larger .grid span {
align-self:center;
justify-self:center;
}
.larger .grid .span2 {
font-size: 32px;
width: 20px;
height: 32px;
}
.stretch.larger .grid .span2 {
align-self:center;
justify-self:center;
}
.stretch.larger .grid.sz .span2 {
align-self:center;
justify-self:center;
}
.stretch.larger .grid.definite .span2 {
align-self:center;
justify-self:center;
}
x {
grid-area: 1 / 1;
min-width: 0;
min-height: 0;
align-self: stretch;
justify-self: stretch;
background: cyan;
}
c {
display: block;
width: 20px;
height: 32px;
}
br {
clear: both;
}
</style>
</head>
<body>
<div id="tests">
<div class="grid"><x></x><span><c>X</c></span></div>
<div class="grid definite"><x></x><span><c>X</c></span></div>
<div class="grid"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid definite"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid sz"><x></x><span><c>X</c></span></div>
<div class="grid sz definite"><x></x><span><c>X</c></span></div>
<div class="grid sz"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid sz definite"><x></x><span class="span2"><c>X</c></span></div>
<br>
<div class="grid min"><x></x><span><c>X</c></span></div>
<div class="grid min"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid sz min"><x></x><span><c>X</c></span></div>
<div class="grid sz min"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid max"><x></x><span><c>X</c></span></div>
<div class="grid max"><x></x><span class="span2"><c>X</c></span></div>
<div class="grid sz max"><x></x><span><c>X</c></span></div>
<div class="grid sz max"><x></x><span class="span2"><c>X</c></span></div>
<br>
</div>
<script>
var tests = document.getElementById('tests');
var n = tests.cloneNode(true);
var wrap = document.createElement('div');
wrap.className = 'larger';
wrap.appendChild(n);
document.body.appendChild(wrap);
var n = tests.cloneNode(true);
var wrap = document.createElement('div');
wrap.className = 'stretch';
wrap.appendChild(n);
document.body.appendChild(wrap);
var n = tests.cloneNode(true);
var wrap = document.createElement('div');
wrap.className = 'stretch larger';
wrap.appendChild(n);
document.body.appendChild(wrap);
</script>
</body></html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/bio.h>
#include <linux/fs.h>
#include "gfs2.h"
#include "incore.h"
#include "inode.h"
#include "glock.h"
#include "log.h"
#include "lops.h"
#include "meta_io.h"
#include "recovery.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
#include "trace_gfs2.h"
/**
* gfs2_pin - Pin a buffer in memory
* @sdp: The superblock
* @bh: The buffer to be pinned
*
* The log lock must be held when calling this function
*/
void gfs2_pin(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
struct gfs2_bufdata *bd;
BUG_ON(!current->journal_info);
clear_buffer_dirty(bh);
if (test_set_buffer_pinned(bh))
gfs2_assert_withdraw(sdp, 0);
if (!buffer_uptodate(bh))
gfs2_io_error_bh(sdp, bh);
bd = bh->b_private;
/* If this buffer is in the AIL and it has already been written
* to in-place disk block, remove it from the AIL.
*/
spin_lock(&sdp->sd_ail_lock);
if (bd->bd_ail)
list_move(&bd->bd_ail_st_list, &bd->bd_ail->ai_ail2_list);
spin_unlock(&sdp->sd_ail_lock);
get_bh(bh);
trace_gfs2_pin(bd, 1);
}
static bool buffer_is_rgrp(const struct gfs2_bufdata *bd)
{
return bd->bd_gl->gl_name.ln_type == LM_TYPE_RGRP;
}
static void maybe_release_space(struct gfs2_bufdata *bd)
{
struct gfs2_glock *gl = bd->bd_gl;
struct gfs2_sbd *sdp = gl->gl_sbd;
struct gfs2_rgrpd *rgd = gl->gl_object;
unsigned int index = bd->bd_bh->b_blocknr - gl->gl_name.ln_number;
struct gfs2_bitmap *bi = rgd->rd_bits + index;
if (bi->bi_clone == 0)
return;
if (sdp->sd_args.ar_discard)
gfs2_rgrp_send_discards(sdp, rgd->rd_data0, bd->bd_bh, bi, 1, NULL);
memcpy(bi->bi_clone + bi->bi_offset,
bd->bd_bh->b_data + bi->bi_offset, bi->bi_len);
clear_bit(GBF_FULL, &bi->bi_flags);
rgd->rd_free_clone = rgd->rd_free;
rgd->rd_extfail_pt = rgd->rd_free;
}
/**
* gfs2_unpin - Unpin a buffer
* @sdp: the filesystem the buffer belongs to
* @bh: The buffer to unpin
* @ai:
* @flags: The inode dirty flags
*
*/
static void gfs2_unpin(struct gfs2_sbd *sdp, struct buffer_head *bh,
struct gfs2_ail *ai)
{
struct gfs2_bufdata *bd = bh->b_private;
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!buffer_pinned(bh));
lock_buffer(bh);
mark_buffer_dirty(bh);
clear_buffer_pinned(bh);
if (buffer_is_rgrp(bd))
maybe_release_space(bd);
spin_lock(&sdp->sd_ail_lock);
if (bd->bd_ail) {
list_del(&bd->bd_ail_st_list);
brelse(bh);
} else {
struct gfs2_glock *gl = bd->bd_gl;
list_add(&bd->bd_ail_gl_list, &gl->gl_ail_list);
atomic_inc(&gl->gl_ail_count);
}
bd->bd_ail = ai;
list_add(&bd->bd_ail_st_list, &ai->ai_ail1_list);
spin_unlock(&sdp->sd_ail_lock);
clear_bit(GLF_LFLUSH, &bd->bd_gl->gl_flags);
trace_gfs2_pin(bd, 0);
unlock_buffer(bh);
}
static inline struct gfs2_log_descriptor *bh_log_desc(struct buffer_head *bh)
{
return (struct gfs2_log_descriptor *)bh->b_data;
}
static inline __be64 *bh_log_ptr(struct buffer_head *bh)
{
struct gfs2_log_descriptor *ld = bh_log_desc(bh);
return (__force __be64 *)(ld + 1);
}
static inline __be64 *bh_ptr_end(struct buffer_head *bh)
{
return (__force __be64 *)(bh->b_data + bh->b_size);
}
/**
* gfs2_log_write_endio - End of I/O for a log buffer
* @bh: The buffer head
* @uptodate: I/O Status
*
*/
static void gfs2_log_write_endio(struct buffer_head *bh, int uptodate)
{
struct gfs2_sbd *sdp = bh->b_private;
bh->b_private = NULL;
end_buffer_write_sync(bh, uptodate);
if (atomic_dec_and_test(&sdp->sd_log_in_flight))
wake_up(&sdp->sd_log_flush_wait);
}
/**
* gfs2_log_get_buf - Get and initialize a buffer to use for log control data
* @sdp: The GFS2 superblock
*
* Returns: the buffer_head
*/
static struct buffer_head *gfs2_log_get_buf(struct gfs2_sbd *sdp)
{
u64 blkno = gfs2_log_bmap(sdp, sdp->sd_log_flush_head);
struct buffer_head *bh;
bh = sb_getblk(sdp->sd_vfs, blkno);
lock_buffer(bh);
memset(bh->b_data, 0, bh->b_size);
set_buffer_uptodate(bh);
clear_buffer_dirty(bh);
gfs2_log_incr_head(sdp);
atomic_inc(&sdp->sd_log_in_flight);
bh->b_private = sdp;
bh->b_end_io = gfs2_log_write_endio;
return bh;
}
/**
* gfs2_fake_write_endio -
* @bh: The buffer head
* @uptodate: The I/O Status
*
*/
static void gfs2_fake_write_endio(struct buffer_head *bh, int uptodate)
{
struct buffer_head *real_bh = bh->b_private;
struct gfs2_bufdata *bd = real_bh->b_private;
struct gfs2_sbd *sdp = bd->bd_gl->gl_sbd;
end_buffer_write_sync(bh, uptodate);
mempool_free(bh, gfs2_bh_pool);
unlock_buffer(real_bh);
brelse(real_bh);
if (atomic_dec_and_test(&sdp->sd_log_in_flight))
wake_up(&sdp->sd_log_flush_wait);
}
/**
* gfs2_log_write_buf - write metadata buffer to log
* @sdp: the filesystem
* @real: the in-place buffer head
*
* Returns: the log buffer descriptor
*/
static void gfs2_log_write_buf(struct gfs2_sbd *sdp, struct buffer_head *real)
{
u64 blkno = gfs2_log_bmap(sdp, sdp->sd_log_flush_head);
struct buffer_head *bh;
bh = mempool_alloc(gfs2_bh_pool, GFP_NOFS);
atomic_set(&bh->b_count, 1);
bh->b_state = (1 << BH_Mapped) | (1 << BH_Uptodate) | (1 << BH_Lock);
set_bh_page(bh, real->b_page, bh_offset(real));
bh->b_blocknr = blkno;
bh->b_size = sdp->sd_sb.sb_bsize;
bh->b_bdev = sdp->sd_vfs->s_bdev;
bh->b_private = real;
bh->b_end_io = gfs2_fake_write_endio;
gfs2_log_incr_head(sdp);
atomic_inc(&sdp->sd_log_in_flight);
submit_bh(WRITE, bh);
}
static struct buffer_head *gfs2_get_log_desc(struct gfs2_sbd *sdp, u32 ld_type)
{
struct buffer_head *bh = gfs2_log_get_buf(sdp);
struct gfs2_log_descriptor *ld = bh_log_desc(bh);
ld->ld_header.mh_magic = cpu_to_be32(GFS2_MAGIC);
ld->ld_header.mh_type = cpu_to_be32(GFS2_METATYPE_LD);
ld->ld_header.mh_format = cpu_to_be32(GFS2_FORMAT_LD);
ld->ld_type = cpu_to_be32(ld_type);
ld->ld_length = 0;
ld->ld_data1 = 0;
ld->ld_data2 = 0;
memset(ld->ld_reserved, 0, sizeof(ld->ld_reserved));
return bh;
}
static void buf_lo_before_commit(struct gfs2_sbd *sdp)
{
struct buffer_head *bh;
struct gfs2_log_descriptor *ld;
struct gfs2_bufdata *bd1 = NULL, *bd2;
unsigned int total;
unsigned int limit;
unsigned int num;
unsigned n;
__be64 *ptr;
limit = buf_limit(sdp);
/* for 4k blocks, limit = 503 */
gfs2_log_lock(sdp);
total = sdp->sd_log_num_buf;
bd1 = bd2 = list_prepare_entry(bd1, &sdp->sd_log_le_buf, bd_list);
while(total) {
num = total;
if (total > limit)
num = limit;
gfs2_log_unlock(sdp);
bh = gfs2_get_log_desc(sdp, GFS2_LOG_DESC_METADATA);
gfs2_log_lock(sdp);
ld = bh_log_desc(bh);
ptr = bh_log_ptr(bh);
ld->ld_length = cpu_to_be32(num + 1);
ld->ld_data1 = cpu_to_be32(num);
n = 0;
list_for_each_entry_continue(bd1, &sdp->sd_log_le_buf, bd_list) {
*ptr++ = cpu_to_be64(bd1->bd_bh->b_blocknr);
if (++n >= num)
break;
}
gfs2_log_unlock(sdp);
submit_bh(WRITE, bh);
gfs2_log_lock(sdp);
n = 0;
list_for_each_entry_continue(bd2, &sdp->sd_log_le_buf, bd_list) {
get_bh(bd2->bd_bh);
gfs2_log_unlock(sdp);
lock_buffer(bd2->bd_bh);
gfs2_log_write_buf(sdp, bd2->bd_bh);
gfs2_log_lock(sdp);
if (++n >= num)
break;
}
BUG_ON(total < num);
total -= num;
}
gfs2_log_unlock(sdp);
}
static void buf_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_ail *ai)
{
struct list_head *head = &sdp->sd_log_le_buf;
struct gfs2_bufdata *bd;
while (!list_empty(head)) {
bd = list_entry(head->next, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
sdp->sd_log_num_buf--;
gfs2_unpin(sdp, bd->bd_bh, ai);
}
gfs2_assert_warn(sdp, !sdp->sd_log_num_buf);
}
static void buf_lo_before_scan(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head, int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (pass != 0)
return;
sdp->sd_found_blocks = 0;
sdp->sd_replayed_blocks = 0;
}
static int buf_lo_scan_elements(struct gfs2_jdesc *jd, unsigned int start,
struct gfs2_log_descriptor *ld, __be64 *ptr,
int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_glock *gl = ip->i_gl;
unsigned int blks = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh_log, *bh_ip;
u64 blkno;
int error = 0;
if (pass != 1 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_METADATA)
return 0;
gfs2_replay_incr_blk(sdp, &start);
for (; blks; gfs2_replay_incr_blk(sdp, &start), blks--) {
blkno = be64_to_cpu(*ptr++);
sdp->sd_found_blocks++;
if (gfs2_revoke_check(sdp, blkno, start))
continue;
error = gfs2_replay_read_block(jd, start, &bh_log);
if (error)
return error;
bh_ip = gfs2_meta_new(gl, blkno);
memcpy(bh_ip->b_data, bh_log->b_data, bh_log->b_size);
if (gfs2_meta_check(sdp, bh_ip))
error = -EIO;
else
mark_buffer_dirty(bh_ip);
brelse(bh_log);
brelse(bh_ip);
if (error)
break;
sdp->sd_replayed_blocks++;
}
return error;
}
static void buf_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_meta_sync(ip->i_gl);
return;
}
if (pass != 1)
return;
gfs2_meta_sync(ip->i_gl);
fs_info(sdp, "jid=%u: Replayed %u of %u blocks\n",
jd->jd_jid, sdp->sd_replayed_blocks, sdp->sd_found_blocks);
}
static void revoke_lo_before_commit(struct gfs2_sbd *sdp)
{
struct gfs2_log_descriptor *ld;
struct gfs2_meta_header *mh;
struct buffer_head *bh;
unsigned int offset;
struct list_head *head = &sdp->sd_log_le_revoke;
struct gfs2_bufdata *bd;
if (!sdp->sd_log_num_revoke)
return;
bh = gfs2_get_log_desc(sdp, GFS2_LOG_DESC_REVOKE);
ld = bh_log_desc(bh);
ld->ld_length = cpu_to_be32(gfs2_struct2blk(sdp, sdp->sd_log_num_revoke,
sizeof(u64)));
ld->ld_data1 = cpu_to_be32(sdp->sd_log_num_revoke);
offset = sizeof(struct gfs2_log_descriptor);
list_for_each_entry(bd, head, bd_list) {
sdp->sd_log_num_revoke--;
if (offset + sizeof(u64) > sdp->sd_sb.sb_bsize) {
submit_bh(WRITE, bh);
bh = gfs2_log_get_buf(sdp);
mh = (struct gfs2_meta_header *)bh->b_data;
mh->mh_magic = cpu_to_be32(GFS2_MAGIC);
mh->mh_type = cpu_to_be32(GFS2_METATYPE_LB);
mh->mh_format = cpu_to_be32(GFS2_FORMAT_LB);
offset = sizeof(struct gfs2_meta_header);
}
*(__be64 *)(bh->b_data + offset) = cpu_to_be64(bd->bd_blkno);
offset += sizeof(u64);
}
gfs2_assert_withdraw(sdp, !sdp->sd_log_num_revoke);
submit_bh(WRITE, bh);
}
static void revoke_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_ail *ai)
{
struct list_head *head = &sdp->sd_log_le_revoke;
struct gfs2_bufdata *bd;
struct gfs2_glock *gl;
while (!list_empty(head)) {
bd = list_entry(head->next, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
gl = bd->bd_gl;
atomic_dec(&gl->gl_revokes);
clear_bit(GLF_LFLUSH, &gl->gl_flags);
kmem_cache_free(gfs2_bufdata_cachep, bd);
}
}
static void revoke_lo_before_scan(struct gfs2_jdesc *jd,
struct gfs2_log_header_host *head, int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (pass != 0)
return;
sdp->sd_found_revokes = 0;
sdp->sd_replay_tail = head->lh_tail;
}
static int revoke_lo_scan_elements(struct gfs2_jdesc *jd, unsigned int start,
struct gfs2_log_descriptor *ld, __be64 *ptr,
int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
unsigned int blks = be32_to_cpu(ld->ld_length);
unsigned int revokes = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh;
unsigned int offset;
u64 blkno;
int first = 1;
int error;
if (pass != 0 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_REVOKE)
return 0;
offset = sizeof(struct gfs2_log_descriptor);
for (; blks; gfs2_replay_incr_blk(sdp, &start), blks--) {
error = gfs2_replay_read_block(jd, start, &bh);
if (error)
return error;
if (!first)
gfs2_metatype_check(sdp, bh, GFS2_METATYPE_LB);
while (offset + sizeof(u64) <= sdp->sd_sb.sb_bsize) {
blkno = be64_to_cpu(*(__be64 *)(bh->b_data + offset));
error = gfs2_revoke_add(sdp, blkno, start);
if (error < 0) {
brelse(bh);
return error;
}
else if (error)
sdp->sd_found_revokes++;
if (!--revokes)
break;
offset += sizeof(u64);
}
brelse(bh);
offset = sizeof(struct gfs2_meta_header);
first = 0;
}
return 0;
}
static void revoke_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_revoke_clean(sdp);
return;
}
if (pass != 1)
return;
fs_info(sdp, "jid=%u: Found %u revoke tags\n",
jd->jd_jid, sdp->sd_found_revokes);
gfs2_revoke_clean(sdp);
}
static void gfs2_check_magic(struct buffer_head *bh)
{
void *kaddr;
__be32 *ptr;
clear_buffer_escaped(bh);
kaddr = kmap_atomic(bh->b_page, KM_USER0);
ptr = kaddr + bh_offset(bh);
if (*ptr == cpu_to_be32(GFS2_MAGIC))
set_buffer_escaped(bh);
kunmap_atomic(kaddr, KM_USER0);
}
static void gfs2_write_blocks(struct gfs2_sbd *sdp, struct buffer_head *bh,
struct list_head *list, struct list_head *done,
unsigned int n)
{
struct buffer_head *bh1;
struct gfs2_log_descriptor *ld;
struct gfs2_bufdata *bd;
__be64 *ptr;
if (!bh)
return;
ld = bh_log_desc(bh);
ld->ld_length = cpu_to_be32(n + 1);
ld->ld_data1 = cpu_to_be32(n);
ptr = bh_log_ptr(bh);
get_bh(bh);
submit_bh(WRITE, bh);
gfs2_log_lock(sdp);
while(!list_empty(list)) {
bd = list_entry(list->next, struct gfs2_bufdata, bd_list);
list_move_tail(&bd->bd_list, done);
get_bh(bd->bd_bh);
while (be64_to_cpu(*ptr) != bd->bd_bh->b_blocknr) {
gfs2_log_incr_head(sdp);
ptr += 2;
}
gfs2_log_unlock(sdp);
lock_buffer(bd->bd_bh);
if (buffer_escaped(bd->bd_bh)) {
void *kaddr;
bh1 = gfs2_log_get_buf(sdp);
kaddr = kmap_atomic(bd->bd_bh->b_page, KM_USER0);
memcpy(bh1->b_data, kaddr + bh_offset(bd->bd_bh),
bh1->b_size);
kunmap_atomic(kaddr, KM_USER0);
*(__be32 *)bh1->b_data = 0;
clear_buffer_escaped(bd->bd_bh);
unlock_buffer(bd->bd_bh);
brelse(bd->bd_bh);
submit_bh(WRITE, bh1);
} else {
gfs2_log_write_buf(sdp, bd->bd_bh);
}
gfs2_log_lock(sdp);
ptr += 2;
}
gfs2_log_unlock(sdp);
brelse(bh);
}
/**
* databuf_lo_before_commit - Scan the data buffers, writing as we go
*
*/
static void databuf_lo_before_commit(struct gfs2_sbd *sdp)
{
struct gfs2_bufdata *bd = NULL;
struct buffer_head *bh = NULL;
unsigned int n = 0;
__be64 *ptr = NULL, *end = NULL;
LIST_HEAD(processed);
LIST_HEAD(in_progress);
gfs2_log_lock(sdp);
while (!list_empty(&sdp->sd_log_le_databuf)) {
if (ptr == end) {
gfs2_log_unlock(sdp);
gfs2_write_blocks(sdp, bh, &in_progress, &processed, n);
n = 0;
bh = gfs2_get_log_desc(sdp, GFS2_LOG_DESC_JDATA);
ptr = bh_log_ptr(bh);
end = bh_ptr_end(bh) - 1;
gfs2_log_lock(sdp);
continue;
}
bd = list_entry(sdp->sd_log_le_databuf.next, struct gfs2_bufdata, bd_list);
list_move_tail(&bd->bd_list, &in_progress);
gfs2_check_magic(bd->bd_bh);
*ptr++ = cpu_to_be64(bd->bd_bh->b_blocknr);
*ptr++ = cpu_to_be64(buffer_escaped(bh) ? 1 : 0);
n++;
}
gfs2_log_unlock(sdp);
gfs2_write_blocks(sdp, bh, &in_progress, &processed, n);
gfs2_log_lock(sdp);
list_splice(&processed, &sdp->sd_log_le_databuf);
gfs2_log_unlock(sdp);
}
static int databuf_lo_scan_elements(struct gfs2_jdesc *jd, unsigned int start,
struct gfs2_log_descriptor *ld,
__be64 *ptr, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
struct gfs2_glock *gl = ip->i_gl;
unsigned int blks = be32_to_cpu(ld->ld_data1);
struct buffer_head *bh_log, *bh_ip;
u64 blkno;
u64 esc;
int error = 0;
if (pass != 1 || be32_to_cpu(ld->ld_type) != GFS2_LOG_DESC_JDATA)
return 0;
gfs2_replay_incr_blk(sdp, &start);
for (; blks; gfs2_replay_incr_blk(sdp, &start), blks--) {
blkno = be64_to_cpu(*ptr++);
esc = be64_to_cpu(*ptr++);
sdp->sd_found_blocks++;
if (gfs2_revoke_check(sdp, blkno, start))
continue;
error = gfs2_replay_read_block(jd, start, &bh_log);
if (error)
return error;
bh_ip = gfs2_meta_new(gl, blkno);
memcpy(bh_ip->b_data, bh_log->b_data, bh_log->b_size);
/* Unescape */
if (esc) {
__be32 *eptr = (__be32 *)bh_ip->b_data;
*eptr = cpu_to_be32(GFS2_MAGIC);
}
mark_buffer_dirty(bh_ip);
brelse(bh_log);
brelse(bh_ip);
sdp->sd_replayed_blocks++;
}
return error;
}
/* FIXME: sort out accounting for log blocks etc. */
static void databuf_lo_after_scan(struct gfs2_jdesc *jd, int error, int pass)
{
struct gfs2_inode *ip = GFS2_I(jd->jd_inode);
struct gfs2_sbd *sdp = GFS2_SB(jd->jd_inode);
if (error) {
gfs2_meta_sync(ip->i_gl);
return;
}
if (pass != 1)
return;
/* data sync? */
gfs2_meta_sync(ip->i_gl);
fs_info(sdp, "jid=%u: Replayed %u of %u data blocks\n",
jd->jd_jid, sdp->sd_replayed_blocks, sdp->sd_found_blocks);
}
static void databuf_lo_after_commit(struct gfs2_sbd *sdp, struct gfs2_ail *ai)
{
struct list_head *head = &sdp->sd_log_le_databuf;
struct gfs2_bufdata *bd;
while (!list_empty(head)) {
bd = list_entry(head->next, struct gfs2_bufdata, bd_list);
list_del_init(&bd->bd_list);
sdp->sd_log_num_databuf--;
gfs2_unpin(sdp, bd->bd_bh, ai);
}
gfs2_assert_warn(sdp, !sdp->sd_log_num_databuf);
}
const struct gfs2_log_operations gfs2_buf_lops = {
.lo_before_commit = buf_lo_before_commit,
.lo_after_commit = buf_lo_after_commit,
.lo_before_scan = buf_lo_before_scan,
.lo_scan_elements = buf_lo_scan_elements,
.lo_after_scan = buf_lo_after_scan,
.lo_name = "buf",
};
const struct gfs2_log_operations gfs2_revoke_lops = {
.lo_before_commit = revoke_lo_before_commit,
.lo_after_commit = revoke_lo_after_commit,
.lo_before_scan = revoke_lo_before_scan,
.lo_scan_elements = revoke_lo_scan_elements,
.lo_after_scan = revoke_lo_after_scan,
.lo_name = "revoke",
};
const struct gfs2_log_operations gfs2_rg_lops = {
.lo_name = "rg",
};
const struct gfs2_log_operations gfs2_databuf_lops = {
.lo_before_commit = databuf_lo_before_commit,
.lo_after_commit = databuf_lo_after_commit,
.lo_scan_elements = databuf_lo_scan_elements,
.lo_after_scan = databuf_lo_after_scan,
.lo_name = "databuf",
};
const struct gfs2_log_operations *gfs2_log_ops[] = {
&gfs2_databuf_lops,
&gfs2_buf_lops,
&gfs2_rg_lops,
&gfs2_revoke_lops,
NULL,
};
| {
"pile_set_name": "Github"
} |
(: Test that importing a range of versions gets the highest available. :)
import module namespace vm = "http://zorba-tests.28.io/modules/ver#1.3-2.0";
vm:version()
| {
"pile_set_name": "Github"
} |
/*
* Debug macros for run-time debugging.
* Turned on/off with CONFIG_RUNTIME_DEBUG option.
*
* Copyright (C) 2001 MontaVista Software Inc.
* Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#ifndef _ASM_DEBUG_H
#define _ASM_DEBUG_H
/*
* run-time macros for catching spurious errors. Eable CONFIG_RUNTIME_DEBUG in
* kernel hacking config menu to use them.
*
* Use them as run-time debugging aid. NEVER USE THEM AS ERROR HANDLING CODE!!!
*/
#ifdef CONFIG_RUNTIME_DEBUG
#include <linux/kernel.h>
#define db_assert(x) if (!(x)) { \
panic("assertion failed at %s:%d: %s", __FILE__, __LINE__, #x); }
#define db_warn(x) if (!(x)) { \
printk(KERN_WARNING "warning at %s:%d: %s", __FILE__, __LINE__, #x); }
#define db_verify(x, y) db_assert(x y)
#define db_verify_warn(x, y) db_warn(x y)
#define db_run(x) do { x; } while (0)
#else
#define db_assert(x)
#define db_warn(x)
#define db_verify(x, y) x
#define db_verify_warn(x, y) x
#define db_run(x)
#endif
#endif /* _ASM_DEBUG_H */
| {
"pile_set_name": "Github"
} |
Mocha Describe and Expectations
Asynchronous Code
Working with Promises
Delayed Root Suite
Chai Spies | {
"pile_set_name": "Github"
} |
"use strict";
exports.__esModule = true;
exports.default = function (path, helpers) {
var node = path.node,
scope = path.scope,
parent = path.parent;
var stepKey = scope.generateUidIdentifier("step");
var stepValue = scope.generateUidIdentifier("value");
var left = node.left;
var declar = void 0;
if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) {
declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue));
} else if (t.isVariableDeclaration(left)) {
declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]);
}
var template = buildForAwait();
(0, _babelTraverse2.default)(template, forAwaitVisitor, null, {
ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"),
ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"),
ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"),
ITERATOR_KEY: scope.generateUidIdentifier("iterator"),
GET_ITERATOR: helpers.getAsyncIterator,
OBJECT: node.right,
STEP_VALUE: stepValue,
STEP_KEY: stepKey,
AWAIT: helpers.wrapAwait
});
template = template.body.body;
var isLabeledParent = t.isLabeledStatement(parent);
var tryBody = template[3].block.body;
var loop = tryBody[0];
if (isLabeledParent) {
tryBody[0] = t.labeledStatement(parent.label, loop);
}
return {
replaceParent: isLabeledParent,
node: template,
declar: declar,
loop: loop
};
};
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _babelTemplate = require("babel-template");
var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var buildForAwait = (0, _babelTemplate2.default)("\n function* wrapper() {\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (\n var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY, STEP_VALUE;\n (\n STEP_KEY = yield AWAIT(ITERATOR_KEY.next()),\n ITERATOR_COMPLETION = STEP_KEY.done,\n STEP_VALUE = yield AWAIT(STEP_KEY.value),\n !ITERATOR_COMPLETION\n );\n ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n yield AWAIT(ITERATOR_KEY.return());\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n }\n");
var forAwaitVisitor = {
noScope: true,
Identifier: function Identifier(path, replacements) {
if (path.node.name in replacements) {
path.replaceInline(replacements[path.node.name]);
}
},
CallExpression: function CallExpression(path, replacements) {
var callee = path.node.callee;
if (t.isIdentifier(callee) && callee.name === "AWAIT" && !replacements.AWAIT) {
path.replaceWith(path.node.arguments[0]);
}
}
};
module.exports = exports["default"]; | {
"pile_set_name": "Github"
} |
/*
* ALSA sequencer System Client
* Copyright (c) 1998 by Frank van de Pol <fvdpol@coil.demon.nl>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef __SND_SEQ_SYSTEM_H
#define __SND_SEQ_SYSTEM_H
#include <sound/seq_kernel.h>
/* entry points for broadcasting system events */
void snd_seq_system_broadcast(int client, int port, int type);
#define snd_seq_system_client_ev_client_start(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_START)
#define snd_seq_system_client_ev_client_exit(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_EXIT)
#define snd_seq_system_client_ev_client_change(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_CHANGE)
#define snd_seq_system_client_ev_port_start(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_START)
#define snd_seq_system_client_ev_port_exit(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_EXIT)
#define snd_seq_system_client_ev_port_change(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_CHANGE)
int snd_seq_system_notify(int client, int port, struct snd_seq_event *ev);
/* register our internal client */
int snd_seq_system_client_init(void);
/* unregister our internal client */
void snd_seq_system_client_done(void);
#endif
| {
"pile_set_name": "Github"
} |
[e-acsl] beginning translation.
[e-acsl] translation done in project "e-acsl".
[eva:alarm] tests/gmp-only/functions.c:42: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:43: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:44: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:46: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:47: Warning:
accessing uninitialized left-value.
assert \initialized((__e_acsl_mpz_struct *)__gen_e_acsl_f1_4);
[eva:alarm] tests/gmp-only/functions.c:47: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:48: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:49: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:53: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:56: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:58: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:63: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:25: Warning:
function __e_acsl_assert: precondition got status unknown.
[eva:alarm] tests/gmp-only/functions.c:68: Warning:
non-finite double value. assert \is_finite(__gen_e_acsl__15);
[eva:alarm] tests/gmp-only/functions.c:68: Warning:
function __e_acsl_assert: precondition got status unknown.
| {
"pile_set_name": "Github"
} |
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/utility for most recent version including documentation.
// see libs/utility/compressed_pair.hpp
//
/* Release notes:
20 Jan 2001:
Fixed obvious bugs (David Abrahams)
07 Oct 2000:
Added better single argument constructor support.
03 Oct 2000:
Added VC6 support (JM).
23rd July 2000:
Additional comments added. (JM)
Jan 2000:
Original version: this version crippled for use with crippled compilers
- John Maddock Jan 2000.
*/
#ifndef BOOST_OB_COMPRESSED_PAIR_HPP
#define BOOST_OB_COMPRESSED_PAIR_HPP
#include <algorithm>
#ifndef BOOST_OBJECT_TYPE_TRAITS_HPP
#include <boost/type_traits/object_traits.hpp>
#endif
#ifndef BOOST_SAME_TRAITS_HPP
#include <boost/type_traits/same_traits.hpp>
#endif
#ifndef BOOST_CALL_TRAITS_HPP
#include <boost/call_traits.hpp>
#endif
namespace boost
{
#ifdef BOOST_MSVC6_MEMBER_TEMPLATES
//
// use member templates to emulate
// partial specialisation. Note that due to
// problems with overload resolution with VC6
// each of the compressed_pair versions that follow
// have one template single-argument constructor
// in place of two specific constructors:
//
template <class T1, class T2>
class compressed_pair;
namespace detail{
template <class A, class T1, class T2>
struct best_conversion_traits
{
typedef char one;
typedef char (&two)[2];
static A a;
static one test(T1);
static two test(T2);
enum { value = sizeof(test(a)) };
};
template <int>
struct init_one;
template <>
struct init_one<1>
{
template <class A, class T1, class T2>
static void init(const A& a, T1* p1, T2*)
{
*p1 = a;
}
};
template <>
struct init_one<2>
{
template <class A, class T1, class T2>
static void init(const A& a, T1*, T2* p2)
{
*p2 = a;
}
};
// T1 != T2, both non-empty
template <class T1, class T2>
class compressed_pair_0
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_0() : _first(), _second() {}
compressed_pair_0(first_param_type x, second_param_type y) : _first(x), _second(y) {}
template <class A>
explicit compressed_pair_0(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, &_first, &_second);
}
compressed_pair_0(const ::boost::compressed_pair<T1,T2>& x)
: _first(x.first()), _second(x.second()) {}
#if 0
compressed_pair_0& operator=(const compressed_pair_0& x) {
cout << "assigning compressed pair 0" << endl;
_first = x._first;
_second = x._second;
cout << "finished assigning compressed pair 0" << endl;
return *this;
}
#endif
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_0& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
// T1 != T2, T2 empty
template <class T1, class T2>
class compressed_pair_1 : T2
{
private:
T1 _first;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_1() : T2(), _first() {}
compressed_pair_1(first_param_type x, second_param_type y) : T2(y), _first(x) {}
template <class A>
explicit compressed_pair_1(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, &_first, static_cast<T2*>(this));
}
compressed_pair_1(const ::boost::compressed_pair<T1,T2>& x)
: T2(x.second()), _first(x.first()) {}
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
// Total weirdness. If the assignment to _first is moved after
// the call to the inherited operator=, then this breaks graph/test/graph.cpp
// by way of iterator_adaptor.
compressed_pair_1& operator=(const compressed_pair_1& x) {
_first = x._first;
T2::operator=(x);
return *this;
}
#endif
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return *this; }
second_const_reference second() const { return *this; }
void swap(compressed_pair_1& y)
{
// no need to swap empty base class:
using std::swap;
swap(_first, y._first);
}
};
// T1 != T2, T1 empty
template <class T1, class T2>
class compressed_pair_2 : T1
{
private:
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_2() : T1(), _second() {}
compressed_pair_2(first_param_type x, second_param_type y) : T1(x), _second(y) {}
template <class A>
explicit compressed_pair_2(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, static_cast<T1*>(this), &_second);
}
compressed_pair_2(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), _second(x.second()) {}
#if 0
compressed_pair_2& operator=(const compressed_pair_2& x) {
cout << "assigning compressed pair 2" << endl;
T1::operator=(x);
_second = x._second;
cout << "finished assigning compressed pair 2" << endl;
return *this;
}
#endif
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_2& y)
{
// no need to swap empty base class:
using std::swap;
swap(_second, y._second);
}
};
// T1 != T2, both empty
template <class T1, class T2>
class compressed_pair_3 : T1, T2
{
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_3() : T1(), T2() {}
compressed_pair_3(first_param_type x, second_param_type y) : T1(x), T2(y) {}
template <class A>
explicit compressed_pair_3(const A& val)
{
init_one<best_conversion_traits<A, T1, T2>::value>::init(val, static_cast<T1*>(this), static_cast<T2*>(this));
}
compressed_pair_3(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), T2(x.second()) {}
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return *this; }
second_const_reference second() const { return *this; }
void swap(compressed_pair_3& y)
{
// no need to swap empty base classes:
}
};
// T1 == T2, and empty
template <class T1, class T2>
class compressed_pair_4 : T1
{
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_4() : T1() {}
compressed_pair_4(first_param_type x, second_param_type y) : T1(x), m_second(y) {}
// only one single argument constructor since T1 == T2
explicit compressed_pair_4(first_param_type x) : T1(x), m_second(x) {}
compressed_pair_4(const ::boost::compressed_pair<T1,T2>& x)
: T1(x.first()), m_second(x.second()) {}
first_reference first() { return *this; }
first_const_reference first() const { return *this; }
second_reference second() { return m_second; }
second_const_reference second() const { return m_second; }
void swap(compressed_pair_4& y)
{
// no need to swap empty base classes:
}
private:
T2 m_second;
};
// T1 == T2, not empty
template <class T1, class T2>
class compressed_pair_5
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair_5() : _first(), _second() {}
compressed_pair_5(first_param_type x, second_param_type y) : _first(x), _second(y) {}
// only one single argument constructor since T1 == T2
explicit compressed_pair_5(first_param_type x) : _first(x), _second(x) {}
compressed_pair_5(const ::boost::compressed_pair<T1,T2>& c)
: _first(c.first()), _second(c.second()) {}
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair_5& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
template <bool e1, bool e2, bool same>
struct compressed_pair_chooser
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_0<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<false, true, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_1<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, false, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_2<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, true, false>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_3<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<true, true, true>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_4<T1, T2> type;
};
};
template <>
struct compressed_pair_chooser<false, false, true>
{
template <class T1, class T2>
struct rebind
{
typedef compressed_pair_5<T1, T2> type;
};
};
template <class T1, class T2>
struct compressed_pair_traits
{
private:
typedef compressed_pair_chooser<is_empty<T1>::value, is_empty<T2>::value, is_same<T1,T2>::value> chooser;
typedef typename chooser::template rebind<T1, T2> bound_type;
public:
typedef typename bound_type::type type;
};
} // namespace detail
template <class T1, class T2>
class compressed_pair : public detail::compressed_pair_traits<T1, T2>::type
{
private:
typedef typename detail::compressed_pair_traits<T1, T2>::type base_type;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair() : base_type() {}
compressed_pair(first_param_type x, second_param_type y) : base_type(x, y) {}
template <class A>
explicit compressed_pair(const A& x) : base_type(x){}
first_reference first() { return base_type::first(); }
first_const_reference first() const { return base_type::first(); }
second_reference second() { return base_type::second(); }
second_const_reference second() const { return base_type::second(); }
};
template <class T1, class T2>
inline void swap(compressed_pair<T1, T2>& x, compressed_pair<T1, T2>& y)
{
x.swap(y);
}
#else
// no partial specialisation, no member templates:
template <class T1, class T2>
class compressed_pair
{
private:
T1 _first;
T2 _second;
public:
typedef T1 first_type;
typedef T2 second_type;
typedef typename call_traits<first_type>::param_type first_param_type;
typedef typename call_traits<second_type>::param_type second_param_type;
typedef typename call_traits<first_type>::reference first_reference;
typedef typename call_traits<second_type>::reference second_reference;
typedef typename call_traits<first_type>::const_reference first_const_reference;
typedef typename call_traits<second_type>::const_reference second_const_reference;
compressed_pair() : _first(), _second() {}
compressed_pair(first_param_type x, second_param_type y) : _first(x), _second(y) {}
explicit compressed_pair(first_param_type x) : _first(x), _second() {}
// can't define this in case T1 == T2:
// explicit compressed_pair(second_param_type y) : _first(), _second(y) {}
first_reference first() { return _first; }
first_const_reference first() const { return _first; }
second_reference second() { return _second; }
second_const_reference second() const { return _second; }
void swap(compressed_pair& y)
{
using std::swap;
swap(_first, y._first);
swap(_second, y._second);
}
};
template <class T1, class T2>
inline void swap(compressed_pair<T1, T2>& x, compressed_pair<T1, T2>& y)
{
x.swap(y);
}
#endif
} // boost
#endif // BOOST_OB_COMPRESSED_PAIR_HPP
| {
"pile_set_name": "Github"
} |
#import "GPUImageTwoInputFilter.h"
@interface GPUImageDifferenceBlendFilter : GPUImageTwoInputFilter
{
}
@end
| {
"pile_set_name": "Github"
} |
/*
* Summary: interface for the libxslt security framework
* Description: the libxslt security framework allow to restrict
* the access to new resources (file or URL) from
* the stylesheet at runtime.
*
* Copy: See Copyright for the status of this software.
*
* Author: Daniel Veillard
*/
#ifndef __XML_XSLT_SECURITY_H__
#define __XML_XSLT_SECURITY_H__
#include <libxml/tree.h>
#include "xsltexports.h"
#include "xsltInternals.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* xsltSecurityPref:
*
* structure to indicate the preferences for security in the XSLT
* transformation.
*/
typedef struct _xsltSecurityPrefs xsltSecurityPrefs;
typedef xsltSecurityPrefs *xsltSecurityPrefsPtr;
/**
* xsltSecurityOption:
*
* the set of option that can be configured
*/
typedef enum {
XSLT_SECPREF_READ_FILE = 1,
XSLT_SECPREF_WRITE_FILE,
XSLT_SECPREF_CREATE_DIRECTORY,
XSLT_SECPREF_READ_NETWORK,
XSLT_SECPREF_WRITE_NETWORK
} xsltSecurityOption;
/**
* xsltSecurityCheck:
*
* User provided function to check the value of a string like a file
* path or an URL ...
*/
typedef int (*xsltSecurityCheck) (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt,
const char *value);
/*
* Module interfaces
*/
XSLTPUBFUN xsltSecurityPrefsPtr XSLTCALL
xsltNewSecurityPrefs (void);
XSLTPUBFUN void XSLTCALL
xsltFreeSecurityPrefs (xsltSecurityPrefsPtr sec);
XSLTPUBFUN int XSLTCALL
xsltSetSecurityPrefs (xsltSecurityPrefsPtr sec,
xsltSecurityOption option,
xsltSecurityCheck func);
XSLTPUBFUN xsltSecurityCheck XSLTCALL
xsltGetSecurityPrefs (xsltSecurityPrefsPtr sec,
xsltSecurityOption option);
XSLTPUBFUN void XSLTCALL
xsltSetDefaultSecurityPrefs (xsltSecurityPrefsPtr sec);
XSLTPUBFUN xsltSecurityPrefsPtr XSLTCALL
xsltGetDefaultSecurityPrefs (void);
XSLTPUBFUN int XSLTCALL
xsltSetCtxtSecurityPrefs (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt);
XSLTPUBFUN int XSLTCALL
xsltSecurityAllow (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt,
const char *value);
XSLTPUBFUN int XSLTCALL
xsltSecurityForbid (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt,
const char *value);
/*
* internal interfaces
*/
XSLTPUBFUN int XSLTCALL
xsltCheckWrite (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt,
const xmlChar *URL);
XSLTPUBFUN int XSLTCALL
xsltCheckRead (xsltSecurityPrefsPtr sec,
xsltTransformContextPtr ctxt,
const xmlChar *URL);
#ifdef __cplusplus
}
#endif
#endif /* __XML_XSLT_SECURITY_H__ */
| {
"pile_set_name": "Github"
} |
package ens
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeDataPushResult invokes the ens.DescribeDataPushResult API synchronously
func (client *Client) DescribeDataPushResult(request *DescribeDataPushResultRequest) (response *DescribeDataPushResultResponse, err error) {
response = CreateDescribeDataPushResultResponse()
err = client.DoAction(request, response)
return
}
// DescribeDataPushResultWithChan invokes the ens.DescribeDataPushResult API asynchronously
func (client *Client) DescribeDataPushResultWithChan(request *DescribeDataPushResultRequest) (<-chan *DescribeDataPushResultResponse, <-chan error) {
responseChan := make(chan *DescribeDataPushResultResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeDataPushResult(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeDataPushResultWithCallback invokes the ens.DescribeDataPushResult API asynchronously
func (client *Client) DescribeDataPushResultWithCallback(request *DescribeDataPushResultRequest, callback func(response *DescribeDataPushResultResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeDataPushResultResponse
var err error
defer close(result)
response, err = client.DescribeDataPushResult(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeDataPushResultRequest is the request struct for api DescribeDataPushResult
type DescribeDataPushResultRequest struct {
*requests.RpcRequest
MaxDate string `position:"Query" name:"MaxDate"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
RegionIds string `position:"Query" name:"RegionIds"`
MinDate string `position:"Query" name:"MinDate"`
DataVersions string `position:"Query" name:"DataVersions"`
AppId string `position:"Query" name:"AppId"`
DataNames string `position:"Query" name:"DataNames"`
}
// DescribeDataPushResultResponse is the response struct for api DescribeDataPushResult
type DescribeDataPushResultResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
PushResults PushResultsInDescribeDataPushResult `json:"PushResults" xml:"PushResults"`
}
// CreateDescribeDataPushResultRequest creates a request to invoke DescribeDataPushResult API
func CreateDescribeDataPushResultRequest() (request *DescribeDataPushResultRequest) {
request = &DescribeDataPushResultRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Ens", "2017-11-10", "DescribeDataPushResult", "ens", "openAPI")
request.Method = requests.POST
return
}
// CreateDescribeDataPushResultResponse creates a response to parse from DescribeDataPushResult response
func CreateDescribeDataPushResultResponse() (response *DescribeDataPushResultResponse) {
response = &DescribeDataPushResultResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
| {
"pile_set_name": "Github"
} |
From 559fbff13af9ce2fbc0b9bc5727a7323e1db6217 Mon Sep 17 00:00:00 2001
From: Eneas U de Queiroz <cote2004-github@yahoo.com>
Date: Thu, 27 Sep 2018 08:29:21 -0300
Subject: Do not use host kernel version to disable AFALG
This patch prevents the Configure script from using the host kernel
version to disable building the AFALG engine on openwrt targets.
Signed-off-by: Eneas U de Queiroz <cote2004-github@yahoo.com>
diff --git a/Configure b/Configure
index 5a699836f3..74d057c219 100755
--- a/Configure
+++ b/Configure
@@ -1532,7 +1532,9 @@ unless ($disabled{"crypto-mdebug-backtrace"})
unless ($disabled{afalgeng}) {
$config{afalgeng}="";
- if (grep { $_ eq 'afalgeng' } @{$target{enable}}) {
+ if ($target =~ m/openwrt$/) {
+ push @{$config{engdirs}}, "afalg";
+ } elsif (grep { $_ eq 'afalgeng' } @{$target{enable}}) {
my $minver = 4*10000 + 1*100 + 0;
if ($config{CROSS_COMPILE} eq "") {
my $verstr = `uname -r`;
| {
"pile_set_name": "Github"
} |
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import android.hardware.camera2.impl.CameraMetadataNative;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
/** Shadow class for {@link CameraMetadataNative} */
@Implements(value = CameraMetadataNative.class, minSdk = LOLLIPOP, isInAndroidSdk = false)
public class ShadowCameraMetadataNative {
@Implementation(minSdk = P, maxSdk = Q)
protected long nativeAllocate() {
return 1L;
}
@Implementation(minSdk = P, maxSdk = Q)
protected long nativeAllocateCopy(CameraMetadataNative other) {
return 1L;
}
}
| {
"pile_set_name": "Github"
} |
// Code generated by solo-kit. DO NOT EDIT.
package v1
import (
"github.com/solo-io/solo-kit/pkg/api/v1/clients"
"github.com/solo-io/solo-kit/pkg/api/v1/clients/factory"
"github.com/solo-io/solo-kit/pkg/api/v1/resources"
"github.com/solo-io/solo-kit/pkg/errors"
)
type UpstreamGroupWatcher interface {
// watch namespace-scoped UpstreamGroups
Watch(namespace string, opts clients.WatchOpts) (<-chan UpstreamGroupList, <-chan error, error)
}
type UpstreamGroupClient interface {
BaseClient() clients.ResourceClient
Register() error
Read(namespace, name string, opts clients.ReadOpts) (*UpstreamGroup, error)
Write(resource *UpstreamGroup, opts clients.WriteOpts) (*UpstreamGroup, error)
Delete(namespace, name string, opts clients.DeleteOpts) error
List(namespace string, opts clients.ListOpts) (UpstreamGroupList, error)
UpstreamGroupWatcher
}
type upstreamGroupClient struct {
rc clients.ResourceClient
}
func NewUpstreamGroupClient(rcFactory factory.ResourceClientFactory) (UpstreamGroupClient, error) {
return NewUpstreamGroupClientWithToken(rcFactory, "")
}
func NewUpstreamGroupClientWithToken(rcFactory factory.ResourceClientFactory, token string) (UpstreamGroupClient, error) {
rc, err := rcFactory.NewResourceClient(factory.NewResourceClientParams{
ResourceType: &UpstreamGroup{},
Token: token,
})
if err != nil {
return nil, errors.Wrapf(err, "creating base UpstreamGroup resource client")
}
return NewUpstreamGroupClientWithBase(rc), nil
}
func NewUpstreamGroupClientWithBase(rc clients.ResourceClient) UpstreamGroupClient {
return &upstreamGroupClient{
rc: rc,
}
}
func (client *upstreamGroupClient) BaseClient() clients.ResourceClient {
return client.rc
}
func (client *upstreamGroupClient) Register() error {
return client.rc.Register()
}
func (client *upstreamGroupClient) Read(namespace, name string, opts clients.ReadOpts) (*UpstreamGroup, error) {
opts = opts.WithDefaults()
resource, err := client.rc.Read(namespace, name, opts)
if err != nil {
return nil, err
}
return resource.(*UpstreamGroup), nil
}
func (client *upstreamGroupClient) Write(upstreamGroup *UpstreamGroup, opts clients.WriteOpts) (*UpstreamGroup, error) {
opts = opts.WithDefaults()
resource, err := client.rc.Write(upstreamGroup, opts)
if err != nil {
return nil, err
}
return resource.(*UpstreamGroup), nil
}
func (client *upstreamGroupClient) Delete(namespace, name string, opts clients.DeleteOpts) error {
opts = opts.WithDefaults()
return client.rc.Delete(namespace, name, opts)
}
func (client *upstreamGroupClient) List(namespace string, opts clients.ListOpts) (UpstreamGroupList, error) {
opts = opts.WithDefaults()
resourceList, err := client.rc.List(namespace, opts)
if err != nil {
return nil, err
}
return convertToUpstreamGroup(resourceList), nil
}
func (client *upstreamGroupClient) Watch(namespace string, opts clients.WatchOpts) (<-chan UpstreamGroupList, <-chan error, error) {
opts = opts.WithDefaults()
resourcesChan, errs, initErr := client.rc.Watch(namespace, opts)
if initErr != nil {
return nil, nil, initErr
}
upstreamGroupsChan := make(chan UpstreamGroupList)
go func() {
for {
select {
case resourceList := <-resourcesChan:
upstreamGroupsChan <- convertToUpstreamGroup(resourceList)
case <-opts.Ctx.Done():
close(upstreamGroupsChan)
return
}
}
}()
return upstreamGroupsChan, errs, nil
}
func convertToUpstreamGroup(resources resources.ResourceList) UpstreamGroupList {
var upstreamGroupList UpstreamGroupList
for _, resource := range resources {
upstreamGroupList = append(upstreamGroupList, resource.(*UpstreamGroup))
}
return upstreamGroupList
}
| {
"pile_set_name": "Github"
} |
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'core-angular-universal'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('core-angular-universal');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('core-angular-universal app is running!');
});
});
| {
"pile_set_name": "Github"
} |
/* *********************************************************************** *
* project: org.matsim.*
* FacilitiesReaderMatsimV1.java
* *
* *********************************************************************** *
* *
* copyright : (C) 2007 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.matsim.facilities;
import java.util.Map;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.matsim.api.core.v01.Coord;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.network.Link;
import org.matsim.core.scenario.ProjectionUtils;
import org.matsim.core.utils.geometry.CoordinateTransformation;
import org.matsim.core.utils.geometry.transformations.IdentityTransformation;
import org.matsim.core.utils.geometry.transformations.TransformationFactory;
import org.matsim.core.utils.io.MatsimXmlParser;
import org.matsim.core.utils.misc.Time;
import org.matsim.utils.objectattributes.AttributeConverter;
import org.matsim.utils.objectattributes.attributable.AttributesXmlReaderDelegate;
import org.xml.sax.Attributes;
/**
* A reader for facilities-files of MATSim according to <code>facilities_v1.dtd</code>.
*
* @author mrieser
* @author balmermi
*/
final class FacilitiesReaderMatsimV1 extends MatsimXmlParser {
private static Logger log = Logger.getLogger(FacilitiesReaderMatsimV1.class);
private final static String FACILITIES = "facilities";
private final static String FACILITY = "facility";
private final static String ACTIVITY = "activity";
private final static String CAPACITY = "capacity";
private final static String OPENTIME = "opentime";
private static final String ATTRIBUTES = "attributes";
private static final String ATTRIBUTE = "attribute";
private final ActivityFacilities facilities;
private final ActivityFacilitiesFactory factory;
private final AttributesXmlReaderDelegate attributesReader = new AttributesXmlReaderDelegate();
private ActivityFacility currfacility = null;
private ActivityOption curractivity = null;
private org.matsim.utils.objectattributes.attributable.Attributes currAttributes = null;
private final String externalInputCRS;
private final String targetCRS;
private CoordinateTransformation coordinateTransformation = new IdentityTransformation();
FacilitiesReaderMatsimV1(
final String externalInputCRS,
final String targetCRS,
final ActivityFacilities facilities) {
this.externalInputCRS = externalInputCRS;
this.targetCRS = targetCRS;
this.facilities = facilities;
this.factory = this.facilities.getFactory();
if (externalInputCRS != null && targetCRS != null) {
this.coordinateTransformation = TransformationFactory.getCoordinateTransformation(externalInputCRS, targetCRS);
ProjectionUtils.putCRS(this.facilities, targetCRS);
}
}
public void putAttributeConverter(Class<?> clazz, AttributeConverter<?> converter) {
this.attributesReader.putAttributeConverter(clazz, converter);
}
public void putAttributeConverters(Map<Class<?>, AttributeConverter<?>> converters) {
this.attributesReader.putAttributeConverters(converters);
}
@Override
public void startTag(final String name, final org.xml.sax.Attributes atts, final Stack<String> context) {
if (FACILITIES.equals(name)) {
startFacilities(atts);
} else if (FACILITY.equals(name)) {
startFacility(atts);
} else if (ACTIVITY.equals(name)) {
startActivity(atts);
} else if (CAPACITY.equals(name)) {
startCapacity(atts);
} else if (OPENTIME.equals(name)) {
startOpentime(atts);
} else if (ATTRIBUTE.equals(name)) {
this.attributesReader.startTag(name, atts, context, this.currAttributes);
} else if (ATTRIBUTES.equals(name)) {
currAttributes = context.peek().equals(FACILITIES) ? this.facilities.getAttributes() : this.currfacility.getAttributes();
attributesReader.startTag(name, atts, context, currAttributes);
}
}
@Override
public void endTag(final String name, final String content, final Stack<String> context) {
if (FACILITY.equals(name)) {
this.facilities.addActivityFacility(this.currfacility);
this.currfacility = null;
} else if (ACTIVITY.equals(name)) {
this.curractivity = null;
} else if (ATTRIBUTES.equalsIgnoreCase(name)) {
if (context.peek().equals(FACILITIES)) {
String inputCRS = (String) currAttributes.getAttribute(ProjectionUtils.INPUT_CRS_ATT);
if (inputCRS != null && targetCRS != null) {
if (externalInputCRS != null) {
// warn or crash?
log.warn("coordinate transformation defined both in config and in input file: setting from input file will be used");
}
coordinateTransformation = TransformationFactory.getCoordinateTransformation(inputCRS, targetCRS);
currAttributes.putAttribute(ProjectionUtils.INPUT_CRS_ATT, targetCRS);
}
}
this.currAttributes = null;
} else if (ATTRIBUTE.equalsIgnoreCase(name)) {
this.attributesReader.endTag(name, content, context);
}
}
private void startFacilities(final Attributes atts) {
this.facilities.setName(atts.getValue("name"));
this.currAttributes = facilities.getAttributes();
if (atts.getValue("aggregation_layer") != null) {
Logger.getLogger(FacilitiesReaderMatsimV1.class).warn("aggregation_layer is deprecated.");
}
}
private void startFacility(final Attributes atts) {
if ( atts.getValue("x") !=null && atts.getValue("y") !=null ) {
if (atts.getValue("linkId") !=null) { //both coord and link present
this.currfacility =
this.factory.createActivityFacility(
Id.create(atts.getValue("id"), ActivityFacility.class),
coordinateTransformation.transform(
new Coord(
Double.parseDouble(atts.getValue("x")),
Double.parseDouble(atts.getValue("y")))),
Id.create(atts.getValue("linkId"),Link.class));
} else { // only coord present
this.currfacility =
this.factory.createActivityFacility(
Id.create(atts.getValue("id"), ActivityFacility.class),
coordinateTransformation.transform(
new Coord(
Double.parseDouble(atts.getValue("x")),
Double.parseDouble(atts.getValue("y")))));
}
} else {
if (atts.getValue("linkId") !=null) { //only link present
this.currfacility =
this.factory.createActivityFacility(
Id.create(atts.getValue("id"), ActivityFacility.class),
Id.create(atts.getValue("linkId"),Link.class));
} else { //neither coord nor link present
throw new RuntimeException("Neither coordinate nor linkId are available for facility id "+ atts.getValue("id")+". Aborting....");
}
}
((ActivityFacilityImpl) this.currfacility).setDesc(atts.getValue("desc"));
}
private void startActivity(final Attributes atts) {
this.curractivity = this.factory.createActivityOption(atts.getValue("type"));
this.currfacility.addActivityOption(this.curractivity);
}
private void startCapacity(final Attributes atts) {
double cap = Double.parseDouble(atts.getValue("value"));
this.curractivity.setCapacity(cap);
}
private void startOpentime(final Attributes atts) {
this.curractivity.addOpeningTime(OpeningTimeImpl.createFromOptionalTimes(
Time.parseOptionalTime(atts.getValue("start_time")),
Time.parseOptionalTime(atts.getValue("end_time"))));
}
}
| {
"pile_set_name": "Github"
} |
// SGI's rope class implementation -*- C++ -*-
// Copyright (C) 2001-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library 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. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/*
* Copyright (c) 1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
/** @file ropeimpl.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{ext/rope}
*/
#include <cstdio>
#include <ostream>
#include <bits/functexcept.h>
#include <ext/algorithm> // For copy_n and lexicographical_compare_3way
#include <ext/memory> // For uninitialized_copy_n
#include <ext/numeric> // For power
namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
using std::size_t;
using std::printf;
using std::basic_ostream;
using std::__throw_length_error;
using std::_Destroy;
using std::__uninitialized_fill_n_a;
// Set buf_start, buf_end, and buf_ptr appropriately, filling tmp_buf
// if necessary. Assumes _M_path_end[leaf_index] and leaf_pos are correct.
// Results in a valid buf_ptr if the iterator can be legitimately
// dereferenced.
template <class _CharT, class _Alloc>
void
_Rope_iterator_base<_CharT, _Alloc>::
_S_setbuf(_Rope_iterator_base<_CharT, _Alloc>& __x)
{
const _RopeRep* __leaf = __x._M_path_end[__x._M_leaf_index];
size_t __leaf_pos = __x._M_leaf_pos;
size_t __pos = __x._M_current_pos;
switch(__leaf->_M_tag)
{
case __detail::_S_leaf:
__x._M_buf_start = ((_Rope_RopeLeaf<_CharT, _Alloc>*)__leaf)->_M_data;
__x._M_buf_ptr = __x._M_buf_start + (__pos - __leaf_pos);
__x._M_buf_end = __x._M_buf_start + __leaf->_M_size;
break;
case __detail::_S_function:
case __detail::_S_substringfn:
{
size_t __len = _S_iterator_buf_len;
size_t __buf_start_pos = __leaf_pos;
size_t __leaf_end = __leaf_pos + __leaf->_M_size;
char_producer<_CharT>* __fn = ((_Rope_RopeFunction<_CharT,
_Alloc>*)__leaf)->_M_fn;
if (__buf_start_pos + __len <= __pos)
{
__buf_start_pos = __pos - __len / 4;
if (__buf_start_pos + __len > __leaf_end)
__buf_start_pos = __leaf_end - __len;
}
if (__buf_start_pos + __len > __leaf_end)
__len = __leaf_end - __buf_start_pos;
(*__fn)(__buf_start_pos - __leaf_pos, __len, __x._M_tmp_buf);
__x._M_buf_ptr = __x._M_tmp_buf + (__pos - __buf_start_pos);
__x._M_buf_start = __x._M_tmp_buf;
__x._M_buf_end = __x._M_tmp_buf + __len;
}
break;
default:
break;
}
}
// Set path and buffer inside a rope iterator. We assume that
// pos and root are already set.
template <class _CharT, class _Alloc>
void
_Rope_iterator_base<_CharT, _Alloc>::
_S_setcache(_Rope_iterator_base<_CharT, _Alloc>& __x)
{
const _RopeRep* __path[int(__detail::_S_max_rope_depth) + 1];
const _RopeRep* __curr_rope;
int __curr_depth = -1; /* index into path */
size_t __curr_start_pos = 0;
size_t __pos = __x._M_current_pos;
unsigned char __dirns = 0; // Bit vector marking right turns in the path
if (__pos >= __x._M_root->_M_size)
{
__x._M_buf_ptr = 0;
return;
}
__curr_rope = __x._M_root;
if (0 != __curr_rope->_M_c_string)
{
/* Treat the root as a leaf. */
__x._M_buf_start = __curr_rope->_M_c_string;
__x._M_buf_end = __curr_rope->_M_c_string + __curr_rope->_M_size;
__x._M_buf_ptr = __curr_rope->_M_c_string + __pos;
__x._M_path_end[0] = __curr_rope;
__x._M_leaf_index = 0;
__x._M_leaf_pos = 0;
return;
}
for(;;)
{
++__curr_depth;
__path[__curr_depth] = __curr_rope;
switch(__curr_rope->_M_tag)
{
case __detail::_S_leaf:
case __detail::_S_function:
case __detail::_S_substringfn:
__x._M_leaf_pos = __curr_start_pos;
goto done;
case __detail::_S_concat:
{
_Rope_RopeConcatenation<_CharT, _Alloc>* __c =
(_Rope_RopeConcatenation<_CharT, _Alloc>*)__curr_rope;
_RopeRep* __left = __c->_M_left;
size_t __left_len = __left->_M_size;
__dirns <<= 1;
if (__pos >= __curr_start_pos + __left_len)
{
__dirns |= 1;
__curr_rope = __c->_M_right;
__curr_start_pos += __left_len;
}
else
__curr_rope = __left;
}
break;
}
}
done:
// Copy last section of path into _M_path_end.
{
int __i = -1;
int __j = __curr_depth + 1 - int(_S_path_cache_len);
if (__j < 0) __j = 0;
while (__j <= __curr_depth)
__x._M_path_end[++__i] = __path[__j++];
__x._M_leaf_index = __i;
}
__x._M_path_directions = __dirns;
_S_setbuf(__x);
}
// Specialized version of the above. Assumes that
// the path cache is valid for the previous position.
template <class _CharT, class _Alloc>
void
_Rope_iterator_base<_CharT, _Alloc>::
_S_setcache_for_incr(_Rope_iterator_base<_CharT, _Alloc>& __x)
{
int __current_index = __x._M_leaf_index;
const _RopeRep* __current_node = __x._M_path_end[__current_index];
size_t __len = __current_node->_M_size;
size_t __node_start_pos = __x._M_leaf_pos;
unsigned char __dirns = __x._M_path_directions;
_Rope_RopeConcatenation<_CharT, _Alloc>* __c;
if (__x._M_current_pos - __node_start_pos < __len)
{
/* More stuff in this leaf, we just didn't cache it. */
_S_setbuf(__x);
return;
}
// node_start_pos is starting position of last_node.
while (--__current_index >= 0)
{
if (!(__dirns & 1) /* Path turned left */)
break;
__current_node = __x._M_path_end[__current_index];
__c = (_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node;
// Otherwise we were in the right child. Thus we should pop
// the concatenation node.
__node_start_pos -= __c->_M_left->_M_size;
__dirns >>= 1;
}
if (__current_index < 0)
{
// We underflowed the cache. Punt.
_S_setcache(__x);
return;
}
__current_node = __x._M_path_end[__current_index];
__c = (_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node;
// current_node is a concatenation node. We are positioned on the first
// character in its right child.
// node_start_pos is starting position of current_node.
__node_start_pos += __c->_M_left->_M_size;
__current_node = __c->_M_right;
__x._M_path_end[++__current_index] = __current_node;
__dirns |= 1;
while (__detail::_S_concat == __current_node->_M_tag)
{
++__current_index;
if (int(_S_path_cache_len) == __current_index)
{
int __i;
for (__i = 0; __i < int(_S_path_cache_len) - 1; __i++)
__x._M_path_end[__i] = __x._M_path_end[__i+1];
--__current_index;
}
__current_node =
((_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node)->_M_left;
__x._M_path_end[__current_index] = __current_node;
__dirns <<= 1;
// node_start_pos is unchanged.
}
__x._M_leaf_index = __current_index;
__x._M_leaf_pos = __node_start_pos;
__x._M_path_directions = __dirns;
_S_setbuf(__x);
}
template <class _CharT, class _Alloc>
void
_Rope_iterator_base<_CharT, _Alloc>::
_M_incr(size_t __n)
{
_M_current_pos += __n;
if (0 != _M_buf_ptr)
{
size_t __chars_left = _M_buf_end - _M_buf_ptr;
if (__chars_left > __n)
_M_buf_ptr += __n;
else if (__chars_left == __n)
{
_M_buf_ptr += __n;
_S_setcache_for_incr(*this);
}
else
_M_buf_ptr = 0;
}
}
template <class _CharT, class _Alloc>
void
_Rope_iterator_base<_CharT, _Alloc>::
_M_decr(size_t __n)
{
if (0 != _M_buf_ptr)
{
size_t __chars_left = _M_buf_ptr - _M_buf_start;
if (__chars_left >= __n)
_M_buf_ptr -= __n;
else
_M_buf_ptr = 0;
}
_M_current_pos -= __n;
}
template <class _CharT, class _Alloc>
void
_Rope_iterator<_CharT, _Alloc>::
_M_check()
{
if (_M_root_rope->_M_tree_ptr != this->_M_root)
{
// _Rope was modified. Get things fixed up.
_RopeRep::_S_unref(this->_M_root);
this->_M_root = _M_root_rope->_M_tree_ptr;
_RopeRep::_S_ref(this->_M_root);
this->_M_buf_ptr = 0;
}
}
template <class _CharT, class _Alloc>
inline
_Rope_const_iterator<_CharT, _Alloc>::
_Rope_const_iterator(const _Rope_iterator<_CharT, _Alloc>& __x)
: _Rope_iterator_base<_CharT, _Alloc>(__x)
{ }
template <class _CharT, class _Alloc>
inline
_Rope_iterator<_CharT, _Alloc>::
_Rope_iterator(rope<_CharT, _Alloc>& __r, size_t __pos)
: _Rope_iterator_base<_CharT,_Alloc>(__r._M_tree_ptr, __pos),
_M_root_rope(&__r)
{ _RopeRep::_S_ref(this->_M_root); }
template <class _CharT, class _Alloc>
inline size_t
rope<_CharT, _Alloc>::
_S_char_ptr_len(const _CharT* __s)
{
const _CharT* __p = __s;
while (!_S_is0(*__p))
++__p;
return (__p - __s);
}
#ifndef __GC
template <class _CharT, class _Alloc>
inline void
_Rope_RopeRep<_CharT, _Alloc>::
_M_free_c_string()
{
_CharT* __cstr = _M_c_string;
if (0 != __cstr)
{
size_t __size = this->_M_size + 1;
_Destroy(__cstr, __cstr + __size, _M_get_allocator());
this->_Data_deallocate(__cstr, __size);
}
}
template <class _CharT, class _Alloc>
inline void
_Rope_RopeRep<_CharT, _Alloc>::
_S_free_string(_CharT* __s, size_t __n, allocator_type& __a)
{
if (!_S_is_basic_char_type((_CharT*)0))
_Destroy(__s, __s + __n, __a);
// This has to be a static member, so this gets a bit messy
__a.deallocate(__s,
_Rope_RopeLeaf<_CharT, _Alloc>::_S_rounded_up_size(__n));
}
// There are several reasons for not doing this with virtual destructors
// and a class specific delete operator:
// - A class specific delete operator can't easily get access to
// allocator instances if we need them.
// - Any virtual function would need a 4 or byte vtable pointer;
// this only requires a one byte tag per object.
template <class _CharT, class _Alloc>
void
_Rope_RopeRep<_CharT, _Alloc>::
_M_free_tree()
{
switch(_M_tag)
{
case __detail::_S_leaf:
{
_Rope_RopeLeaf<_CharT, _Alloc>* __l
= (_Rope_RopeLeaf<_CharT, _Alloc>*)this;
__l->_Rope_RopeLeaf<_CharT, _Alloc>::~_Rope_RopeLeaf();
this->_L_deallocate(__l, 1);
break;
}
case __detail::_S_concat:
{
_Rope_RopeConcatenation<_CharT,_Alloc>* __c
= (_Rope_RopeConcatenation<_CharT, _Alloc>*)this;
__c->_Rope_RopeConcatenation<_CharT, _Alloc>::
~_Rope_RopeConcatenation();
this->_C_deallocate(__c, 1);
break;
}
case __detail::_S_function:
{
_Rope_RopeFunction<_CharT, _Alloc>* __f
= (_Rope_RopeFunction<_CharT, _Alloc>*)this;
__f->_Rope_RopeFunction<_CharT, _Alloc>::~_Rope_RopeFunction();
this->_F_deallocate(__f, 1);
break;
}
case __detail::_S_substringfn:
{
_Rope_RopeSubstring<_CharT, _Alloc>* __ss =
(_Rope_RopeSubstring<_CharT, _Alloc>*)this;
__ss->_Rope_RopeSubstring<_CharT, _Alloc>::
~_Rope_RopeSubstring();
this->_S_deallocate(__ss, 1);
break;
}
}
}
#else
template <class _CharT, class _Alloc>
inline void
_Rope_RopeRep<_CharT, _Alloc>::
_S_free_string(const _CharT*, size_t, allocator_type)
{ }
#endif
// Concatenate a C string onto a leaf rope by copying the rope data.
// Used for short ropes.
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeLeaf*
rope<_CharT, _Alloc>::
_S_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter, size_t __len)
{
size_t __old_len = __r->_M_size;
_CharT* __new_data = (_CharT*)
rope::_Data_allocate(_S_rounded_up_size(__old_len + __len));
_RopeLeaf* __result;
uninitialized_copy_n(__r->_M_data, __old_len, __new_data);
uninitialized_copy_n(__iter, __len, __new_data + __old_len);
_S_cond_store_eos(__new_data[__old_len + __len]);
__try
{
__result = _S_new_RopeLeaf(__new_data, __old_len + __len,
__r->_M_get_allocator());
}
__catch(...)
{
_RopeRep::__STL_FREE_STRING(__new_data, __old_len + __len,
__r->_M_get_allocator());
__throw_exception_again;
}
return __result;
}
#ifndef __GC
// As above, but it's OK to clobber original if refcount is 1
template <class _CharT, class _Alloc>
typename rope<_CharT,_Alloc>::_RopeLeaf*
rope<_CharT, _Alloc>::
_S_destr_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter,
size_t __len)
{
if (__r->_M_ref_count > 1)
return _S_leaf_concat_char_iter(__r, __iter, __len);
size_t __old_len = __r->_M_size;
if (_S_allocated_capacity(__old_len) >= __old_len + __len)
{
// The space has been partially initialized for the standard
// character types. But that doesn't matter for those types.
uninitialized_copy_n(__iter, __len, __r->_M_data + __old_len);
if (_S_is_basic_char_type((_CharT*)0))
_S_cond_store_eos(__r->_M_data[__old_len + __len]);
else if (__r->_M_c_string != __r->_M_data && 0 != __r->_M_c_string)
{
__r->_M_free_c_string();
__r->_M_c_string = 0;
}
__r->_M_size = __old_len + __len;
__r->_M_ref_count = 2;
return __r;
}
else
{
_RopeLeaf* __result = _S_leaf_concat_char_iter(__r, __iter, __len);
return __result;
}
}
#endif
// Assumes left and right are not 0.
// Does not increment (nor decrement on exception) child reference counts.
// Result has ref count 1.
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeRep*
rope<_CharT, _Alloc>::
_S_tree_concat(_RopeRep* __left, _RopeRep* __right)
{
_RopeConcatenation* __result = _S_new_RopeConcatenation(__left, __right,
__left->
_M_get_allocator());
size_t __depth = __result->_M_depth;
if (__depth > 20
&& (__result->_M_size < 1000
|| __depth > size_t(__detail::_S_max_rope_depth)))
{
_RopeRep* __balanced;
__try
{
__balanced = _S_balance(__result);
__result->_M_unref_nonnil();
}
__catch(...)
{
rope::_C_deallocate(__result,1);
__throw_exception_again;
}
// In case of exception, we need to deallocate
// otherwise dangling result node. But caller
// still owns its children. Thus unref is
// inappropriate.
return __balanced;
}
else
return __result;
}
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeRep*
rope<_CharT, _Alloc>::
_S_concat_char_iter(_RopeRep* __r, const _CharT*__s, size_t __slen)
{
_RopeRep* __result;
if (0 == __slen)
{
_S_ref(__r);
return __r;
}
if (0 == __r)
return __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen,
__r->_M_get_allocator());
if (__r->_M_tag == __detail::_S_leaf
&& __r->_M_size + __slen <= size_t(_S_copy_max))
{
__result = _S_leaf_concat_char_iter((_RopeLeaf*)__r, __s, __slen);
return __result;
}
if (__detail::_S_concat == __r->_M_tag
&& __detail::_S_leaf == ((_RopeConcatenation*) __r)->_M_right->_M_tag)
{
_RopeLeaf* __right =
(_RopeLeaf* )(((_RopeConcatenation* )__r)->_M_right);
if (__right->_M_size + __slen <= size_t(_S_copy_max))
{
_RopeRep* __left = ((_RopeConcatenation*)__r)->_M_left;
_RopeRep* __nright =
_S_leaf_concat_char_iter((_RopeLeaf*)__right, __s, __slen);
__left->_M_ref_nonnil();
__try
{ __result = _S_tree_concat(__left, __nright); }
__catch(...)
{
_S_unref(__left);
_S_unref(__nright);
__throw_exception_again;
}
return __result;
}
}
_RopeRep* __nright =
__STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen, __r->_M_get_allocator());
__try
{
__r->_M_ref_nonnil();
__result = _S_tree_concat(__r, __nright);
}
__catch(...)
{
_S_unref(__r);
_S_unref(__nright);
__throw_exception_again;
}
return __result;
}
#ifndef __GC
template <class _CharT, class _Alloc>
typename rope<_CharT,_Alloc>::_RopeRep*
rope<_CharT,_Alloc>::
_S_destr_concat_char_iter(_RopeRep* __r, const _CharT* __s, size_t __slen)
{
_RopeRep* __result;
if (0 == __r)
return __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen,
__r->_M_get_allocator());
size_t __count = __r->_M_ref_count;
size_t __orig_size = __r->_M_size;
if (__count > 1)
return _S_concat_char_iter(__r, __s, __slen);
if (0 == __slen)
{
__r->_M_ref_count = 2; // One more than before
return __r;
}
if (__orig_size + __slen <= size_t(_S_copy_max)
&& __detail::_S_leaf == __r->_M_tag)
{
__result = _S_destr_leaf_concat_char_iter((_RopeLeaf*)__r, __s,
__slen);
return __result;
}
if (__detail::_S_concat == __r->_M_tag)
{
_RopeLeaf* __right = (_RopeLeaf*)(((_RopeConcatenation*)
__r)->_M_right);
if (__detail::_S_leaf == __right->_M_tag
&& __right->_M_size + __slen <= size_t(_S_copy_max))
{
_RopeRep* __new_right =
_S_destr_leaf_concat_char_iter(__right, __s, __slen);
if (__right == __new_right)
__new_right->_M_ref_count = 1;
else
__right->_M_unref_nonnil();
__r->_M_ref_count = 2; // One more than before.
((_RopeConcatenation*)__r)->_M_right = __new_right;
__r->_M_size = __orig_size + __slen;
if (0 != __r->_M_c_string)
{
__r->_M_free_c_string();
__r->_M_c_string = 0;
}
return __r;
}
}
_RopeRep* __right =
__STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen, __r->_M_get_allocator());
__r->_M_ref_nonnil();
__try
{ __result = _S_tree_concat(__r, __right); }
__catch(...)
{
_S_unref(__r);
_S_unref(__right);
__throw_exception_again;
}
return __result;
}
#endif /* !__GC */
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeRep*
rope<_CharT, _Alloc>::
_S_concat(_RopeRep* __left, _RopeRep* __right)
{
if (0 == __left)
{
_S_ref(__right);
return __right;
}
if (0 == __right)
{
__left->_M_ref_nonnil();
return __left;
}
if (__detail::_S_leaf == __right->_M_tag)
{
if (__detail::_S_leaf == __left->_M_tag)
{
if (__right->_M_size + __left->_M_size <= size_t(_S_copy_max))
return _S_leaf_concat_char_iter((_RopeLeaf*)__left,
((_RopeLeaf*)__right)->_M_data,
__right->_M_size);
}
else if (__detail::_S_concat == __left->_M_tag
&& __detail::_S_leaf == ((_RopeConcatenation*)
__left)->_M_right->_M_tag)
{
_RopeLeaf* __leftright =
(_RopeLeaf*)(((_RopeConcatenation*)__left)->_M_right);
if (__leftright->_M_size
+ __right->_M_size <= size_t(_S_copy_max))
{
_RopeRep* __leftleft = ((_RopeConcatenation*)__left)->_M_left;
_RopeRep* __rest = _S_leaf_concat_char_iter(__leftright,
((_RopeLeaf*)
__right)->
_M_data,
__right->_M_size);
__leftleft->_M_ref_nonnil();
__try
{ return(_S_tree_concat(__leftleft, __rest)); }
__catch(...)
{
_S_unref(__leftleft);
_S_unref(__rest);
__throw_exception_again;
}
}
}
}
__left->_M_ref_nonnil();
__right->_M_ref_nonnil();
__try
{ return(_S_tree_concat(__left, __right)); }
__catch(...)
{
_S_unref(__left);
_S_unref(__right);
__throw_exception_again;
}
}
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeRep*
rope<_CharT, _Alloc>::
_S_substring(_RopeRep* __base, size_t __start, size_t __endp1)
{
if (0 == __base)
return 0;
size_t __len = __base->_M_size;
size_t __adj_endp1;
const size_t __lazy_threshold = 128;
if (__endp1 >= __len)
{
if (0 == __start)
{
__base->_M_ref_nonnil();
return __base;
}
else
__adj_endp1 = __len;
}
else
__adj_endp1 = __endp1;
switch(__base->_M_tag)
{
case __detail::_S_concat:
{
_RopeConcatenation* __c = (_RopeConcatenation*)__base;
_RopeRep* __left = __c->_M_left;
_RopeRep* __right = __c->_M_right;
size_t __left_len = __left->_M_size;
_RopeRep* __result;
if (__adj_endp1 <= __left_len)
return _S_substring(__left, __start, __endp1);
else if (__start >= __left_len)
return _S_substring(__right, __start - __left_len,
__adj_endp1 - __left_len);
_Self_destruct_ptr __left_result(_S_substring(__left,
__start,
__left_len));
_Self_destruct_ptr __right_result(_S_substring(__right, 0,
__endp1
- __left_len));
__result = _S_concat(__left_result, __right_result);
return __result;
}
case __detail::_S_leaf:
{
_RopeLeaf* __l = (_RopeLeaf*)__base;
_RopeLeaf* __result;
size_t __result_len;
if (__start >= __adj_endp1)
return 0;
__result_len = __adj_endp1 - __start;
if (__result_len > __lazy_threshold)
goto lazy;
#ifdef __GC
const _CharT* __section = __l->_M_data + __start;
__result = _S_new_RopeLeaf(__section, __result_len,
__base->_M_get_allocator());
__result->_M_c_string = 0; // Not eos terminated.
#else
// We should sometimes create substring node instead.
__result = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__l->_M_data + __start,
__result_len,
__base->
_M_get_allocator());
#endif
return __result;
}
case __detail::_S_substringfn:
// Avoid introducing multiple layers of substring nodes.
{
_RopeSubstring* __old = (_RopeSubstring*)__base;
size_t __result_len;
if (__start >= __adj_endp1)
return 0;
__result_len = __adj_endp1 - __start;
if (__result_len > __lazy_threshold)
{
_RopeSubstring* __result =
_S_new_RopeSubstring(__old->_M_base,
__start + __old->_M_start,
__adj_endp1 - __start,
__base->_M_get_allocator());
return __result;
} // *** else fall through: ***
}
case __detail::_S_function:
{
_RopeFunction* __f = (_RopeFunction*)__base;
_CharT* __section;
size_t __result_len;
if (__start >= __adj_endp1)
return 0;
__result_len = __adj_endp1 - __start;
if (__result_len > __lazy_threshold)
goto lazy;
__section = (_CharT*)
rope::_Data_allocate(_S_rounded_up_size(__result_len));
__try
{ (*(__f->_M_fn))(__start, __result_len, __section); }
__catch(...)
{
_RopeRep::__STL_FREE_STRING(__section, __result_len,
__base->_M_get_allocator());
__throw_exception_again;
}
_S_cond_store_eos(__section[__result_len]);
return _S_new_RopeLeaf(__section, __result_len,
__base->_M_get_allocator());
}
}
lazy:
{
// Create substring node.
return _S_new_RopeSubstring(__base, __start, __adj_endp1 - __start,
__base->_M_get_allocator());
}
}
template<class _CharT>
class _Rope_flatten_char_consumer
: public _Rope_char_consumer<_CharT>
{
private:
_CharT* _M_buf_ptr;
public:
_Rope_flatten_char_consumer(_CharT* __buffer)
{ _M_buf_ptr = __buffer; };
~_Rope_flatten_char_consumer() {}
bool
operator()(const _CharT* __leaf, size_t __n)
{
uninitialized_copy_n(__leaf, __n, _M_buf_ptr);
_M_buf_ptr += __n;
return true;
}
};
template<class _CharT>
class _Rope_find_char_char_consumer
: public _Rope_char_consumer<_CharT>
{
private:
_CharT _M_pattern;
public:
size_t _M_count; // Number of nonmatching characters
_Rope_find_char_char_consumer(_CharT __p)
: _M_pattern(__p), _M_count(0) {}
~_Rope_find_char_char_consumer() {}
bool
operator()(const _CharT* __leaf, size_t __n)
{
size_t __i;
for (__i = 0; __i < __n; __i++)
{
if (__leaf[__i] == _M_pattern)
{
_M_count += __i;
return false;
}
}
_M_count += __n; return true;
}
};
template<class _CharT, class _Traits>
// Here _CharT is both the stream and rope character type.
class _Rope_insert_char_consumer
: public _Rope_char_consumer<_CharT>
{
private:
typedef basic_ostream<_CharT,_Traits> _Insert_ostream;
_Insert_ostream& _M_o;
public:
_Rope_insert_char_consumer(_Insert_ostream& __writer)
: _M_o(__writer) {};
~_Rope_insert_char_consumer() { };
// Caller is presumed to own the ostream
bool operator() (const _CharT* __leaf, size_t __n);
// Returns true to continue traversal.
};
template<class _CharT, class _Traits>
bool
_Rope_insert_char_consumer<_CharT, _Traits>::
operator()(const _CharT* __leaf, size_t __n)
{
size_t __i;
// We assume that formatting is set up correctly for each element.
for (__i = 0; __i < __n; __i++)
_M_o.put(__leaf[__i]);
return true;
}
template <class _CharT, class _Alloc>
bool
rope<_CharT, _Alloc>::
_S_apply_to_pieces(_Rope_char_consumer<_CharT>& __c,
const _RopeRep* __r, size_t __begin, size_t __end)
{
if (0 == __r)
return true;
switch(__r->_M_tag)
{
case __detail::_S_concat:
{
_RopeConcatenation* __conc = (_RopeConcatenation*)__r;
_RopeRep* __left = __conc->_M_left;
size_t __left_len = __left->_M_size;
if (__begin < __left_len)
{
size_t __left_end = std::min(__left_len, __end);
if (!_S_apply_to_pieces(__c, __left, __begin, __left_end))
return false;
}
if (__end > __left_len)
{
_RopeRep* __right = __conc->_M_right;
size_t __right_start = std::max(__left_len, __begin);
if (!_S_apply_to_pieces(__c, __right,
__right_start - __left_len,
__end - __left_len))
return false;
}
}
return true;
case __detail::_S_leaf:
{
_RopeLeaf* __l = (_RopeLeaf*)__r;
return __c(__l->_M_data + __begin, __end - __begin);
}
case __detail::_S_function:
case __detail::_S_substringfn:
{
_RopeFunction* __f = (_RopeFunction*)__r;
size_t __len = __end - __begin;
bool __result;
_CharT* __buffer =
(_CharT*)_Alloc().allocate(__len * sizeof(_CharT));
__try
{
(*(__f->_M_fn))(__begin, __len, __buffer);
__result = __c(__buffer, __len);
_Alloc().deallocate(__buffer, __len * sizeof(_CharT));
}
__catch(...)
{
_Alloc().deallocate(__buffer, __len * sizeof(_CharT));
__throw_exception_again;
}
return __result;
}
default:
return false;
}
}
template<class _CharT, class _Traits>
inline void
_Rope_fill(basic_ostream<_CharT, _Traits>& __o, size_t __n)
{
char __f = __o.fill();
size_t __i;
for (__i = 0; __i < __n; __i++)
__o.put(__f);
}
template <class _CharT>
inline bool
_Rope_is_simple(_CharT*)
{ return false; }
inline bool
_Rope_is_simple(char*)
{ return true; }
inline bool
_Rope_is_simple(wchar_t*)
{ return true; }
template<class _CharT, class _Traits, class _Alloc>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __o,
const rope<_CharT, _Alloc>& __r)
{
size_t __w = __o.width();
bool __left = bool(__o.flags() & std::ios::left);
size_t __pad_len;
size_t __rope_len = __r.size();
_Rope_insert_char_consumer<_CharT, _Traits> __c(__o);
bool __is_simple = _Rope_is_simple((_CharT*)0);
if (__rope_len < __w)
__pad_len = __w - __rope_len;
else
__pad_len = 0;
if (!__is_simple)
__o.width(__w / __rope_len);
__try
{
if (__is_simple && !__left && __pad_len > 0)
_Rope_fill(__o, __pad_len);
__r.apply_to_pieces(0, __r.size(), __c);
if (__is_simple && __left && __pad_len > 0)
_Rope_fill(__o, __pad_len);
if (!__is_simple)
__o.width(__w);
}
__catch(...)
{
if (!__is_simple)
__o.width(__w);
__throw_exception_again;
}
return __o;
}
template <class _CharT, class _Alloc>
_CharT*
rope<_CharT, _Alloc>::
_S_flatten(_RopeRep* __r, size_t __start, size_t __len,
_CharT* __buffer)
{
_Rope_flatten_char_consumer<_CharT> __c(__buffer);
_S_apply_to_pieces(__c, __r, __start, __start + __len);
return(__buffer + __len);
}
template <class _CharT, class _Alloc>
size_t
rope<_CharT, _Alloc>::
find(_CharT __pattern, size_t __start) const
{
_Rope_find_char_char_consumer<_CharT> __c(__pattern);
_S_apply_to_pieces(__c, this->_M_tree_ptr, __start, size());
size_type __result_pos = __start + __c._M_count;
#ifndef __STL_OLD_ROPE_SEMANTICS
if (__result_pos == size())
__result_pos = npos;
#endif
return __result_pos;
}
template <class _CharT, class _Alloc>
_CharT*
rope<_CharT, _Alloc>::
_S_flatten(_RopeRep* __r, _CharT* __buffer)
{
if (0 == __r)
return __buffer;
switch(__r->_M_tag)
{
case __detail::_S_concat:
{
_RopeConcatenation* __c = (_RopeConcatenation*)__r;
_RopeRep* __left = __c->_M_left;
_RopeRep* __right = __c->_M_right;
_CharT* __rest = _S_flatten(__left, __buffer);
return _S_flatten(__right, __rest);
}
case __detail::_S_leaf:
{
_RopeLeaf* __l = (_RopeLeaf*)__r;
return copy_n(__l->_M_data, __l->_M_size, __buffer).second;
}
case __detail::_S_function:
case __detail::_S_substringfn:
// We don't yet do anything with substring nodes.
// This needs to be fixed before ropefiles will work well.
{
_RopeFunction* __f = (_RopeFunction*)__r;
(*(__f->_M_fn))(0, __f->_M_size, __buffer);
return __buffer + __f->_M_size;
}
default:
return 0;
}
}
// This needs work for _CharT != char
template <class _CharT, class _Alloc>
void
rope<_CharT, _Alloc>::
_S_dump(_RopeRep* __r, int __indent)
{
for (int __i = 0; __i < __indent; __i++)
putchar(' ');
if (0 == __r)
{
printf("NULL\n");
return;
}
if (_S_concat == __r->_M_tag)
{
_RopeConcatenation* __c = (_RopeConcatenation*)__r;
_RopeRep* __left = __c->_M_left;
_RopeRep* __right = __c->_M_right;
#ifdef __GC
printf("Concatenation %p (depth = %d, len = %ld, %s balanced)\n",
__r, __r->_M_depth, __r->_M_size,
__r->_M_is_balanced? "" : "not");
#else
printf("Concatenation %p (rc = %ld, depth = %d, "
"len = %ld, %s balanced)\n",
__r, __r->_M_ref_count, __r->_M_depth, __r->_M_size,
__r->_M_is_balanced? "" : "not");
#endif
_S_dump(__left, __indent + 2);
_S_dump(__right, __indent + 2);
return;
}
else
{
char* __kind;
switch (__r->_M_tag)
{
case __detail::_S_leaf:
__kind = "Leaf";
break;
case __detail::_S_function:
__kind = "Function";
break;
case __detail::_S_substringfn:
__kind = "Function representing substring";
break;
default:
__kind = "(corrupted kind field!)";
}
#ifdef __GC
printf("%s %p (depth = %d, len = %ld) ",
__kind, __r, __r->_M_depth, __r->_M_size);
#else
printf("%s %p (rc = %ld, depth = %d, len = %ld) ",
__kind, __r, __r->_M_ref_count, __r->_M_depth, __r->_M_size);
#endif
if (_S_is_one_byte_char_type((_CharT*)0))
{
const int __max_len = 40;
_Self_destruct_ptr __prefix(_S_substring(__r, 0, __max_len));
_CharT __buffer[__max_len + 1];
bool __too_big = __r->_M_size > __prefix->_M_size;
_S_flatten(__prefix, __buffer);
__buffer[__prefix->_M_size] = _S_eos((_CharT*)0);
printf("%s%s\n", (char*)__buffer,
__too_big? "...\n" : "\n");
}
else
printf("\n");
}
}
template <class _CharT, class _Alloc>
const unsigned long
rope<_CharT, _Alloc>::
_S_min_len[int(__detail::_S_max_rope_depth) + 1] = {
/* 0 */1, /* 1 */2, /* 2 */3, /* 3 */5, /* 4 */8, /* 5 */13, /* 6 */21,
/* 7 */34, /* 8 */55, /* 9 */89, /* 10 */144, /* 11 */233, /* 12 */377,
/* 13 */610, /* 14 */987, /* 15 */1597, /* 16 */2584, /* 17 */4181,
/* 18 */6765, /* 19 */10946, /* 20 */17711, /* 21 */28657, /* 22 */46368,
/* 23 */75025, /* 24 */121393, /* 25 */196418, /* 26 */317811,
/* 27 */514229, /* 28 */832040, /* 29 */1346269, /* 30 */2178309,
/* 31 */3524578, /* 32 */5702887, /* 33 */9227465, /* 34 */14930352,
/* 35 */24157817, /* 36 */39088169, /* 37 */63245986, /* 38 */102334155,
/* 39 */165580141, /* 40 */267914296, /* 41 */433494437,
/* 42 */701408733, /* 43 */1134903170, /* 44 */1836311903,
/* 45 */2971215073u };
// These are Fibonacci numbers < 2**32.
template <class _CharT, class _Alloc>
typename rope<_CharT, _Alloc>::_RopeRep*
rope<_CharT, _Alloc>::
_S_balance(_RopeRep* __r)
{
_RopeRep* __forest[int(__detail::_S_max_rope_depth) + 1];
_RopeRep* __result = 0;
int __i;
// Invariant:
// The concatenation of forest in descending order is equal to __r.
// __forest[__i]._M_size >= _S_min_len[__i]
// __forest[__i]._M_depth = __i
// References from forest are included in refcount.
for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
__forest[__i] = 0;
__try
{
_S_add_to_forest(__r, __forest);
for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
if (0 != __forest[__i])
{
#ifndef __GC
_Self_destruct_ptr __old(__result);
#endif
__result = _S_concat(__forest[__i], __result);
__forest[__i]->_M_unref_nonnil();
#if !defined(__GC) && __cpp_exceptions
__forest[__i] = 0;
#endif
}
}
__catch(...)
{
for(__i = 0; __i <= int(__detail::_S_max_rope_depth); __i++)
_S_unref(__forest[__i]);
__throw_exception_again;
}
if (__result->_M_depth > int(__detail::_S_max_rope_depth))
__throw_length_error(__N("rope::_S_balance"));
return(__result);
}
template <class _CharT, class _Alloc>
void
rope<_CharT, _Alloc>::
_S_add_to_forest(_RopeRep* __r, _RopeRep** __forest)
{
if (__r->_M_is_balanced)
{
_S_add_leaf_to_forest(__r, __forest);
return;
}
{
_RopeConcatenation* __c = (_RopeConcatenation*)__r;
_S_add_to_forest(__c->_M_left, __forest);
_S_add_to_forest(__c->_M_right, __forest);
}
}
template <class _CharT, class _Alloc>
void
rope<_CharT, _Alloc>::
_S_add_leaf_to_forest(_RopeRep* __r, _RopeRep** __forest)
{
_RopeRep* __insertee; // included in refcount
_RopeRep* __too_tiny = 0; // included in refcount
int __i; // forest[0..__i-1] is empty
size_t __s = __r->_M_size;
for (__i = 0; __s >= _S_min_len[__i+1]/* not this bucket */; ++__i)
{
if (0 != __forest[__i])
{
#ifndef __GC
_Self_destruct_ptr __old(__too_tiny);
#endif
__too_tiny = _S_concat_and_set_balanced(__forest[__i],
__too_tiny);
__forest[__i]->_M_unref_nonnil();
__forest[__i] = 0;
}
}
{
#ifndef __GC
_Self_destruct_ptr __old(__too_tiny);
#endif
__insertee = _S_concat_and_set_balanced(__too_tiny, __r);
}
// Too_tiny dead, and no longer included in refcount.
// Insertee is live and included.
for (;; ++__i)
{
if (0 != __forest[__i])
{
#ifndef __GC
_Self_destruct_ptr __old(__insertee);
#endif
__insertee = _S_concat_and_set_balanced(__forest[__i],
__insertee);
__forest[__i]->_M_unref_nonnil();
__forest[__i] = 0;
}
if (__i == int(__detail::_S_max_rope_depth)
|| __insertee->_M_size < _S_min_len[__i+1])
{
__forest[__i] = __insertee;
// refcount is OK since __insertee is now dead.
return;
}
}
}
template <class _CharT, class _Alloc>
_CharT
rope<_CharT, _Alloc>::
_S_fetch(_RopeRep* __r, size_type __i)
{
__GC_CONST _CharT* __cstr = __r->_M_c_string;
if (0 != __cstr)
return __cstr[__i];
for(;;)
{
switch(__r->_M_tag)
{
case __detail::_S_concat:
{
_RopeConcatenation* __c = (_RopeConcatenation*)__r;
_RopeRep* __left = __c->_M_left;
size_t __left_len = __left->_M_size;
if (__i >= __left_len)
{
__i -= __left_len;
__r = __c->_M_right;
}
else
__r = __left;
}
break;
case __detail::_S_leaf:
{
_RopeLeaf* __l = (_RopeLeaf*)__r;
return __l->_M_data[__i];
}
case __detail::_S_function:
case __detail::_S_substringfn:
{
_RopeFunction* __f = (_RopeFunction*)__r;
_CharT __result;
(*(__f->_M_fn))(__i, 1, &__result);
return __result;
}
}
}
}
#ifndef __GC
// Return a uniquely referenced character slot for the given
// position, or 0 if that's not possible.
template <class _CharT, class _Alloc>
_CharT*
rope<_CharT, _Alloc>::
_S_fetch_ptr(_RopeRep* __r, size_type __i)
{
_RopeRep* __clrstack[__detail::_S_max_rope_depth];
size_t __csptr = 0;
for(;;)
{
if (__r->_M_ref_count > 1)
return 0;
switch(__r->_M_tag)
{
case __detail::_S_concat:
{
_RopeConcatenation* __c = (_RopeConcatenation*)__r;
_RopeRep* __left = __c->_M_left;
size_t __left_len = __left->_M_size;
if (__c->_M_c_string != 0)
__clrstack[__csptr++] = __c;
if (__i >= __left_len)
{
__i -= __left_len;
__r = __c->_M_right;
}
else
__r = __left;
}
break;
case __detail::_S_leaf:
{
_RopeLeaf* __l = (_RopeLeaf*)__r;
if (__l->_M_c_string != __l->_M_data && __l->_M_c_string != 0)
__clrstack[__csptr++] = __l;
while (__csptr > 0)
{
-- __csptr;
_RopeRep* __d = __clrstack[__csptr];
__d->_M_free_c_string();
__d->_M_c_string = 0;
}
return __l->_M_data + __i;
}
case __detail::_S_function:
case __detail::_S_substringfn:
return 0;
}
}
}
#endif /* __GC */
// The following could be implemented trivially using
// lexicographical_compare_3way.
// We do a little more work to avoid dealing with rope iterators for
// flat strings.
template <class _CharT, class _Alloc>
int
rope<_CharT, _Alloc>::
_S_compare (const _RopeRep* __left, const _RopeRep* __right)
{
size_t __left_len;
size_t __right_len;
if (0 == __right)
return 0 != __left;
if (0 == __left)
return -1;
__left_len = __left->_M_size;
__right_len = __right->_M_size;
if (__detail::_S_leaf == __left->_M_tag)
{
_RopeLeaf* __l = (_RopeLeaf*) __left;
if (__detail::_S_leaf == __right->_M_tag)
{
_RopeLeaf* __r = (_RopeLeaf*) __right;
return lexicographical_compare_3way(__l->_M_data,
__l->_M_data + __left_len,
__r->_M_data, __r->_M_data
+ __right_len);
}
else
{
const_iterator __rstart(__right, 0);
const_iterator __rend(__right, __right_len);
return lexicographical_compare_3way(__l->_M_data, __l->_M_data
+ __left_len,
__rstart, __rend);
}
}
else
{
const_iterator __lstart(__left, 0);
const_iterator __lend(__left, __left_len);
if (__detail::_S_leaf == __right->_M_tag)
{
_RopeLeaf* __r = (_RopeLeaf*) __right;
return lexicographical_compare_3way(__lstart, __lend,
__r->_M_data, __r->_M_data
+ __right_len);
}
else
{
const_iterator __rstart(__right, 0);
const_iterator __rend(__right, __right_len);
return lexicographical_compare_3way(__lstart, __lend,
__rstart, __rend);
}
}
}
// Assignment to reference proxies.
template <class _CharT, class _Alloc>
_Rope_char_ref_proxy<_CharT, _Alloc>&
_Rope_char_ref_proxy<_CharT, _Alloc>::
operator=(_CharT __c)
{
_RopeRep* __old = _M_root->_M_tree_ptr;
#ifndef __GC
// First check for the case in which everything is uniquely
// referenced. In that case we can do this destructively.
_CharT* __ptr = _My_rope::_S_fetch_ptr(__old, _M_pos);
if (0 != __ptr)
{
*__ptr = __c;
return *this;
}
#endif
_Self_destruct_ptr __left(_My_rope::_S_substring(__old, 0, _M_pos));
_Self_destruct_ptr __right(_My_rope::_S_substring(__old, _M_pos + 1,
__old->_M_size));
_Self_destruct_ptr __result_left(_My_rope::
_S_destr_concat_char_iter(__left,
&__c, 1));
_RopeRep* __result = _My_rope::_S_concat(__result_left, __right);
#ifndef __GC
_RopeRep::_S_unref(__old);
#endif
_M_root->_M_tree_ptr = __result;
return *this;
}
template <class _CharT, class _Alloc>
inline _Rope_char_ref_proxy<_CharT, _Alloc>::
operator _CharT() const
{
if (_M_current_valid)
return _M_current;
else
return _My_rope::_S_fetch(_M_root->_M_tree_ptr, _M_pos);
}
template <class _CharT, class _Alloc>
_Rope_char_ptr_proxy<_CharT, _Alloc>
_Rope_char_ref_proxy<_CharT, _Alloc>::
operator&() const
{ return _Rope_char_ptr_proxy<_CharT, _Alloc>(*this); }
template <class _CharT, class _Alloc>
rope<_CharT, _Alloc>::
rope(size_t __n, _CharT __c, const allocator_type& __a)
: _Base(__a)
{
rope<_CharT,_Alloc> __result;
const size_t __exponentiate_threshold = 32;
size_t __exponent;
size_t __rest;
_CharT* __rest_buffer;
_RopeRep* __remainder;
rope<_CharT, _Alloc> __remainder_rope;
if (0 == __n)
return;
__exponent = __n / __exponentiate_threshold;
__rest = __n % __exponentiate_threshold;
if (0 == __rest)
__remainder = 0;
else
{
__rest_buffer = this->_Data_allocate(_S_rounded_up_size(__rest));
__uninitialized_fill_n_a(__rest_buffer, __rest, __c,
_M_get_allocator());
_S_cond_store_eos(__rest_buffer[__rest]);
__try
{ __remainder = _S_new_RopeLeaf(__rest_buffer, __rest,
_M_get_allocator()); }
__catch(...)
{
_RopeRep::__STL_FREE_STRING(__rest_buffer, __rest,
_M_get_allocator());
__throw_exception_again;
}
}
__remainder_rope._M_tree_ptr = __remainder;
if (__exponent != 0)
{
_CharT* __base_buffer =
this->_Data_allocate(_S_rounded_up_size(__exponentiate_threshold));
_RopeLeaf* __base_leaf;
rope __base_rope;
__uninitialized_fill_n_a(__base_buffer, __exponentiate_threshold, __c,
_M_get_allocator());
_S_cond_store_eos(__base_buffer[__exponentiate_threshold]);
__try
{
__base_leaf = _S_new_RopeLeaf(__base_buffer,
__exponentiate_threshold,
_M_get_allocator());
}
__catch(...)
{
_RopeRep::__STL_FREE_STRING(__base_buffer,
__exponentiate_threshold,
_M_get_allocator());
__throw_exception_again;
}
__base_rope._M_tree_ptr = __base_leaf;
if (1 == __exponent)
__result = __base_rope;
else
__result = power(__base_rope, __exponent,
_Rope_Concat_fn<_CharT, _Alloc>());
if (0 != __remainder)
__result += __remainder_rope;
}
else
__result = __remainder_rope;
this->_M_tree_ptr = __result._M_tree_ptr;
this->_M_tree_ptr->_M_ref_nonnil();
}
template<class _CharT, class _Alloc>
_CharT
rope<_CharT, _Alloc>::_S_empty_c_str[1];
template<class _CharT, class _Alloc>
const _CharT*
rope<_CharT, _Alloc>::
c_str() const
{
if (0 == this->_M_tree_ptr)
{
_S_empty_c_str[0] = _S_eos((_CharT*)0); // Possibly redundant,
// but probably fast.
return _S_empty_c_str;
}
__gthread_mutex_lock (&this->_M_tree_ptr->_M_c_string_lock);
__GC_CONST _CharT* __result = this->_M_tree_ptr->_M_c_string;
if (0 == __result)
{
size_t __s = size();
__result = this->_Data_allocate(__s + 1);
_S_flatten(this->_M_tree_ptr, __result);
__result[__s] = _S_eos((_CharT*)0);
this->_M_tree_ptr->_M_c_string = __result;
}
__gthread_mutex_unlock (&this->_M_tree_ptr->_M_c_string_lock);
return(__result);
}
template<class _CharT, class _Alloc>
const _CharT* rope<_CharT, _Alloc>::
replace_with_c_str()
{
if (0 == this->_M_tree_ptr)
{
_S_empty_c_str[0] = _S_eos((_CharT*)0);
return _S_empty_c_str;
}
__GC_CONST _CharT* __old_c_string = this->_M_tree_ptr->_M_c_string;
if (__detail::_S_leaf == this->_M_tree_ptr->_M_tag
&& 0 != __old_c_string)
return(__old_c_string);
size_t __s = size();
_CharT* __result = this->_Data_allocate(_S_rounded_up_size(__s));
_S_flatten(this->_M_tree_ptr, __result);
__result[__s] = _S_eos((_CharT*)0);
this->_M_tree_ptr->_M_unref_nonnil();
this->_M_tree_ptr = _S_new_RopeLeaf(__result, __s,
this->_M_get_allocator());
return(__result);
}
// Algorithm specializations. More should be added.
template<class _Rope_iterator> // was templated on CharT and Alloc
void // VC++ workaround
_Rope_rotate(_Rope_iterator __first,
_Rope_iterator __middle,
_Rope_iterator __last)
{
typedef typename _Rope_iterator::value_type _CharT;
typedef typename _Rope_iterator::_allocator_type _Alloc;
rope<_CharT, _Alloc>& __r(__first.container());
rope<_CharT, _Alloc> __prefix = __r.substr(0, __first.index());
rope<_CharT, _Alloc> __suffix =
__r.substr(__last.index(), __r.size() - __last.index());
rope<_CharT, _Alloc> __part1 =
__r.substr(__middle.index(), __last.index() - __middle.index());
rope<_CharT, _Alloc> __part2 =
__r.substr(__first.index(), __middle.index() - __first.index());
__r = __prefix;
__r += __part1;
__r += __part2;
__r += __suffix;
}
#if !defined(__GNUC__)
// Appears to confuse g++
inline void
rotate(_Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __first,
_Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __middle,
_Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __last)
{ _Rope_rotate(__first, __middle, __last); }
#endif
# if 0
// Probably not useful for several reasons:
// - for SGIs 7.1 compiler and probably some others,
// this forces lots of rope<wchar_t, ...> instantiations, creating a
// code bloat and compile time problem. (Fixed in 7.2.)
// - wchar_t is 4 bytes wide on most UNIX platforms, making it
// unattractive for unicode strings. Unsigned short may be a better
// character type.
inline void
rotate(_Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __first,
_Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __middle,
_Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __last)
{ _Rope_rotate(__first, __middle, __last); }
# endif
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project>
<!-- Type providers currently can't run inside the .NET Core 2.0 hosted compiler, see https://github.com/Microsoft/visualfsharp/pull/3658#issuecomment-334773415 -->
<PropertyGroup>
<IsWindows Condition="'$(OS)' == 'Windows_NT'">true</IsWindows>
<IsOSX Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">true</IsOSX>
<IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\FSharp</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\FSharp</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\FSharp</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)' == 'true' AND Exists('C:\Program Files (x86)\Microsoft SDKs\F#\10.1\Framework\v4.0\fsc.exe')">
<FscToolPath>C:\Program Files (x86)\Microsoft SDKs\F#\10.1\Framework\v4.0</FscToolPath>
<FscToolExe>fsc.exe</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsOSX)' == 'true' AND Exists('/Library/Frameworks/Mono.framework/Versions/Current/Commands/fsharpc')">
<FscToolPath>/Library/Frameworks/Mono.framework/Versions/Current/Commands</FscToolPath>
<FscToolExe>fsharpc</FscToolExe>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)' == 'true' AND Exists('/usr/bin/fsharpc')">
<FscToolPath>/usr/bin</FscToolPath>
<FscToolExe>fsharpc</FscToolExe>
</PropertyGroup>
</Project> | {
"pile_set_name": "Github"
} |
"use strict";
if (!require("./is-implemented")()) {
Object.defineProperty(Math, "imul", { value: require("./shim"),
configurable: true,
enumerable: false,
writable: true });
}
| {
"pile_set_name": "Github"
} |
namespace EasyCaching.Serialization.Json
{
using System;
using System.IO;
using System.Text;
using EasyCaching.Core.Internal;
using EasyCaching.Core.Serialization;
using Newtonsoft.Json;
/// <summary>
/// Default json serializer.
/// </summary>
public class DefaultJsonSerializer : IEasyCachingSerializer
{
/// <summary>
/// The json serializer.
/// </summary>
private readonly JsonSerializer jsonSerializer;
/// <summary>
/// The name.
/// </summary>
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="T:EasyCaching.Serialization.Json.DefaultJsonSerializer"/> class.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="serializerSettings">serializerSettings.</param>
public DefaultJsonSerializer(string name, JsonSerializerSettings serializerSettings)
{
_name = name;
jsonSerializer = JsonSerializer.Create(serializerSettings);
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => _name;
/// <summary>
/// Deserialize the specified bytes.
/// </summary>
/// <returns>The deserialize.</returns>
/// <param name="bytes">Bytes.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T Deserialize<T>(byte[] bytes)
{
using (var ms = new MemoryStream(bytes))
using (var sr = new StreamReader(ms, Encoding.UTF8))
using (var jtr = new JsonTextReader(sr))
{
return jsonSerializer.Deserialize<T>(jtr);
}
}
/// <summary>
/// Deserialize the specified bytes.
/// </summary>
/// <returns>The deserialize.</returns>
/// <param name="bytes">Bytes.</param>
/// <param name="type">Type.</param>
public object Deserialize(byte[] bytes, Type type)
{
using (var ms = new MemoryStream(bytes))
using (var sr = new StreamReader(ms, Encoding.UTF8))
using (var jtr = new JsonTextReader(sr))
{
return jsonSerializer.Deserialize(jtr, type);
}
}
/// <summary>
/// Serialize the specified value.
/// </summary>
/// <returns>The serialize.</returns>
/// <param name="value">Value.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public byte[] Serialize<T>(T value)
{
using (var ms = new MemoryStream())
{
using (var sr = new StreamWriter(ms, Encoding.UTF8))
using (var jtr = new JsonTextWriter(sr))
{
jsonSerializer.Serialize(jtr, value);
}
return ms.ToArray();
}
}
#region Mainly For Memcached
/// <summary>
/// Serializes the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="obj">Object.</param>
public ArraySegment<byte> SerializeObject(object obj)
{
var typeName = TypeHelper.BuildTypeName(obj.GetType()); // Get type
using (var ms = new MemoryStream())
using (var tw = new StreamWriter(ms))
using (var jw = new JsonTextWriter(tw))
{
jw.WriteStartArray(); // [
jw.WriteValue(typeName); // "type",
jsonSerializer.Serialize(jw, obj); // obj
jw.WriteEndArray(); // ]
jw.Flush();
return new ArraySegment<byte>(ms.ToArray(), 0, (int)ms.Length);
}
}
/// <summary>
/// Deserializes the object.
/// </summary>
/// <returns>The object.</returns>
/// <param name="value">Value.</param>
public object DeserializeObject(ArraySegment<byte> value)
{
using (var ms = new MemoryStream(value.Array, value.Offset, value.Count, writable: false))
using (var tr = new StreamReader(ms))
using (var jr = new JsonTextReader(tr))
{
jr.Read();
if (jr.TokenType == JsonToken.StartArray)
{
// read type
var typeName = jr.ReadAsString();
var type = Type.GetType(typeName, throwOnError: true);// Get type
// read object
jr.Read();
return jsonSerializer.Deserialize(jr, type);
}
else
{
throw new InvalidDataException("JsonTranscoder only supports [\"TypeName\", object]");
}
}
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/gem/protocol/brake_motor_rpt_2_71.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
Brakemotorrpt271::Brakemotorrpt271() {}
const int32_t Brakemotorrpt271::ID = 0x71;
void Brakemotorrpt271::Parse(const std::uint8_t* bytes, int32_t length,
ChassisDetail* chassis) const {
chassis->mutable_gem()
->mutable_brake_motor_rpt_2_71()
->set_encoder_temperature(encoder_temperature(bytes, length));
chassis->mutable_gem()->mutable_brake_motor_rpt_2_71()->set_motor_temperature(
motor_temperature(bytes, length));
chassis->mutable_gem()->mutable_brake_motor_rpt_2_71()->set_angular_speed(
angular_speed(bytes, length));
}
// config detail: {'name': 'encoder_temperature', 'offset': -40.0,
// 'precision': 1.0, 'len': 16, 'is_signed_var': True, 'physical_range':
// '[-32808|32727]', 'bit': 7, 'type': 'int', 'order': 'motorola',
// 'physical_unit': 'deg C'}
int Brakemotorrpt271::encoder_temperature(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 1);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
int ret = x + -40;
return ret;
}
// config detail: {'name': 'motor_temperature', 'offset': -40.0,
// 'precision': 1.0, 'len': 16, 'is_signed_var': True, 'physical_range':
// '[-32808|32727]', 'bit': 23, 'type': 'int', 'order': 'motorola',
// 'physical_unit': 'deg C'}
int Brakemotorrpt271::motor_temperature(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 3);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
int ret = x + -40;
return ret;
}
// config detail: {'name': 'angular_speed', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': False, 'physical_range': '[0|4294967.295]',
// 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rev/s'}
double Brakemotorrpt271::angular_speed(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 5);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t2(bytes + 6);
t = t2.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t3(bytes + 7);
t = t3.get_byte(0, 8);
x <<= 8;
x |= t;
double ret = x * 0.001000;
return ret;
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| {
"pile_set_name": "Github"
} |
#import "GPUImageColorInvertFilter.h"
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
NSString *const kGPUImageInvertFragmentShaderString = SHADER_STRING
(
varying highp vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
gl_FragColor = vec4((1.0 - textureColor.rgb), textureColor.w);
}
);
#else
NSString *const kGPUImageInvertFragmentShaderString = SHADER_STRING
(
varying vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
gl_FragColor = vec4((1.0 - textureColor.rgb), textureColor.w);
}
);
#endif
@implementation GPUImageColorInvertFilter
- (id)init;
{
if (!(self = [super initWithFragmentShaderFromString:kGPUImageInvertFragmentShaderString]))
{
return nil;
}
return self;
}
@end
| {
"pile_set_name": "Github"
} |
<Window x:Class="MyCustomControl.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:MyCustomControl">
<Grid>
<uc:NumericUpDown />
</Grid>
</Window>
| {
"pile_set_name": "Github"
} |
unit wmusers;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, HTTPDefs, websession, fpHTTP, fpWeb,
db, dbf, fpwebdata, fpextjs,extjsjson,extjsxml;
type
{ TFPWebModule1 }
TFPWebModule1 = class(TFPWebModule)
Dbf1: TDbf;
procedure TFPWebActions0Request(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
procedure TFPWebActions1Request(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
procedure TFPWebActions2Request(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
procedure TFPWebActions3Request(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
private
{ private declarations }
procedure GetAdaptorAndFormatter(P : TFPWebDataProvider; Var F :TExtJSDataFormatter; ARequest : TRequest; AResponse : TResponse);
public
{ public declarations }
end;
var
FPWebModule1: TFPWebModule1;
Var
ResponseFileName : String; // Set to non empty to write request responses to a file.
implementation
{$R *.lfm}
{$define wmdebug}
{$ifdef wmdebug}
uses dbugintf;
{$endif}
{ TFPWebModule1 }
Procedure SaveResponse(M : TStream);
begin
if (ResponseFileName<>'') then
With TFileStream.Create(ResponseFileName,fmCreate) do
try
CopyFrom(M,0);
finally
Free;
end;
end;
procedure TFPWebModule1.GetAdaptorAndFormatter(P : TFPWebDataProvider; Var F :TExtJSDataFormatter; ARequest : TRequest; AResponse : TResponse);
begin
If Request.QueryFields.values['format']='xml' then
begin
F:=TExtJSXMLDataFormatter.Create(Self);
TExtJSXMLDataFormatter(F).TotalProperty:='total';
AResponse.ContentType:='text/xml';
P.Adaptor:=TExtJSXMLWebdataInputAdaptor.Create(Nil);
end
else
begin
P.Adaptor:=TExtJSJSonWebdataInputAdaptor.Create(Nil);
F:=TExtJSJSONDataFormatter.Create(Self);
end;
P.Adaptor.Request:=ARequest;
F.Adaptor:=P.Adaptor;
F.Provider:=P;
end;
procedure TFPWebModule1.TFPWebActions0Request(Sender: TObject;
ARequest: TRequest; AResponse: TResponse; var Handled: Boolean);
Var
PN : String;
P : TFPWebDataProvider;
F : TExtJSDataFormatter;
DS : TDatasource;
M : TMemoryStream;
L : Text;
begin
// Providername;
PN:=ARequest.GetNextPathInfo;
P:=TFPWebDataProvider.Create(Self);
try
GetAdaptorAndFormatter(P,F,ARequest,AResponse);
{$ifdef wmdebug} SendDebug(className+' '+F.ClassName);{$endif}
try
DS:=TDatasource.Create(Self);
try
DBF1.TableName:=ExtractFilePath(ParamStr(0))+'users.dbf';
DS.Dataset:=DBf1;
DBF1.Open;
try
P.Datasource:=DS;
P.Adaptor.Action:=wdaRead;
P.ApplyParams;
M:=TMemoryStream.Create;
try
F.GetContent(ARequest,M,Handled);
M.Position:=0;
Response.ContentStream:=M;
Response.SendResponse;
Response.ContentStream:=Nil;
SaveResponse(M);
finally
M.Free;
end;
finally
DBF1.Close;
end;
finally
DS.Free;
end;
finally
F.Free;
end;
finally
P.Free;
end;
end;
procedure TFPWebModule1.TFPWebActions1Request(Sender: TObject;
ARequest: TRequest; AResponse: TResponse; var Handled: Boolean);
Var
PN : String;
P : TFPWebDataProvider;
F : TExtJSDataFormatter;
DS : TDatasource;
M : TMemoryStream;
L : Text;
begin
// Providername;
PN:=ARequest.GetNextPathInfo;
// P:=GetWebDataProvider(PN);
P:=TFPWebDataProvider.Create(Self);
try
P.IDFieldName:='ID';
GetAdaptorAndFormatter(P,F,ARequest,AResponse);
{$ifdef wmdebug} SendDebug(className+' '+F.ClassName);{$endif}
try
DS:=TDatasource.Create(Self);
try
DBF1.TableName:=ExtractFilePath(ParamStr(0))+'users.dbf';
DS.Dataset:=DBf1;
DBF1.Open;
try
P.Datasource:=DS;
P.Adaptor.Action:=wdaInsert;
P.ApplyParams;
M:=TMemoryStream.Create;
try
F.GetContent(ARequest,M,Handled);
M.Position:=0;
Response.ContentStream:=M;
Response.SendResponse;
Response.ContentStream:=Nil;
SaveResponse(M);
finally
M.Free;
end;
finally
DBF1.Close;
end;
finally
DS.Free;
end;
finally
F.Free;
end;
finally
P.Free;
end;
end;
procedure TFPWebModule1.TFPWebActions2Request(Sender: TObject;
ARequest: TRequest; AResponse: TResponse; var Handled: Boolean);
Var
PN : String;
P : TFPWebDataProvider;
F : TExtJSDataFormatter;
DS : TDatasource;
M : TMemoryStream;
L : Text;
begin
// Providername;
{$ifdef wmdebug} SendDebug('Update request received');{$endif}
PN:=ARequest.GetNextPathInfo;
// P:=GetWebDataProvider(PN);
P:=TFPWebDataProvider.Create(Self);
try
P.IDFieldName:='ID';
GetAdaptorAndFormatter(P,F,ARequest,AResponse);
{$ifdef wmdebug} SendDebug(className+' '+F.ClassName);{$endif}
try
DS:=TDatasource.Create(Self);
try
DBF1.TableName:=ExtractFilePath(ParamStr(0))+'users.dbf';
DS.Dataset:=DBf1;
DBF1.Open;
try
P.Datasource:=DS;
P.Adaptor.Action:=wdaUpdate;
P.ApplyParams;
M:=TMemoryStream.Create;
try
F.GetContent(ARequest,M,Handled);
M.Position:=0;
Response.ContentStream:=M;
Response.SendResponse;
Response.ContentStream:=Nil;
SaveResponse(M);
finally
M.Free;
end;
finally
DBF1.Close;
end;
finally
DS.Free;
end;
finally
F.Free;
end;
finally
P.Free;
end;
end;
procedure TFPWebModule1.TFPWebActions3Request(Sender: TObject;
ARequest: TRequest; AResponse: TResponse; var Handled: Boolean);
Var
PN : String;
P : TFPWebDataProvider;
F : TExtJSDataFormatter;
DS : TDatasource;
M : TMemoryStream;
L : Text;
begin
// Providername;
PN:=ARequest.GetNextPathInfo;
// P:=GetWebDataProvider(PN);
P:=TFPWebDataProvider.Create(Self);
try
P.IDFieldName:='ID';
GetAdaptorAndFormatter(P,F,ARequest,AResponse);
{$ifdef wmdebug} SendDebug('className '+F.ClassName);{$endif}
try
DS:=TDatasource.Create(Self);
try
DBF1.TableName:=ExtractFilePath(ParamStr(0))+'users.dbf';
DS.Dataset:=DBf1;
DBF1.Open;
try
P.Datasource:=DS;
P.Adaptor.Action:=wdaDelete;
P.ApplyParams;
M:=TMemoryStream.Create;
try
F.GetContent(ARequest,M,Handled);
M.Position:=0;
Response.ContentStream:=M;
Response.SendResponse;
Response.ContentStream:=Nil;
SaveResponse(M);
finally
M.Free;
end;
finally
DBF1.Close;
end;
finally
DS.Free;
end;
finally
F.Free;
end;
finally
P.Free;
end;
end;
initialization
RegisterHTTPModule('Provider', TFPWebModule1);
end.
| {
"pile_set_name": "Github"
} |
package cn.uncode.schedule.quartz;
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.support.ArgumentConvertingMethodInvoker;
import org.springframework.scheduling.quartz.JobMethodInvocationFailedException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.MethodInvoker;
import org.springframework.util.ReflectionUtils;
import cn.uncode.schedule.ConsoleManager;
import cn.uncode.schedule.util.ScheduleUtil;
/**
* {@link org.springframework.beans.factory.FactoryBean} that exposes a
* {@link org.quartz.JobDetail} object which delegates job execution to a
* specified (static or non-static) method. Avoids the need for implementing
* a one-line Quartz Job that just invokes an existing service method on a
* Spring-managed target bean.
*
* <p>Inherits common configuration properties from the {@link MethodInvoker}
* base class, such as {@link #setTargetObject "targetObject"} and
* {@link #setTargetMethod "targetMethod"}, adding support for lookup of the target
* bean by name through the {@link #setTargetBeanName "targetBeanName"} property
* (as alternative to specifying a "targetObject" directly, allowing for
* non-singleton target objects).
*
* <p>Supports both concurrently running jobs and non-currently running
* jobs through the "concurrent" property. Jobs created by this
* MethodInvokingJobDetailFactoryBean are by default volatile and durable
* (according to Quartz terminology).
*
* <p><b>NOTE: JobDetails created via this FactoryBean are <i>not</i>
* serializable and thus not suitable for persistent job stores.</b>
* You need to implement your own Quartz Job as a thin wrapper for each case
* where you want a persistent job to delegate to a specific service method.
*
* <p>Compatible with Quartz 1.5+ as well as Quartz 2.0/2.1, as of Spring 3.1.
*
* @author Juergen Hoeller
* @author Alef Arendsen
* @since 18.02.2004
* @see #setTargetBeanName
* @see #setTargetObject
* @see #setTargetMethod
* @see #setConcurrent
*/
public class MethodInvokingJobDetailFactoryBean extends ArgumentConvertingMethodInvoker
implements FactoryBean<JobDetail>, BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, InitializingBean {
private static final transient Logger LOGGER = LoggerFactory.getLogger(MethodInvokingJobDetailFactoryBean.class);
private static Class<?> jobDetailImplClass;
private static Method setResultMethod;
static {
try {
jobDetailImplClass = Class.forName("org.quartz.impl.JobDetailImpl");
}
catch (ClassNotFoundException ex) {
jobDetailImplClass = null;
}
try {
Class<?> jobExecutionContextClass =
QuartzJobBean.class.getClassLoader().loadClass("org.quartz.JobExecutionContext");
setResultMethod = jobExecutionContextClass.getMethod("setResult", Object.class);
}
catch (Exception ex) {
throw new IllegalStateException("Incompatible Quartz API: " + ex);
}
}
private String name;
private String group = Scheduler.DEFAULT_GROUP;
private boolean concurrent = true;
private String targetBeanName;
private String[] jobListenerNames;
private String beanName;
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private BeanFactory beanFactory;
private JobDetail jobDetail;
/**
* Set the name of the job.
* <p>Default is the bean name of this FactoryBean.
* @see org.quartz.JobDetail#setName
*/
public void setName(String name) {
this.name = name;
}
/**
* Set the group of the job.
* <p>Default is the default group of the Scheduler.
* @see org.quartz.JobDetail#setGroup
* @see org.quartz.Scheduler#DEFAULT_GROUP
*/
public void setGroup(String group) {
this.group = group;
}
/**
* Specify whether or not multiple jobs should be run in a concurrent
* fashion. The behavior when one does not want concurrent jobs to be
* executed is realized through adding the {@link StatefulJob} interface.
* More information on stateful versus stateless jobs can be found
* <a href="http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-03">here</a>.
* <p>The default setting is to run jobs concurrently.
*/
public void setConcurrent(boolean concurrent) {
this.concurrent = concurrent;
}
/**
* Set the name of the target bean in the Spring BeanFactory.
* <p>This is an alternative to specifying {@link #setTargetObject "targetObject"},
* allowing for non-singleton beans to be invoked. Note that specified
* "targetObject" and {@link #setTargetClass "targetClass"} values will
* override the corresponding effect of this "targetBeanName" setting
* (i.e. statically pre-define the bean type or even the bean object).
*/
public void setTargetBeanName(String targetBeanName) {
this.targetBeanName = targetBeanName;
}
/**
* Set a list of JobListener names for this job, referring to
* non-global JobListeners registered with the Scheduler.
* <p>A JobListener name always refers to the name returned
* by the JobListener implementation.
* @see SchedulerFactoryBean#setJobListeners
* @see org.quartz.JobListener#getName
*/
public void setJobListenerNames(String[] names) {
this.jobListenerNames = names;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
protected Class<?> resolveClassName(String className) throws ClassNotFoundException {
return ClassUtils.forName(className, this.beanClassLoader);
}
public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException {
prepare();
// Use specific name if given, else fall back to bean name.
String name = (this.name != null ? this.name : this.beanName);
// Consider the concurrent flag to choose between stateful and stateless job.
Class<?> jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class);
// Build JobDetail instance.
if (jobDetailImplClass != null) {
// Using Quartz 2.0 JobDetailImpl class...
this.jobDetail = (JobDetail) BeanUtils.instantiate(jobDetailImplClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this.jobDetail);
bw.setPropertyValue("name", name);
bw.setPropertyValue("group", this.group);
bw.setPropertyValue("jobClass", jobClass);
bw.setPropertyValue("durability", true);
((JobDataMap) bw.getPropertyValue("jobDataMap")).put("methodInvoker", this);
}
// Register job listener names.
if (this.jobListenerNames != null) {
for (String jobListenerName : this.jobListenerNames) {
if (jobListenerName != null) {
throw new IllegalStateException("Non-global JobListeners not supported on Quartz 2 - " +
"manually register a Matcher against the Quartz ListenerManager instead");
}
//this.jobDetail.addJobListener(jobListenerName);
}
}
postProcessJobDetail(this.jobDetail);
}
/**
* Callback for post-processing the JobDetail to be exposed by this FactoryBean.
* <p>The default implementation is empty. Can be overridden in subclasses.
* @param jobDetail the JobDetail prepared by this FactoryBean
*/
protected void postProcessJobDetail(JobDetail jobDetail) {
}
/**
* Overridden to support the {@link #setTargetBeanName "targetBeanName"} feature.
*/
@Override
public Class<?> getTargetClass() {
Class<?> targetClass = super.getTargetClass();
if (targetClass == null && this.targetBeanName != null) {
Assert.state(this.beanFactory != null, "BeanFactory must be set when using 'targetBeanName'");
targetClass = this.beanFactory.getType(this.targetBeanName);
}
return targetClass;
}
/**
* Overridden to support the {@link #setTargetBeanName "targetBeanName"} feature.
*/
@Override
public Object getTargetObject() {
Object targetObject = super.getTargetObject();
if (targetObject == null && this.targetBeanName != null) {
Assert.state(this.beanFactory != null, "BeanFactory must be set when using 'targetBeanName'");
targetObject = this.beanFactory.getBean(this.targetBeanName);
}
return targetObject;
}
public JobDetail getObject() {
return this.jobDetail;
}
public Class<? extends JobDetail> getObjectType() {
return (this.jobDetail != null ? this.jobDetail.getClass() : JobDetail.class);
}
public boolean isSingleton() {
return true;
}
/**
* Quartz Job implementation that invokes a specified method.
* Automatically applied by MethodInvokingJobDetailFactoryBean.
*/
public static class MethodInvokingJob extends QuartzJobBean {
protected static final Log logger = LogFactory.getLog(MethodInvokingJob.class);
private MethodInvoker methodInvoker;
/**
* Set the MethodInvoker to use.
*/
public void setMethodInvoker(MethodInvoker methodInvoker) {
this.methodInvoker = methodInvoker;
}
/**
* Invoke the method via the MethodInvoker.
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
String name = ScheduleUtil.getTaskNameFormBean(context.getJobDetail().getKey().getName(), this.methodInvoker.getTargetMethod());
boolean isOwner = false;
try {
if(ConsoleManager.getScheduleManager().getZkManager().checkZookeeperState()){
isOwner = ConsoleManager.getScheduleManager().getScheduleDataManager().isOwner(name, ConsoleManager.getScheduleManager().getScheduleServerUUid());
ConsoleManager.getScheduleManager().getIsOwnerMap().put(name, isOwner);
}else{
// 如果zk不可用,使用历史数据
if(null != ConsoleManager.getScheduleManager().getIsOwnerMap()){
isOwner = ConsoleManager.getScheduleManager().getIsOwnerMap().get(name);
}
}
} catch (Exception e) {
LOGGER.error("Check task owner error.", e);
}
if(isOwner){
ReflectionUtils.invokeMethod(setResultMethod, context, this.methodInvoker.invoke());
LOGGER.info("Cron job has been executed.");
}
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof JobExecutionException) {
// -> JobExecutionException, to be logged at info level by Quartz
throw (JobExecutionException) ex.getTargetException();
}
else {
// -> "unhandled exception", to be logged at error level by Quartz
throw new JobMethodInvocationFailedException(this.methodInvoker, ex.getTargetException());
}
}
catch (Exception ex) {
// -> "unhandled exception", to be logged at error level by Quartz
throw new JobMethodInvocationFailedException(this.methodInvoker, ex);
}
}
}
/**
* Extension of the MethodInvokingJob, implementing the StatefulJob interface.
* Quartz checks whether or not jobs are stateful and if so,
* won't let jobs interfere with each other.
*/
public static class StatefulMethodInvokingJob extends MethodInvokingJob implements Job {
// No implementation, just an addition of the tag interface StatefulJob
// in order to allow stateful method invoking jobs.
}
}
| {
"pile_set_name": "Github"
} |
{
"name" : "difflet",
"description" : "colorful diffs for javascript objects",
"version" : "0.2.0",
"repository" : {
"type" : "git",
"url" : "git://github.com/substack/difflet.git"
},
"main" : "index.js",
"keywords" : [
"diff",
"object",
"compare"
],
"directories" : {
"lib" : ".",
"example" : "example",
"test" : "test"
},
"scripts" : {
"test" : "tap test/*.js"
},
"dependencies" : {
"traverse" : "0.6.x",
"charm" : "0.0.x",
"deep-equal" : "0.0.x"
},
"devDependencies" : {
"tap" : "0.1.x",
"ent" : "0.0.x"
},
"engines" : {
"node" : ">=0.4.0"
},
"license" : "MIT",
"author" : {
"name" : "James Halliday",
"email" : "mail@substack.net",
"url" : "http://substack.net"
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.